Programs & Examples On #Data virtualization

Spring cannot find bean xml configuration file when it does exist

In Spring all source files are inside src/main/java. Similarly, the resources are generally kept inside src/main/resources. So keep your spring configuration file inside resources folder.

Make sure you have the ClassPath entry for your files inside src/main/resources as well.

In .classpath check for the following 2 lines. If they are missing add them.

<classpathentry path="src/main/java" kind="src"/>
<classpathentry path="src/main/resources" kind="src" />

So, if you have everything in place the below code should work.

ApplicationContext ctx = new ClassPathXmlApplicationContext("Spring-Module.xml");

How to display the function, procedure, triggers source code in postgresql?

For function:

you can query the pg_proc view , just as the following

select proname,prosrc from pg_proc where proname= your_function_name; 

Another way is that just execute the commont \df and \ef which can list the functions.

skytf=> \df           
                                             List of functions
 Schema |         Name         | Result data type |              Argument data types               |  Type  
--------+----------------------+------------------+------------------------------------------------+--------
 public | pg_buffercache_pages | SETOF record     |                                                | normal


skytf=> \ef  pg_buffercache_pages

It will show the source code of the function.

For triggers:

I dont't know if there is a direct way to get the source code. Just know the following way, may be it will help you!

  • step 1 : Get the table oid of the trigger:
    skytf=> select tgrelid from pg_trigger  where tgname='insert_tbl_tmp_trigger';
      tgrelid
    ---------
       26599
    (1 row)
  • step 2: Get the table name of the above oid !
    skytf=> select oid,relname  from pg_class where oid=26599;
      oid  |           relname           
    -------+-----------------------------
     26599 | tbl_tmp
    (1 row)
  • step 3: list the table information
    skytf=> \d tbl_tmp

It will show you the details of the trigger of the table . Usually a trigger uses a function. So you can get the source code of the trigger function just as the above that I pointed out !

How to include the reference of DocumentFormat.OpenXml.dll on Mono2.10?

What worked for me:

  1. Add a folder to the project call it ThirdParty.
  2. Add in the ThirdParty folder both DocumentFormat.OpenXML.dll and WindowsBase.dll
  3. Make sure the the project uses the ThirdParty dir as reference for both the DLLs
  4. Build and published to an external server.

how to run command "mysqladmin flush-hosts" on Amazon RDS database Server instance?

For normal MySQL, just connect as the 'root' administrative super user, and issue the command:

FLUSH HOSTS

Even in the case of too many connections, MySQL should be keeping a connection in reserve so that a super user can connect.

The mysqladmin client generally connects as root anyway and issues the above SQL.

How can I split a delimited string into an array in PHP?

$myString = "9,[email protected],8";
$myArray = explode(',', $myString);
foreach($myArray as $my_Array){
    echo $my_Array.'<br>';  
}

Output

9
[email protected]
8

Center an element in Bootstrap 4 Navbar

from the docs

Navbars may contain bits of text with the help of .navbar-text. This class adjusts vertical alignment and horizontal spacing for strings of text.

i applied the .navbar-text class to my <li> element, so the result is

<li class="nav-item navbar-text">

this centers the links vertically with respect to my navbar-brand img

Serialize an object to XML

I have a simple way to serialize an object to XML using C#, it works great and it's highly reusable. I know this is an older thread, but I wanted to post this because someone may find this helpful to them.

Here is how I call the method:

var objectToSerialize = new MyObject();
var xmlString = objectToSerialize.ToXmlString();

Here is the class that does the work:

Note: Since these are extension methods they need to be in a static class.

using System.IO;
using System.Xml.Serialization;

public static class XmlTools
{
    public static string ToXmlString<T>(this T input)
    {
        using (var writer = new StringWriter())
        {
            input.ToXml(writer);
            return writer.ToString();
        }
    }

    private static void ToXml<T>(this T objectToSerialize, StringWriter writer)
    {
        new XmlSerializer(typeof(T)).Serialize(writer, objectToSerialize);
    }
}

ExpressJS - throw er Unhandled error event

->check what’s running on port 8080 or what ever port u want to check

lsof -i @localhost:8080

if something is running u can close it or use some kill command to close it

How does the "view" method work in PyTorch?

What is the meaning of parameter -1?

You can read -1 as dynamic number of parameters or "anything". Because of that there can be only one parameter -1 in view().

If you ask x.view(-1,1) this will output tensor shape [anything, 1] depending on the number of elements in x. For example:

import torch
x = torch.tensor([1, 2, 3, 4])
print(x,x.shape)
print("...")
print(x.view(-1,1), x.view(-1,1).shape)
print(x.view(1,-1), x.view(1,-1).shape)

Will output:

tensor([1, 2, 3, 4]) torch.Size([4])
...
tensor([[1],
        [2],
        [3],
        [4]]) torch.Size([4, 1])
tensor([[1, 2, 3, 4]]) torch.Size([1, 4])

How to find third or n?? maximum salary from salary table?

Try this Query

SELECT DISTINCT salary
FROM emp E WHERE
&no =(SELECT COUNT(DISTINCT salary) 
FROM emp WHERE E.salary <= salary)

Put n= which value you want

Using multiple property files (via PropertyPlaceholderConfigurer) in multiple projects/modules

I know that this is an old question, but the ignore-unresolvable property was not working for me and I didn't know why.

The problem was that I needed an external resource (something like location="file:${CATALINA_HOME}/conf/db-override.properties") and the ignore-unresolvable="true" does not do the job in this case.

What one needs to do for ignoring a missing external resource is:

ignore-resource-not-found="true"

Just in case anyone else bumps into this.

Comments in .gitignore?

Yes, you may put comments in there. They however must start at the beginning of a line.

cf. http://git-scm.com/book/en/Git-Basics-Recording-Changes-to-the-Repository#Ignoring-Files

The rules for the patterns you can put in the .gitignore file are as follows:
- Blank lines or lines starting with # are ignored.
[…]

The comment character is #, example:

# no .a files
*.a

Read file from line 2 or skip header row

If you want the first line and then you want to perform some operation on file this code will helpful.

with open(filename , 'r') as f:
    first_line = f.readline()
    for line in f:
            # Perform some operations

Android ADB devices unauthorized

in Developer options,

  1. Enable USB debugging.

enter image description here

  1. Give a authorization.

enter image description here

(if there is no a Developer option menu, you have to click 3 times build number of Phone State menu to be developer. you can sse a developer option menu.)

enter image description here

How to setup Main class in manifest file in jar produced by NetBeans project

Don't hesitate but look into your project files after you have built your project for the first time. Look for a manifest file and choose open with notepad.

Add the line:

Main-Class: package.myMainClassName

Where package is your package and myClassName is the class with the main(String[] args) method.

Return multiple values to a method caller

In C#7 There is a new Tuple syntax:

static (string foo, int bar) GetTuple()
{
    return ("hello", 5);
}

You can return this as a record:

var result = GetTuple();
var foo = result.foo
// foo == "hello"

You can also use the new deconstructor syntax:

(string foo) = GetTuple();
// foo == "hello"

Be careful with serialisation however, all this is syntactic sugar - in the actual compiled code this will be a Tuple<string, int> (as per the accepted answer) with Item1 and Item2 instead of foo and bar. That means that serialisation (or deserialisation) will use those property names instead.

So, for serialisation declare a record class and return that instead.

Also new in C#7 is an improved syntax for out parameters. You can now declare the out inline, which is better suited in some contexts:

if(int.TryParse("123", out int result)) {
    // Do something with result
}

However, mostly you'll use this in .NET's own libraries, rather than in you own functions.

Inserting into Oracle and retrieving the generated sequence ID

You can use the below statement to get the inserted Id to a variable-like thing.

INSERT INTO  YOUR_TABLE(ID) VALUES ('10') returning ID into :Inserted_Value;

Now you can retrieve the value using the below statement

SELECT :Inserted_Value FROM DUAL;

Python foreach equivalent

For an updated answer you can build a forEach function in Python easily:

def forEach(list, function):
    for i, v in enumerate(list):
        function(v, i, list)

You could also adapt this to map, reduce, filter, and any other array functions from other languages or precedence you'd want to bring over. For loops are fast enough, but the boiler plate is longer than forEach or the other functions. You could also extend list to have these functions with a local pointer to a class so you could call them directly on lists as well.

Saving a Numpy array as an image

The world probably doesn't need yet another package for writing a numpy array to a PNG file, but for those who can't get enough, I recently put up numpngw on github:

https://github.com/WarrenWeckesser/numpngw

and on pypi: https://pypi.python.org/pypi/numpngw/

The only external dependency is numpy.

Here's the first example from the examples directory of the repository. The essential line is simply

write_png('example1.png', img)

where img is a numpy array. All the code before that line is import statements and code to create img.

import numpy as np
from numpngw import write_png


# Example 1
#
# Create an 8-bit RGB image.

img = np.zeros((80, 128, 3), dtype=np.uint8)

grad = np.linspace(0, 255, img.shape[1])

img[:16, :, :] = 127
img[16:32, :, 0] = grad
img[32:48, :, 1] = grad[::-1]
img[48:64, :, 2] = grad
img[64:, :, :] = 127

write_png('example1.png', img)

Here's the PNG file that it creates:

example1.png

Get distance between two points in canvas

i tend to use this calculation a lot in things i make, so i like to add it to the Math object:

Math.dist=function(x1,y1,x2,y2){ 
  if(!x2) x2=0; 
  if(!y2) y2=0;
  return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)); 
}
Math.dist(0,0, 3,4); //the output will be 5
Math.dist(1,1, 4,5); //the output will be 5
Math.dist(3,4); //the output will be 5

Update:

this approach is especially happy making when you end up in situations something akin to this (i often do):

varName.dist=Math.sqrt( ( (varName.paramX-varX)/2-cx )*( (varName.paramX-varX)/2-cx ) + ( (varName.paramY-varY)/2-cy )*( (varName.paramY-varY)/2-cy ) );

that horrid thing becomes the much more manageable:

varName.dist=Math.dist((varName.paramX-varX)/2, (varName.paramY-varY)/2, cx, cy);

How to resolve merge conflicts in Git repository?

I follow the below process.

The process to fix merge conflict:

  1. First, pull the latest from the destination branch to which you want to merge git pull origin develop

  2. As you get the latest from the destination, now resolve the conflict manually in IDE by deleting those extra characters.

  3. Do a git add to add these edited files to the git queue so that it can be commit and push to the same branch you are working on.

  4. As git add is done, do a git commit to commit the changes.

  5. Now push the changes to your working branch by git push origin HEAD

This is it and you will see it resolved in your pull request if you are using Bitbucket or GitHub.

How to accept Date params in a GET request to Spring MVC Controller?

... or you can do it the right way and have a coherent rule for serialisation/deserialisation of dates all across your application. put this in application.properties:

spring.mvc.date-format=yyyy-MM-dd

how to replace an entire column on Pandas.DataFrame

If you don't mind getting a new data frame object returned as opposed to updating the original Pandas .assign() will avoid SettingWithCopyWarning. Your example:

df = df.assign(B=df1['E'])

Null check in VB

Change your Ands to AndAlsos

A standard And will test both expressions. If comp.Container is Nothing, then the second expression will raise a NullReferenceException because you're accessing a property on a null object.

AndAlso will short-circuit the logical evaluation. If comp.Container is Nothing, then the 2nd expression will not be evaluated.

Disabling Strict Standards in PHP 5.4

Heads up, you might need to restart LAMP, Apache or whatever your using to make this take affect. Racked our brains for a while on this one, seemed to make no affect until services were restarted, presumably because the website was caching.

JavaScript: Parsing a string Boolean value?

You can use JSON.parse for that:

JSON.parse("true"); //returns boolean true

When to use extern in C++

This comes in useful when you have global variables. You declare the existence of global variables in a header, so that each source file that includes the header knows about it, but you only need to “define” it once in one of your source files.

To clarify, using extern int x; tells the compiler that an object of type int called x exists somewhere. It's not the compilers job to know where it exists, it just needs to know the type and name so it knows how to use it. Once all of the source files have been compiled, the linker will resolve all of the references of x to the one definition that it finds in one of the compiled source files. For it to work, the definition of the x variable needs to have what's called “external linkage”, which basically means that it needs to be declared outside of a function (at what's usually called “the file scope”) and without the static keyword.

header:

#ifndef HEADER_H
#define HEADER_H

// any source file that includes this will be able to use "global_x"
extern int global_x;

void print_global_x();

#endif

source 1:

#include "header.h"

// since global_x still needs to be defined somewhere,
// we define it (for example) in this source file
int global_x;

int main()
{
    //set global_x here:
    global_x = 5;

    print_global_x();
}

source 2:

#include <iostream>
#include "header.h"

void print_global_x()
{
    //print global_x here:
    std::cout << global_x << std::endl;
}

AsyncTask Android example

Concept and code here

I have created a simple example for using AsyncTask of Android. It starts with onPreExecute(), doInBackground(), publishProgress() and finally onProgressUpdate().

In this, doInBackground() works as a background thread, while other works in the UI Thread. You can't access an UI element in doInBackground(). The sequence is the same as I have mentioned.

However, if you need to update any widget from doInBackground, you can publishProgress from doInBackground which will call onProgressUpdate to update your UI widget.

class TestAsync extends AsyncTask<Void, Integer, String> {
    String TAG = getClass().getSimpleName();

    protected void onPreExecute() {
        super.onPreExecute();
        Log.d(TAG + " PreExceute","On pre Exceute......");
    }

    protected String doInBackground(Void...arg0) {
        Log.d(TAG + " DoINBackGround", "On doInBackground...");

        for (int i=0; i<10; i++){
            Integer in = new Integer(i);
            publishProgress(i);
        }
        return "You are at PostExecute";
    }

    protected void onProgressUpdate(Integer...a) {
        super.onProgressUpdate(a);
        Log.d(TAG + " onProgressUpdate", "You are in progress update ... " + a[0]);
    }

    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        Log.d(TAG + " onPostExecute", "" + result);
    }
}

Call it like this in your activity:

new TestAsync().execute();

Developer Reference Here

How to execute a shell script in PHP?

You might have disabled the exec privileges, most of the LAMP packages have those disabled. Check your php.ini for this line:

disable_functions = exec

And remove the exec, shell_exec entries if there are there.

Good Luck!

Calculating distance between two points, using latitude longitude?

Future readers who stumble upon this SOF article.

Obviously, the question was asked in 2010 and its now 2019. But it comes up early in an internet search. The original question does not discount use of third-party-library (when I wrote this answer).

public double calculateDistanceInMeters(double lat1, double long1, double lat2,
                                     double long2) {


    double dist = org.apache.lucene.util.SloppyMath.haversinMeters(lat1, long1, lat2, long2);
    return dist;
}

and

<dependency>
  <groupId>org.apache.lucene</groupId>
  <artifactId>lucene-spatial</artifactId>
  <version>8.2.0</version>
</dependency>

https://mvnrepository.com/artifact/org.apache.lucene/lucene-spatial/8.2.0

Please read documentation about "SloppyMath" before diving in!

https://lucene.apache.org/core/8_2_0/core/org/apache/lucene/util/SloppyMath.html

unknown type name 'uint8_t', MinGW

To use uint8_t type alias, you have to include stdint.h standard header.

Autoplay audio files on an iPad with HTML5

I confirm that the audio isn't working as described (at least on iPad running 4.3.5). The specific issue is the audio won't load in an asynchronous method (ajax, timer event, etc) but it will play if it was preloaded. The problem is the load has to be on a user-triggered event. So if you can have a button for the user to initiate the playing you can do something like:

function initSounds() {
    window.sounds = new Object();
    var sound = new Audio('assets/sounds/clap.mp3');
    sound.load();
    window.sounds['clap.mp3'] = sound;
}

Then to play it, eg in an ajax request, you can do

function doSomething() {
    $.post('testReply.php',function(data){
        window.sounds['clap.mp3'].play();
    }); 
}

Not the greatest solution, but it may help, especially knowing the culprit is the load function in a non-user-triggered event.

Edit: I found Apple's explanation, and it affects iOS 4+: http://developer.apple.com/library/safari/#documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html

How to have css3 animation to loop forever

I stumbled upon the same problem: a page with many independent animations, each one with its own parameters, which must be repeated forever.

Merging this clue with this other clue I found an easy solution: after the end of all your animations the wrapping div is restored, forcing the animations to restart.

All you have to do is to add these few lines of Javascript, so easy they don't even need any external library, in the <head> section of your page:

<script>
setInterval(function(){
var container = document.getElementById('content');
var tmp = container.innerHTML;
container.innerHTML= tmp;
}, 35000 // length of the whole show in milliseconds
);
</script>

BTW, the closing </head> in your code is misplaced: it must be before the starting <body>.

How to add directory to classpath in an application run profile in IntelliJ IDEA?

I am using Idea 8. in your module dependancies tab (in the project structure dialog). Add a "Module Library". There you can select a Jar Directory to add. Then make sure the run profile is using the Classpath and JDK of the correct module when it runs (this is in the run config dialog.

Differences between ConstraintLayout and RelativeLayout

A big difference is that ConstraintLayout respects constraints even if the view is gone. So it won't break the layout if you have a chain and you want to make a view disappear in the middle.

Error With Port 8080 already in use

This Worked for me > In Eclipse NEON double clicked on Server tab which redirects server overview window

Here you can change port number based on your requirement for Tomcat Admin and HTTP port.

And restarted the server.

Hope this helps you.

How to leave/exit/deactivate a Python virtualenv

You can use virtualenvwrapper in order to ease the way you work with virtualenv.

Installing virtualenvwrapper:

pip install virtualenvwrapper

If you are using a standard shell, open your ~/.bashrc or ~/.zshrc if you use Oh My Zsh. Add these two lines:

export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh

To activate an existing virtualenv, use command workon:

$ workon myenv
(myenv)$

In order to deactivate your virtualenv:

(myenv)$ deactivate

Here is my tutorial, step by step on how to install virtualenv and virtualenvwrapper.

What algorithms compute directions from point A to point B on a map?

The current state of the art in terms of query times for static road networks is the Hub labelling algorithm proposed by Abraham et al. http://link.springer.com/chapter/10.1007/978-3-642-20662-7_20 . A through and excellently written survey of the field was recently published as a Microsoft technical report http://research.microsoft.com/pubs/207102/MSR-TR-2014-4.pdf .

The short version is...

The Hub labelling algorithm provides the fastest queries for static road networks but requires a large amount of ram to run (18 GiB).

Transit node routing is slightly slower, although, it only requires around 2 GiB of memory and has a quicker preprocessing time.

Contraction Hierarchies provide a nice trade off between quick preprocessing times, low space requirements (0.4 GiB) and fast query times.

No one algorithm is completely dominate...

This Google tech talk by Peter Sanders may be of interest

https://www.youtube.com/watch?v=-0ErpE8tQbw

Also this talk by Andrew Goldberg

https://www.youtube.com/watch?v=WPrkc78XLhw

An open source implementation of contraction hierarchies is available from Peter Sanders research group website at KIT. http://algo2.iti.kit.edu/english/routeplanning.php

Also an easily accessible blog post written by Microsoft on there usage of the CRP algorithm... http://blogs.bing.com/maps/2012/01/05/bing-maps-new-routing-engine/

Ifelse statement in R with multiple conditions

Very simple use of any

df <- <your structure>

df$Den <- apply(df,1,function(i) {ifelse(any(is.na(i)) | any(i != 1), 0, 1)})

"Least Astonishment" and the Mutable Default Argument

Why don't you introspect?

I'm really surprised no one has performed the insightful introspection offered by Python (2 and 3 apply) on callables.

Given a simple little function func defined as:

>>> def func(a = []):
...    a.append(5)

When Python encounters it, the first thing it will do is compile it in order to create a code object for this function. While this compilation step is done, Python evaluates* and then stores the default arguments (an empty list [] here) in the function object itself. As the top answer mentioned: the list a can now be considered a member of the function func.

So, let's do some introspection, a before and after to examine how the list gets expanded inside the function object. I'm using Python 3.x for this, for Python 2 the same applies (use __defaults__ or func_defaults in Python 2; yes, two names for the same thing).

Function Before Execution:

>>> def func(a = []):
...     a.append(5)
...     

After Python executes this definition it will take any default parameters specified (a = [] here) and cram them in the __defaults__ attribute for the function object (relevant section: Callables):

>>> func.__defaults__
([],)

O.k, so an empty list as the single entry in __defaults__, just as expected.

Function After Execution:

Let's now execute this function:

>>> func()

Now, let's see those __defaults__ again:

>>> func.__defaults__
([5],)

Astonished? The value inside the object changes! Consecutive calls to the function will now simply append to that embedded list object:

>>> func(); func(); func()
>>> func.__defaults__
([5, 5, 5, 5],)

So, there you have it, the reason why this 'flaw' happens, is because default arguments are part of the function object. There's nothing weird going on here, it's all just a bit surprising.

The common solution to combat this is to use None as the default and then initialize in the function body:

def func(a = None):
    # or: a = [] if a is None else a
    if a is None:
        a = []

Since the function body is executed anew each time, you always get a fresh new empty list if no argument was passed for a.


To further verify that the list in __defaults__ is the same as that used in the function func you can just change your function to return the id of the list a used inside the function body. Then, compare it to the list in __defaults__ (position [0] in __defaults__) and you'll see how these are indeed refering to the same list instance:

>>> def func(a = []): 
...     a.append(5)
...     return id(a)
>>>
>>> id(func.__defaults__[0]) == func()
True

All with the power of introspection!


* To verify that Python evaluates the default arguments during compilation of the function, try executing the following:

def bar(a=input('Did you just see me without calling the function?')): 
    pass  # use raw_input in Py2

as you'll notice, input() is called before the process of building the function and binding it to the name bar is made.

Is there a naming convention for MySQL?

Thankfully, PHP developers aren't "Camel case bigots" like some development communities I know.

Your conventions sound fine.

Just so long as they're a) simple, and b) consistent - I don't see any problems :)

PS: Personally, I think 5) is overkill...

What is the difference between 'java', 'javaw', and 'javaws'?

java: Java application executor which is associated with a console to display output/errors

javaw: (Java windowed) application executor not associated with console. So no display of output/errors. It can be used to silently push the output/errors to text files. It is mostly used to launch GUI-based applications.

javaws: (Java web start) to download and run the distributed web applications. Again, no console is associated.

All are part of JRE and use the same JVM.

ActiveMQ connection refused

I had also similar problem. In my case brokerUrl was not configured properly. So that's way I received following Error:

Cause: Error While attempting to add new Connection to the pool: nested exception is javax.jms.JMSException: Could not connect to broker URL : tcp://localhost:61616. Reason: java.net.ConnectException: Connection refused

& I resolved it following way.

   ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();

  connectionFactory.setBrokerURL("tcp://hostname:61616");
  connectionFactory.setUserName("admin");
  connectionFactory.setPassword("admin");

Calling Javascript from a html form

Remove javascript: from onclick=".., onsubmit=".. declarations

javascript: prefix is used only in href="" or similar attributes (not events related)

Anaconda-Navigator - Ubuntu16.04

To run anaconda-navigator:

$ source ~/anaconda3/bin/activate root
$ anaconda-navigator

How do I print an IFrame from javascript in Safari/Chrome

Here is my complete, cross browser solution:

In the iframe page:

function printPage() { print(); }

In the main page

function printIframe(id)
{
    var iframe = document.frames
        ? document.frames[id]
        : document.getElementById(id);
    var ifWin = iframe.contentWindow || iframe;

    iframe.focus();
    ifWin.printPage();
    return false;
}

Update: Many people seem to be having problems with this in versions of IE released since I had this problem. I do not have the time to re-investigate this right now, but, if you are stuck I suggest you read all the comments in this entire thread!

How to print without newline or space?

The new (as of Python 3.x) print function has an optional end parameter that lets you modify the ending character:

print("HELLO", end="")
print("HELLO")

Output:

HELLOHELLO

There's also sep for separator:

print("HELLO", "HELLO", "HELLO", sep="")

Output:

HELLOHELLOHELLO

If you wanted to use this in Python 2.x just add this at the start of your file:

from __future__ import print_function

How do I see which checkbox is checked?

If the checkbox is checked, then the checkbox's value will be passed. Otherwise, the field is not passed in the HTTP post.

if (isset($_POST['mycheckbox'])) {
    echo "checked!";
}

Sending SOAP request using Python Requests

It is indeed possible.

Here is an example calling the Weather SOAP Service using plain requests lib:

import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
         <SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
            <SOAP-ENV:Header/>
              <ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
         </SOAP-ENV:Envelope>"""

response = requests.post(url,data=body,headers=headers)
print response.content

Some notes:

  • The headers are important. Most SOAP requests will not work without the correct headers. application/soap+xml is probably the more correct header to use (but the weatherservice prefers text/xml
  • This will return the response as a string of xml - you would then need to parse that xml.
  • For simplicity I have included the request as plain text. But best practise would be to store this as a template, then you can load it using jinja2 (for example) - and also pass in variables.

For example:

from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()

Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).

You can do the above with suds like so:

from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service

result = client.service.GetWeatherInformation() 
print result 

Note: when using suds, you will almost always end up needing to use the doctor!

Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:

sudo tcpdump -As 0 

This can be helpful for inspecting the requests that actually go over the wire.

The above two code snippets are also available as gists:

jQuery - how to write 'if not equal to' (opposite of ==)

The opposite of the == compare operator is !=.

"code ." Not working in Command Line for Visual Studio Code on OSX/Mac

I was having the same problem. I have to add Vs Code to my applications folder. It worked without editing a file.

  1. Open Applications Folder

enter image description here

  1. Search for VS Code in your search

enter image description here

  1. Drag Vs Code to the applications folder

enter image description here

This will work for you.

htaccess "order" Deny, Allow, Deny

Just use order allow,deny instead and remove the deny from all line.

Why does Git treat this text file as a binary file?

Change the Aux.js to another name, like Sig.js.

The source tree still shows it as a binary file, but you can stage(add) it and commit.

Determining the current foreground application from a background task or service

In lollipop and up:

Add to mainfest:

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

And do something like this:

if( mTaskId < 0 )
{
    List<AppTask> tasks = mActivityManager.getAppTasks(); 
    if( tasks.size() > 0 )
        mTaskId = tasks.get( 0 ).getTaskInfo().id;
}

PostgreSQL: ERROR: operator does not exist: integer = character varying

I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).

If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::.

Something along these lines:

create view view1
as 
select table1.col1,table2.col1,table3.col3
from table1 
inner join
table2 
inner join 
table3
on 
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */
....;

Notice the varchar typecasting on the table1.col4.

Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.

Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).

Does bootstrap 4 have a built in horizontal divider?

<div class="dropdown">
  <button data-toggle="dropdown">
      Sample Button
  </button>
  <ul class="dropdown-menu">
      <li>A</li>
      <li>B</li>
      <li class="dropdown-divider"></li>
      <li>C</li>
  </ul>
</div>

This is the sample code for the horizontal divider in bootstrap 4. Output looks like this:

class="dropdown-divider" used in bootstrap 4, while class="divider" used in bootstrap 3 for horizontal divider

What is the '.well' equivalent class in Bootstrap 4

Update 2018...

card has replaced the well.

Bootstrap 4

<div class="card card-body bg-light">
     Well
</div>

or, as two DIVs...

<div class="card bg-light">
    <div class="card-body">
        ...
    </div>
</div>

(Note: in Bootstrap 4 Alpha, these were known as card-block instead of card-body and bg-faded instead of bg-light)

http://codeply.com/go/rW2d0qxx08

Implementing Singleton with an Enum (in Java)

Like all enum instances, Java instantiates each object when the class is loaded, with some guarantee that it's instantiated exactly once per JVM. Think of the INSTANCE declaration as a public static final field: Java will instantiate the object the first time the class is referred to.

The instances are created during static initialization, which is defined in the Java Language Specification, section 12.4.

For what it's worth, Joshua Bloch describes this pattern in detail as item 3 of Effective Java Second Edition.

How to add "active" class to wp_nav_menu() current menu item (simple way)

In header.php insert this code to show menu:

<?php
    wp_nav_menu(
        array(
            'theme_location' => 'menu-one',
            'walker' => new Custom_Walker_Nav_Menu_Top
        )
    );
?>

In functions.php use this:

class Custom_Walker_Nav_Menu_top extends Walker_Nav_Menu
{
    function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
        $is_current_item = '';
        if(array_search('current-menu-item', $item->classes) != 0)
        {
            $is_current_item = ' class="active"';
        }
        echo '<li'.$is_current_item.'><a href="'.$item->url.'">'.$item->title;
    }

    function end_el( &$output, $item, $depth = 0, $args = array() ) {
        echo '</a></li>';
    }
}

How can I clone an SQL Server database on the same server in SQL Server 2008 Express?

Script based on Joe answer (detach, copy files, attach both).

  1. Run Managment Studio as Administrator account.

It's not necessary, but maybe access denied error on executing.

  1. Configure sql server for execute xp_cmdshel
EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
EXEC sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE
GO
  1. Run script, but type your db names in @dbName and @copyDBName variables before.
USE master;
GO 

DECLARE @dbName NVARCHAR(255) = 'Products'
DECLARE @copyDBName NVARCHAR(255) = 'Products_branch'

-- get DB files
CREATE TABLE ##DBFileNames([FileName] NVARCHAR(255))
EXEC('
    INSERT INTO ##DBFileNames([FileName])
    SELECT [filename] FROM ' + @dbName + '.sys.sysfiles')

-- drop connections
EXEC('ALTER DATABASE ' + @dbName + ' SET OFFLINE WITH ROLLBACK IMMEDIATE')

EXEC('ALTER DATABASE ' + @dbName + ' SET SINGLE_USER')

-- detach
EXEC('EXEC sp_detach_db @dbname = ''' + @dbName + '''')

-- copy files
DECLARE @filename NVARCHAR(255), @path NVARCHAR(255), @ext NVARCHAR(255), @copyFileName NVARCHAR(255), @command NVARCHAR(MAX) = ''
DECLARE 
    @oldAttachCommand NVARCHAR(MAX) = 
        'CREATE DATABASE ' + @dbName + ' ON ', 
    @newAttachCommand NVARCHAR(MAX) = 
        'CREATE DATABASE ' + @copyDBName + ' ON '

DECLARE curs CURSOR FOR 
SELECT [filename] FROM ##DBFileNames
OPEN curs  
FETCH NEXT FROM curs INTO @filename
WHILE @@FETCH_STATUS = 0  
BEGIN
    SET @path = REVERSE(RIGHT(REVERSE(@filename),(LEN(@filename)-CHARINDEX('\', REVERSE(@filename),1))+1))
    SET @ext = RIGHT(@filename,4)
    SET @copyFileName = @path + @copyDBName + @ext

    SET @command = 'EXEC master..xp_cmdshell ''COPY "' + @filename + '" "' + @copyFileName + '"'''
    PRINT @command
    EXEC(@command);

    SET @oldAttachCommand = @oldAttachCommand + '(FILENAME = "' + @filename + '"),'
    SET @newAttachCommand = @newAttachCommand + '(FILENAME = "' + @copyFileName + '"),'

    FETCH NEXT FROM curs INTO @filename
END
CLOSE curs 
DEALLOCATE curs

-- attach
SET @oldAttachCommand = LEFT(@oldAttachCommand, LEN(@oldAttachCommand) - 1) + ' FOR ATTACH'
SET @newAttachCommand = LEFT(@newAttachCommand, LEN(@newAttachCommand) - 1) + ' FOR ATTACH'

-- attach old db
PRINT @oldAttachCommand
EXEC(@oldAttachCommand)

-- attach copy db
PRINT @newAttachCommand
EXEC(@newAttachCommand)

DROP TABLE ##DBFileNames

How to do a recursive find/replace of a string with awk or sed?

Simplest way to replace (all files, directory, recursive)

find . -type f -not -path '*/\.*' -exec sed -i 's/foo/bar/g' {} +

Note: Sometimes you might need to ignore some hidden files i.e. .git, you can use above command.

If you want to include hidden files use,

find . -type f  -exec sed -i 's/foo/bar/g' {} +

In both case the string foo will be replaced with new string bar

Java SSLException: hostname in certificate didn't match

I had similar problem. I was using Android's DefaultHttpClient. I have read that HttpsURLConnection can handle this kind of exception. So I created custom HostnameVerifier which uses the verifier from HttpsURLConnection. I also wrapped the implementation to custom HttpClient.

public class CustomHttpClient extends DefaultHttpClient {

public CustomHttpClient() {
    super();
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier(new CustomHostnameVerifier());
    Scheme scheme = (new Scheme("https", socketFactory, 443));
    getConnectionManager().getSchemeRegistry().register(scheme);
}

Here is the CustomHostnameVerifier class:

public class CustomHostnameVerifier implements org.apache.http.conn.ssl.X509HostnameVerifier {

@Override
public boolean verify(String host, SSLSession session) {
    HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
    return hv.verify(host, session);
}

@Override
public void verify(String host, SSLSocket ssl) throws IOException {
}

@Override
public void verify(String host, X509Certificate cert) throws SSLException {

}

@Override
public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {

}

}

ssh remote host identification has changed

Use

ssh-keygen -R [hostname]

Example with an ip address/hostname would be:

ssh-keygen -R 168.9.9.2

This will update the offending of your host from the known_hosts. You can also provide the path of the known_hosts with -f flag.

Changing button text onclick

this can be done easily with a vbs code (as i'm not so familiar with js )

<input type="button" id="btn" Value="Close" onclick="check">
<script Language="VBScript">
sub check
if btn.Value="Close" then btn.Value="Open" 
end sub
</script>

and you're done , however this changes the Name to display only and does not change the function {onclick} , i did some researches on how to do the second one and seem there isnt' something like

btn.onclick = ".."

but i figured out a way using <"span"> tag it goes like this :

<script Language="VBScript">
  Sub function1
  MsgBox "function1"
  span.InnerHTML= "<Input type=""button"" Value=""button2"" onclick=""function2"">"
  End Sub

   Sub function2
  MsgBox "function2"
  span.InnerHTML = "<Input type=""button"" Value=""button1"" onclick=""function1"">"
  End Sub
  </script>
  <body>
  <span id="span" name="span" >
  <input type="button" Value="button1" onclick="function1">
  </span>
  </body>

try it yourself , change the codes in sub function1 and sub function2, basically all you need to know to make it in jscript is the line

span.InnerHTML = "..." 

the rest is your code you wanna execute

hope this helps :D

How to run a python script from IDLE interactive shell?

You can use this in python3:

exec(open(filename).read())

Change UITableView height dynamically

for resizing my table I went with this solution in my tableview controller witch is perfectly fine:

[objectManager getObjectsAtPath:self.searchURLString
                         parameters:nil
                            success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
                                NSArray* results = [mappingResult array];
                                self.eventArray = results;
                                NSLog(@"Events number at first: %i", [self.eventArray count]);
                                CGRect newFrame = self.activityFeedTableView.frame;
                                newFrame.size.height = self.cellsHeight + 30.0;
                                self.activityFeedTableView.frame = newFrame;

                                self.cellsHeight = 0.0;

                            }
                            failure:^(RKObjectRequestOperation *operation, NSError *error) {
                                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                                                message:[error localizedDescription]
                                                                               delegate:nil
                                                                      cancelButtonTitle:@"OK"
                                                                      otherButtonTitles:nil];
                                [alert show];
                                NSLog(@"Hit error: %@", error);
                            }];

The resizing part is in a method but here is just so you can see it. Now the only problem I haveis resizing the scroll view in the other view controller as I have no idea when the tableview has finished resizing. At the moment I'm doing it with performSelector: afterDelay: but this is really not a good way to do it. Any ideas?

How is the java memory pool divided?

Heap memory

The heap memory is the runtime data area from which the Java VM allocates memory for all class instances and arrays. The heap may be of a fixed or variable size. The garbage collector is an automatic memory management system that reclaims heap memory for objects.

  • Eden Space: The pool from which memory is initially allocated for most objects.

  • Survivor Space: The pool containing objects that have survived the garbage collection of the Eden space.

  • Tenured Generation or Old Gen: The pool containing objects that have existed for some time in the survivor space.

Non-heap memory

Non-heap memory includes a method area shared among all threads and memory required for the internal processing or optimization for the Java VM. It stores per-class structures such as a runtime constant pool, field and method data, and the code for methods and constructors. The method area is logically part of the heap but, depending on the implementation, a Java VM may not garbage collect or compact it. Like the heap memory, the method area may be of a fixed or variable size. The memory for the method area does not need to be contiguous.

  • Permanent Generation: The pool containing all the reflective data of the virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas.

  • Code Cache: The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code.

Here's some documentation on how to use Jconsole.

The import com.google.android.gms cannot be resolved

In my case or all using android studio

you can import google play service

place in your build.gradle

compile 'com.google.android.gms:play-services:7.8.0'

or latest version of play services depend in time you watch this answer

More Specific import

please review this individual gradle imports

https://developers.google.com/android/guides/setup

Google Maps

com.google.android.gms:play-services-maps:7.8.0

error may occurred

if you face error while you sync project with gradle files

enter image description here

make sure you install latest update

1- Android Support Repository.

2- Android Support Library.

3- Google Repository.

4-Google Play Services.

enter image description here

You may need restart your android studio to response

How to declare array of zeros in python (or an array of a certain size)

Just for completeness: To declare a multidimensional list of zeros in python you have to use a list comprehension like this:

buckets = [[0 for col in range(5)] for row in range(10)]

to avoid reference sharing between the rows.

This looks more clumsy than chester1000's code, but is essential if the values are supposed to be changed later. See the Python FAQ for more details.

Doing a join across two databases with different collations on SQL Server and getting an error

A general purpose way is to coerce the collation to DATABASE_DEFAULT. This removes hardcoding the collation name which could change.

It's also useful for temp table and table variables, and where you may not know the server collation (eg you are a vendor placing your system on the customer's server)

select
    sone_field collate DATABASE_DEFAULT
from
    table_1
    inner join
    table_2 on table_1.field collate DATABASE_DEFAULT = table_2.field
where whatever

Excel function to get first word from sentence in other cell

A1                   A2 
Toronto<b> is nice   =LEFT(A1,(FIND("<",A1,1)-1))

Not sure if the syntax is correct but the forumla in A2 will work for you,

How do I convert an integer to string as part of a PostgreSQL query?

You can cast an integer to a string in this way

intval::text

and so in your case

SELECT * FROM table WHERE <some integer>::text = 'string of numbers'

In Rails, how do you render JSON using a view?

Just add show.json.erb file with the contents

<%= @user.to_json %>

Sometimes it is useful when you need some extra helper methods that are not available in controller, i.e. image_path(@user.avatar) or something to generate additional properties in JSON:

<%= @user.attributes.merge(:avatar => image_path(@user.avatar)).to_json %>

Use CASE statement to check if column exists in table - SQL Server

Final answer was a combination of two of the above (I've upvoted both to show my appreciation!):

select case 
   when exists (
      SELECT 1 
      FROM Sys.columns c 
      WHERE c.[object_id] = OBJECT_ID('dbo.Tags') 
         AND c.name = 'ModifiedByUserId'
   ) 
   then 1 
   else 0 
end

How to create a bash script to check the SSH connection?

You can check this with the return-value ssh gives you:

$ ssh -q user@downhost exit
$ echo $?
255

$ ssh -q user@uphost exit
$ echo $?
0

EDIT: Another approach would be to use nmap (you won't need to have keys or login-stuff):

$ a=`nmap uphost -PN -p ssh | grep open`
$ b=`nmap downhost -PN -p ssh | grep open`

$ echo $a
22/tcp open ssh
$ echo $b
(empty string)

But you'll have to grep the message (nmap does not use the return-value to show if a port was filtered, closed or open).

EDIT2:

If you're interested in the actual state of the ssh-port, you can substitute grep open with egrep 'open|closed|filtered':

$ nmap host -PN -p ssh | egrep 'open|closed|filtered'

Just to be complete.

Month name as a string

For getting month in string variable use the code below

For example the month of September:

M -> 9

MM -> 09

MMM -> Sep

MMMM -> September

String monthname=(String)android.text.format.DateFormat.format("MMMM", new Date())

Unit Testing: DateTime.Now

One clean way to do this is to inject VirtualTime. It allows you to control time. First install VirtualTime

Install-Package VirtualTime

That allows to, for example, make time that moves 5 times faster on all calls to DateTime.Now or UtcNow

var DateTime = DateTime.Now.ToVirtualTime(5);

To make time move slower , eg 5 times slower do

var DateTime = DateTime.Now.ToVirtualTime(0.5);

To make time stand still do

var DateTime = DateTime.Now.ToVirtualTime(0);

Moving backwards in time is not tested yet

Here are a sample test:

[TestMethod]
public void it_should_make_time_move_faster()
{
    int speedOfTimePerMs = 1000;
    int timeToPassMs = 3000;
    int expectedElapsedVirtualTime = speedOfTimePerMs * timeToPassMs;
    DateTime whenTimeStarts = DateTime.Now;
    ITime time = whenTimeStarts.ToVirtualTime(speedOfTimePerMs);
    Thread.Sleep(timeToPassMs);
    DateTime expectedTime = DateTime.Now.AddMilliseconds(expectedElapsedVirtualTime - timeToPassMs);
    DateTime virtualTime = time.Now;

    Assert.IsTrue(TestHelper.AreEqualWithinMarginOfError(expectedTime, virtualTime, MarginOfErrorMs));
}

You can check out more tests here:

https://github.com/VirtualTime/VirtualTime/blob/master/VirtualTimeLib.Tests/when_virtual_time_is_used.cs

What DateTime.Now.ToVirtualTime extension gives you is an instance of ITime which you pass to a method / class that depends on ITime. some DateTime.Now.ToVirtualTime is setup in the DI container of your choice

Here is another example injecting into a class contrustor

public class AlarmClock
{
    private ITime DateTime;
    public AlarmClock(ITime dateTime, int numberOfHours)
    {
        DateTime = dateTime;
        SetTime = DateTime.UtcNow.AddHours(numberOfHours);
        Task.Run(() =>
        {
            while (!IsAlarmOn)
            {
                IsAlarmOn = (SetTime - DateTime.UtcNow).TotalMilliseconds < 0;
            }
        });
    }
    public DateTime SetTime { get; set; }
    public bool IsAlarmOn { get; set; }
}

[TestMethod]
public void it_can_be_injected_as_a_dependency()
{
    //virtual time has to be 1000*3.75 faster to get to an hour 
    //in 1000 ms real time
    var dateTime = DateTime.Now.ToVirtualTime(1000 * 3.75);
    var numberOfHoursBeforeAlarmSounds = 1;
    var alarmClock = new AlarmClock(dateTime, numberOfHoursBeforeAlarmSounds);
    Assert.IsFalse(alarmClock.IsAlarmOn);
    System.Threading.Thread.Sleep(1000);
    Assert.IsTrue(alarmClock.IsAlarmOn);
}

How to use "not" in xpath?

not() is a function in xpath (as opposed to an operator), so

//a[not(contains(@id, 'xx'))]

Create a basic matrix in C (input by user !)

How about the following?

First ask the user for the number of rows and columns, store that in say, nrows and ncols (i.e. scanf("%d", &nrows);) and then allocate memory for a 2D array of size nrows x ncols. Thus you can have a matrix of a size specified by the user, and not fixed at some dimension you've hardcoded!

Then store the elements with for(i = 0;i < nrows; ++i) ... and display the elements in the same way except you throw in newlines after every row, i.e.

for(i = 0; i < nrows; ++i)
{
   for(j = 0; j < ncols ; ++j) 
   {
      printf("%d\t",mat[i][j]);
   }
printf("\n");
}

How to delete parent element using jQuery

$('#' + catId).parent().remove('.subcatBtns');

How to list branches that contain a given commit?

You may run:

git log <SHA1>..HEAD --ancestry-path --merges

From comment of last commit in the output you may find original branch name

Example:

       c---e---g--- feature
      /         \
-a---b---d---f---h---j--- master

git log e..master --ancestry-path --merges

commit h
Merge: g f
Author: Eugen Konkov <>
Date:   Sat Oct 1 00:54:18 2016 +0300

    Merge branch 'feature' into master

android EditText - finished typing event

Better way, you can also use EditText onFocusChange listener to check whether user has done editing: (Need not rely on user pressing the Done or Enter button on Soft keyboard)

 ((EditText)findViewById(R.id.youredittext)).setOnFocusChangeListener(new OnFocusChangeListener() {

    @Override
    public void onFocusChange(View v, boolean hasFocus) {

      // When focus is lost check that the text field has valid values.

      if (!hasFocus) { {
         // Validate youredittext
      }
    }
 });

Note : For more than one EditText, you can also let your class implement View.OnFocusChangeListener then set the listeners to each of you EditText and validate them as below

((EditText)findViewById(R.id.edittext1)).setOnFocusChangeListener(this);
((EditText)findViewById(R.id.edittext2)).setOnFocusChangeListener(this);

    @Override
    public void onFocusChange(View v, boolean hasFocus) {

      // When focus is lost check that the text field has valid values.

      if (!hasFocus) {
        switch (view.getId()) {
           case R.id.edittext1:
                 // Validate EditText1
                 break;
           case R.id.edittext2:
                 // Validate EditText2
                 break;
        }
      }
    }

Error: 0xC0202009 at Data Flow Task, OLE DB Destination [43]: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80040E21

In my case the underlying system account through which the package was running was locked out. Once we got the system account unlocked and reran the package, it executed successfully. The developer said that he got to know of this while debugging wherein he directly tried to connect to the server and check the status of the connection.

convert pfx format to p12

This is more of a continuation of jglouie's response.

If you are using openssl to convert the PKCS#12 certificate to public/private PEM keys, there is no need to rename the file. Assuming the file is called cert.pfx, the following three commands will create a public pem key and an encrypted private pem key:

openssl pkcs12 -in cert.pfx     -out cert.pem     -nodes -nokeys
openssl pkcs12 -in cert.pfx     -out cert_key.pem -nodes -nocerts
openssl rsa    -in cert_key.pem -out cert_key.pem -des3

The first two commands may prompt for an import password. This will be a password that was provided with the PKCS#12 file.

The third command will let you specify the encryption passphrase for the certificate. This is what you will enter when using the certificate.

Check if an object exists

I think the easiest from a logical and efficiency point of view is using the queryset's exists() function, documented here:

https://docs.djangoproject.com/en/stable/ref/models/querysets/#django.db.models.query.QuerySet.exists

So in your example above I would simply write:

if User.objects.filter(email = cleaned_info['username']).exists():
    # at least one object satisfying query exists
else:
    # no object satisfying query exists

How to inflate one view with a layout

If you are you trying to attach a child view to the RelativeLayout? you can do by following

RelativeLayout item = (RelativeLayout)findViewById(R.id.item);
View child = getLayoutInflater().inflate(R.layout.child, item, true);

How to vertically align label and input in Bootstrap 3?

The problem is that your <label> is inside of an <h2> tag, and header tags have a margin set by the default stylesheet.

How to install ia32-libs in Ubuntu 14.04 LTS (Trusty Tahr)

I had the same problem as above and Eclipse suggested installing:

Hint: On 64-bit systems, make sure the 32-bit libraries are installed:   
   "sudo apt-get install ia32-libs"    
or on some systems,  
   "sudo apt-get install lib32z1"   

When I tried to install ia32-libs, Ubuntu prompted to install three other packages:

$ sudo apt-get install ia32-libs  
Reading package lists... Done  
Building dependency tree         
Reading state information... Done  
Package ia32-libs is not available, but is referred to by another package.  
This may mean that the package is missing, has been obsoleted, or  
is only available from another source  
However the following packages replace it:  
  lib32z1 lib32ncurses5 lib32bz2-1.0  

E: Package 'ia32-libs' has no installation candidate  
$   
$ sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0    

With Android Studio and intellij, I also had to install the 32bit version of libstdc++6:

sudo apt-get install lib32stdc++6

how to set length of an column in hibernate with maximum length

Use @Column annotation and define its length attribute. Check Hibernate's documentation for references (section 2.2.2.3).

Style disabled button with CSS

When your button is disabled it directly sets the opacity. So first of all we have to set its opacity as

.v-button{
    opacity:1;    
}

Programmatically set image to UIImageView with Xcode 6.1/Swift

How about this;

myImageView.image=UIImage(named: "image_1")

where image_1 is within the assets folder as image_1.png.

This worked for me since i'm using a switch case to display an image slide.

Starting the week on Monday with isoWeekday()

For those who want isoWeek to be the default you can modify moment's behaviour as such:

const moment = require('moment');
const proto = Object.getPrototypeOf(moment());

const {startOf, endOf} = proto;
proto.startOf = function(period) {
  if (period === 'week') {
    period = 'isoWeek';
  }
  return startOf.call(this, period);
};
proto.endOf = function(period) {
  if (period === 'week') {
    period = 'isoWeek';
  }
  return endOf.call(this, period);
};

Now you can simply use someDate.startOf('week') without worrying you'll get sunday or having to think about whether to use isoweek or isoWeek etc.

Plus you can store this in a variable like const period = 'week' and use it safely in subtract() or add() operations, e.g. moment().subtract(1, period).startOf(period);. This won't work with period being isoWeek.

Add Items to ListView - Android

public OnClickListener moreListener = new OnClickListener() {

    @Override
      public void onClick(View v) {
          adapter.add("aaaa")
      }
}

Material Design not styling alert dialogs

Material Design styling alert dialogs: Custom Font, Button, Color & shape,..

 MaterialAlertDialogBuilder(requireContext(),
                R.style.MyAlertDialogTheme
            )
                .setIcon(R.drawable.ic_dialogs_24px)
                .setTitle("Feedback")
                //.setView(R.layout.edit_text)
                .setMessage("Do you have any additional comments?")
                .setPositiveButton("Send") { dialog, _ ->

                    val input =
                        (dialog as AlertDialog).findViewById<TextView>(
                            android.R.id.text1
                        )
                    Toast.makeText(context, input!!.text, Toast.LENGTH_LONG).show()

                }
                .setNegativeButton("Cancel") { _, _ ->
                    Toast.makeText(requireContext(), "Clicked cancel", Toast.LENGTH_SHORT).show()
                }
                .show()

Style:

  <style name="MyAlertDialogTheme" parent="Theme.MaterialComponents.DayNight.Dialog.Alert">
  
        <item name="android:textAppearanceSmall">@style/MyTextAppearance</item>
        <item name="android:textAppearanceMedium">@style/MyTextAppearance</item>
        <item name="android:textAppearanceLarge">@style/MyTextAppearance</item>

        <item name="buttonBarPositiveButtonStyle">@style/Alert.Button.Positive</item>
        <item name="buttonBarNegativeButtonStyle">@style/Alert.Button.Neutral</item>
        <item name="buttonBarNeutralButtonStyle">@style/Alert.Button.Neutral</item>

        <item name="android:backgroundDimEnabled">true</item>

        <item name="shapeAppearanceOverlay">@style/ShapeAppearanceOverlay.MyApp.Dialog.Rounded
        </item>

    </style>




    <style name="MyTextAppearance" parent="TextAppearance.AppCompat">
        <item name="android:fontFamily">@font/rosarivo</item>
    </style>


        <style name="Alert.Button.Positive" parent="Widget.MaterialComponents.Button.TextButton">
   <!--     <item name="backgroundTint">@color/colorPrimaryDark</item>-->
        <item name="backgroundTint">@android:color/transparent</item>
        <item name="rippleColor">@color/colorAccent</item>
        <item name="android:textColor">@color/colorPrimary</item>
       <!-- <item name="android:textColor">@android:color/white</item>-->
        <item name="android:textSize">14sp</item>
        <item name="android:textAllCaps">false</item>
    </style>


    <style name="Alert.Button.Neutral" parent="Widget.MaterialComponents.Button.TextButton">
        <item name="backgroundTint">@android:color/transparent</item>
        <item name="rippleColor">@color/colorAccent</item>
        <item name="android:textColor">@color/colorPrimary</item>
        <!--<item name="android:textColor">@android:color/darker_gray</item>-->
        <item name="android:textSize">14sp</item>
        <item name="android:textAllCaps">false</item>
    </style>


  <style name="ShapeAppearanceOverlay.MyApp.Dialog.Rounded" parent="">
        <item name="cornerFamily">rounded</item>
        <item name="cornerSize">8dp</item>
    </style>

Output: enter image description here

Eclipse fonts and background color

Background color of views (navigator, console, tasks etc) is set according to the desktop (system) settings. On Linux/GNome I changed System/Preferences/Appeareance to change this color.

Editor colors are set chaotically by different editors, search for background in eclipse preferences to find different options. One easy way to get beautiful dark (and not only dark) themes is to install Afae plugin, and then pick theme within its preferences (twilight theme is beautiful, for example) - again, eclipse prefs, Afae group. Of course this applies only when you edit with Afae.

@POST in RESTful web service

Please find example below, it might help you

package jersey.rest.test;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/hello")
public class SimpleService {
    @GET
    @Path("/{param}")
    public Response getMsg(@PathParam("param") String msg) {
        String output = "Get:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @POST
    @Path("/{param}")
    public Response postMsg(@PathParam("param") String msg) {
        String output = "POST:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @POST
    @Path("/post")
    //@Consumes(MediaType.TEXT_XML)
    public Response postStrMsg( String msg) {
        String output = "POST:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @PUT
    @Path("/{param}")
    public Response putMsg(@PathParam("param") String msg) {
        String output = "PUT: Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @DELETE
    @Path("/{param}")
    public Response deleteMsg(@PathParam("param") String msg) {
        String output = "DELETE:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @HEAD
    @Path("/{param}")
    public Response headMsg(@PathParam("param") String msg) {
        String output = "HEAD:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }
}

for testing you can use any tool like RestClient (http://code.google.com/p/rest-client/)

I want to vertical-align text in select box

just had this problem, but for mobile devices, mainly mobile firefox. The trick for me was to define a height, padding, line height, and finally box sizing, all on the select element. Not using your example numbers here, but for the sake of an example:

padding: 20px;
height: 60px;
line-height: 1;
-webkit-box-sizing: padding-box;
-moz-box-sizing: padding-box;
box-sizing: padding-box;

Is there a JavaScript strcmp()?

Javascript doesn't have it, as you point out.

A quick search came up with:

function strcmp ( str1, str2 ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Waldo Malqui Silva
    // +      input by: Steve Hilder
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: gorthaur
    // *     example 1: strcmp( 'waldo', 'owald' );
    // *     returns 1: 1
    // *     example 2: strcmp( 'owald', 'waldo' );
    // *     returns 2: -1

    return ( ( str1 == str2 ) ? 0 : ( ( str1 > str2 ) ? 1 : -1 ) );
}

from http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_strcmp/

Of course, you could just add localeCompare if needed:

if (typeof(String.prototype.localeCompare) === 'undefined') {
    String.prototype.localeCompare = function(str, locale, options) {
        return ((this == str) ? 0 : ((this > str) ? 1 : -1));
    };
}

And use str1.localeCompare(str2) everywhere, without having to worry wether the local browser has shipped with it. The only problem is that you would have to add support for locales and options if you care about that.

Matrix Transpose in Python

The "best" answer has already been submitted, but I thought I would add that you can use nested list comprehensions, as seen in the Python Tutorial.

Here is how you could get a transposed array:

def matrixTranspose( matrix ):
    if not matrix: return []
    return [ [ row[ i ] for row in matrix ] for i in range( len( matrix[ 0 ] ) ) ]

Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)

In the line of what Christian suggests, you could also do:

$('head').append("<style>.span::after{ content:'bar' }</style>");

How to set TLS version on apache HttpClient

Since this only came up hidden in comments, difficult to find as a solution:

You can use java -Dhttps.protocols=TLSv1,TLSv1.1, but you need to use also useSystemProperties()

client = HttpClientBuilder.create().useSystemProperties();

We use this setup in our system now as this enables us to set this only for some usage of the code. In our case we still have some Java 7 running and one API end point disallowed TLSv1, so we use java -Dhttps.protocols=TLSv1,TLSv1.1,TLSv1.2 to enable current TLS versions. Thanks @jebeaudet for pointing in this direction.

Alternative to header("Content-type: text/xml");

Now I see what you are doing. You cannot send output to the screen then change the headers. If you are trying to create an XML file of map marker and download them to display, they should be in separate files.

Take this

<?php
require("database.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','&lt;',$htmlStr);
$xmlStr=str_replace('>','&gt;',$xmlStr);
$xmlStr=str_replace('"','&quot;',$xmlStr);
$xmlStr=str_replace("'",'&#39;',$xmlStr);
$xmlStr=str_replace("&",'&amp;',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
  die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
  die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
  // ADD TO XML DOCUMENT NODE
  echo '<marker ';
  echo 'name="' . parseToXML($row['name']) . '" ';
  echo 'address="' . parseToXML($row['address']) . '" ';
  echo 'lat="' . $row['lat'] . '" ';
  echo 'lng="' . $row['lng'] . '" ';
  echo 'type="' . $row['type'] . '" ';
  echo '/>';
}
// End XML file
echo '</markers>';
?>

and place it in phpsqlajax_genxml.php so your javascript can download the XML file. You are trying to do too many things in the same file.

How do I jump to a closing bracket in Visual Studio Code?

The 'go to bracket' shortcut takes cursor before the bracket, unlike the 'end' key which takes after the bracket. WASDMap VSCode extension is very helpful for navigating and selecting text using WASD keys.

Convert string to date then format the date

    String start_dt = "2011-01-01"; // Input String

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); // Existing Pattern
    Date getStartDt = formatter.parse(start_dt); //Returns Date Format according to existing pattern

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd-yyyy");// New Pattern
    String formattedDate = simpleDateFormat.format(getStartDt); // Format given String to new pattern

    System.out.println(formattedDate); //outputs: 01-01-2011

How to change the background color of the options menu?

One thing to note that you guys are over-complicating the problem just like a lot of other posts! All you need to do is create drawable selectors with whatever backgrounds you need and set them to actual items. I just spend two hours trying your solutions (all suggested on this page) and none of them worked. Not to mention that there are tons of errors that essentially slow your performance in those try/catch blocks you have.

Anyways here is a menu xml file:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/m1"
          android:icon="@drawable/item1_selector"
          />
    <item android:id="@+id/m2"
          android:icon="@drawable/item2_selector"
          />
</menu>

Now in your item1_selector:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/item_highlighted" />
    <item android:state_selected="true" android:drawable="@drawable/item_highlighted" />
    <item android:state_focused="true" android:drawable="@drawable/item_nonhighlighted" />
    <item android:drawable="@drawable/item_nonhighlighted" />
</selector>

Next time you decide to go to the supermarket through Canada try google maps!

How to convert a string to JSON object in PHP

you can use this for example

$array = json_decode($string,true)

but validate the Json before. You can validate from http://jsonviewer.stack.hu/

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

OpenSSH cannot use PKCS#12 files out of the box. As others suggested, you must extract the private key in PEM format which gets you from the land of OpenSSL to OpenSSH. Other solutions mentioned here don’t work for me. I use OS X 10.9 Mavericks (10.9.3 at the moment) with “prepackaged” utilities (OpenSSL 0.9.8y, OpenSSH 6.2p2).

First, extract a private key in PEM format which will be used directly by OpenSSH:

openssl pkcs12 -in filename.p12 -clcerts -nodes -nocerts | openssl rsa > ~/.ssh/id_rsa

I strongly suggest to encrypt the private key with password:

openssl pkcs12 -in filename.p12 -clcerts -nodes -nocerts | openssl rsa -passout 'pass:Passw0rd!' > ~/.ssh/id_rsa

Obviously, writing a plain-text password on command-line is not safe either, so you should delete the last command from history or just make sure it doesn’t get there. Different shells have different ways. You can prefix your command with space to prevent it from being saved to history in Bash and many other shells. Here is also how to delete the command from history in Bash:

history -d $(history | tail -n 2 | awk 'NR == 1 { print $1 }')

Alternatively, you can use different way to pass a private key password to OpenSSL - consult OpenSSL documentation for pass phrase arguments.

Then, create an OpenSSH public key which can be added to authorized_keys file:

ssh-keygen -y -f ~/.ssh/id_rsa > ~/.ssh/id_rsa.pub

Android setOnClickListener method - How does it work?

That what manual says about setOnClickListener method is:

public void setOnClickListener (View.OnClickListener l)

Added in API level 1 Register a callback to be invoked when this view is clicked. If this view is not clickable, it becomes clickable.

Parameters

l View.OnClickListener: The callback that will run

And normally you have to use it like this

public class ExampleActivity extends Activity implements OnClickListener {
    protected void onCreate(Bundle savedValues) {
        ...
        Button button = (Button)findViewById(R.id.corky);
        button.setOnClickListener(this);
    }

    // Implement the OnClickListener callback
    public void onClick(View v) {
      // do something when the button is clicked
    }
    ...
}

Take a look at this lesson as well Building a Simple Calculator using Android Studio.

Get the client's IP address in socket.io

In 1.3.5 :

var clientIP = socket.handshake.headers.host;

package android.support.v4.app does not exist ; in Android studio 0.8

[for some reasons this answer is related to Eclipse, NOT Android Studio!]

Have you tried setting the support libraries to your class path? This link from the Android Developer's website has some info on how to do that.

Try following these steps from the website:

Create a library project based on the support library code:

  • Make sure you have downloaded the Android Support Library using the SDK Manager.
  • Create a library project and ensure the required JAR files are included in the project's build path:

    • Select File > Import.
    • Select Existing Android Code Into Workspace and click Next.
    • Browse to the SDK installation directory and then to the Support Library folder. For example, if you are adding the appcompat project, browse to /extras/android/support/v7/appcompat/.
    • Click Finish to import the project. For the v7 appcompat project, you should now see a new project titled android-support-v7-appcompat.
    • In the new library project, expand the libs/ folder, right-click each .jar file and select Build Path > Add to Build Path. For example, when creating the the v7 appcompat project, add both the android-support-v4.jar and android-support-v7-appcompat.jar files to the build path.
    • Right-click the library project folder and select Build Path > Configure Build Path.
    • In the Order and Export tab, check the .jar files you just added to the build path, so they are available to projects that depend on this library project. For example, the appcompat project requires you to export both the android-support-v4.jar and android-support-v7-appcompat.jar files.
    • Uncheck Android Dependencies.
    • Click OK to complete the changes.
  • You now have a library project for your selected Support Library that you can use with one or more application projects.

    • Add the library to your application project:
    • In the Project Explorer, right-click your project and select Properties.
    • In the category panel on the left side of the dialog, select Android.
    • In the Library pane, click the Add button.
    • Select the library project and click OK. For example, the appcompat project should be listed as android-support-v7-appcompat.
    • In the properties window, click OK.

Stored procedure return into DataSet in C# .Net

You can declare SqlConnection and SqlCommand instances at global level so that you can use it through out the class. Connection string is in Web.Config.

SqlConnection sqlConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["SqlConnector"].ConnectionString);
SqlCommand sqlcomm = new SqlCommand();

Now you can use the below method to pass values to Stored Procedure and get the DataSet.

public DataSet GetDataSet(string paramValue)
{
    sqlcomm.Connection = sqlConn;
    using (sqlConn)
    {
        try
        {
            using (SqlDataAdapter da = new SqlDataAdapter())
            {  
                // This will be your input parameter and its value
                sqlcomm.Parameters.AddWithValue("@ParameterName", paramValue);

                // You can retrieve values of `output` variables
                var returnParam = new SqlParameter
                {
                    ParameterName = "@Error",
                    Direction = ParameterDirection.Output,
                    Size = 1000
                };
                sqlcomm.Parameters.Add(returnParam);
                // Name of stored procedure
                sqlcomm.CommandText = "StoredProcedureName";
                da.SelectCommand = sqlcomm;
                da.SelectCommand.CommandType = CommandType.StoredProcedure;

                DataSet ds = new DataSet();
                da.Fill(ds);                            
            }
        }
        catch (SQLException ex)
        {
            Console.WriteLine("SQL Error: " + ex.Message);
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.Message);
        }
    }
    return new DataSet();
}

The following is the sample of connection string in config file

<connectionStrings>
    <add name="SqlConnector"
         connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=YourDatabaseName;User id=YourUserName;Password=YourPassword"
         providerName="System.Data.SqlClient" />
</connectionStrings>

How to make rectangular image appear circular with CSS

you can only make circle from square using border-radius.

border-radius doesn't increase or reduce heights nor widths.

Your request is to use only image tag , it is basicly not possible if tag is not a square.

If you want to use a blank image and set another in bg, it is going to be painfull , one background for each image to set.

Cropping can only be done if a wrapper is there to do so. inthat case , you have many ways to do it

What does the error "arguments imply differing number of rows: x, y" mean?

Though this isn't a DIRECT answer to your question, I just encountered a similar problem, and thought I'd mentioned it:

I had an instance where it was instantiating a new (no doubt very inefficent) record for data.frame (a result of recursive searching) and it was giving me the same error.

I had this:

return(
  data.frame(
    user_id = gift$email,
    sourced_from_agent_id = gift$source,
    method_used = method,
    given_to = gift$account,
    recurring_subscription_id = NULL,
    notes = notes,
    stringsAsFactors = FALSE
  )
)

turns out... it was the = NULL. When I switched to = NA, it worked fine. Just in case anyone else with a similar problem hits THIS post as I did.

How to print a groupby object

If you're simply looking for a way to display it, you could use describe():

grp = df.groupby['colName']
grp.describe()

This gives you a neat table.

Adding Google Translate to a web site

<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'ar', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

How to create a delay in Swift?

Try the following implementation in Swift 3.0

func delayWithSeconds(_ seconds: Double, completion: @escaping () -> ()) {
    DispatchQueue.main.asyncAfter(deadline: .now() + seconds) { 
        completion()
    }
}

Usage

delayWithSeconds(1) {
   //Do something
}

Android: android.content.res.Resources$NotFoundException: String resource ID #0x5

Just wanted to point out another reason this error can be thrown is if you defined a string resource for one translation of your app but did not provide a default string resource.

Example of the Issue:

As you can see below, I had a string resource for a Spanish string "get_started". It can still be referenced in code, but if the phone is not in Spanish it will have no resource to load and crash when calling getString().

values-es/strings.xml

<string name="get_started">SIGUIENTE</string>

Reference to resource

textView.setText(getString(R.string.get_started)

Logcat:

06-11 11:46:37.835    7007-7007/? E/AndroidRuntime? FATAL EXCEPTION: main
Process: com.app.test PID: 7007
android.content.res.Resources$NotFoundException: String resource ID #0x7f0700fd
        at android.content.res.Resources.getText(Resources.java:299)
        at android.content.res.Resources.getString(Resources.java:385)
        at com.juvomobileinc.tigousa.ui.signin.SignInFragment$4.onClick(SignInFragment.java:188)
        at android.view.View.performClick(View.java:4780)
        at android.view.View$PerformClick.run(View.java:19866)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Solution to the Issue

Preventing this is quite simple, just make sure that you always have a default string resource in values/strings.xml so that if the phone is in another language it will always have a resource to fall back to.

values/strings.xml

<string name="get_started">Get Started</string>

values-en/strings.xml

<string name="get_started">Get Started</string>

values-es/strings.xml

<string name="get_started">Siguiente</string>

values-de/strings.xml

<string name="get_started">Ioslegen</string>

Why do I have ORA-00904 even when the column is present?

It could be a case-sensitivity issue. Normally tables and columns are not case sensitive, but they will be if you use quotation marks. For example:

create table bad_design("goodLuckSelectingThisColumn" number);

How I can get web page's content and save it into the string variable

Webclient client = new Webclient();
string content = client.DownloadString(url);

Pass the URL of page who you want to get. You can parse the result using htmlagilitypack.

Html5 Full screen video

From CSS

video {
    position: fixed; right: 0; bottom: 0;
    min-width: 100%; min-height: 100%;
    width: auto; height: auto; z-index: -100;
    background: url(polina.jpg) no-repeat;
    background-size: cover;
}

How to initialize a private static const map in C++?

You could try this:

MyClass.h

class MyClass {
private:
    static const std::map<key, value> m_myMap; 
    static const std::map<key, value> createMyStaticConstantMap();
public:
    static std::map<key, value> getMyConstantStaticMap( return m_myMap );
}; //MyClass

MyClass.cpp

#include "MyClass.h"

const std::map<key, value> MyClass::m_myMap = MyClass::createMyStaticConstantMap();

const std::map<key, value> MyClass::createMyStaticConstantMap() {
    std::map<key, value> mMap;
    mMap.insert( std::make_pair( key1, value1 ) );
    mMap.insert( std::make_pair( key2, value2 ) );
    // ....
    mMap.insert( std::make_pair( lastKey, lastValue ) ); 
    return mMap;
} // createMyStaticConstantMap

With this implementation your classes constant static map is a private member and can be accessible to other classes using a public get method. Otherwise since it is constant and can not change, you can remove the public get method and move the map variable into the classes public section. I would however leave the createMap method private or protected if inheritance and or polymorphism is required. Here are some samples of use.

 std::map<key,value> m1 = MyClass::getMyMap();
 // then do work on m1 or
 unsigned index = some predetermined value
 MyClass::getMyMap().at( index ); // As long as index is valid this will 
 // retun map.second or map->second value so if in this case key is an
 // unsigned and value is a std::string then you could do
 std::cout << std::string( MyClass::getMyMap().at( some index that exists in map ) ); 
// and it will print out to the console the string locted in the map at this index. 
//You can do this before any class object is instantiated or declared. 

 //If you are using a pointer to your class such as:
 std::shared_ptr<MyClass> || std::unique_ptr<MyClass>
 // Then it would look like this:
 pMyClass->getMyMap().at( index ); // And Will do the same as above
 // Even if you have not yet called the std pointer's reset method on
 // this class object. 

 // This will only work on static methods only, and all data in static methods must be available first.

I had edited my original post, there was nothing wrong with the original code in which I posted for it compiled, built and ran correctly, it was just that my first version I presented as an answer the map was declared as public and the map was const but wasn't static.

php: Get html source code with cURL

Try http://php.net/manual/en/curl.examples-basic.php :)

<?php

$ch = curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt", "w");

curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);

$output = curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

As the documentation says:

The basic idea behind the cURL functions is that you initialize a cURL session using the curl_init(), then you can set all your options for the transfer via the curl_setopt(), then you can execute the session with the curl_exec() and then you finish off your session using the curl_close().

How do I compute derivative using Numpy?

The most straight-forward way I can think of is using numpy's gradient function:

x = numpy.linspace(0,10,1000)
dx = x[1]-x[0]
y = x**2 + 1
dydx = numpy.gradient(y, dx)

This way, dydx will be computed using central differences and will have the same length as y, unlike numpy.diff, which uses forward differences and will return (n-1) size vector.

no matching function for call to ' '

You are passing pointers (Complex*) when your function takes references (const Complex&). A reference and a pointer are entirely different things. When a function expects a reference argument, you need to pass it the object directly. The reference only means that the object is not copied.

To get an object to pass to your function, you would need to dereference your pointers:

Complex::distanta(*firstComplexNumber, *secondComplexNumber);

Or get your function to take pointer arguments.

However, I wouldn't really suggest either of the above solutions. Since you don't need dynamic allocation here (and you are leaking memory because you don't delete what you have newed), you're better off not using pointers in the first place:

Complex firstComplexNumber(81, 93);
Complex secondComplexNumber(31, 19);
Complex::distanta(firstComplexNumber, secondComplexNumber);

How to tell bash that the line continues on the next line

The character is a backslash \

From the bash manual:

The backslash character ‘\’ may be used to remove any special meaning for the next character read and for line continuation.

String.strip() in Python

strip removes the whitespace from the beginning and end of the string. If you want the whitespace, don't call strip.

In Linux, how to tell how much memory processes are using?

Use top or htop and pay attention to the "RES" (resident memory size) column.

What's the UIScrollView contentInset property for?

Content insets solve the problem of having content that goes underneath other parts of the User Interface and yet still remains reachable using scroll bars. In other words, the purpose of the Content Inset is to make the interaction area smaller than its actual area.

Consider the case where we have three logical areas of the screen:

TOP BUTTONS

TEXT

BOTTOM TAB BAR

and we want the TEXT to never appear transparently underneath the TOP BUTTONS, but we want the Text to appear underneath the BOTTOM TAB BAR and yet still allow scrolling so we could update the text sitting transparently under the BOTTOM TAB BAR.

Then we would set the top origin to be below the TOP BUTTONS, and the height to include the bottom of BOTTOM TAB BAR. To gain access to the Text sitting underneath the BOTTOM TAB BAR content we would set the bottom inset to be the height of the BOTTOM TAB BAR.

Without the inset, the scroller would not let you scroll up the content enough to type into it. With the inset, it is as if the content had extra "BLANK CONTENT" the size of the content inset. Blank text has been "inset" into the real "content" -- that's how I remember the concept.

How to style the menu items on an Android action bar

I did this way:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="actionMenuTextAppearance">@style/MenuTextAppearance</item>
    <item name="android:actionMenuTextAppearance">@style/MenuTextAppearance</item>
    <item name="actionMenuTextColor">@color/colorAccent</item>
</style>

<style name="MenuTextAppearance" >
    <item name="android:textAppearance">@android:style/TextAppearance.Large</item>
    <item name="android:textSize">20sp</item>
    <item name="android:textStyle">bold</item>
</style>

Reload nginx configuration

If your system has systemctl

sudo systemctl reload nginx

If your system supports service (using debian/ubuntu) try this

sudo service nginx reload

If not (using centos/fedora/etc) you can try the init script

sudo /etc/init.d/nginx reload

Build .so file from .c file using gcc command line

To generate a shared library you need first to compile your C code with the -fPIC (position independent code) flag.

gcc -c -fPIC hello.c -o hello.o

This will generate an object file (.o), now you take it and create the .so file:

gcc hello.o -shared -o libhello.so

EDIT: Suggestions from the comments:

You can use

gcc -shared -o libhello.so -fPIC hello.c

to do it in one step. – Jonathan Leffler

I also suggest to add -Wall to get all warnings, and -g to get debugging information, to your gcc commands. – Basile Starynkevitch

Checking Value of Radio Button Group via JavaScript?

Try:


var selectedVal;

for( i = 0; i < document.form_name.gender.length; i++ )
{
  if(document.form_name.gender[i].checked)
    selectedVal = document.form_name.gender[i].value; //male or female
    break;
  }
}

Debug vs Release in CMake

If you want to build a different configuration without regenerating if using you can also run cmake --build {$PWD} --config <cfg> For multi-configuration tools, choose <cfg> ex. Debug, Release, MinSizeRel, RelWithDebInfo

https://cmake.org/cmake/help/v2.8.11/cmake.html#opt%3a--builddir

Where can I set environment variables that crontab will use?

  • Set Globally env
sudo sh -c "echo MY_GLOBAL_ENV_TO_MY_CURRENT_DIR=$(pwd)" >> /etc/environment"
  • Add scheduled job to start a script
crontab -e

  */5 * * * * sh -c "$MY_GLOBAL_ENV_TO_MY_CURRENT_DIR/start.sh"

=)

How to construct a REST API that takes an array of id's for the resources

As much as I prefer this approach:-

    api.com/users?id=id1,id2,id3,id4,id5

The correct way is

    api.com/users?ids[]=id1&ids[]=id2&ids[]=id3&ids[]=id4&ids[]=id5

or

    api.com/users?ids=id1&ids=id2&ids=id3&ids=id4&ids=id5

This is how rack does it. This is how php does it. This is how node does it as well...

Programmatically set TextBlock Foreground Color

Foreground needs a Brush, so you can use

textBlock.Foreground = Brushes.Navy;

If you want to use the color from RGB or ARGB then

textBlock.Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(100, 255, 125, 35)); 

or

textBlock.Foreground = new System.Windows.Media.SolidColorBrush(Colors.Navy); 

To get the Color from Hex

textBlock.Foreground = new System.Windows.Media.SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFDFD991")); 

Counting array elements in Python

The method len() returns the number of elements in the list.

Syntax:

len(myArray)

Eg:

myArray = [1, 2, 3]
len(myArray)

Output:

3

Run git pull over all subdirectories

The mr utility (a.k.a., myrepos) provides an outstanding solution to this very problem. Install it using your favorite package manager, or just grab the mr script directly from github and put it in $HOME/bin or somewhere else on your PATH. Then, cd to the parent plugins folder shared by these repos and create a basic .mrconfig file with contents similar to the following (adjusting the URLs as needed):

# File: .mrconfig
[cms]
checkout = git clone 'https://<username>@github.com/<username>/cms' 'cms'

[admin]
checkout = git clone 'https://<username>@github.com/<username>/admin' 'admin'

[chart]
checkout = git clone 'https://<username>@github.com/<username>/chart' 'chart'

After that, you can run mr up from the top level plugins folder to pull updates from each repository. (Note that this will also do the initial clone if the target working copy doesn't yet exist.) Other commands you can execute include mr st, mr push, mr log, mr diff, etc—run mr help to see what's possible. There's a mr run command that acts as a pass-through, allowing you to access VCS commands not directly suported by mr itself (e.g., mr run git tag STAGING_081220015). And you can even create your own custom commands that execute arbitrary bits of shell script targeting all repos!

mr is an extremely useful tool for dealing with multiple repos. Since the plugins folder is in your home directory, you might also be interested in vcsh. Together with mr, it provides a powerful mechanism for managing all of your configuration files. See this blog post by Thomas Ferris Nicolaisen for an overview.

Android: set view style programmatically

if inside own custom view : val editText = TextInputEditText(context, attrs, defStyleAttr)

Running multiple async tasks and waiting for them all to complete

Both answers didn't mention the awaitable Task.WhenAll:

var task1 = DoWorkAsync();
var task2 = DoMoreWorkAsync();

await Task.WhenAll(task1, task2);

The main difference between Task.WaitAll and Task.WhenAll is that the former will block (similar to using Wait on a single task) while the latter will not and can be awaited, yielding control back to the caller until all tasks finish.

More so, exception handling differs:

Task.WaitAll:

At least one of the Task instances was canceled -or- an exception was thrown during the execution of at least one of the Task instances. If a task was canceled, the AggregateException contains an OperationCanceledException in its InnerExceptions collection.

Task.WhenAll:

If any of the supplied tasks completes in a faulted state, the returned task will also complete in a Faulted state, where its exceptions will contain the aggregation of the set of unwrapped exceptions from each of the supplied tasks.

If none of the supplied tasks faulted but at least one of them was canceled, the returned task will end in the Canceled state.

If none of the tasks faulted and none of the tasks were canceled, the resulting task will end in the RanToCompletion state. If the supplied array/enumerable contains no tasks, the returned task will immediately transition to a RanToCompletion state before it's returned to the caller.

How do I modify fields inside the new PostgreSQL JSON datatype?

what do you think about this solution ?

It will add the new value or update an existing one.

Edit: edited to make it work with null and empty object

Edit2: edited to make it work with object in the object...

create or replace function updateJsonb(object1 json, object2 json)
returns jsonb
language plpgsql
as
$$
declare
    result jsonb;
    tempObj1 text;
    tempObj2 text;

begin
    tempObj1 = substr(object1::text, 2, length(object1::text) - 2); --remove the first { and last }
    tempObj2 = substr(object2::text, 2, length(object2::text) - 2); --remove the first { and last }

    IF object1::text != '{}' and object1::text != 'null' and object1::text != '[]' THEN
        result = ('{' || tempObj1 || ',' || tempObj2 || '}')::jsonb;
    ELSE
        result = ('{' || tempObj2 || '}')::jsonb;
    END IF;
    return result;
end;
$$;

usage:

update table_name
set data = updatejsonb(data, '{"test": "ok"}'::json)

How to check if there exists a process with a given pid in Python?

Combining Giampaolo Rodolà's answer for POSIX and mine for Windows I got this:

import os
if os.name == 'posix':
    def pid_exists(pid):
        """Check whether pid exists in the current process table."""
        import errno
        if pid < 0:
            return False
        try:
            os.kill(pid, 0)
        except OSError as e:
            return e.errno == errno.EPERM
        else:
            return True
else:
    def pid_exists(pid):
        import ctypes
        kernel32 = ctypes.windll.kernel32
        SYNCHRONIZE = 0x100000

        process = kernel32.OpenProcess(SYNCHRONIZE, 0, pid)
        if process != 0:
            kernel32.CloseHandle(process)
            return True
        else:
            return False

Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays'

Remember to pipe Observables to async, like *ngFor item of items$ | async, where you are trying to *ngFor item of items$ where items$ is obviously an Observable because you notated it with the $ similar to items$: Observable<IValuePair>, and your assignment may be something like this.items$ = this.someDataService.someMethod<IValuePair>() which returns an Observable of type T.

Adding to this... I believe I have used notation like *ngFor item of (items$ | async)?.someProperty

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

Vacuousness

I don't recommend trying to define or use a function which computes whether any value in the whole world is empty. What does it really mean to be "empty"? If I have `let human = { name: 'bob', stomach: 'empty' }`, should `isEmpty(human)` return `true`? If I have `let reg = new RegExp('');`, should `isEmpty(reg)` return `true`? What about `isEmpty([ null, null, null, null ])` - this list only contains emptiness, so is the list itself empty? I want to put forward here some notes on "vacuousness" (an intentionally obscure word, to avoid pre-existing associations) in javascript - and I want to argue that "vacuousness" in javascript values should never be dealt with generically.

Truthiness/Falsiness

For deciding how to determine the "vacuousness" of values, we need to accomodate javascript's inbuilt, inherent sense of whether values are "truthy" or "falsy". Naturally, `null` and `undefined` are both "falsy". Less naturally, the number `0` (and no other number except `NaN`) is also "falsy". Least naturally: `''` is falsy, but `[]` and `{}` (and `new Set()`, and `new Map()`) are truthy - although they all seem equally vacuous!

Null vs Undefined

There is also some discussion concerning `null` vs `undefined` - do we really need both in order to express vacuousness in our programs? I personally avoid ever having the letters u, n, d, e, f, i, n, e, d appear in my code in that order. I always use `null` to signify "vacuousness". Again, though, we need to accomodate javascript's inherent sense of how `null` and `undefined` differ:
  • Trying to access a non-existent property gives undefined
  • Omitting a parameter when calling a function results in that parameter receiving undefined:

_x000D_
_x000D_
let f = a => a;
console.log(f('hi'));
console.log(f());
_x000D_
_x000D_
_x000D_

  • Parameters with default values receive the default only when given undefined, not null:

_x000D_
_x000D_
let f = (v='hello') => v;
console.log(f(null));
console.log(f(undefined));
_x000D_
_x000D_
_x000D_


Non-generic Vacuousness

I believe that vacuousness should never be dealt with in a generic fashion. We should instead always have the rigour to get more information about our data before determining if it is vacuous - I mainly do this by checking what type of data I'm dealing with:

_x000D_
_x000D_
let isType = (value, Cls) => {
  // Intentional use of loose comparison operator detects `null`
  // and `undefined`, and nothing else!
  return value != null && Object.getPrototypeOf(value).constructor === Cls;
};
_x000D_
_x000D_
_x000D_

Note that this function ignores polymorphism - it expects value to be a direct instance of Cls, and not an instance of a subclass of Cls. I avoid instanceof for two main reasons:

  • ([] instanceof Object) === true ("An Array is an Object")
  • ('' instanceof String) === false ("A String is not a String")

Note that Object.getPrototypeOf is used to avoid a case like let v = { constructor: String }; The isType function still returns correctly for isType(v, String) (false), and isType(v, Object) (true).

Overall, I recommend using this isType function along with these tips:

  • Minimize the amount of code processing values of unknown type. E.g., for let v = JSON.parse(someRawValue);, our v variable is now of unknown type. As early as possible, we should limit our possibilities. The best way to do this can be by requiring a particular type: e.g. if (!isType(v, Array)) throw new Error('Expected Array'); - this is a really quick and expressive way to remove the generic nature of v, and ensure it's always an Array. Sometimes, though, we need to allow v to be of multiple types. In those cases, we should create blocks of code where v is no longer generic, as early as possible:

_x000D_
_x000D_
if (isType(v, String)) {
  /* v isn't generic in this block - It's a String! */
} else if (isType(v, Number)) {
  /* v isn't generic in this block - It's a Number! */
} else if (isType(v, Array)) {
  /* v isn't generic in this block - it's an Array! */
} else {
  throw new Error('Expected String, Number, or Array');
}
_x000D_
_x000D_
_x000D_

  • Always use "whitelists" for validation. If you require a value to be, e.g., a String, Number, or Array, check for those 3 "white" possibilities, and throw an Error if none of the 3 are satisfied. We should be able to see that checking for "black" possibilities isn't very useful: Say we write if (v === null) throw new Error('Null value rejected'); - this is great for ensuring that null values don't make it through, but if a value does make it through, we still know hardly anything about it. A value v which passes this null-check is still VERY generic - it's anything but null! Blacklists hardly dispell generic-ness.
  • Unless a value is null, never consider "a vacuous value". Instead, consider "an X which is vacuous". Essentially, never consider doing anything like if (isEmpty(val)) { /* ... */ } - no matter how that isEmpty function is implemented (I don't want to know...), it isn't meaningful! And it's way too generic! Vacuousness should only be calculated with knowledge of val's type. Vacuousness-checks should look like this:
    • "A string, with no chars": if (isType(val, String) && val.length === 0) ...

    • "An Object, with 0 props": if (isType(val, Object) && Object.entries(val).length === 0) ...

    • "A number, equal or less than zero": if (isType(val, Number) && val <= 0) ...

    • "An Array, with no items": if (isType(val, Array) && val.length === 0) ...

    • The only exception is when null is used to signify certain functionality. In this case it's meaningful to say: "A vacuous value": if (val === null) ...

Bootstrap NavBar with left, center or right aligned items

I needed something similar (left, center and right aligned items), but with ability to mark centered items as active. What worked for me was:

http://www.bootply.com/CSI2KcCoEM

<nav class="navbar navbar-default" role="navigation">
  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>    
  </div>
  <div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
      <li class="navbar-left"><a href="#">Left 1</a></li>
      <li class="navbar-left"><a href="#">Left 2</a></li>
      <li class="active"><a href="#">Center 1</a></li>
      <li><a href="#">Center 2</a></li>
      <li><a href="#">Center 3</a></li>
      <li class="navbar-right"><a href="#">Right 1</a></li>
      <li class="navbar-right"><a href="#">Right 2</a></li>
    </ul>
  </div>
</nav>

CSS:

@media (min-width: 768px) {
  .navbar-nav {
    width: 100%;
    text-align: center;
  }
  .navbar-nav > li {
    float: none;
    display: inline-block;
  }
  .navbar-nav > li.navbar-right {
    float: right !important;
  }
}

How to detect if numpy is installed

I think you also may use this

>> import numpy
>> print numpy.__version__

Update: for python3 use print(numpy.__version__)

MySQL select query with multiple conditions

also you can use "AND" instead of "OR" if you want both attributes to be applied.

select * from tickets where (assigned_to='1') and (status='open') order by created_at desc;

Why is using onClick() in HTML a bad practice?

Two more reasons not to use inline handlers:

They can require tedious quote escaping issues

Given an arbitrary string, if you want to be able to construct an inline handler that calls a function with that string, for the general solution, you'll have to escape the attribute delimiters (with the associated HTML entity), and you'll have to escape the delimiter used for the string inside the attribute, like the following:

_x000D_
_x000D_
const str = prompt('What string to display on click?', 'foo\'"bar');
const escapedStr = str
  // since the attribute value is going to be using " delimiters,
  // replace "s with their corresponding HTML entity:
  .replace(/"/g, '&quot;')
  // since the string literal inside the attribute is going to delimited with 's,
  // escape 's:
  .replace(/'/g, "\\'");
  
document.body.insertAdjacentHTML(
  'beforeend',
  '<button onclick="alert(\'' + escapedStr + '\')">click</button>'
);
_x000D_
_x000D_
_x000D_

That's incredibly ugly. From the above example, if you didn't replace the 's, a SyntaxError would result, because alert('foo'"bar') is not valid syntax. If you didn't replace the "s, then the browser would interpret it as an end to the onclick attribute (delimited with "s above), which would also be incorrect.

If one habitually uses inline handlers, one would have to make sure to remember do something similar to the above (and do it right) every time, which is tedious and hard to understand at a glance. Better to avoid inline handlers entirely so that the arbitrary string can be used in a simple closure:

_x000D_
_x000D_
const str = prompt('What string to display on click?', 'foo\'"bar');
const button = document.body.appendChild(document.createElement('button'));
button.textContent = 'click';
button.onclick = () => alert(str);
_x000D_
_x000D_
_x000D_

Isn't that so much nicer?


The scope chain of an inline handler is extremely peculiar

What do you think the following code will log?

_x000D_
_x000D_
let disabled = true;
_x000D_
<form>
  <button onclick="console.log(disabled);">click</button>
</form>
_x000D_
_x000D_
_x000D_

Try it, run the snippet. It's probably not what you were expecting. Why does it produce what it does? Because inline handlers run inside with blocks. The above code is inside three with blocks: one for the document, one for the <form>, and one for the <button>:

_x000D_
_x000D_
let disabled = true;
_x000D_
<form>
  <button onclick="console.log(disabled);">click</button>
</form>
_x000D_
_x000D_
_x000D_

enter image description here

Since disabled is a property of the button, referencing disabled inside the inline handler refers to the button's property, not the outer disabled variable. This is quite counter-intuitive. with has many problems: it can be the source of confusing bugs and significantly slows down code. It isn't even permitted at all in strict mode. But with inline handlers, you're forced to run the code through withs - and not just through one with, but through multiple nested withs. It's crazy.

with should never be used in code. Because inline handlers implicitly require with along with all its confusing behavior, inline handlers should be avoided as well.

How to have Ellipsis effect on Text

To Achieve ellipses for the text use the Text property numberofLines={1} which will automatically truncate the text with an ellipsis you can specify the ellipsizeMode as "head", "middle", "tail" or "clip" By default it is tail

https://reactnative.dev/docs/text#ellipsizemode

git recover deleted file where no commit was made after the delete

If you have installed ToroiseGIT then just select "Revert..." menu item for parent folder popup-menu.

How to turn off word wrapping in HTML?

I wonder why you find as solution the "white-space" with "nowrap" or "pre", it is not doing the correct behaviour: you force your text in a single line! The text should break lines, but not break words as default. This is caused by some css attributes: word-wrap, overflow-wrap, word-break, and hyphens. So you can have either:

word-break: break-all;
word-wrap: break-word;
overflow-wrap: break-word;
-webkit-hyphens: auto;
-moz-hyphens: auto;
-ms-hyphens: auto;
hyphens: auto;

So the solution is remove them, or override them with "unset" or "normal":

word-break: unset;
word-wrap: unset;
overflow-wrap: unset;
-webkit-hyphens: unset;
-moz-hyphens: unset;
-ms-hyphens: unset;
hyphens: unset;

UPDATE: i provide also proof with JSfiddle: https://jsfiddle.net/azozp8rr/

How do you check if a certain index exists in a table?

You can do it using a straight forward select like this:

SELECT * 
FROM sys.indexes 
WHERE name='YourIndexName' AND object_id = OBJECT_ID('Schema.YourTableName')

Python unicode equal comparison failed

You may use the == operator to compare unicode objects for equality.

>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>> 
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>> 

But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode object to a str object, like so:

>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False

See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.

Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.

I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."

Spring Boot JPA - configuring auto reconnect

In case anyone is using custom DataSource

@Bean(name = "managementDataSource")
@ConfigurationProperties(prefix = "management.datasource")
public DataSource dataSource() {
    return DataSourceBuilder.create().build();
}

Properties should look like the following. Notice the @ConfigurationProperties with prefix. The prefix is everything before the actual property name

management.datasource.test-on-borrow=true
management.datasource.validation-query=SELECT 1

A reference for Spring Version 1.4.4.RELEASE

JavaScript string and number conversion

You can do it like this:

// step 1 
var one = "1" + "2" + "3"; // string value "123"

// step 2
var two = parseInt(one); // integer value 123

// step 3
var three = 123 + 100; // integer value 223

// step 4
var four = three.toString(); // string value "223"

CSS: how to get scrollbars for div inside container of fixed height

FWIW, here is my approach = a simple one that works for me:

<div id="outerDivWrapper">
   <div id="outerDiv">
      <div id="scrollableContent">
blah blah blah
      </div>
   </div>
</div>

html, body {
   height: 100%;
   margin: 0em;
}

#outerDivWrapper, #outerDiv {
   height: 100%;
   margin: 0em;
}

#scrollableContent {
   height: 100%;
   margin: 0em;
   overflow-y: auto;
}

How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?

NSDictionary   *dict = [NSDictionary dictionaryWithObject: @"String" forKey: @"Test"];
NSMutableDictionary *anotherDict = [NSMutableDictionary dictionary];

[anotherDict setObject: dict forKey: "sub-dictionary-key"];
[anotherDict setObject: @"Another String" forKey: @"another test"];

NSLog(@"Dictionary: %@, Mutable Dictionary: %@", dict, anotherDict);

// now we can save these to a file
NSString   *savePath = [@"~/Documents/Saved.data" stringByExpandingTildeInPath];
[anotherDict writeToFile: savePath atomically: YES];

//and restore them
NSMutableDictionary  *restored = [NSDictionary dictionaryWithContentsOfFile: savePath];

How can I make a clickable link in an NSAttributedString?

A quick addition to Duncan C's original description vis-á-vie IB behavior. He writes: "It's trivial to make hyperlinks clickable in a UITextView. You just set the "detect links" checkbox on the view in IB, and it detects http links and turns them into hyperlinks."

My experience (at least in xcode 7) is that you also have to unclick the "Editable" behavior for the urls to be detected & clickable.

The executable gets signed with invalid entitlements in Xcode

Another thing to check - make sure you have the correct entities selected in both

Targets -> Your Target -> Build Settings -> Signing

and

Project -> Your Project -> Build Settings -> Code Signing Entity

I got this message when I had a full dev profile selected in one and a different (non-developer) Apple ID selected in the other, even with no entitlements requested in the app.

Vertically center text in a 100% height div?

Since it is absolutely positioned you can use top: 50% to vertically align it in the center.

But then you run into the issue of the page being bigger than you want it to be. For that you can use the overflow: hidden for the parent div. This is what I used to create the same effect:

The CSS:

div.parent {
    width: 100%;
    height: 300px;
    position: relative;
    overflow: hidden;
}
div.parent div.absolute {
    position: absolute;
    top: 50%;
    height: 300px;
}

The HTML:

<div class="parent">
    <div class="absolute">This is vertically center aligned</div>
</div>

Increasing the JVM maximum heap size for memory intensive applications

Below conf works for me:

JAVA_HOME=/JDK1.7.51-64/jdk1.7.0_51/
PATH=/JDK1.7.51-64/jdk1.7.0_51/bin:$PATH
export PATH
export JAVA_HOME

JVM_ARGS="-d64 -Xms1024m -Xmx15360m -server"

/JDK1.7.51-64/jdk1.7.0_51/bin/java $JVM_ARGS -jar `dirname $0`/ApacheJMeter.jar "$@"

How to add one column into existing SQL Table

What about something like:

Alter Table Products
Add LastUpdate varchar(200) null

Do you need something more complex than this?

Uncaught TypeError: Cannot set property 'value' of null

It seems to be this function

h_url=document.getElementById("u").value;

You can help yourself using some 'console.log' to see what object is Null.

Convert wchar_t to char

one could also convert wchar_t --> wstring --> string --> char

wchar_t wide;
wstring wstrValue;
wstrValue[0] = wide

string strValue;
strValue.assign(wstrValue.begin(), wstrValue.end());  // convert wstring to string

char char_value = strValue[0];

IE Enable/Disable Proxy Settings via Registry

modifying the proxy value under

[HKEY_USERS\<your SID>\Software\Microsoft\Windows\CurrentVersion\Internet Settings]

doesnt need to restart ie

Looping through a Scripting.Dictionary using index/item number

According to the documentation of the Item property:

Sets or returns an item for a specified key in a Dictionary object.

In your case, you don't have an item whose key is 1 so doing:

s = d.Item(i)

actually creates a new key / value pair in your dictionary, and the value is empty because you have not used the optional newItem argument.

The Dictionary also has the Items method which allows looping over the indices:

a = d.Items
For i = 0 To d.Count - 1
    s = a(i)
Next i

How to perform a for-each loop over all the files under a specified path?

Here is a better way to loop over files as it handles spaces and newlines in file names:

#!/bin/bash

find . -type f -iname "*.txt" -print0 | while IFS= read -r -d $'\0' line; do
    echo "$line"
    ls -l "$line"    
done

Get Category name from Post ID

echo '<p>'. get_the_category( $id )[0]->name .'</p>';

is what you maybe looking for.

How can I limit possible inputs in a HTML5 "number" element?

<input type="number" onchange="this.value=Math.max(Math.min(this.value, 100), -100);" />

or if you want to be able enter nothing

<input type="number" onchange="this.value=this.value ? Math.max(Math.min(this.value,100),-100) : null" />

Export and import table dump (.sql) using pgAdmin

If you have Git bash installed, you can do something like this:

/c/Program\ Files\ \(x86\)/PostgreSQL/9.3/bin/psql -U <pg_role_name> -d <pg_database_name> < <path_to_your>.sql

jQuery loop over JSON result from AJAX Success?

$each will work.. Another option is jQuery Ajax Callback for array result

function displayResultForLog(result) {
  if (result.hasOwnProperty("d")) {
    result = result.d
  }

  if (result !== undefined && result != null) {
    if (result.hasOwnProperty('length')) {
      if (result.length >= 1) {
        for (i = 0; i < result.length; i++) {
          var sentDate = result[i];
        }
      } else {
        $(requiredTable).append('Length is 0');
      }
    } else {
      $(requiredTable).append('Length is not available.');
    }

  } else {
    $(requiredTable).append('Result is null.');
  }
}

WebAPI Multiple Put/Post parameters

We passed Json object by HttpPost method, and parse it in dynamic object. it works fine. this is sample code:

webapi:

[HttpPost]
public string DoJson2(dynamic data)
{
   //whole:
   var c = JsonConvert.DeserializeObject<YourObjectTypeHere>(data.ToString()); 

   //or 
   var c1 = JsonConvert.DeserializeObject< ComplexObject1 >(data.c1.ToString());

   var c2 = JsonConvert.DeserializeObject< ComplexObject2 >(data.c2.ToString());

   string appName = data.AppName;
   int appInstanceID = data.AppInstanceID;
   string processGUID = data.ProcessGUID;
   int userID = data.UserID;
   string userName = data.UserName;
   var performer = JsonConvert.DeserializeObject< NextActivityPerformers >(data.NextActivityPerformers.ToString());

   ...
}

The complex object type could be object, array and dictionary.

ajaxPost:
...
Content-Type: application/json,
data: {"AppName":"SamplePrice",
       "AppInstanceID":"100",
       "ProcessGUID":"072af8c3-482a-4b1c??-890b-685ce2fcc75d",
       "UserID":"20",
       "UserName":"Jack",
       "NextActivityPerformers":{
           "39??c71004-d822-4c15-9ff2-94ca1068d745":[{
                 "UserID":10,
                 "UserName":"Smith"
           }]
       }}
...

What is the difference between connection and read timeout for sockets?

  1. What is the difference between connection and read timeout for sockets?

The connection timeout is the timeout in making the initial connection; i.e. completing the TCP connection handshake. The read timeout is the timeout on waiting to read data1. If the server (or network) fails to deliver any data <timeout> seconds after the client makes a socket read call, a read timeout error will be raised.

  1. What does connection timeout set to "infinity" mean? In what situation can it remain in an infinitive loop? and what can trigger that the infinity-loop dies?

It means that the connection attempt can potentially block for ever. There is no infinite loop, but the attempt to connect can be unblocked by another thread closing the socket. (A Thread.interrupt() call may also do the trick ... not sure.)

  1. What does read timeout set to "infinity" mean? In what situation can it remain in an infinite loop? What can trigger that the infinite loop to end?

It means that a call to read on the socket stream may block for ever. Once again there is no infinite loop, but the read can be unblocked by a Thread.interrupt() call, closing the socket, and (of course) the other end sending data or closing the connection.


1 - It is not ... as one commenter thought ... the timeout on how long a socket can be open, or idle.

Javascript decoding html entities

Using jQuery the easiest will be:

var text = '&lt;p&gt;name&lt;/p&gt;&lt;p&gt;&lt;span style="font-size:xx-small;"&gt;ajde&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;em&gt;da&lt;/em&gt;&lt;/p&gt;';

var output = $("<div />").html(text).text();
console.log(output);

DEMO: http://jsfiddle.net/LKGZx/

How to remove leading and trailing zeros in a string? Python

Assuming you have other data types (and not only string) in your list try this. This removes trailing and leading zeros from strings and leaves other data types untouched. This also handles the special case s = '0'

e.g

a = ['001', '200', 'akdl00', 200, 100, '0']

b = [(lambda x: x.strip('0') if isinstance(x,str) and len(x) != 1 else x)(x) for x in a]

b
>>>['1', '2', 'akdl', 200, 100, '0']

String formatting in Python 3

That line works as-is in Python 3.

>>> sys.version
'3.2 (r32:88445, Oct 20 2012, 14:09:29) \n[GCC 4.5.2]'
>>> "(%d goals, $%d)" % (self.goals, self.penalties)
'(1 goals, $2)'

How can I get name of element with jQuery?

var name = $('#myElement').attr('name');

Best way to script remote SSH commands in Batch (Windows)

As an alternative option you could install OpenSSH http://www.mls-software.com/opensshd.html and then simply ssh user@host -pw password -m command_run

Edit: After a response from user2687375 when installing, select client only. Once this is done you should be able to initiate SSH from command.

Then you can create an ssh batch script such as

ECHO OFF
CLS
:MENU
ECHO.
ECHO ........................
ECHO SSH servers
ECHO ........................
ECHO.
ECHO 1 - Web Server 1
ECHO 2 - Web Server 2
ECHO E - EXIT
ECHO.

SET /P M=Type 1 - 2 then press ENTER:
IF %M%==1 GOTO WEB1
IF %M%==2 GOTO WEB2
IF %M%==E GOTO EOF

REM ------------------------------
REM SSH Server details
REM ------------------------------

:WEB1
CLS
call ssh [email protected]
cmd /k

:WEB2
CLS
call ssh [email protected]
cmd /k

LINQ query to select top five

var list = (from t in ctn.Items
           where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
           orderby t.Delivery.SubmissionDate
           select t).Take(5);

How can I measure the similarity between two images?

Well a really base-level method to use could go through every pixel colour and compare it with the corresponding pixel colour on the second image - but that's a probably a very very slow solution.

How to create a list of objects?

if my_list is the list that you want to store your objects in it and my_object is your object wanted to be stored, use this structure:

my_list.append(my_object)

what's data-reactid attribute in html?

The data-reactid attribute is a custom attribute used so that React can uniquely identify its components within the DOM.

This is important because React applications can be rendered at the server as well as the client. Internally React builds up a representation of references to the DOM nodes that make up your application (simplified version is below).

{
  id: '.1oqi7occu80',
  node: DivRef,
  children: [
    {
      id: '.1oqi7occu80.0',
      node: SpanRef,
      children: [
        {
          id: '.1oqi7occu80.0.0',
          node: InputRef,
          children: []
        }
      ]
    }
  ]
}

There's no way to share the actual object references between the server and the client and sending a serialized version of the entire component tree is potentially expensive. When the application is rendered at the server and React is loaded at the client, the only data it has are the data-reactid attributes.

<div data-reactid='.loqi70ccu80'>
  <span data-reactid='.loqi70ccu80.0'>
    <input data-reactid='.loqi70ccu80.0' />
  </span>
</div>

It needs to be able to convert that back into the data structure above. The way it does that is with the unique data-reactid attributes. This is called inflating the component tree.

You might also notice that if React renders at the client-side, it uses the data-reactid attribute, even though it doesn't need to lose its references. In some browsers, it inserts your application into the DOM using .innerHTML then it inflates the component tree straight away, as a performance boost.

The other interesting difference is that client-side rendered React ids will have an incremental integer format (like .0.1.4.3), whereas server-rendered ones will be prefixed with a random string (such as .loqi70ccu80.1.4.3). This is because the application might be rendered across multiple servers and it's important that there are no collisions. At the client-side, there is only one rendering process, which means counters can be used to ensure unique ids.

React 15 uses document.createElement instead, so client rendered markup won't include these attributes anymore.

Getting "error": "unsupported_grant_type" when trying to get a JWT by calling an OWIN OAuth secured Web Api via Postman

With Postman, select Body tab and choose the raw option and type the following:

grant_type=password&username=yourusername&password=yourpassword

@viewChild not working - cannot read property nativeElement of undefined

it just simple :import this directory

import {Component, Directive, Input, ViewChild} from '@angular/core';

How to use local docker images with Minikube?

This Answer isnt limited to minikube!

Use a local registry:

docker run -d -p 5000:5000 --restart=always --name registry registry:2

Now tag your image properly:

docker tag ubuntu localhost:5000/ubuntu

Note that localhost should be changed to dns name of the machine running registry container.

Now push your image to local registry:

docker push localhost:5000/ubuntu

You should be able to pull it back:

docker pull localhost:5000/ubuntu

Now change your yaml file to use local registry.

Think about mounting volume at appropriate location to persist the images on registry.

update:

as Eli stated, you'll need to add the local registry as insecure in order to use http (may not apply when using localhost but does apply if using the local hostname)

Don't use http in production, make the effort for securing things up.

Proper way to initialize C++ structs

From what you've told us it does appear to be a false positive in valgrind. The new syntax with () should value-initialize the object, assuming it is POD.

Is it possible that some subpart of your struct isn't actually POD and that's preventing the expected initialization? Are you able to simplify your code into a postable example that still flags the valgrind error?

Alternately perhaps your compiler doesn't actually value-initialize POD structures.

In any case probably the simplest solution is to write constructor(s) as needed for the struct/subparts.

Asp.Net MVC with Drop Down List, and SelectListItem Assistance

You have a view model to which your view is strongly typed => use strongly typed helpers:

<%= Html.DropDownListFor(
    x => x.SelectedAccountId, 
    new SelectList(Model.Accounts, "Value", "Text")
) %>

Also notice that I use a SelectList for the second argument.

And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:

public ActionResult AccountTransaction()
{
    var accounts = Services.AccountServices.GetAccounts(false);
    var viewModel = new AccountTransactionView
    {
        Accounts = accounts.Select(a => new SelectListItem
        {
            Text = a.Description,
            Value = a.AccountId.ToString()
        })
    };
    return View(viewModel);
}

How to compare DateTime without time via LINQ?

Try this code

var today = DateTime.Today;
var q = db.Games.Where(t => DbFunctions.TruncateTime(t.StartDate) <= today);

UEFA/FIFA scores API

You can find stats-dot-com - personally I think their are better than opta. ESPN seems don't provide data in full and do not provide live data feeds (unfortunatelly).

We've been seeking for official data feed providing for our fantasy games (solutionsforfantasysport.com) and still staying with stats-com mainly (used opta, datafactory as well)

Referencing another schema in Mongoose

Late reply, but adding that Mongoose also has the concept of Subdocuments

With this syntax, you should be able to reference your userSchema as a type in your postSchema like so:

var userSchema = new Schema({
    twittername: String,
    twitterID: Number,
    displayName: String,
    profilePic: String,
});

var postSchema = new Schema({
    name: String,
    postedBy: userSchema,
    dateCreated: Date,
    comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});

Note the updated postedBy field with type userSchema.

This will embed the user object within the post, saving an extra lookup required by using a reference. Sometimes this could be preferable, other times the ref/populate route might be the way to go. Depends on what your application is doing.

Can I mask an input text in a bat file?

You can set the forground color to black such:

:: see https://stackoverflow.com/questions/33293220/what-is-the-fastest-color-function-in-batch
@echo off
for /F %%a in ('echo prompt $E ^| cmd') do set "ESC=%%a"
set color_white=%ESC%[37m
set color_black=%ESC%[30m
echo(
set /p user=Username:
set /p pass=password:%color_black%
echo %color_white%
echo blablablba

Enjoy!!! C.

Excel formula to get cell color

Color is not data.

The Get.cell technique has flaws.

  1. It does not update as soon as the cell color changes, but only when the cell (or the sheet) is recalculated.
  2. It does not have sufficient numbers for the millions of colors that are available in modern Excel. See the screenshot and notice how the different intensities of yellow or purple all have the same number.

enter image description here

That does not surprise, since the Get.cell uses an old XML command, i.e. a command from the macro language Excel used before VBA was introduced. At that time, Excel colors were limited to less than 60.

Again: Color is not data.

If you want to color-code your cells, use conditional formatting based on the cell values or based on rules that can be expressed with logical formulas. The logic that leads to conditional formatting can also be used in other places to report on the data, regardless of the color value of the cell.

"unadd" a file to svn before commit

svn rm --keep-local folder_name

Note: In svn 1.5.4 svn rm deletes unversioned files even when --keep-local is specified. See http://svn.haxx.se/users/archive-2009-11/0058.shtml for more information.

Responsive Google Map?

in the iframe tag, you can easily add width='100%' instead of the preset value giving to you by the map

like this:

 <iframe src="https://www.google.com/maps/embed?anyLocation" width="100%" height="400" frameborder="0" style="border:0;" allowfullscreen=""></iframe>

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

I came here with the same Error, though one with a different origin.

It is caused by unsupported float index in 1.12.0 and newer numpy versions even if the code should be considered as valid.

An int type is expected, not a np.float64

Solution: Try to install numpy 1.11.0

sudo pip install -U numpy==1.11.0.

Strip double quotes from a string in .NET

If you only want to strip the quotes from the ends of the string (not the middle), and there is a chance that there can be spaces at either end of the string (i.e. parsing a CSV format file where there is a space after the commas), then you need to call the Trim function twice...for example:

string myStr = " \"sometext\"";     //(notice the leading space)
myStr = myStr.Trim('"');            //(would leave the first quote: "sometext)
myStr = myStr.Trim().Trim('"');     //(would get what you want: sometext)