Programs & Examples On #Xfdf

XFDF is the XML version of the "Forms Data Format (FDF)" specification. It is designed to representing form data and annotations that are contained in a PDF form.

OSX El Capitan: sudo pip install OSError: [Errno: 1] Operation not permitted

Same error

Installing collected packages: six, pyparsing, packaging, appdirs, setuptools
Exception:
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 342, in run
    prefix=options.prefix_path,
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 784, in install
    **kwargs
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 851, in install
    self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 1064, in move_wheel_files
    isolated=self.isolated,
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 345, in move_wheel_files
    clobber(source, lib_dir, True)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 323, in clobber
    shutil.copyfile(srcfile, destfile)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py", line 83, in copyfile
    with open(dst, 'wb') as fdst:
IOError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/six.py'

and here I use --user without sudo to solve this issue

$ pip install --user scikit-image h5py keras pygame
Collecting scikit-image
  Downloading http://mirrors.aliyun.com/pypi/packages/65/69/27a1d55ce8f77c8ac757938707105b1070ff4f2ae47d2dc99461bfae4491/scikit_image-0.13.0-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (28.1MB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 28.1MB 380kB/s
Collecting h5py
  Downloading http://mirrors.aliyun.com/pypi/packages/b7/cc/1c29b0815b12de2c92b5323cad60f724ac8f0e39d0166d0b9dfacbcb70dd/h5py-2.7.0-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (4.5MB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 4.5MB 503kB/s
Requirement already satisfied: keras in /Library/Python/2.7/site-packages
Requirement already satisfied: pygame in /Library/Python/2.7/site-packages
Requirement already satisfied: matplotlib>=1.3.1 in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from scikit-image)
Requirement already satisfied: six>=1.7.3 in /Library/Python/2.7/site-packages (from scikit-image)
Requirement already satisfied: pillow>=2.1.0 in /Library/Python/2.7/site-packages (from scikit-image)
Requirement already satisfied: networkx>=1.8 in /Library/Python/2.7/site-packages (from scikit-image)
Requirement already satisfied: PyWavelets>=0.4.0 in /Library/Python/2.7/site-packages (from scikit-image)
Collecting scipy>=0.17.0 (from scikit-image)
  Downloading http://mirrors.aliyun.com/pypi/packages/72/eb/d398b9f63ee936575edc62520477d6c2353ed013bacd656bd0c8bc1d0fa7/scipy-0.19.0-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (16.2MB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 16.2MB 990kB/s
Requirement already satisfied: numpy>=1.7 in /Library/Python/2.7/site-packages (from h5py)
Requirement already satisfied: theano in /Library/Python/2.7/site-packages (from keras)
Requirement already satisfied: pyyaml in /Library/Python/2.7/site-packages (from keras)
Requirement already satisfied: python-dateutil in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: tornado in /Library/Python/2.7/site-packages (from matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: pyparsing>=1.5.6 in /Users/qiuwei/Library/Python/2.7/lib/python/site-packages (from matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: nose in /Library/Python/2.7/site-packages (from matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: olefile in /Library/Python/2.7/site-packages (from pillow>=2.1.0->scikit-image)
Requirement already satisfied: decorator>=3.4.0 in /Library/Python/2.7/site-packages (from networkx>=1.8->scikit-image)
Requirement already satisfied: singledispatch in /Library/Python/2.7/site-packages (from tornado->matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: certifi in /Library/Python/2.7/site-packages (from tornado->matplotlib>=1.3.1->scikit-image)
Requirement already satisfied: backports_abc>=0.4 in /Library/Python/2.7/site-packages (from tornado->matplotlib>=1.3.1->scikit-image)
Installing collected packages: scipy, scikit-image, h5py
Successfully installed h5py-2.7.0 scikit-image-0.13.0 scipy-0.19.0 

Hope it will help someone who encounter similar issue!

What is a .pid file and what does it contain?

To understand pid files, refer this DOC

Some times there are certain applications that require additional support of extra plugins and utilities. So it keeps track of these utilities and plugin process running ids using this pid file for reference.

That is why whenever you restart an application all necessary plugins and dependant apps must be restarted since the pid file will become stale.

Lotus Notes email as an attachment to another email

Copy the mail as a document link (right click on the mail and you should get this option) and paste it in the new mail. This worked for me

Error when checking Java version: could not find java.dll

Reinstall JDK and set system variable JAVA_HOME on your JDK. (e.g. C:\tools\jdk7)
And add JAVA_HOME variable to your PATH system variable

Type in command line

echo %JAVA_HOME%

and

java -version

To verify whether your installation was done successfully.


This problem generally occurs in Windows when your "Java Runtime Environment" registry entry is missing or mismatched with the installed JDK. The mismatch can be due to multiple JDKs.

Steps to resolve:

  1. Open the Run window:

    Press windows+R

  2. Open registry window:

    Type regedit and enter.

  3. Go to: \HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\

  4. If Java Runtime Environment is not present inside JavaSoft, then create a new Key and give the name Java Runtime Environment.

  5. For Java Runtime Environment create "CurrentVersion" String Key and give appropriate version as value:

JRE regedit entry

  1. Create a new subkey of 1.8.

  2. For 1.8 create a String Key with name JavaHome with the value of JRE home:

    JRE regedit entry 2

Ref: https://mybindirectory.blogspot.com/2019/05/error-could-not-find-javadll.html

Overlaying a DIV On Top Of HTML 5 Video

<div id="video_box">
  <div id="video_overlays"></div>
  <div>
    <video id="player" src="http://video.webmfiles.org/big-buck-bunny_trailer.webm" type="video/webm" onclick="this.play();">Your browser does not support this streaming content.</video>
  </div>
</div>

for this you need to just add css like this:

#video_overlays {
  position: absolute;
  background-color: rgba(0, 0, 0, 0.46);
  z-index: 2;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}
#video_box{position: relative;}

How to check if an array value exists?

To check if the index is defined: isset($something['say'])

Https Connection Android

I make this class and found

package com.example.fakessl;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;

import android.util.Log;

public class CertificadoAceptar {
    private static TrustManager[] trustManagers;

    public static class _FakeX509TrustManager implements
            javax.net.ssl.X509TrustManager {
        private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};

        public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException {
        }

        public boolean isClientTrusted(X509Certificate[] chain) {
            return (true);
        }

        public boolean isServerTrusted(X509Certificate[] chain) {
            return (true);
        }

        public X509Certificate[] getAcceptedIssuers() {
            return (_AcceptedIssuers);
        }
    }

    public static void allowAllSSL() {

        javax.net.ssl.HttpsURLConnection
                .setDefaultHostnameVerifier(new HostnameVerifier() {
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                });

        javax.net.ssl.SSLContext context = null;

        if (trustManagers == null) {
            trustManagers = new javax.net.ssl.TrustManager[] { new _FakeX509TrustManager() };
        }

        try {
            context = javax.net.ssl.SSLContext.getInstance("TLS");
            context.init(null, trustManagers, new SecureRandom());
        } catch (NoSuchAlgorithmException e) {
            Log.e("allowAllSSL", e.toString());
        } catch (KeyManagementException e) {
            Log.e("allowAllSSL", e.toString());
        }
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context
                .getSocketFactory());
    }
}

in you code white this

CertificadoAceptar ca = new CertificadoAceptar();
ca.allowAllSSL();
HttpsTransportSE Transport = new HttpsTransportSE("iphost or host name", 8080, "/WS/wsexample.asmx?WSDL", 30000);

generate random double numbers in c++

This should be performant, thread-safe and flexible enough for many uses:

#include <random>
#include <iostream>

template<typename Numeric, typename Generator = std::mt19937>
Numeric random(Numeric from, Numeric to)
{
    thread_local static Generator gen(std::random_device{}());

    using dist_type = typename std::conditional
    <
        std::is_integral<Numeric>::value
        , std::uniform_int_distribution<Numeric>
        , std::uniform_real_distribution<Numeric>
    >::type;

    thread_local static dist_type dist;

    return dist(gen, typename dist_type::param_type{from, to});
}

int main(int, char*[])
{
    for(auto i = 0U; i < 20; ++i)
        std::cout << random<double>(0.0, 0.3) << '\n';
}

How to copy directory recursively in python and overwrite all?

Have a look at the shutil package, especially rmtree and copytree. You can check if a file / path exists with os.paths.exists(<path>).

import shutil
import os

def copy_and_overwrite(from_path, to_path):
    if os.path.exists(to_path):
        shutil.rmtree(to_path)
    shutil.copytree(from_path, to_path)

Vincent was right about copytree not working, if dirs already exist. So distutils is the nicer version. Below is a fixed version of shutil.copytree. It's basically copied 1-1, except the first os.makedirs() put behind an if-else-construct:

import os
from shutil import *
def copytree(src, dst, symlinks=False, ignore=None):
    names = os.listdir(src)
    if ignore is not None:
        ignored_names = ignore(src, names)
    else:
        ignored_names = set()

    if not os.path.isdir(dst): # This one line does the trick
        os.makedirs(dst)
    errors = []
    for name in names:
        if name in ignored_names:
            continue
        srcname = os.path.join(src, name)
        dstname = os.path.join(dst, name)
        try:
            if symlinks and os.path.islink(srcname):
                linkto = os.readlink(srcname)
                os.symlink(linkto, dstname)
            elif os.path.isdir(srcname):
                copytree(srcname, dstname, symlinks, ignore)
            else:
                # Will raise a SpecialFileError for unsupported file types
                copy2(srcname, dstname)
        # catch the Error from the recursive copytree so that we can
        # continue with other files
        except Error, err:
            errors.extend(err.args[0])
        except EnvironmentError, why:
            errors.append((srcname, dstname, str(why)))
    try:
        copystat(src, dst)
    except OSError, why:
        if WindowsError is not None and isinstance(why, WindowsError):
            # Copying file access times may fail on Windows
            pass
        else:
            errors.extend((src, dst, str(why)))
    if errors:
        raise Error, errors

WSDL/SOAP Test With soapui

definitions is a root element of WSDL so it looks like you are not loading WSDL.

Edit:

I tested it and it looks like the whole problem is with your web server. Your web server returns WSDL to browser but it doesn't return it to any tool because these tools are using very minimalistic HTTP requests without many HTTP headers. One of missing headers is Accept. Once this header is not included in the request your server throws HTTP 400 Bad request.

The easy approach to continue is opening WSDL in the browser, save the wsdl to a file and import that file to soapUI instead of the WSDL from URL.

How to solve "sign_and_send_pubkey: signing failed: agent refused operation"?

To this error:

# git pull
sign_and_send_pubkey: signing failed: agent refused operation
[email protected]: Permission denied (publickey).    
fatal: Could not read from remote repository.

Please make sure you have the correct access rights and the repository exists.

Verify or add again the public key in Github account > profile > ssh.

I solved like this:

# chmod 400 ~/.ssh/id_rsa

# ls  ~/.ssh/id_rsa -ls  
4 -r--------. 1 reinaldo reinaldo 1679 Jul 26  2017 /home/reinaldo/.ssh/id_rsa

# git pull                                 
remote: Counting objects: 35, done.
remote: Compressing objects: 100% (19/19), done.
remote: Total 35 (delta 9), reused 34 (delta 9), pack-reused 0
Unpacking objects: 100% (35/35), done.

Thank you.

How to tell if a string contains a certain character in JavaScript?

Use a regular expression to accomplish this.

function isAlphanumeric( str ) {
 return /^[0-9a-zA-Z]+$/.test(str);
}

Python: split a list based on a condition?

good.append(x) if x in goodvals else bad.append(x)

This elegant and concise answer by @dansalmo showed up buried in the comments, so I'm just reposting it here as an answer so it can get the prominence it deserves, especially for new readers.

Complete example:

good, bad = [], []
for x in my_list:
    good.append(x) if x in goodvals else bad.append(x)

How to iterate through XML in Powershell?

PowerShell has built-in XML and XPath functions. You can use the Select-Xml cmdlet with an XPath query to select nodes from XML object and then .Node.'#text' to access node value.

[xml]$xml = Get-Content $serviceStatePath
$nodes = Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml
$nodes | ForEach-Object {$_.Node.'#text'}

Or shorter

[xml]$xml = Get-Content $serviceStatePath
Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml |
  % {$_.Node.'#text'}

How do I write stderr to a file while using "tee" with a pipe?

If you're using zsh, you can use multiple redirections, so you don't even need tee:

./cmd 1>&1 2>&2 1>out_file 2>err_file

Here you're simply redirecting each stream to itself and the target file.


Full example

% (echo "out"; echo "err">/dev/stderr) 1>&1 2>&2 1>/tmp/out_file 2>/tmp/err_file
out
err
% cat /tmp/out_file
out
% cat /tmp/err_file
err

Note that this requires the MULTIOS option to be set (which is the default).

MULTIOS

Perform implicit tees or cats when multiple redirections are attempted (see Redirection).

Table scroll with HTML and CSS

This work for me

Demo: jsfiddle

$(function() 
{
    Fixed_Header();
});

function Fixed_Header()
{
    $('.User_Table thead').css({'position': 'absolute'});
    $('.User_Table tbody tr:eq("2") td').each(function(index,e){
        $('.User_Table thead tr th:eq("'+index+'")').css({'width' : $(this).outerWidth() +"px" });
    });
    var Header_Height = $('.User_Table thead').outerHeight();
    $('.User_Table thead').css({'margin-top' : "-"+Header_Height+"px"});
    $('.User_Table').css({'margin-top' : Header_Height+"px"});
}

Bootstrap modal in React.js

You can use React-Bootstrap (https://react-bootstrap.github.io/components/modal). There is an example for modals at that link. Once you have loaded react-bootstrap, the modal component can be used as a react component:

var Modal = ReactBootstrap.Modal;

can then be used as a react component as <Modal/>.

For Bootstrap 4, there is react-strap (https://reactstrap.github.io). React-Bootstrap only supports Bootstrap 3.

Detecting Windows or Linux?

You can use "system.properties.os", for example:

public class GetOs {

  public static void main (String[] args) {
    String s = 
      "name: " + System.getProperty ("os.name");
    s += ", version: " + System.getProperty ("os.version");
    s += ", arch: " + System.getProperty ("os.arch");
    System.out.println ("OS=" + s);
  }
}

// EXAMPLE OUTPUT: OS=name: Windows 7, version: 6.1, arch: amd64

Here are more details:

Find all elements with a certain attribute value in jquery

Use string concatenation. Try this:

$('div[imageId="'+imageN +'"]').each(function() {
    $(this);   
});

How can I keep Bootstrap popovers alive while being hovered?

Here is a solution I devised that seems to work well while also allowing you to use the normal Bootstrap implementation for turning on all popovers.

Original fiddle: https://jsfiddle.net/eXpressive/hfear592/

Ported to this question:

<a href="#" id="example" class="btn btn-danger" rel="popover" >hover for popover</a>

$('#example').popover({
    html : true,
    trigger : 'hover',
    content : function() {
        return '<div class="box"></div>';
    }
}).on('hide.bs.popover', function () {
    if ($(".popover:hover").length) {
      return false;
    }                
}); 

$('body').on('mouseleave', '.popover', function(){
    $('.popover').popover('hide');
});

WHERE clause on SQL Server "Text" data type

You can use LIKE instead of =. Without any wildcards this will have the same effect.

DECLARE @Village TABLE
        (CastleType TEXT)

INSERT INTO @Village
VALUES
  (
    'foo'
  )

SELECT *
FROM   @Village
WHERE  [CastleType] LIKE 'foo' 

text is deprecated. Changing to varchar(max) will be easier to work with.

Also how large is the data likely to be? If you are going to be doing equality comparisons you will ideally want to index this column. This isn't possible if you declare the column as anything wider than 900 bytes though you can add a computed checksum or hash column that can be used to speed this type of query up.

for each loop in Objective-C for accessing NSMutable dictionary

If you need to mutate the dictionary while enumerating:

for (NSString* key in xyz.allKeys) {
    [xyz setValue:[NSNumber numberWithBool:YES] forKey:key];
}

How to count frequency of characters in a string?

package com.dipu.string;

import java.util.HashMap;
import java.util.Map;

public class RepetativeCharInString {
    public static void main(String[] args) {
        String data = "aaabbbcccdddffffrss";
        char[] charArray = data.toCharArray();
        Map<Character, Integer> map = new HashMap<>();
        for (char c : charArray) {
            if (map.containsKey(c)) {
                map.put(c, map.get(c) + 1);
            } else {
                map.put(c, 1);
            }
        }
        System.out.println(map);

    }
}

Hide separator line on one UITableViewCell

Swift:

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    ...

    // remove separator for last cell
    cell.separatorInset = indexPath.row < numberOfRowsInSection-1
        ? tableView.separatorInset
        : UIEdgeInsets(top: 0, left: tableView.bounds.size.width, bottom: 0, right: 0)

    return cell
}

Objective-C:

- (UITableViewCell *)tableView:(UITableView *)tableView
     cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    ...

    // remove separator for last cell
    cell.separatorInset = (indexPath.row < numberOfRowsInSection-1)
        ? tableView.separatorInset
        : UIEdgeInsetsMake(0.f, tableView.bounds.size.width, 0.f, 0.f);

    return cell;
}

What is the correct Performance Counter to get CPU and Memory Usage of a Process?

From this post:

To get the entire PC CPU and Memory usage:

using System.Diagnostics;

Then declare globally:

private PerformanceCounter theCPUCounter = 
   new PerformanceCounter("Processor", "% Processor Time", "_Total"); 

Then to get the CPU time, simply call the NextValue() method:

this.theCPUCounter.NextValue();

This will get you the CPU usage

As for memory usage, same thing applies I believe:

private PerformanceCounter theMemCounter = 
   new PerformanceCounter("Memory", "Available MBytes");

Then to get the memory usage, simply call the NextValue() method:

this.theMemCounter.NextValue();

For a specific process CPU and Memory usage:

private PerformanceCounter theCPUCounter = 
   new PerformanceCounter("Process", "% Processor Time",              
   Process.GetCurrentProcess().ProcessName);

where Process.GetCurrentProcess().ProcessName is the process name you wish to get the information about.

private PerformanceCounter theMemCounter = 
   new PerformanceCounter("Process", "Working Set",
   Process.GetCurrentProcess().ProcessName);

where Process.GetCurrentProcess().ProcessName is the process name you wish to get the information about.

Note that Working Set may not be sufficient in its own right to determine the process' memory footprint -- see What is private bytes, virtual bytes, working set?

To retrieve all Categories, see Walkthrough: Retrieving Categories and Counters

The difference between Processor\% Processor Time and Process\% Processor Time is Processor is from the PC itself and Process is per individual process. So the processor time of the processor would be usage on the PC. Processor time of a process would be the specified processes usage. For full description of category names: Performance Monitor Counters

An alternative to using the Performance Counter

Use System.Diagnostics.Process.TotalProcessorTime and System.Diagnostics.ProcessThread.TotalProcessorTime properties to calculate your processor usage as this article describes.

jQuery Cross Domain Ajax

Unfortunately it seems that this web service returns JSON which contains another JSON - parsing contents of the inner JSON is successful. The solution is ugly but works for me. JSON.parse(...) tries to convert the entire string and fails. Assuming that you always get the answer starting with {"AuthenticateUserResult": and interesting data is after this, try:

$.ajax({
    type: 'GET',
    dataType: "text",
    crossDomain: true,
    url: "http://someotherdomain.com/service.svc",
    success: function (responseData, textStatus, jqXHR) {
        var authResult = JSON.parse(
            responseData.replace(
                '{"AuthenticateUserResult":"', ''
            ).replace('}"}', '}')
        );
        console.log("in");
    },
    error: function (responseData, textStatus, errorThrown) {
        alert('POST failed.');
    }
});

It is very important that dataType must be text to prevent auto-parsing of malformed JSON you are receiving from web service.

Basically, I'm wiping out the outer JSON by removing topmost braces and key AuthenticateUserResult along with leading and trailing quotation marks. The result is a well formed JSON, ready for parsing.

Detect browser or tab closing

window.onbeforeunload = function ()
{       

    if (isProcess > 0) 
    {
        return true;       
    }   

    else
    { 
        //do something      
    }
}; 

This function show a confirmation dialog box if you close window or refresh page during any process in browser.This function work in all browsers.You have to set isProcess var in your ajax process.

Get index of selected option with jQuery

try this

 alert(document.getElementById("dropDownMenuKategorie").selectedIndex);

Is there an online application that automatically draws tree structures for phrases/sentences?

There are lots of options out there. Many of which are available as downloadable software as well as public websites. I do not think many of them expect to be used as API's unless they explicitly state that.

The one that I found effective was Enju which did not have the character limit that the Marc's Carnagie Mellon link had. Marc also mentioned a VISL scanner in comments, but that requires java in the browser, which is a non-starter for me.

Note that recently, Google has offered a new NLP Machine Learning API that providers amoung other features, a automatic sentence parser. I will likely not update this answer again, especially since the question is closed, but I suspect that the other big ML cloud stacks will soon support the same.

ImportError: No module named PyQt4.QtCore

As mentioned in the comments, you need to install the python-qt4 package - no need to recompile it yourself.

sudo apt-get install python-qt4

HTTP Basic Authentication credentials passed in URL and encryption

Will the username and password be automatically SSL encrypted? Is the same true for GETs and POSTs

Yes, yes yes.

The entire communication (save for the DNS lookup if the IP for the hostname isn't already cached) is encrypted when SSL is in use.

Saving ssh key fails

If you're using Windows, the unix-style default path of ssh-keygen is at fault.

In Line 2 it says Enter file in which to save the key (/c/Users/Eva/.ssh/id_rsa):. That full filename in the parantheses is the default, obviously Windows cannot access a file like that. If you type the Windows equivalent (c:\Users\Eva\.ssh\id_rsa), it should work.

Before running this, you also need to create the folder. You can do this by running mkdir c:\Users\Eva\.ssh, or by created the folder ".ssh." from File Explorer (note the second dot at the end, which will get removed automatically, and is required to create a folder that has a dot at the beginning).

c:\Users\Administrator\.ssh>ssh-keygen -t rsa -C "[email protected]"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/Administrator/.ssh/id_rsa): C:\Users\Administrator\.ssh\id_rsa
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in C:\Users\Administrator\.ssh\id_rsa.
Your public key has been saved in C:\Users\Administrator\.ssh\id_rsa.pub.
The key fingerprint is:
... [email protected]
The key's randomart image is:...`

I know this is an old thread, but I thought the answer might help others.

Display string multiple times

Python 2.x:

print '-' * 3

Python 3.x:

print('-' * 3)

ViewBag, ViewData and TempData

1)TempData

Allows you to store data that will survive for a redirect. Internally it uses the Session as backing store, after the redirect is made the data is automatically evicted. The pattern is the following:

public ActionResult Foo()
{
    // store something into the tempdata that will be available during a single redirect
    TempData["foo"] = "bar";

    // you should always redirect if you store something into TempData to
    // a controller action that will consume this data
    return RedirectToAction("bar");
}

public ActionResult Bar()
{
    var foo = TempData["foo"];
    ...
}

2)ViewBag, ViewData

Allows you to store data in a controller action that will be used in the corresponding view. This assumes that the action returns a view and doesn't redirect. Lives only during the current request.

The pattern is the following:

public ActionResult Foo()
{
    ViewBag.Foo = "bar";
    return View();
}

and in the view:

@ViewBag.Foo

or with ViewData:

public ActionResult Foo()
{
    ViewData["Foo"] = "bar";
    return View();
}

and in the view:

@ViewData["Foo"]

ViewBag is just a dynamic wrapper around ViewData and exists only in ASP.NET MVC 3.

This being said, none of those two constructs should ever be used. You should use view models and strongly typed views. So the correct pattern is the following:

View model:

public class MyViewModel
{
    public string Foo { get; set; }
}

Action:

public Action Foo()
{
    var model = new MyViewModel { Foo = "bar" };
    return View(model);
}

Strongly typed view:

@model MyViewModel
@Model.Foo

After this brief introduction let's answer your question:

My requirement is I want to set a value in a controller one, that controller will redirect to ControllerTwo and Controller2 will render the View.

public class OneController: Controller
{
    public ActionResult Index()
    {
        TempData["foo"] = "bar";
        return RedirectToAction("index", "two");
    }
}

public class TwoController: Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            Foo = TempData["foo"] as string
        };
        return View(model);
    }
}

and the corresponding view (~/Views/Two/Index.cshtml):

@model MyViewModel
@Html.DisplayFor(x => x.Foo)

There are drawbacks of using TempData as well: if the user hits F5 on the target page the data will be lost.

Personally I don't use TempData neither. It's because internally it uses Session and I disable session in my applications. I prefer a more RESTful way to achieve this. Which is: in the first controller action that performs the redirect store the object in your data store and user the generated unique id when redirecting. Then on the target action use this id to fetch back the initially stored object:

public class OneController: Controller
{
    public ActionResult Index()
    {
        var id = Repository.SaveData("foo");
        return RedirectToAction("index", "two", new { id = id });
    }
}

public class TwoController: Controller
{
    public ActionResult Index(string id)
    {
        var model = new MyViewModel
        {
            Foo = Repository.GetData(id)
        };
        return View(model);
    }
}

The view stays the same.

log4net hierarchy and logging levels

As others have noted, it is usually preferable to specify a minimum logging level to log that level and any others more severe than it. It seems like you are just thinking about the logging levels backwards.

However, if you want more fine-grained control over logging individual levels, you can tell log4net to log only one or more specific levels using the following syntax:

<filter type="log4net.Filter.LevelMatchFilter">
  <levelToMatch value="WARN"/>
</filter>

Or to exclude a specific logging level by adding a "deny" node to the filter.

You can stack multiple filters together to specify multiple levels. For instance, if you wanted only WARN and FATAL levels. If the levels you wanted were consecutive, then the LevelRangeFilter is more appropriate.

Reference Doc: log4net.Filter.LevelMatchFilter

If the other answers haven't given you enough information, hopefully this will help you get what you want out of log4net.

Getting a list of all subdirectories in the current directory

Listing Out only directories

print("\nWe are listing out only the directories in current directory -")
directories_in_curdir = filter(os.path.isdir, os.listdir(os.curdir))
print(directories_in_curdir)

Listing Out only files in current directory

files = filter(os.path.isfile, os.listdir(os.curdir))
print("\nThe following are the list of all files in the current directory -")
print(files)

how to destroy bootstrap modal window completely?

If modal shadow remains darker and not going for showing more than one modal then this will be helpful

$('.modal').live('hide',function(){
    if($('.modal-backdrop').length>1){
        $('.modal-backdrop')[0].remove();
    }
});

determine DB2 text string length

Mostly we write below statement select * from table where length(ltrim(rtrim(field)))=10;

How to get a URL parameter in Express?

You can do something like req.param('tagId')

Java Object Null Check for method

If you are using Java 7 You can use Objects.requireNotNull(object[, optionalMessage]); - to check if the parameter is null. To check if each element is not null just use

if(null != books[i]){/*do stuff*/}

Example:

public static double calculateInventoryTotal(Book[] books){
    Objects.requireNotNull(books, "Books must not be null");

    double total = 0;

    for (int i = 0; i < books.length; i++){
        if(null != book[i]){
            total += books[i].getPrice();
        }
    }

    return total;
}

How to get rid of blank pages in PDF exported from SSRS

In BIDS or SSDT-BI, do the following:

  1. Click on Report > Report Properties > Layout tab (Page Setup tab in SSDT-BI)
  2. Make a note of the values for Page width, Left margin, Right margin
  3. Close and go back to the design surface
  4. In the Properties window, select Body
  5. Click the + symbol to expand the Size node
  6. Make a note of the value for Width

To render in PDF correctly Body Width + Left margin + Right margin must be less than or equal to Page width. When you see blank pages being rendered it is almost always because the body width plus margins is greater than the page width.

Remember: (Body Width + Left margin + Right margin) <= (Page width)

Execution failed for task ':app:processDebugResources' even with latest build tools

After updating my Android SDK I stumbled upon this very problem and I tried many ways without success. What was most irritating to me when searching for a fix, were the lots of answers suggesting to change the CompileSdkVersion to a certain number while obviously this number changes with time, so here's what I did instead.

I created a new project and ran it on the emulator to make sure it's working, then checked its "\android\app\build.gradle" file and copied the numeric value of CompileSdkVersion and pasted into the same file in my other project that could not be built properly anymore. Now my problem's gone. Hope that helps.

Count elements with jQuery

The best way would be to use .each()

var num = 0;

$('.className').each(function(){
    num++;
});

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

You also get this message when you do not specify a targetOrigin in calls to window.postMessage().

In this example we post a message to the first iFrame and use * as target, which should allow communication to any targetOrigin.

window.frames[0].postMessage({
                    message : "Hi there",
                    command :"hi-there-command",
                    data : "Some Data"
                }, '*')

Lua String replace

Try:

name = "^aH^ai"
name = name:gsub("%^a", "")

See also: http://lua-users.org/wiki/StringLibraryTutorial

How do you auto format code in Visual Studio?

I have a Mac and I clicked Code > Preferences > Settings > Workspace > Formatting and then selected Format On Save.

Now every time I hit cmd + s it auto formats the file.

enter image description here

Can't find bundle for base name /Bundle, locale en_US

I had the same problemo, and balus solution fixed it.

For the record:

WEB-INF\faces-config is

<?xml version="1.0" encoding="UTF-8"?>
<faces-config
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
version="2.0">
    <application>
        <locale-config>
            <default-locale>en</default-locale>
        </locale-config>
        <message-bundle>
            Message
        </message-bundle>
    </application>
</faces-config>

And had Message.properties under WebContent\Resources (after mkyong's tutorial)

the pesky exception appeared even when i renamed the bundle to "Message_en_us" and "Message_en". Moving it to src\ worked.

Should someone post the missing piece to make bundles work under resources,it would be a beautiful thing.

Comparing date part only without comparing time in JavaScript

As I don't see here similar approach, and I'm not enjoying setting h/m/s/ms to 0, as it can cause problems with accurate transition to local time zone with changed date object (I presume so), let me introduce here this, written few moments ago, lil function:

+: Easy to use, makes a basic comparison operations done (comparing day, month and year without time.)
-: It seems that this is a complete opposite of "out of the box" thinking.

function datecompare(date1, sign, date2) {
    var day1 = date1.getDate();
    var mon1 = date1.getMonth();
    var year1 = date1.getFullYear();
    var day2 = date2.getDate();
    var mon2 = date2.getMonth();
    var year2 = date2.getFullYear();
    if (sign === '===') {
        if (day1 === day2 && mon1 === mon2 && year1 === year2) return true;
        else return false;
    }
    else if (sign === '>') {
        if (year1 > year2) return true;
        else if (year1 === year2 && mon1 > mon2) return true;
        else if (year1 === year2 && mon1 === mon2 && day1 > day2) return true;
        else return false;
    }    
}

Usage:

datecompare(date1, '===', date2) for equality check,
datecompare(date1, '>', date2) for greater check,
!datecompare(date1, '>', date2) for less or equal check

Also, obviously, you can switch date1 and date2 in places to achieve any other simple comparison.

Visual Studio popup: "the operation could not be completed"

I had a similar problem on opening Razor Views

  • I logged on to my Azure account which was asking to re-enter my credntials.
  • Restart VS 2015 Update 1

How to change the color of a CheckBox?

You can change the color directly in XML. Use buttonTint for the box: (as of API level 23)

<CheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:buttonTint="@color/CHECK_COLOR" />

You can also do this using appCompatCheckbox v7 for older API levels:

<android.support.v7.widget.AppCompatCheckBox 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    app:buttonTint="@color/COLOR_HERE" /> 

How to make custom error pages work in ASP.NET MVC 4

It seems i came late to the party, but you should better check this out too.

So in system.web for caching up exceptions within the application such as return HttpNotFound()

  <system.web>
    <customErrors mode="RemoteOnly">
      <error statusCode="404" redirect="/page-not-found" />
      <error statusCode="500" redirect="/internal-server-error" />
    </customErrors>
  </system.web>

and in system.webServer for catching up errors that were caught by IIS and did not made their way to the asp.net framework

 <system.webServer>
    <httpErrors errorMode="DetailedLocalOnly">
      <remove statusCode="404"/>
      <error statusCode="404" path="/page-not-found" responseMode="Redirect"/>
      <remove statusCode="500"/>
      <error statusCode="500" path="/internal-server-error" responseMode="Redirect"/>
  </system.webServer>

In the last one if you worry about the client response then change the responseMode="Redirect" to responseMode="File" and serve a static html file, since this one will display a friendly page with an 200 response code.

How to make a rest post call from ReactJS code?

you can install superagent

npm install superagent --save

then for make post call to server

import request from "../../node_modules/superagent/superagent";

request
.post('http://localhost/userLogin')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send({ username: "username", password: "password" })
.end(function(err, res){
console.log(res.text);
});  

Can't connect to local MySQL server through socket '/var/mysql/mysql.sock' (38)

Another workaround is to edit /etc/my.cnf and include host in the section [client]

 [client]
 #password       = your_password
 host            = 127.0.0.1
 port            = 3306
 socket          = /var/run/mysql/mysql.sock

And then restarting the mysql service.

This workaround was tested in: Server version: 5.5.25a-log Source distribution

what is right way to do API call in react js?

You can also fetch data with hooks in your function components

full example with api call: https://codesandbox.io/s/jvvkoo8pq3

second example: https://jsfiddle.net/bradcypert/jhrt40yv/6/

const Repos = ({user}) => {
  const [repos, setRepos] = React.useState([]);

  React.useEffect(() => {
    const fetchData = async () => {
        const response = await axios.get(`https://api.github.com/users/${user}/repos`);
        setRepos(response.data);
    }

    fetchData();
  }, []);

  return (
  <div>
    {repos.map(repo =>
      <div key={repo.id}>{repo.name}</div>
    )}
  </div>
  );
}

ReactDOM.render(<Repos user="bradcypert" />, document.querySelector("#app"))

How to replace url parameter with javascript/jquery?

How about something like this:

<script>
function changeQueryVariable(keyString, replaceString) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    var replaced = false;
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == keyString) {
            vars[i] = pair[0] + "="+ replaceString;
            replaced = true;
        }
    }
    if (!replaced) vars.push(keyString + "=" + replaceString);
    return vars.join("&");
}
</script>

What does 'useLegacyV2RuntimeActivationPolicy' do in the .NET 4 config?

Here's an explanation I wrote recently to help with the void of information on this attribute. http://www.marklio.com/marklio/PermaLink,guid,ecc34c3c-be44-4422-86b7-900900e451f9.aspx (Internet Archive Wayback Machine link)

To quote the most relevant bits:

[Installing .NET] v4 is “non-impactful”. It should not change the behavior of existing components when installed.

The useLegacyV2RuntimeActivationPolicy attribute basically lets you say, “I have some dependencies on the legacy shim APIs. Please make them work the way they used to with respect to the chosen runtime.”

Why don’t we make this the default behavior? You might argue that this behavior is more compatible, and makes porting code from previous versions much easier. If you’ll recall, this can’t be the default behavior because it would make installation of v4 impactful, which can break existing apps installed on your machine.

The full post explains this in more detail. At RTM, the MSDN docs on this should be better.

How to speed up insertion performance in PostgreSQL

Use COPY table TO ... WITH BINARY which is according to the documentation is "somewhat faster than the text and CSV formats." Only do this if you have millions of rows to insert, and if you are comfortable with binary data.

Here is an example recipe in Python, using psycopg2 with binary input.

How to get an object's property's value by property name?

Try this :

$obj = @{
    SomeProp = "Hello"
}

Write-Host "Property Value is $($obj."SomeProp")"

Getting the minimum of two values in SQL

Use Case:

   Select Case When @PaidThisMonth < @OwedPast 
               Then @PaidThisMonth Else @OwedPast End PaidForPast

As Inline table valued UDF

CREATE FUNCTION Minimum
(@Param1 Integer, @Param2 Integer)
Returns Table As
Return(Select Case When @Param1 < @Param2 
                   Then @Param1 Else @Param2 End MinValue)

Usage:

Select MinValue as PaidforPast 
From dbo.Minimum(@PaidThisMonth, @OwedPast)

ADDENDUM: This is probably best for when addressing only two possible values, if there are more than two, consider Craig's answer using Values clause.

What is javax.inject.Named annotation supposed to be used for?

Regarding #2, according to the JSR-330 spec:

This package provides dependency injection annotations that enable portable classes, but it leaves external dependency configuration up to the injector implementation.

So it's up to the provider to determine which objects are available for injection. In the case of Spring it is all Spring beans. And any class annotated with JSR-330 annotations are automatically added as Spring beans when using an AnnotationConfigApplicationContext.

How to get HttpClient to pass credentials along with the request?

In .NET Core, I managed to get a System.Net.Http.HttpClient with UseDefaultCredentials = true to pass through the authenticated user's Windows credentials to a back end service by using WindowsIdentity.RunImpersonated.

HttpClient client = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true } );
HttpResponseMessage response = null;

if (identity is WindowsIdentity windowsIdentity)
{
    await WindowsIdentity.RunImpersonated(windowsIdentity.AccessToken, async () =>
    {
        var request = new HttpRequestMessage(HttpMethod.Get, url)
        response = await client.SendAsync(request);
    });
}

How to access static resources when mapping a global front controller servlet on /*

With regard to Tomcat, a lot depends on the particular version. There was a bug fix https://bz.apache.org/bugzilla/show_bug.cgi?id=50026 which means the servlet-mapping (other than for '/') for the default servlet behaves differently in Tomcat 6.0.29 (and earlier) compared with later versions.

How do I scroll to an element using JavaScript?

try this function

function navigate(divId) {
$j('html, body').animate({ scrollTop: $j("#"+divId).offset().top }, 1500);
}

Pass the div id as parameter it will work I am using it already

Fixed header, footer with scrollable content

Now we've got CSS grid. Welcome to 2019.

_x000D_
_x000D_
/* Required */_x000D_
body {_x000D_
   margin: 0;_x000D_
   height: 100%;_x000D_
}_x000D_
_x000D_
#wrapper {_x000D_
   height: 100vh;_x000D_
   display: grid;_x000D_
   grid-template-rows: 30px 1fr 30px;_x000D_
}_x000D_
_x000D_
#content {_x000D_
   overflow-y: scroll;_x000D_
}_x000D_
_x000D_
/* Optional */_x000D_
#wrapper > * {_x000D_
   padding: 5px;_x000D_
}_x000D_
_x000D_
#header {_x000D_
   background-color: #ff0000ff;_x000D_
}_x000D_
_x000D_
#content {_x000D_
   background-color: #00ff00ff;_x000D_
}_x000D_
_x000D_
#footer {_x000D_
   background-color: #0000ffff;_x000D_
}
_x000D_
<body>_x000D_
   <div id="wrapper">_x000D_
      <div id="header">Header Content</div>_x000D_
      <div id="content">_x000D_
         Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
      </div>_x000D_
      <div id="footer">Footer Content</div>_x000D_
   </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Process.start: how to get the output?

When you create your Process object set StartInfo appropriately:

var proc = new Process 
{
    StartInfo = new ProcessStartInfo
    {
        FileName = "program.exe",
        Arguments = "command line arguments to your executable",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};

then start the process and read from it:

proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
    string line = proc.StandardOutput.ReadLine();
    // do something with line
}

You can use int.Parse() or int.TryParse() to convert the strings to numeric values. You may have to do some string manipulation first if there are invalid numeric characters in the strings you read.

Should switch statements always contain a default clause?

Having a default clause when it's not really needed is Defensive programming This usually leads to code that is overly complex because of too much error handling code. This error handling and detection code harms the readability of the code, makes maintenance harder, and eventually leads to more bugs than it solves.

So I believe that if the default shouldn't be reached - you don't have to add it.

Note that "shouldn't be reached" means that if it reached it's a bug in the software - you do need to test values that may contain unwanted values because of user input, etc.

Adding a user on .htpasswd

FWIW, htpasswd -n username will output the result directly to stdout, and avoid touching files altogether.

Error: unable to verify the first certificate in nodejs

This actually solved it for me, from https://www.npmjs.com/package/ssl-root-cas

// INCORRECT (but might still work)
var server = https.createServer({
  key: fs.readFileSync('privkey.pem', 'ascii'),
  cert: fs.readFileSync('cert.pem', 'ascii') // a PEM containing ONLY the SERVER certificate
});

// CORRECT (should always work)
var server = https.createServer({
  key: fs.readFileSync('privkey.pem', 'ascii'),
  cert: fs.readFileSync('fullchain.pem', 'ascii') // a PEM containing the SERVER and ALL INTERMEDIATES
});

How can I escape white space in a bash loop list?

Why not just put

IFS='\n'

in front of the for command? This changes the field separator from < Space>< Tab>< Newline> to just < Newline>

R error "sum not meaningful for factors"

The error comes when you try to call sum(x) and x is a factor.

What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)

simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:

family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))

For a detailed explanation of why the intermediate as.character step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?

How to create a service running a .exe file on Windows 2012 Server?

You can just do that too, it seems to work well too. sc create "Servicename" binPath= "Path\To\your\App.exe" DisplayName= "My Custom Service"

You can open the registry and add a string named Description in your service's registry key to add a little more descriptive information about it. It will be shown in services.msc.

CodeIgniter - return only one row?

$this->db->get()->row()->campaign_id;

Session variables not working php

The other important reason sessions can not work is playing with the session cookie settings, eg. setting session cookie lifetime to 0 or other low values because of simple mistake or by other developer for a reason.

session_set_cookie_params(0)

Data access object (DAO) in Java

Data Access Object Pattern or DAO pattern is used to separate low level data accessing API or operations from high level business services. Following are the participants in Data Access Object Pattern.

Data Access Object Interface - This interface defines the standard operations to be performed on a model object(s).

Data Access Object concrete class -This class implements above interface. This class is responsible to get data from a datasource which can be database / xml or any other storage mechanism.

Model Object or Value Object - This object is simple POJO containing get/set methods to store data retrieved using DAO class.

Sample code here..

Relative path in HTML

You say your website is in http://localhost/mywebsite, and let's say that your image is inside a subfolder named pictures/:

Absolute path

If you use an absolute path, / would point to the root of the site, not the root of the document: localhost in your case. That's why you need to specify your document's folder in order to access the pictures folder:

"/mywebsite/pictures/picture.png"

And it would be the same as:

"http://localhost/mywebsite/pictures/picture.png"

Relative path

A relative path is always relative to the root of the document, so if your html is at the same level of the directory, you'd need to start the path directly with your picture's directory name:

"pictures/picture.png"

But there are other perks with relative paths:

dot-slash (./)

Dot (.) points to the same directory and the slash (/) gives access to it:

So this:

"pictures/picture.png"

Would be the same as this:

"./pictures/picture.png"

Double-dot-slash (../)

In this case, a double dot (..) points to the upper directory and likewise, the slash (/) gives you access to it. So if you wanted to access a picture that is on a directory one level above of the current directory your document is, your URL would look like this:

"../picture.png"

You can play around with them as much as you want, a little example would be this:

Let's say you're on directory A, and you want to access directory X.

- root
   |- a
      |- A
   |- b
   |- x
      |- X

Your URL would look either:

Absolute path

"/x/X/picture.png"

Or:

Relative path

"./../x/X/picture.png"

The program can't start because libgcc_s_dw2-1.dll is missing

Add "-static" to other linker options solves this problem. I was just having the same issue after I tested this on another system, but not on my own, so even if you haven't noticed this on your development system, you should check that you have this set if you're statically linking.

Another note, copying the DLL into the same folder as the executable is not a solution as it defeats the idea of statically linking.

Another option is to use the TDM version of MinGW which solves this problem.

Update edit: this may not solve the problem for everyone. Another reason I recently discovered for this is when you use a library compiled by someone else, in my case it was SFML which was improperly compiled and so required a DLL that did not exist as it was compiled with a different version of MinGW than what I use. I use a dwarf build, this used another one, so I didn't have the DLL anywhere and of course, I didn't want it as it was a static build. The solution may be to find another build of the library, or build it yourself.

Android WebView, how to handle redirects in app instead of opening a browser

You will have to set your custom WebviewClient overriding shouldOverrideUrlLoading method for your webview before loading the url.

mWebView.setWebViewClient(new WebViewClient()
        {
            @SuppressWarnings("deprecation")
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String url)
            {
                return shouldOverrideUrlLoading(url);
            }

            @TargetApi(Build.VERSION_CODES.N)
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest request)
            {
                Uri uri = request.getUrl();
                return shouldOverrideUrlLoading(uri.toString());
            }

            private boolean shouldOverrideUrlLoading(final String url)
            {
                Log.i(TAG, "shouldOverrideUrlLoading() URL : " + url);

                // Here put your code

                return true; // Returning True means that application wants to leave the current WebView and handle the url itself, otherwise return false.
            }
        });

Checkout the example code for handling redirect urls and open PDF without download, in webview. https://gist.github.com/ashishdas09/014a408f9f37504eb2608d98abf49500

any tool for java object to object mapping?

I'm happy to add Moo as an option, although clearly I'm biased towards it: http://geoffreywiseman.github.com/Moo/

It's very easy to use for simple cases, reasonable capable for more complex cases, although there are still some areas where I can imagine enhancing it for even further complexities.

How to sum a variable by group

library(plyr)
ddply(tbl, .(Category), summarise, sum = sum(Frequency))

Match everything except for specified strings

I had the same question, the solutions proposed were almost working but they had some issue. In the end the regex I used is:

^(?!red|green|blue).*

I tested it in Javascript and .NET.

.* should't be placed inside the negative lookahead like this: ^(?!.*red|green|blue) or it would make the first element behave different from the rest (i.e. "anotherred" wouldn't be matched while "anothergreen" would)

Filter element based on .data() key/value

Two things I noticed (they may be mistakes from when you wrote it down though).

  1. You missed a dot in the first example ( $('.navlink').click )
  2. For filter to work, you have to return a value ( return $(this).data("selected")==true )

Sql Query to list all views in an SQL Server 2005 database

Some time you need to access with schema name,as an example you are using AdventureWorks Database you need to access with schemas.

 SELECT s.name +'.'+v.name FROM sys.views v inner join sys.schemas s on s.schema_id = v.schema_id 

CSS to make HTML page footer stay at bottom of the page with a minimum height, but not overlap the page

A very simple approach which works great cross browser is this:

http://matthewjamestaylor.com/blog/keeping-footers-at-the-bottom-of-the-page

_x000D_
_x000D_
html,_x000D_
body {_x000D_
   margin:0;_x000D_
   padding:0;_x000D_
   height:100%;_x000D_
}_x000D_
#container {_x000D_
   min-height:100%;_x000D_
   position:relative;_x000D_
}_x000D_
#header {_x000D_
   background:#ff0;_x000D_
   padding:10px;_x000D_
}_x000D_
#body {_x000D_
   padding:10px;_x000D_
   padding-bottom:60px;   /* Height of the footer */_x000D_
}_x000D_
#footer {_x000D_
   position:absolute;_x000D_
   bottom:0;_x000D_
   width:100%;_x000D_
   height:60px;   /* Height of the footer */_x000D_
   background:#6cf;_x000D_
}
_x000D_
<div id="container">_x000D_
   <div id="header">header</div>_x000D_
   <div id="body">body</div>_x000D_
   <div id="footer">footer</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

oracle sql: update if exists else insert

You could use the SQL%ROWCOUNT Oracle variable:

UPDATE table1
  SET field2 = value2, 
      field3 = value3 
WHERE field1 = value1; 

IF (SQL%ROWCOUNT = 0) THEN 

  INSERT INTO table (field1, field2, field3)
  VALUES (value1, value2, value3);

END IF; 

It would be easier just to determine if your primary key (i.e. field1) has a value and then perform an insert or update accordingly. That is, if you use said values as parameters for a stored procedure.

Eclipse can't find / load main class

Standard troubleshooting steps for Eclipse should include deleting and re-importing the project at some point, which when I have dealt with this error has worked.

Converting binary to decimal integer output

Try this solution:

def binary_int_to_decimal(binary):
    n = 0
    for d in binary:
        n = n * 2 + d

    return n

PHP to search within txt file and echo the whole line

looks like you're better off systeming out to system("grep \"$QUERY\"") since that script won't be particularly high performance either way. Otherwise http://php.net/manual/en/function.file.php shows you how to loop over lines and you can use http://php.net/manual/en/function.strstr.php for finding matches.

Could not load file or assembly '' or one of its dependencies

Another possible cause: make sure you haven't accidentally given both of the projects the same assembly name in project properties.

Create a Date with a set timezone without using a string representation

This is BEST solution

Using:

// TO ALL dates
Date.timezoneOffset(-240) // +4 UTC

// Override offset only for THIS date
new Date().timezoneOffset(-180) // +3 UTC

Code:

Date.prototype.timezoneOffset = new Date().getTimezoneOffset();

Date.setTimezoneOffset = function(timezoneOffset) {
  return this.prototype.timezoneOffset = timezoneOffset;
};

Date.getTimezoneOffset = function() {
  return this.prototype.timezoneOffset;
};

Date.prototype.setTimezoneOffset = function(timezoneOffset) {
  return this.timezoneOffset = timezoneOffset;
};

Date.prototype.getTimezoneOffset = function() {
  return this.timezoneOffset;
};

Date.prototype.toString = function() {
  var offsetDate, offsetTime;
  offsetTime = this.timezoneOffset * 60 * 1000;
  offsetDate = new Date(this.getTime() - offsetTime);
  return offsetDate.toUTCString();
};

['Milliseconds', 'Seconds', 'Minutes', 'Hours', 'Date', 'Month', 'FullYear', 'Year', 'Day'].forEach((function(_this) {
  return function(key) {
    Date.prototype["get" + key] = function() {
      var offsetDate, offsetTime;
      offsetTime = this.timezoneOffset * 60 * 1000;
      offsetDate = new Date(this.getTime() - offsetTime);
      return offsetDate["getUTC" + key]();
    };
    return Date.prototype["set" + key] = function(value) {
      var offsetDate, offsetTime, time;
      offsetTime = this.timezoneOffset * 60 * 1000;
      offsetDate = new Date(this.getTime() - offsetTime);
      offsetDate["setUTC" + key](value);
      time = offsetDate.getTime() + offsetTime;
      this.setTime(time);
      return time;
    };
  };
})(this));

Coffee version:

Date.prototype.timezoneOffset = new Date().getTimezoneOffset()


Date.setTimezoneOffset = (timezoneOffset)->
    return @prototype.timezoneOffset = timezoneOffset


Date.getTimezoneOffset = ->
    return @prototype.timezoneOffset


Date.prototype.setTimezoneOffset = (timezoneOffset)->
    return @timezoneOffset = timezoneOffset


Date.prototype.getTimezoneOffset = ->
    return @timezoneOffset


Date.prototype.toString = ->
    offsetTime = @timezoneOffset * 60 * 1000
    offsetDate = new Date(@getTime() - offsetTime)
    return offsetDate.toUTCString()


[
    'Milliseconds', 'Seconds', 'Minutes', 'Hours',
    'Date', 'Month', 'FullYear', 'Year', 'Day'
]
.forEach (key)=>
    Date.prototype["get#{key}"] = ->
        offsetTime = @timezoneOffset * 60 * 1000
        offsetDate = new Date(@getTime() - offsetTime)
        return offsetDate["getUTC#{key}"]()

    Date.prototype["set#{key}"] = (value)->
        offsetTime = @timezoneOffset * 60 * 1000
        offsetDate = new Date(@getTime() - offsetTime)
        offsetDate["setUTC#{key}"](value)
        time = offsetDate.getTime() + offsetTime
        @setTime(time)
        return time

How do I change the number of open files limit in Linux?

You could always try doing a ulimit -n 2048. This will only reset the limit for your current shell and the number you specify must not exceed the hard limit

Each operating system has a different hard limit setup in a configuration file. For instance, the hard open file limit on Solaris can be set on boot from /etc/system.

set rlim_fd_max = 166384
set rlim_fd_cur = 8192

On OS X, this same data must be set in /etc/sysctl.conf.

kern.maxfilesperproc=166384
kern.maxfiles=8192

Under Linux, these settings are often in /etc/security/limits.conf.

There are two kinds of limits:

  • soft limits are simply the currently enforced limits
  • hard limits mark the maximum value which cannot be exceeded by setting a soft limit

Soft limits could be set by any user while hard limits are changeable only by root. Limits are a property of a process. They are inherited when a child process is created so system-wide limits should be set during the system initialization in init scripts and user limits should be set during user login for example by using pam_limits.

There are often defaults set when the machine boots. So, even though you may reset your ulimit in an individual shell, you may find that it resets back to the previous value on reboot. You may want to grep your boot scripts for the existence ulimit commands if you want to change the default.

How to disable an input box using angular.js

Your markup should contain an additional attribute called ng-disabled whose value should be a condition or expression that would evaluate to be either true or false.

    <input data-ng-model="userInf.username"  class="span12 editEmail" 
       type="text"  placeholder="[email protected]"  
       pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}" 
       required 
       ng-disabled="{condition or expression}"
/>

And in the controller you may have some code that would affect the value of ng-disabled directive.

pip installing in global site-packages instead of virtualenv

I hit into the same issue while installing a python package from within a virtualenv. The root cause in my case was different. From within the virtualenv, I was (out of habit on Ubuntu), doing:

sudo easy_install -Z <package>

This caused the bin/pip shebang to be ignored and it used the root's non virtualenv python to install it in the global site-packages. Since we have a virtual environment, we should install the package without "sudo"

SQL Server query to find all permissions/access for all users in a database

CREATE PROCEDURE Get_permission 
AS 
    DECLARE @db_name  VARCHAR(200), 
            @sql_text VARCHAR(max) 

    SET @sql_text='Create table ##db_name (user_name varchar(max),' 

    DECLARE db_cursor CURSOR FOR 
      SELECT name 
      FROM   sys.databases 

    OPEN db_cursor 

    FETCH next FROM db_cursor INTO @db_name 

    WHILE @@FETCH_STATUS = 0 
      BEGIN 
          SET @sql_text=@sql_text + @db_name + ' varchar(max),' 

          FETCH next FROM db_cursor INTO @db_name 
      END 

    CLOSE db_cursor 

    SET @sql_text=@sql_text + 'Server_perm varchar(max))' 

    EXEC (@sql_text) 

    DEALLOCATE db_cursor 

    DECLARE @RoleName VARCHAR(50) 
    DECLARE @UserName VARCHAR(50) 
    DECLARE @CMD VARCHAR(1000) 

    CREATE TABLE #permission 
      ( 
         user_name    VARCHAR(50), 
         databasename VARCHAR(50), 
         role         VARCHAR(50) 
      ) 

    DECLARE longspcur CURSOR FOR 
      SELECT name 
      FROM   sys.server_principals 
      WHERE  type IN ( 'S', 'U', 'G' ) 
             AND principal_id > 4 
             AND name NOT LIKE '##%' 
             AND name <> 'NT AUTHORITY\SYSTEM' 
             AND name <> 'ONDEMAND\Administrator' 
             AND name NOT LIKE 'steel%' 

    OPEN longspcur 

    FETCH next FROM longspcur INTO @UserName 

    WHILE @@FETCH_STATUS = 0 
      BEGIN 
          CREATE TABLE #userroles_kk 
            ( 
               databasename VARCHAR(50), 
               role         VARCHAR(50) 
            ) 

          CREATE TABLE #rolemember_kk 
            ( 
               dbrole     VARCHAR(100), 
               membername VARCHAR(100), 
               membersid  VARBINARY(2048) 
            ) 

          SET @CMD = 'use ? truncate table #RoleMember_kk insert into #RoleMember_kk exec sp_helprolemember  insert into #UserRoles_kk (DatabaseName, Role) select db_name(), dbRole from #RoleMember_kk where MemberName = ''' + @UserName + '''' 

          EXEC Sp_msforeachdb 
            @CMD 

          INSERT INTO #permission 
          SELECT @UserName 'user', 
                 b.name, 
                 u.role 
          FROM   sys.sysdatabases b 
                 LEFT OUTER JOIN #userroles_kk u 
                              ON u.databasename = b.name --and u.Role='db_owner' 
          ORDER  BY 1 

          DROP TABLE #userroles_kk; 

          DROP TABLE #rolemember_kk; 

          FETCH next FROM longspcur INTO @UserName 
      END 

    CLOSE longspcur 

    DEALLOCATE longspcur 

    TRUNCATE TABLE ##db_name 

    DECLARE @d1 VARCHAR(max), 
            @d2 VARCHAR(max), 
            @d3 VARCHAR(max), 
            @ss VARCHAR(max) 
    DECLARE perm_cur CURSOR FOR 
      SELECT * 
      FROM   #permission 
      ORDER  BY 2 DESC 

    OPEN perm_cur 

    FETCH next FROM perm_cur INTO @d1, @d2, @d3 

    WHILE @@FETCH_STATUS = 0 
      BEGIN 
          IF NOT EXISTS(SELECT 1 
                        FROM   ##db_name 
                        WHERE  user_name = @d1) 
            BEGIN 
                SET @ss='insert into ##db_name(user_name) values (''' 
                        + @d1 + ''')' 

                EXEC (@ss) 

                SET @ss='update ##db_name set ' + @d2 + '=''' + @d3 
                        + ''' where user_name=''' + @d1 + '''' 

                EXEC (@ss) 
            END 
          ELSE 
            BEGIN 
                DECLARE @var            NVARCHAR(max), 
                        @ParmDefinition NVARCHAR(max), 
                        @var1           NVARCHAR(max) 

                SET @var = N'select @var1=' + @d2 
                           + ' from ##db_name where USER_NAME=''' + @d1 
                           + ''''; 
                SET @ParmDefinition = N'@var1 nvarchar(300) OUTPUT'; 

                EXECUTE Sp_executesql 
                  @var, 
                  @ParmDefinition, 
                  @var1=@var1 output; 

                SET @var1=Isnull(@var1, ' ') 
                SET @var= '  update ##db_name set ' + @d2 + '=''' + @var1 + ' ' 
                          + @d3 + ''' where user_name=''' + @d1 + '''  ' 

                EXEC (@var) 
            END 

          FETCH next FROM perm_cur INTO @d1, @d2, @d3 
      END 

    CLOSE perm_cur 

    DEALLOCATE perm_cur 

    SELECT * 
    FROM   ##db_name 

    DROP TABLE ##db_name 

    DROP TABLE #permission 

Sorting an array in C?

In your particular case the fastest sort is probably the one described in this answer. It is exactly optimized for an array of 6 ints and uses sorting networks. It is 20 times (measured on x86) faster than library qsort. Sorting networks are optimal for sort of fixed length arrays. As they are a fixed sequence of instructions they can even be implemented easily by hardware.

Generally speaking there is many sorting algorithms optimized for some specialized case. The general purpose algorithms like heap sort or quick sort are optimized for in place sorting of an array of items. They yield a complexity of O(n.log(n)), n being the number of items to sort.

The library function qsort() is very well coded and efficient in terms of complexity, but uses a call to some comparizon function provided by user, and this call has a quite high cost.

For sorting very large amount of datas algorithms have also to take care of swapping of data to and from disk, this is the kind of sorts implemented in databases and your best bet if you have such needs is to put datas in some database and use the built in sort.

Align items in a stack panel?

Could not get this working using a DockPanel quite the way I wanted and reversing the flow direction of a StackPanel is troublesome. Using a grid is not an option as items inside of it may be hidden at runtime and thus I do not know the total number of columns at design time. The best and simplest solution I could come up with is:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
    <StackPanel Grid.Column="1" Orientation="Horizontal">
        <!-- Right aligned controls go here -->
    </StackPanel>
</Grid>

This will result in controls inside of the StackPanel being aligned to the right side of the available space regardless of the number of controls - both at design and runtime. Yay! :)

Why does configure say no C compiler found when GCC is installed?

I had the same issue with mind. I tried using sudo apt-get install build-essential It still won't work. I simply created a hardlink to the gcc-x binary in the /usr/bin/ folder. sudo ls /usr/bin/gcc-x /usr/bin/gcc

That worked for me!

How to extract .war files in java? ZIP vs JAR

Jar class/package is for specific Jar file mechanisms where there is a manifest that is used by the Jar files in some cases.

The Zip file class/package handles any compressed files that include Jar files, which is a type of compressed file.

The Jar classes thus extend the Zip package classes.

How to get full width in body element

You can use CSS to do it for example

<style>
html{
    width:100%;
    height:100%;
}
body{
    width:100%;
    height:100%;
    background-color:#DDD;
}
</style>

How to stop a function

I'm just going to do this

def function():
  while True:
    #code here

    break

Use "break" to stop the function.

What are the ascii values of up down left right?

this is what i get:

Left - 19 Up - 5 Right - 4 Down - 24

Works in Visual Fox Pro

How do you import classes in JSP?

In the page tag:

<%@ page import="java.util.List" %>

Disabling buttons on react native

Use disabled true property

<TouchableOpacity disabled={true}> </TouchableOpacity>

How to add images in select list?

UPDATE: As of 2018, this seems to work now. Tested in Chrome, Firefox, IE and Edge

UPDATE: Yes I changed the background-color, not the image, stop voting me down, showing that you can change style here is still a useful contribution.

<!DOCTYPE html>
<html>
<body>

<style>
select#newlocale option[value="volvo"]   { background-color: powderblue;   }
select#newlocale option[value="opel"]   { background-color: red;   }
select#newlocale option[value="audi"]   { background-color: green;   }
</style> 

<select id="newlocale">
  <option value="volvo"><div >Volvo</div></option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>
  
</body>
</html>

Vuex - Computed property "name" was assigned to but it has no setter

It should be like this.

In your Component

computed: {
        ...mapGetters({
                nameFromStore: 'name'
            }),
        name: {
           get(){
             return this.nameFromStore
           },
           set(newName){
             return newName
           } 
        }
    }

In your store

export const store = new Vuex.Store({
         state:{
             name : "Stackoverflow"
         },
         getters: {
                 name: (state) => {
                     return state.name;
                 }
         }
}

What does "opt" mean (as in the "opt" directory)? Is it an abbreviation?

It's usually describes as for optional add-on software packagessource, or anything that isn't part of the base system. Only some distributions use it, others simply use /usr/local.

C++ Cout & Cin & System "Ambiguous"

This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.

Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.

In this case I'd ask why you're including both cstdlib and stdlib.h; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib puts them in the namespace std in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!

Anyway, your use of using namespace std (which I would recommend against, in future) means that std::system from cstdlib now conflicts with system from stdlib.h. I can't explain what's going on with std::cout and std::cin.

Try removing #include <stdlib.h> and see what happens.

If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.

C# IPAddress from string

You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.

Have you tried using System.Net.IPAddress just in case?

System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("127.0.0.1");  //127.0.0.1 as an example

The docs on Microsoft's site have a complete example which works fine on my machine.

How to make PopUp window in java

Check out Swing Dialogs (mainly focused on JOptionPane, as mentioned by @mcfinnigan).

Update TextView Every Second

You can also use TimerTask for that.

Here is an method

private void setTimerTask() {
    long delay = 3000;
    long periodToRepeat = 60 * 1000; /* 1 mint */
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                 //   do your stuff here.
                }
            });
        }
    }, 3000, 3000);
}

ini_set("memory_limit") in PHP 5.3.3 is not working at all

Let's do a test with 2 examples:

    <?php    
    $memory = (int)ini_get("memory_limit"); // Display your current value in php.ini (for example: 64M)
    echo "original memory: ".$memory."<br>";
    ini_set('memory_limit','128M'); // Try to override the memory limit for this script
    echo "new memory:".$memory;
    }
    // Will display:
    // original memory: 64
    // new memory: 64
    ?>

The above example doesn't work for overriding the memory_limit value. But This will work:

    <?php
    $memory = (int)ini_get("memory_limit"); // get the current value
    ini_set('memory_limit','128'); // override the value
    echo "original memory: ".$memory."<br>"; // echo the original value
    $new_memory = (int)ini_get("memory_limit"); // get the new value
    echo "new memory: ".$new_memory;  // echo the new value
    // Will display:
    // original memory: 64
    // new memory: 128
    ?>

You have to place the ini_set('memory_limit','128M'); at the top of the file or at least before any echo.

As for me, suhosin wasn't the solution because it doesn't even appear in my phpinfo(), but this worked:

    <?php
    ini_set('memory_limit','2048M'); // set at the top of the file
    (...)
    ?>

Regular expression to match exact number of characters?

What you have is correct, but this is more consice:

^[A-Z]{3}$

What is the default initialization of an array in Java?

Everything in a Java program not explicitly set to something by the programmer, is initialized to a zero value.

  • For references (anything that holds an object) that is null.
  • For int/short/byte/long that is a 0.
  • For float/double that is a 0.0
  • For booleans that is a false.
  • For char that is the null character '\u0000' (whose decimal equivalent is 0).

When you create an array of something, all entries are also zeroed. So your array contains five zeros right after it is created by new.

Note (based on comments): The Java Virtual Machine is not required to zero out the underlying memory when allocating local variables (this allows efficient stack operations if needed) so to avoid random values the Java Language Specification requires local variables to be initialized.

How to kill a process in MacOS?

Some cases you might want to kill all the process running in a specific port. For example, if I am running a node app on 3000 port and I want to kill that and start a new one; then I found this command useful.

Find the process IDs running on TCP port 3000 and kill it

kill -9 `lsof -i TCP:3000 | awk '/LISTEN/{print $2}'`

How to set root password to null

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('');

Can I use a case/switch statement with two variables?

I don't believe a switch/case is any faster than a series of if/elseif's. They do the same thing, but if/elseif's you can check multiple variables. You cannot use a switch/case on more than one value.

How to use RANK() in SQL Server

SELECT contendernum,totals, RANK() OVER (ORDER BY totals ASC) AS xRank FROM
(
SELECT ContenderNum ,SUM(Criteria1+Criteria2+Criteria3+Criteria4) AS totals
FROM dbo.Cat1GroupImpersonation
 GROUP BY ContenderNum
) AS a

Trying to detect browser close event

Try following code works for me under Linux chrome environment. Before running make sure jquery is attached to the document.

$(document).ready(function()
{
    $(window).bind("beforeunload", function() { 
        return confirm("Do you really want to close?"); 
    });
});

For simple follow following steps:

  1. open http://jsfiddle.net/
  2. enter something into html, css or javascript box
  3. try to close tab in chrome

It should show following picture:

enter image description here

Select distinct using linq

myList.GroupBy(test => test.id)
      .Select(grp => grp.First());

Edit: as getting this IEnumerable<> into a List<> seems to be a mystery to many people, you can simply write:

var result = myList.GroupBy(test => test.id)
                   .Select(grp => grp.First())
                   .ToList();

But one is often better off working with the IEnumerable rather than IList as the Linq above is lazily evaluated: it doesn't actually do all of the work until the enumerable is iterated. When you call ToList it actually walks the entire enumerable forcing all of the work to be done up front. (And may take a little while if your enumerable is infinitely long.)

The flipside to this advice is that each time you enumerate such an IEnumerable the work to evaluate it has to be done afresh. So you need to decide for each case whether it is better to work with the lazily evaluated IEnumerable or to realize it into a List, Set, Dictionary or whatnot.

What is an index in SQL?

A clustered index is like the contents of a phone book. You can open the book at 'Hilditch, David' and find all the information for all of the 'Hilditch's right next to each other. Here the keys for the clustered index are (lastname, firstname).

This makes clustered indexes great for retrieving lots of data based on range based queries since all the data is located next to each other.

Since the clustered index is actually related to how the data is stored, there is only one of them possible per table (although you can cheat to simulate multiple clustered indexes).

A non-clustered index is different in that you can have many of them and they then point at the data in the clustered index. You could have e.g. a non-clustered index at the back of a phone book which is keyed on (town, address)

Imagine if you had to search through the phone book for all the people who live in 'London' - with only the clustered index you would have to search every single item in the phone book since the key on the clustered index is on (lastname, firstname) and as a result the people living in London are scattered randomly throughout the index.

If you have a non-clustered index on (town) then these queries can be performed much more quickly.

Hope that helps!

How to convert comma separated string into numeric array in javascript

The split() method is used to split a string into an array of substrings, and returns the new array.

Syntax:
  string.split(separator,limit)


arr =  strVale.split(',');

SEE HERE

Targeting only Firefox with CSS

A variation on your idea is to have a server-side USER-AGENT detector that will figure out what style sheet to attach to the page. This way you can have a firefox.css, ie.css, opera.css, etc.

You can accomplish a similar thing in Javascript itself, although you may not regard it as clean.

I have done a similar thing by having a default.css which includes all common styles and then specific style sheets are added to override, or enhance the defaults.

Python object.__repr__(self) should be an expression?

Guideline: If you can succinctly provide an exact representation, format it as a Python expression (which implies that it can be both eval'd and copied directly into source code, in the right context). If providing an inexact representation, use <...> format.

There are many possible representations for any value, but the one that's most interesting for Python programmers is an expression that recreates the value. Remember that those who understand Python are the target audience—and that's also why inexact representations should include relevant context. Even the default <XXX object at 0xNNN>, while almost entirely useless, still provides type, id() (to distinguish different objects), and indication that no better representation is available.

What is an idiomatic way of representing enums in Go?

As of Go 1.4, the go generate tool has been introduced together with the stringer command that makes your enum easily debuggable and printable.

What is the correct way to declare a boolean variable in Java?

There is no reason to do that. In fact, I would choose to combine declaration and initialization as in

final Boolean isMatch = email1.equals (email2);

using the final keyword so you can't change it (accidentally) afterwards anymore either.

How to convert XML to JSON in Python?

In general, you want to go from XML to regular objects of your language (since there are usually reasonable tools to do this, and it's the harder conversion). And then from Plain Old Object produce JSON -- there are tools for this, too, and it's a quite simple serialization (since JSON is "Object Notation", natural fit for serializing objects). I assume Python has its set of tools.

How to set locale in DatePipe in Angular 2?

Solution with LOCALE_ID is great if you want to set the language for your app once. But it doesn’t work, if you want to change the language during runtime. For this case you can implement custom date pipe.

import { DatePipe } from '@angular/common';
import { Pipe, PipeTransform } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Pipe({
  name: 'localizedDate',
  pure: false
})
export class LocalizedDatePipe implements PipeTransform {

  constructor(private translateService: TranslateService) {
  }

  transform(value: any, pattern: string = 'mediumDate'): any {
    const datePipe: DatePipe = new DatePipe(this.translateService.currentLang);
    return datePipe.transform(value, pattern);
  }

}

Now if you change the app display language using TranslateService (see ngx-translate)

this.translateService.use('en');

the formats within your app should automatically being updated.

Example of use:

<p>{{ 'note.created-at' | translate:{date: note.createdAt | localizedDate} }}</p>
<p>{{ 'note.updated-at' | translate:{date: note.updatedAt | localizedDate:'fullDate'} }}</p>

or check my simple "Notes" project here.

enter image description here

Simple UDP example to send and receive data from same socket

(I presume you are aware that using UDP(User Datagram Protocol) does not guarantee delivery, checks for duplicates and congestion control and will just answer your question).

In your server this line:

var data = udpServer.Receive(ref groupEP);

re-assigns groupEP from what you had to a the address you receive something on.

This line:

udpServer.Send(new byte[] { 1 }, 1); 

Will not work since you have not specified who to send the data to. (It works on your client because you called connect which means send will always be sent to the end point you connected to, of course we don't want that on the server as we could have many clients). I would:

UdpClient udpServer = new UdpClient(UDP_LISTEN_PORT);

while (true)
{
    var remoteEP = new IPEndPoint(IPAddress.Any, 11000);
    var data = udpServer.Receive(ref remoteEP);
    udpServer.Send(new byte[] { 1 }, 1, remoteEP); // if data is received reply letting the client know that we got his data          
}

Also if you have server and client on the same machine you should have them on different ports.

How do I capture the output into a variable from an external process in PowerShell?

I tried the answers, but in my case I did not get the raw output. Instead it was converted to a PowerShell exception.

The raw result I got with:

$rawOutput = (cmd /c <command> 2`>`&1)

How to scroll UITableView to specific position

Swift 4.2 version:

let indexPath:IndexPath = IndexPath(row: 0, section: 0)
self.tableView.scrollToRow(at: indexPath, at: .none, animated: true)

Enum: These are the available tableView scroll positions - here for reference. You don't need to include this section in your code.

public enum UITableViewScrollPosition : Int {

case None
case Top
case Middle
case Bottom
}

DidSelectRow:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    let theCell:UITableViewCell? = tableView.cellForRowAtIndexPath(indexPath)

    if let theCell = theCell {
        var tableViewCenter:CGPoint = tableView.contentOffset
        tableViewCenter.y += tableView.frame.size.height/2

        tableView.contentOffset = CGPointMake(0, theCell.center.y-65)
        tableView.reloadData()
    }

}

SQLPLUS error:ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA

You're missing service name:

 SQL> connect username/password@hostname:port/SERVICENAME

EDIT

If you can connect to the database from other computer try running there:

select sys_context('USERENV','SERVICE_NAME') from dual

and

select sys_context('USERENV','SID') from dual

Get list of all tables in Oracle?

Simple query to select the tables for the current user:

  SELECT table_name FROM user_tables;

How to get function parameter names/values dynamically?

This package uses recast in order to create an AST and then the parameter names are gathered from their, this allows it to support pattern matching, default arguments, arrow functions and other ES6 features.

https://www.npmjs.com/package/es-arguments

Checking if a SQL Server login already exists

First you have to check login existence using syslogins view:

IF NOT EXISTS 
    (SELECT name  
     FROM master.sys.server_principals
     WHERE name = 'YourLoginName')
BEGIN
    CREATE LOGIN [YourLoginName] WITH PASSWORD = N'password'
END

Then you have to check your database existence:

USE your_dbname

IF NOT EXISTS
    (SELECT name
     FROM sys.database_principals
     WHERE name = 'your_dbname')
BEGIN
    CREATE USER [your_dbname] FOR LOGIN [YourLoginName] 
END

How can I stream webcam video with C#?

The usual API for this is DirectShow.

You can use P/Invoke to import the C++ APIs, but I think there are already a few projects out there that have done this.

http://channel9.msdn.com/forums/TechOff/93476-Programatically-Using-A-Webcam-In-C/

http://www.codeproject.com/KB/directx/DirXVidStrm.aspx

To get the streaming part, you probably want to use DirectShow to apply a compression codec to reduce lag, then you can get a Stream and transmit it. You could consider using multicast to reduce network load.

C++ equivalent of StringBuffer/StringBuilder?

Since std::string in C++ is mutable you can use that. It has a += operator and an append function.

If you need to append numerical data use the std::to_string functions.

If you want even more flexibility in the form of being able to serialise any object to a string then use the std::stringstream class. But you'll need to implement your own streaming operator functions for it to work with your own custom classes.

How to Git stash pop specific stash in 1.8.3?

As Robert pointed out, quotation marks might do the trick for you:

git stash pop stash@"{1}"

How to load GIF image in Swift?

Load GIF image Swift :

## Reference.

#1 : Copy the swift file from This Link :

#2 : Load GIF image Using Name

    let jeremyGif = UIImage.gifImageWithName("funny")
    let imageView = UIImageView(image: jeremyGif)
    imageView.frame = CGRect(x: 20.0, y: 50.0, width: self.view.frame.size.width - 40, height: 150.0)
    view.addSubview(imageView)

#3 : Load GIF image Using Data

    let imageData = try? Data(contentsOf: Bundle.main.url(forResource: "play", withExtension: "gif")!)
    let advTimeGif = UIImage.gifImageWithData(imageData!)
    let imageView2 = UIImageView(image: advTimeGif)
    imageView2.frame = CGRect(x: 20.0, y: 220.0, width: 
    self.view.frame.size.width - 40, height: 150.0)
    view.addSubview(imageView2)

#4 : Load GIF image Using URL

    let gifURL : String = "http://www.gifbin.com/bin/4802swswsw04.gif"
    let imageURL = UIImage.gifImageWithURL(gifURL)
    let imageView3 = UIImageView(image: imageURL)
    imageView3.frame = CGRect(x: 20.0, y: 390.0, width: self.view.frame.size.width - 40, height: 150.0)
    view.addSubview(imageView3)

Download Demo Code

OUTPUT :

iPhone 8 / iOS 11 / xCode 9

enter image description here

Table Naming Dilemma: Singular vs. Plural Names

I am a fan of singular table names as they make my ER diagrams using CASE syntax easier to read, but by reading these responses I'm getting the feeling it never caught on very well? I personally love it. There is a good overview with examples of how readable your models can be when you use singular table names, add action verbs to your relationships and form good sentences for every relationships. It's all a bit of overkill for a 20 table database but if you have a DB with hundreds of tables and a complex design how will your developers ever understand it without a good readable diagram?

http://www.aisintl.com/case/method.html

As for prefixing tables and views I absolutely hate that practice. Give a person no information at all before giving them possibly bad information. Anyone browsing a db for objects can quite easily tell a table from a view, but if I have a table named tblUsers that for some reason I decide to restructure in the future into two tables, with a view unifying them to keep from breaking old code I now have a view named tblUsers. At this point I am left with two unappealing options, leave a view named with a tbl prefix which may confuse some developers, or force another layer, either middle tier or application to be rewritten to reference my new structure or name viewUsers. That negates a large part of the value of views IMHO.

How to read and write xml files?

Ok, already having DOM, JaxB and XStream in the list of answers, there is still a complete different way to read and write XML: Data projection You can decouple the XML structure and the Java structure by using a library that provides read and writeable views to the XML Data as Java interfaces. From the tutorials:

Given some real world XML:

<weatherdata>
  <weather
    ... 
    degreetype="F"
    lat="50.5520210266113" lon="6.24060010910034" 
    searchlocation="Monschau, Stadt Aachen, NW, Germany" 
            ... >
    <current ... skytext="Clear" temperature="46"/>
  </weather>
</weatherdata>

With data projection you can define a projection interface:

public interface WeatherData {

@XBRead("/weatherdata/weather/@searchlocation")   
String getLocation();

@XBRead("/weatherdata/weather/current/@temperature")
int getTemperature();

@XBRead("/weatherdata/weather/@degreetype")
String getDegreeType();

@XBRead("/weatherdata/weather/current/@skytext")
String getSkytext();

/**
 * This would be our "sub projection". A structure grouping two attribute
 * values in one object.
 */
interface Coordinates {
    @XBRead("@lon")
    double getLongitude();

    @XBRead("@lat")
    double getLatitude();
}

@XBRead("/weatherdata/weather")
Coordinates getCoordinates();
}

And use instances of this interface just like POJOs:

private void printWeatherData(String location) throws IOException {

final String BaseURL = "http://weather.service.msn.com/find.aspx?outputview=search&weasearchstr=";

// We let the projector fetch the data for us
WeatherData weatherData = new XBProjector().io().url(BaseURL + location).read(WeatherData.class);

// Print some values
System.out.println("The weather in " + weatherData.getLocation() + ":");
System.out.println(weatherData.getSkytext());
System.out.println("Temperature: " + weatherData.getTemperature() + "°"
                                   + weatherData.getDegreeType());

// Access our sub projection
Coordinates coordinates = weatherData.getCoordinates();
System.out.println("The place is located at " + coordinates.getLatitude() + ","
                                              + coordinates.getLongitude());
}

This works even for creating XML, the XPath expressions can be writable.

A beginner's guide to SQL database design

I started with this book: Relational Database Design Clearly Explained (The Morgan Kaufmann Series in Data Management Systems) (Paperback) by Jan L. Harrington and found it very clear and helpful

and as you get up to speed this one was good too Database Systems: A Practical Approach to Design, Implementation and Management (International Computer Science Series) (Paperback)

I think SQL and database design are different (but complementary) skills.

MySQLi prepared statements error reporting

Not sure if this answers your question or not. Sorry if not

To get the error reported from the mysql database about your query you need to use your connection object as the focus.

so:

echo $mysqliDatabaseConnection->error

would echo the error being sent from mysql about your query.

Hope that helps

Get an array of list element contents in jQuery

Without redundant intermediate arrays:

arr = $('li').map(function(i,el) {
    return $(el).text();
}).get();

See jsfiddle demo

How to display a Yes/No dialog box on Android?

Steve H's answer is spot on, but here's a bit more information: the reason that dialogs work the way they do is because dialogs in Android are asynchronous (execution does not stop when the dialog is displayed). Because of this, you have to use a callback to handle the user's selection.

Check out this question for a longer discussion between the differences in Android and .NET (as it relates to dialogs): Dialogs / AlertDialogs: How to "block execution" while dialog is up (.NET-style)

Create a new object from type parameter in generic class

Not quite answering the question, but, there is a nice library for those kind of problems: https://github.com/typestack/class-transformer (although it won't work for generic types, as they don't really exists at run-time (here all work is done with class names (which are classes constructors)))

For instance:

import {Type, plainToClass, deserialize} from "class-transformer";

export class Foo
{
    @Type(Bar)
    public nestedClass: Bar;

    public someVar: string;

    public someMethod(): string
    {
        return this.nestedClass.someVar + this.someVar;
    }
}

export class Bar
{
    public someVar: string;
}

const json = '{"someVar": "a", "nestedClass": {"someVar": "B"}}';
const optionA = plainToClass(Foo, JSON.parse(json));
const optionB = deserialize(Foo, json);

optionA.someMethod(); // works
optionB.someMethod(); // works

Get total number of items on Json object?

In addition to kieran's answer, apparently, modern browsers have an Object.keys function. In this case, you could do this:

Object.keys(jsonArray).length;

More details in this answer on How to list the properties of a javascript object

1114 (HY000): The table is full

Unless you enabled innodb_file_per_table option, InnoDB keeps all data in one file, usually called ibdata1.

Check the size of that file and check you have enough disk space in the drive it resides on.

What does the restrict keyword mean in C++?

There's no such keyword in C++. List of C++ keywords can be found in section 2.11/1 of C++ language standard. restrict is a keyword in C99 version of C language and not in C++.

Can I make a phone call from HTML on Android?

I have just written an app which can make a call from a web page - I don't know if this is any use to you, but I include anyway:

in your onCreate you'll need to use a webview and assign a WebViewClient, as below:

browser = (WebView) findViewById(R.id.webkit);
browser.setWebViewClient(new InternalWebViewClient());

then handle the click on a phone number like this:

private class InternalWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
         if (url.indexOf("tel:") > -1) {
            startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
            return true;
        } else {
            return false;
        }
    }
}

Let me know if you need more pointers.

Run cron job only if it isn't already running

Docs: https://www.timkay.com/solo/

solo is a very simple script (10 lines) that prevents a program from running more than one copy at a time. It is useful with cron to make sure that a job doesn't run before a previous one has finished.

Example

* * * * * solo -port=3801 ./job.pl blah blah

How to use jQuery in AngularJS

The best option is create a directive and wrap the slider features there. The secret is use $timeout, the jquery code will be called only when DOM is ready.

angular.module('app')
.directive('my-slider', 
    ['$timeout', function($timeout) {
        return {
            restrict:'E',
            scope: true,
            template: '<div id="{{ id }}"></div>',
            link: function($scope) {
                $scope.id = String(Math.random()).substr(2, 8);

                $timeout(function() {
                    angular.element('#'+$scope.id).slider();                    
                });
            }
        };
    }]
);

jquery save json data object in cookie

With serialize the data as JSON and Base64, dependency jquery.cookie.js :

var putCookieObj = function(key, value) {
    $.cookie(key, btoa(JSON.stringify(value)));
}

var getCookieObj = function (key) {
    var cookie = $.cookie(key);
    if (typeof cookie === "undefined") return null;
    return JSON.parse(atob(cookie));
}

:)

How to check if a String contains another String in a case insensitive manner in Java?

We can use stream with anyMatch and contains of Java 8

public class Test2 {
    public static void main(String[] args) {

        String a = "Gina Gini Protijayi Soudipta";
        String b = "Gini";

        System.out.println(WordPresentOrNot(a, b));
    }// main

    private static boolean WordPresentOrNot(String a, String b) {
    //contains is case sensitive. That's why change it to upper or lower case. Then check
        // Here we are using stream with anyMatch
        boolean match = Arrays.stream(a.toLowerCase().split(" ")).anyMatch(b.toLowerCase()::contains);
        return match;
    }

}

Export database schema into SQL file

Have you tried the Generate Scripts (Right click, tasks, generate scripts) option in SQL Management Studio? Does that produce what you mean by a "SQL File"?

How to check if a file exists before creating a new file

Looked around a bit, and the only thing I find is using the open system call. It is the only function I found that allows you to create a file in a way that will fail if it already exists

#include <fcntl.h>
#include <errno.h>

int fd=open(filename, O_WRONLY | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
if (fd < 0) {
  /* file exists or otherwise uncreatable
     you might want to check errno*/
}else {
  /* File is open to writing */
}

Note that you have to give permissions since you are creating a file.

This also removes any race conditions there might be

How to check if a String contains any of some strings

public static bool ContainsAny(this string haystack, IEnumerable<string> needles)
{
    return needles.Any(haystack.Contains);
}

Run ssh and immediately execute command

You can use the LocalCommand command-line option if the PermitLocalCommand option is enabled:

ssh username@hostname -o LocalCommand="tmux list-sessions"

For more details about the available options, see the ssh_config man page.

How do I setup the InternetExplorerDriver so it works

    using System.Text;
    ...
    ..
    static void Main(String[] args){ 
    var driver =  new InternetExplorerDriver(@"C:\Users\PathToTheFolderContainingIEDriver.exe"); 
    driver.Navigate().GoToUrl("https://www.google.com/");
    Console.Read();
    }

You need not include the .exe file. The path to the folder containing the .exe worked for me

Best way to get value from Collection by index

In general, there is no good way, as Collections are not guaranteed to have fixed indices. Yes, you can iterate through them, which is how toArray (and other functions) work. But the iteration order isn't necessarily fixed, and if you're trying to index into a general Collection, you're probably doing something wrong. It would make more sense to index into a List.

How to expand and compute log(a + b)?

In general, one doesn't expand out log(a + b); you just deal with it as is. That said, there are occasionally circumstances where it makes sense to use the following identity:

log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a)

(In fact, this identity is often used when implementing log in math libraries).

How to set time to midnight for current day?

Most of the suggested solutions can cause a 1 day error depending on the time associated with each date. If you are looking for an integer number of calendar days between to dates, regardless of the time associated with each date, I have found that this works well:

return (dateOne.Value.Date - dateTwo.Value.Date).Days;

How to open a different activity on recyclerView item onclick

iconView = (ImageView) itemLayoutView .findViewById(R.id.iconId);

        itemLayoutView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(v.getContext(), SecondPage.class);
                v.getContext().startActivity(intent);
                Toast.makeText(v.getContext(), "os version is: " + feed.getTitle(), Toast.LENGTH_SHORT).show();
            }
        });

Print text in Oracle SQL Developer SQL Worksheet window

PROMPT text to print

Note: must use Run as Script (F5) not Run Statement (Ctl + Enter)

Android Paint: .measureText() vs .getTextBounds()

Sorry for answering again on that question... I needed to embed the image.

I think the results @mice found are missleading. The observations might be correct for the font size of 60 but they turn much more different when the text is smaller. Eg. 10px. In that case the text is actually drawn BEYOND the bounds.

enter image description here

Sourcecode of the screenshot:

  @Override
  protected void onDraw( Canvas canvas ) {
    for( int i = 0; i < 20; i++ ) {
      int startSize = 10;
      int curSize = i + startSize;
      paint.setTextSize( curSize );
      String text = i + startSize + " - " + TEXT_SNIPPET;
      Rect bounds = new Rect();
      paint.getTextBounds( text, 0, text.length(), bounds );
      float top = STEP_DISTANCE * i + curSize;
      bounds.top += top;
      bounds.bottom += top;
      canvas.drawRect( bounds, bgPaint );
      canvas.drawText( text, 0, STEP_DISTANCE * i + curSize, paint );
    }
  }

git push vs git push origin <branchname>

First, you need to create your branch locally

git checkout -b your_branch

After that, you can work locally in your branch, when you are ready to share the branch, push it. The next command push the branch to the remote repository origin and tracks it

git push -u origin your_branch

Your Teammates/colleagues can push to your branch by doing commits and then push explicitly

... work ...
git commit
... work ...
git commit
git push origin HEAD:refs/heads/your_branch 

How to get class object's name as a string in Javascript?

Shog9 is right that this doesn't make all that much sense to ask, since an object could be referred to by multiple variables. If you don't really care about that, and all you want is to find the name of one of the global variables that refers to that object, you could do the following hack:

function myClass() { 
  this.myName = function () { 
    // search through the global object for a name that resolves to this object
    for (var name in this.global) 
      if (this.global[name] == this) 
        return name 
  } 
}
// store the global object, which can be referred to as this at the top level, in a
// property on our prototype, so we can refer to it in our object's methods
myClass.prototype.global = this
// create a global variable referring to an object
var myVar = new myClass()
myVar.myName() // returns "myVar"

Note that this is an ugly hack, and should not be used in production code. If there is more than one variable referring to an object, you can't tell which one you'll get. It will only search the global variables, so it won't work if a variable is local to a function. In general, if you need to name something, you should pass the name in to the constructor when you create it.

edit: To respond to your clarification, if you need to be able to refer to something from an event handler, you shouldn't be referring to it by name, but instead add a function that refers to the object directly. Here's a quick example that I whipped up that shows something similar, I think, to what you're trying to do:

function myConstructor () {
  this.count = 0
  this.clickme = function () {
    this.count += 1
    alert(this.count)
  }

  var newDiv = document.createElement("div")
  var contents = document.createTextNode("Click me!")

  // This is the crucial part. We don't construct an onclick handler by creating a
  // string, but instead we pass in a function that does what we want. In order to
  // refer to the object, we can't use this directly (since that will refer to the 
  // div when running event handler), but we create an anonymous function with an 
  // argument and pass this in as that argument.
  newDiv.onclick = (function (obj) { 
    return function () {
      obj.clickme()
    }
  })(this)

  newDiv.appendChild(contents)
  document.getElementById("frobnozzle").appendChild(newDiv)

}
window.onload = function () {
  var myVar = new myConstructor()
}

A non-blocking read on a subprocess.PIPE in Python

One solution is to make another process to perform your read of the process, or make a thread of the process with a timeout.

Here's the threaded version of a timeout function:

http://code.activestate.com/recipes/473878/

However, do you need to read the stdout as it's coming in? Another solution may be to dump the output to a file and wait for the process to finish using p.wait().

f = open('myprogram_output.txt','w')
p = subprocess.Popen('myprogram.exe', stdout=f)
p.wait()
f.close()


str = open('myprogram_output.txt','r').read()

Get a random item from a JavaScript array

jQuery is JavaScript! It's just a JavaScript framework. So to find a random item, just use plain old JavaScript, for example,

var randomItem = items[Math.floor(Math.random()*items.length)]

How to add multiple columns to pandas dataframe in one assignment?

if adding a lot of missing columns (a, b, c ,....) with the same value, here 0, i did this:

    new_cols = ["a", "b", "c" ] 
    df[new_cols] = pd.DataFrame([[0] * len(new_cols)], index=df.index)

It's based on the second variant of the accepted answer.

Set scroll position

... Or just replace body by documentElement:

document.documentElement.scrollTop = 0;

How to cast or convert an unsigned int to int in C?

If you have a variable unsigned int x;, you can convert it to an int using (int)x.

Displaying unicode symbols in HTML

Unlike proposed by Nicolas, the meta tag isn’t actually ignored by the browsers. However, the Content-Type HTTP header always has precedence over the presence of a meta tag in the document.

So make sure that you either send the correct encoding via the HTTP header, or don’t send this HTTP header at all (not recommended). The meta tag is mainly a fallback option for local documents which aren’t sent via HTTP traffic.

Using HTML entities should also be considered a workaround – that’s tiptoeing around the real problem. Configuring the web server properly prevents a lot of nuisance.

How can I read and manipulate CSV file data in C++?

If what you're really doing is manipulating a CSV file itself, Nelson's answer makes sense. However, my suspicion is that the CSV is simply an artifact of the problem you're solving. In C++, that probably means you have something like this as your data model:

struct Customer {
    int id;
    std::string first_name;
    std::string last_name;
    struct {
        std::string street;
        std::string unit;
    } address;
    char state[2];
    int zip;
};

Thus, when you're working with a collection of data, it makes sense to have std::vector<Customer> or std::set<Customer>.

With that in mind, think of your CSV handling as two operations:

// if you wanted to go nuts, you could use a forward iterator concept for both of these
class CSVReader {
public:
    CSVReader(const std::string &inputFile);
    bool hasNextLine();
    void readNextLine(std::vector<std::string> &fields);
private:
    /* secrets */
};
class CSVWriter {
public:
    CSVWriter(const std::string &outputFile);
    void writeNextLine(const std::vector<std::string> &fields);
private:
    /* more secrets */
};
void readCustomers(CSVReader &reader, std::vector<Customer> &customers);
void writeCustomers(CSVWriter &writer, const std::vector<Customer> &customers);

Read and write a single row at a time, rather than keeping a complete in-memory representation of the file itself. There are a few obvious benefits:

  1. Your data is represented in a form that makes sense for your problem (customers), rather than the current solution (CSV files).
  2. You can trivially add adapters for other data formats, such as bulk SQL import/export, Excel/OO spreadsheet files, or even an HTML <table> rendering.
  3. Your memory footprint is likely to be smaller (depends on relative sizeof(Customer) vs. the number of bytes in a single row).
  4. CSVReader and CSVWriter can be reused as the basis for an in-memory model (such as Nelson's) without loss of performance or functionality. The converse is not true.

How to have PHP display errors? (I've added ini_set and error_reporting, but just gives 500 on errors)

Adding to what deceze said above. This is a parse error, so in order to debug a parse error, create a new file in the root named debugSyntax.php. Put this in it:

<?php

///////    SYNTAX ERROR CHECK    ////////////
error_reporting(E_ALL);
ini_set('display_errors','On');

//replace "pageToTest.php" with the file path that you want to test. 
include('pageToTest.php'); 

?>

Run the debugSyntax.php page and it will display parse errors from the page that you chose to test.

What is the difference between 0.0.0.0, 127.0.0.1 and localhost?

In current version of Jekyll, it defaults to http://127.0.0.1:4000/.
This is good, if you are connected to a network but do not want anyone else to access your application.

However it may happen that you want to see how your application runs on a mobile or from some other laptop/computer.

In that case, you can use

jekyll serve --host 0.0.0.0

This binds your application to the host & next use following to connect to it from some other host

http://host's IP adress/4000 

Binding to static property

These answers are all good if you want to follow good conventions but the OP wanted something simple, which is what I wanted too instead of dealing with GUI design patterns. If all you want to do is have a string in a basic GUI app you can update ad-hoc without anything fancy, you can just access it directly in your C# source.

Let's say you've got a really basic WPF app MainWindow XAML like this,

<Window x:Class="MyWPFApp.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:MyWPFApp"
            mc:Ignorable="d"
            Title="MainWindow"
            Height="200"
            Width="400"
            Background="White" >
    <Grid>
        <TextBlock x:Name="textBlock"                   
                       Text=".."
                       HorizontalAlignment="Center"
                       VerticalAlignment="Top"
                       FontWeight="Bold"
                       FontFamily="Helvetica"
                       FontSize="16"
                       Foreground="Blue" Margin="0,10,0,0"
             />
        <Button x:Name="Find_Kilroy"
                    Content="Poke Kilroy"
                    Click="Button_Click_Poke_Kilroy"
                    HorizontalAlignment="Center"
                    VerticalAlignment="Center"
                    FontFamily="Helvetica"
                    FontWeight="Bold"
                    FontSize="14"
                    Width="280"
            />
    </Grid>
</Window>

That will look something like this:

enter image description here

In your MainWindow XAML's source, you could have something like this where all we're doing in changing the value directly via textBlock.Text's get/set functionality:

using System.Windows;

namespace MyWPFApp
{
    public partial class MainWindow : Window
    {
        public MainWindow() { InitializeComponent(); }

        private void Button_Click_Poke_Kilroy(object sender, RoutedEventArgs e)
        {
            textBlock.Text = "              \\|||/\r\n" +
                             "              (o o) \r\n" +
                             "----ooO- (_) -Ooo----";
        }
    }
}

Then when you trigger that click event by clicking the button, voila! Kilroy appears :)

enter image description here

Download File Using Javascript/jQuery

I don't know if the question is just too old, but setting window.location to a download url will work, as long as the download mime type is correct (for example a zip archive).

var download = function(downloadURL) {

   location = downloadURL;

});

download('http://example.com/archive.zip'); //correct usage
download('http://example.com/page.html'); //DON'T

WCF ServiceHost access rights

please open your Visual Studio in Administration Mode then try it.

How can I do GUI programming in C?

A C compiler itself won't provide you with GUI functionality, but there are plenty of libraries for that sort of thing. The most popular is probably GTK+, but it may be a little too complicated if you are just starting out and want to quickly get a GUI up and running.

For something a little simpler, I would recommend IUP. With it, you can use a simple GUI definition language called LED to layout controls (but you can do it with pure C, if you want to).

Apache: Restrict access to specific source IP inside virtual host

In Apache 2.4, the authorization configuration syntax has changed, and the Order, Deny or Allow directives should no longer be used.

The new way to do this would be:

<VirtualHost *:8080>
    <Location />
        Require ip 192.168.1.0
    </Location>
    ...
</VirtualHost>

Further examples using the new syntax can be found in the Apache documentation: Upgrading to 2.4 from 2.2

Getting a random value from a JavaScript array

Create one random value and pass to array

Please try following code..

//For Search textbox random value
var myPlaceHolderArray = ['Hotels in New York...', 'Hotels in San Francisco...', 'Hotels Near Disney World...', 'Hotels in Atlanta...'];
var rand = Math.floor(Math.random() * myPlaceHolderArray.length);
var Placeholdervalue = myPlaceHolderArray[rand];

alert(Placeholdervalue);

Pause in Python

Try os.system("pause") — I used it and it worked for me.

Make sure to include import os at the top of your script.

Iterating on a file doesn't work the second time

The file object is a buffer. When you read from the buffer, that portion that you read is consumed (the read position is shifted forward). When you read through the entire file, the read position is at the end of the file (EOF), so it returns nothing because there is nothing left to read.

If you have to reset the read position on a file object for some reason, you can do:

f.seek(0)

How can I do division with variables in a Linux shell?

Those variables are shell variables. To expand them as parameters to another program (ie expr), you need to use the $ prefix:

expr $x / $y

The reason it complained is because it thought you were trying to operate on alphabetic characters (ie non-integer)

If you are using the Bash shell, you can achieve the same result using expression syntax:

echo $((x / y))

Or:

z=$((x / y))
echo $z

node.js shell command execution

@TonyO'Hagan is comprehrensive shelljs answer, but, I would like to highlight the synchronous version of his answer:

var shell = require('shelljs');
var output = shell.exec('netstat -rn', {silent:true}).output;
console.log(output);

Convert UTF-8 encoded NSData to NSString

Just to summarize, here's a complete answer, that worked for me.

My problem was that when I used

[NSString stringWithUTF8String:(char *)data.bytes];

The string I got was unpredictable: Around 70% it did contain the expected value, but too often it resulted with Null or even worse: garbaged at the end of the string.

After some digging I switched to

[[NSString alloc] initWithBytes:(char *)data.bytes length:data.length encoding:NSUTF8StringEncoding];

And got the expected result every time.

Android: How to detect double-tap?

GuestureDetecter Works Well on Most Devices, I would like to know how the time between two clicks can be customized on double click event, i wasn't able to do that. I updated the above code by "Bughi" "DoubleClickListner", added a timer using handler that executes a code after a specific delay on single click, and if double click is performed before that delay it cancels the timer and single click task and only execute double click task. Code is working Fine Makes it perfect to use as double click listner:

  private Timer timer = null;  //at class level;
  private int DELAY   = 500;

  view.setOnClickListener(new DoubleClickListener() {

        @Override
        public void onSingleClick(View v) {

    final Handler  handler          = new Handler();
                final Runnable mRunnable        = new Runnable() {
                    public void run() {
                        processSingleClickEvent(v); //Do what ever u want on single click

                    }
                };

                TimerTask timertask = new TimerTask() {
                    @Override
                    public void run() {
                        handler.post(mRunnable);
                    }
                };
                timer   =   new Timer();
                timer.schedule(timertask, DELAY);       

        }

        @Override
        public void onDoubleClick(View v) {
                if(timer!=null)
                {
                 timer.cancel(); //Cancels Running Tasks or Waiting Tasks.
                 timer.purge();  //Frees Memory by erasing cancelled Tasks.
                }
              processDoubleClickEvent(v);//Do what ever u want on Double Click

        }
    });

How to show grep result with complete path or file name

If you want to see the full paths, I would recommend to cd to the top directory (of your drive if using windows)

cd C:\
grep -r somethingtosearch C:\Users\Ozzesh\temp

Or on Linux:

cd /
grep -r somethingtosearch ~/temp

if you really resist on your file name filtering (*.log) AND you want recursive (files are not all in the same directory), combining find and grep is the most flexible way:

cd /
find ~/temp -iname '*.log' -type f -exec grep somethingtosearch '{}' \;

C++ Fatal Error LNK1120: 1 unresolved externals

In my case, the argument type was different in the header file and .cpp file. In the header file the type was std::wstring and in the .cpp file it was LPCWSTR.

jQuery: print_r() display equivalent?

Top comment has a broken link to the console.log documentation for Firebug, so here is a link to the wiki article about Console. I started using it and am quite satisfied with it as an alternative to PHP's print_r().

Also of note is that Firebug gives you access to returned JSON objects even without you manually logging them:

  • In the console you can see the url of the AJAX response.
  • Click the triangle to expand the response and see details.
  • Click the JSON tab in the details.
  • You will see the response data organized with expansion triangles.

This method take a couple more clicks to get at the data but doesn't require any additions in your actual javascript and doesn't shift your focus in Firebug out of the console (using console.log creates a link to the DOM section of firebug, forcing you to click back to console after).

For my money I'd rather click a couple more times when I want to inspect rather than mess around with the log, especially since keeps the console neat by not adding any additional cruft.

What's the yield keyword in JavaScript?

Before you learn about yield you need to know about generators. Generators are created using the function* syntax. Generator functions do not execute code but instead returns a type of iterator called a generator. When a value is given using the next method, the generator function keeps executing until it comes across a yield keyword. Using yield gives you back an object containing two values, one is value and the other is done (boolean). The value can be an array, object etc.

GetElementByID - Multiple IDs

You can do it with document.getElementByID Here is how.

function dostuff (var here) {
  if(add statment here) {
  document.getElementById('First ID'));
  document.getElementById('Second ID'));
  }
}

There you go! xD

How do I get my solution in Visual Studio back online in TFS?

I searched for the solution online and found this solution but wasn't too keen on the registry change.

I found a better way: right-click on the solution name right at the top of the Solution Explorer and select the Go Online option. Clicking this allowed me to select the files that had been changed when I was offline and make the solution online again.

After finding the solution, I found the following msdn forum thread which confirmed the above.

How to send multiple data fields via Ajax?

You can send data through JSON or via normal POST, here is an example for JSON.

 var value1 = 1;
 var value2 = 2;
 var value3 = 3;   
 $.ajax({
      type: "POST",
      contentType: "application/json; charset=utf-8",
      url: "yoururlhere",
      data: { data1: value1, data2: value2, data3: value3 },
      success: function (result) {
           // do something here
      }
 });

If you want to use it via normal post try this

 $.ajax({
      type: "POST",
      url: $('form').attr("action"),   
      data: $('#form0').serialize(),
      success: function (result) {
         // do something here
      }
 });

How to order by with union in SQL?

As other answers stated , 'Order by' after LAST Union should apply to both datasets joined by union.

I was having two data sets but using different tables but same columns. 'Order by' after LAST Union didn't still worked. Using ALIAS for column used in 'order by' did the trick.

Select Name, Address for Employee 
Union
Select Customer_Name, Address from Customer
order by customer_name;   --Won't work

So solution is use Alias 'User_Name' :

Select Name as User_Name, Address for Employee 
Union
Select Customer_Name as User_Name, Address from Customer
order by User_Name; 

[ :Unexpected operator in shell programming

Do not use any reserved keyword as the start of any variable name: eg HOSTNAME will fail as HOST {TYPE|NAME} are reserved

How to use glyphicons in bootstrap 3.0

If yout download a customized bootstrap 3 distro you must:

  1. Download the full distro from https://github.com/twbs/bootstrap/archive/v3.0.0.zip
  2. Uncompress and upload the entire folder called fonts to your bootstrap directory. Put together with the other folders "css, js".

Example Before:

\css
\js
index.html

Example After Upload:

\css
\fonts
\js
index.html

TypeError: Invalid dimensions for image data when plotting array with imshow()

There is a (somewhat) related question on StackOverflow:

Here the problem was that an array of shape (nx,ny,1) is still considered a 3D array, and must be squeezed or sliced into a 2D array.

More generally, the reason for the Exception

TypeError: Invalid dimensions for image data

is shown here: matplotlib.pyplot.imshow() needs a 2D array, or a 3D array with the third dimension being of shape 3 or 4!

You can easily check this with (these checks are done by imshow, this function is only meant to give a more specific message in case it's not a valid input):

from __future__ import print_function
import numpy as np

def valid_imshow_data(data):
    data = np.asarray(data)
    if data.ndim == 2:
        return True
    elif data.ndim == 3:
        if 3 <= data.shape[2] <= 4:
            return True
        else:
            print('The "data" has 3 dimensions but the last dimension '
                  'must have a length of 3 (RGB) or 4 (RGBA), not "{}".'
                  ''.format(data.shape[2]))
            return False
    else:
        print('To visualize an image the data must be 2 dimensional or '
              '3 dimensional, not "{}".'
              ''.format(data.ndim))
        return False

In your case:

>>> new_SN_map = np.array([1,2,3])
>>> valid_imshow_data(new_SN_map)
To visualize an image the data must be 2 dimensional or 3 dimensional, not "1".
False

The np.asarray is what is done internally by matplotlib.pyplot.imshow so it's generally best you do it too. If you have a numpy array it's obsolete but if not (for example a list) it's necessary.


In your specific case you got a 1D array, so you need to add a dimension with np.expand_dims()

import matplotlib.pyplot as plt
a = np.array([1,2,3,4,5])
a = np.expand_dims(a, axis=0)  # or axis=1
plt.imshow(a)
plt.show()

enter image description here

or just use something that accepts 1D arrays like plot:

a = np.array([1,2,3,4,5])
plt.plot(a)
plt.show()

enter image description here

How to get a property value based on the name

You want Reflection

Type t = typeof(Car);
PropertyInfo prop = t.GetProperty("Make");
if(null != prop)
return prop.GetValue(this, null);