Programs & Examples On #Schematron

Schematron is a structural, rule-based validation language for XML documents. It uses XPath and XSLT to validate rules most other schemas can not.

Python Pip install Error: Unable to find vcvarsall.bat. Tried all solutions

I have tried all suggestions and found my own simple solution.

The problem is that codes written in external environment like C need compiler. Look for its own VS environment, i.e. VS 2008.

Currently my machine runs VS 2012 and faces Unable to find vcvarsall.bat. I studied codes that i want to install to find the VS version. It was VS 2008. i have add to system variable VS90COMNTOOLS as variable name and gave the value of VS120COMNTOOLS.

You can find my step by step solution below:

  1. Right click on My Computer.
  2. Click Properties
  3. Advanced system settings
  4. Environment variables
  5. Add New system variable
  6. Enter VS90COMNTOOLS to the variable name
  7. Enter the value of current version to the new variable.
  8. Close all windows

Now open a new session and pip install your-package

pip is not able to install packages correctly: Permission denied error

Set up a virtualenv:

% curl -kLso /tmp/get-pip.py https://bootstrap.pypa.io/get-pip.py 
% sudo python /tmp/get-pip.py

These commands install pip into the global site-packages directory.

% sudo pip install virtualenv

and ditto for virtualenv:

% mkdir -p ~/.virtualenvs

I like my virtualenvs under one tree in my home directory called .virtualenvs

% virtualenv ~/.virtualenvs/lxmltest

Creates a virtualenv.

% . ~/.virtualenvs/lxmltest/bin/activate

Removes the need to specify the full path to pip/python in this virtualenv.

% pip install lxml

Alternatively execute ~/.virtualenvs/lxmltest/bin/pip install lxml if you chose not to follow the previous step. Note, I'm not sure how far along you are, so some of these steps can be safely skipped. Of course, if you mess something up, you can always rm -Rf ~/.virtualenvs/lxmltest and start again from a new virtualenv.

Google Maps setCenter()

@phoenix24 answer actually helped me (whose own asnwer did not solve my problem btw). The correct arguments for setCenter is

map.setCenter({lat:LAT_VALUE, lng:LONG_VALUE});

Google Documentation

By the way if your variable are lat and lng the following code will work

map.setCenter({lat:lat, lng:lng});

This actually solved my very intricate problem so I thought I will post it here.

How to retrieve the LoaderException property?

try
{
  // load the assembly or type
}
catch (Exception ex)
{
  if (ex is System.Reflection.ReflectionTypeLoadException)
  {
    var typeLoadException = ex as ReflectionTypeLoadException;
    var loaderExceptions  = typeLoadException.LoaderExceptions;
  }
}

How to apply CSS to iframe?

As an alternative, you can use CSS-in-JS technology, like below lib:

https://github.com/cssobj/cssobj

It can inject JS object as CSS to iframe, dynamically

Using margin / padding to space <span> from the rest of the <p>

Overall just add display:block; to your span. You can leave your html unchanged.

Demo

You can do it with the following css:

p {
    font-size:24px; 
    font-weight: 300; 
    -webkit-font-smoothing: subpixel-antialiased; 
    margin-top:0px;
}

p span {
    font-size:16px; 
    font-style: italic; 
    margin-top:20px; 
    padding-left:10px; 
    display:inline-block;
}

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

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

Just add the JVM Option:

AddVMOption -Duser.language=en

The file will be like this:

enter image description here

Single TextView with multiple colored text

You can use Spannable to apply effects to your TextView:

Here is my example for colouring just the first part of a TextView text (while allowing you to set the color dynamically rather than hard coding it into a String as with the HTML example!)

    mTextView.setText("Red text is here", BufferType.SPANNABLE);
    Spannable span = (Spannable) mTextView.getText();
    span.setSpan(new ForegroundColorSpan(0xFFFF0000), 0, "Red".length(),
             Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

In this example you can replace 0xFFFF0000 with a getResources().getColor(R.color.red)

Removing element from array in component state

The cleanest way to do this that I've seen is with filter:

removeItem(index) {
  this.setState({
    data: this.state.data.filter((_, i) => i !== index)
  });
}

websocket.send() parameter

As I understand it, you want the server be able to send messages through from client 1 to client 2. You cannot directly connect two clients because one of the two ends of a WebSocket connection needs to be a server.

This is some pseudocodish JavaScript:

Client:

var websocket = new WebSocket("server address");

websocket.onmessage = function(str) {
  console.log("Someone sent: ", str);
};

// Tell the server this is client 1 (swap for client 2 of course)
websocket.send(JSON.stringify({
  id: "client1"
}));

// Tell the server we want to send something to the other client
websocket.send(JSON.stringify({
  to: "client2",
  data: "foo"
}));

Server:

var clients = {};

server.on("data", function(client, str) {
  var obj = JSON.parse(str);

  if("id" in obj) {
    // New client, add it to the id/client object
    clients[obj.id] = client;
  } else {
    // Send data to the client requested
    clients[obj.to].send(obj.data);
  }
});

Clear form after submission with jQuery

try this in your post methods callback function

$(':input','#myform')
 .not(':button, :submit, :reset, :hidden')
 .val('')
 .removeAttr('checked')
 .removeAttr('selected');

for more info read this

How to pass a value from one Activity to another in Android?

Its simple If you are passing String X from A to B.
A--> B

In Activity A
1) Create Intent
2) Put data in intent using putExtra method of intent
3) Start activity

Intent i = new Intent(A.this, B.class);
i.putExtra("MY_kEY",X);

In Activity B
inside onCreate method
1) Get intent object
2) Get stored value using key(MY_KEY)

Intent intent = getIntent();
String result = intent.getStringExtra("MY_KEY");

This is the standard way to send data from A to B. you can send any data type, it could be int, boolean, ArrayList, String[]. Based on the datatype you stored in Activity as key, value pair retrieving method might differ like if you are passing int value then you will call

intent.getIntExtra("KEY");

You can even send Class objects too but for that, you have to make your class object implement the Serializable or Parceable interface.

TransactionTooLargeException

How much data you can send across size. If data exceeds a certain amount in size then you might get TransactionTooLargeException. Suppose you are trying to send bitmap across the activity and if the size exceeds certain data size then you might see this exception.

jQuery $("#radioButton").change(...) not firing during de-selection

My problem was similar and this worked for me:

$('body').on('change', '.radioClassNameHere', function() { ...

How to get CRON to call in the correct PATHs

Should you use webmin then these are the steps how to set the PATH value:

System
  -> Scheduled Cron Jobs
       -> Create a new environment variable
            -> For user: <Select the user name>
            -> Variable name: PATH
            -> Value: /usr/bin:/bin:<your personal path>
            -> Add environment variable: Before all Cron jobs for user

Installing MySQL Python on Mac OS X

To install PyMySQL

install pip => sudo easy_install pip

install PyMySQL=> sudo easy_install-3.7 pymysql

terminal command to check whether installed or not => pip3 list

or

install PyMySQL=> sudo pip install PyMySQL

terminal command to check whether installed or not => pip3 list

MySQL

The macOS Sierra Public Beta’s didn’t play well with MySQL 5.7.x, but these issues are now resolved by using MySQL 5.7.16

MySQL doesn’t come pre-loaded with macOS Sierra and needs to be dowloaded from the MySQL site.

( https://dev.mysql.com/downloads/mysql/) The latest version of MySQL 5.7.16 does work with the public release of macOS.

If you already have MySQL 5.7 and you have upgraded OS from El Capitan to Sierra I expect that to be ok, but will be interested if anyone comments on that.

Use the Mac OS X 10.11 (x86, 64-bit), DMG Archive version (works on macOS Sierra).

If you are upgrading from a previous OSX and have an older MySQL version you do not have to update it. One thing with MySQL upgrades always take a data dump of your database in case things go south and before you upgrade to macOS Sierra make sure your MySQL Server is not running.

When downloading you don’t have to sign up, look for » No thanks, just take me to the downloads! – go straight to the download mirrors and download the software from a mirror which is closest to you.

Once downloaded open the .dmg and run the installer.

When it is finished installing you get a dialog box with a temporary mysql root password – that is a MySQL root password not a macOS admin password, copy and paste it so you can use it. But I have found that the temporary password is pretty much useless so we’ll need to change it straight away.

You are also told: If you lose this password, please consult the section How to Reset the Root Password in the MySQL reference manual.(https://dev.mysql.com/doc/refman/5.7/en/resetting-permissions.html)

Change the MySQL root password

Note that this is not the same as the root or admin password of macOS – this is a unique password for the mysql root user, use one and remember/jot down somewhere what it is.

Stop MySQL

sudo /usr/local/mysql/support-files/mysql.server stop

if stop throws permission issue

Check the error file first.

tail -f /usr/local/mysql/data/*.err

Do a complete shut down or kill the process. Confirm that no mysql process is running

mysqladmin -uroot shutdown
sudo killall mysqld 

ps -ef | grep mysql

Give permisiions

sudo chown -RL root:mysql /usr/local/mysql
sudo chown -RL mysql:mysql /usr/local/mysql/data
chmod -R 755 /usr/local/mysql/data
chmod -R 755 /usr/local/mysql/data/accountname.local.pid

or Right click->get info and change the permission for 
/usr/local/mysql/data
/usr/local/mysql/data/Pushparajas-MacBook-Pro.local.pid

Start mysql

sudo mysql.server start

Start it in safe mode:

sudo mysqld_safe --skip-grant-tables

This will be an ongoing command until the process is finished so open another shell/terminal window, and log in with a password which is temporary generated:

mysql -u root -p
FLUSH PRIVILEGES;
ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass'

; Change the lowercase ‘MyNewPass’ to what you want – and keep the single quotes.

\q

Start MySQL

sudo /usr/local/mysql/support-files/mysql.server start

Starting MySQL

You can then start the MySQL server from the System Preferences or via the command line.

Command line start MySQL.

sudo /usr/local/mysql/support-files/mysql.server start

To find the MySQL version from the terminal, type at the prompt:

/usr/local/mysql/bin/mysql -v -uroot -p

This also puts you in to a shell interactive dialogue with mySQL, type \q to exit.

After installation, in order to use mysql commands without typing the full path to the commands you need to add the mysql directory to your shell path, (optional step) this is done in your “.bash_profile” file in your home directory, if you don’t have that file just create it using vi or nano:

cd ; nano .bash_profile
export PATH="/usr/local/mysql/bin:$PATH"

The first command brings you to your home directory and opens the .bash_profile file or creates a new one if it doesn’t exist, then add in the line above which adds the mysql binary path to commands that you can run. Exit the file with type “control + x” and when prompted save the change by typing “y”. Last thing to do here is to reload the shell for the above to work straight away.

source ~/.bash_profile
mysql -v

You will get the version number again, just type “q” to exit.

Fix the 2002 MySQL Socket error

Fix the looming 2002 socket error – which is linking where MySQL places the socket and where macOS thinks it should be, MySQL puts it in /tmp and macOS looks for it in /var/mysql the socket is a type of file that allows mysql client/server communication.

sudo mkdir /var/mysql
sudo ln -s /tmp/mysql.sock /var/mysql/mysql.sock

phpMyAdmin

uncomment below line in httpd.conf file

LoadModule php7_module libexec/apache2/libphp7.so

First fix the 2002 socket error if you haven’t done so from the MySQL section-

sudo mkdir /var/mysql
sudo ln -s /tmp/mysql.sock /var/mysql/mysql.sock

Download phpMyAdmin, (https://www.phpmyadmin.net/downloads/) the zip English package will suit a lot of users, then unzip it and move the folder with its contents into the document root level(~/Sites/) renaming folder to ‘phpmyadmin’.

Make the config folder

mkdir ~/Sites/phpmyadmin/config

Change the permissions

chmod o+w ~/Sites/phpmyadmin/config

Run the set up in the browser http://localhost/~username/phpmyadmin/setup/ or http://localhost/phpmyadmin/setup/

You need to create a new localhost mysql server connection, click new server.

Switch to the Authentication tab and set the local mysql root user and the password.

Add in the username “root” (maybe already populated, add in the password that you set up earlier for the MySQL root user set up, click on save and you are returned to the previous screen. (This is not the macOS Admin or root password – it is the MySQL root user).

Make sure you click on save, then a config.inc.php is now in the /config directory of phpmyadmin directory, move this file to the root level of /phpmyadmin and then remove the now empty /config directory.

In the latest phpmyadmin, download the config.inc.php and place in phpmyadmin directory.

If you want to setup new server move config.inc.php to some location and try http://localhost/~username/phpmyadmin/setup

Now going to http://localhost/~username/phpmyadmin/ will now allow you to interact with your MySQL databases.

To upgrade phpmyadmin just download the latest version and copy the older ‘config.inc.php‘ from the existing directory into the new folder and replace – backup the older one just in case.

Permissions

To run a website with no permission issues it is best to set the web root and its contents to be writeable by all, since it’s a local development it shouldn’t be a security issue.

Lets say that you have a site in the User Sites folder at the following location ~/Sites/testsite you would set it to be writeable like so:

sudo chmod -R a+w ~/Sites/testsite

If you are concerned about security then instead of making it world writeable you can set the owner to be Apache _www but when working on files you would have to authenticate more as admin you are “not” the owner, you would do this like so:

sudo chown -R _www ~/Sites/testsite

This will set the contents recursively to be owned by the Apache user. If you had the website stored at the System level Document root at say ~/Sites/testsite then it would have to be the latter:

sudo chown -R _www ~/Sites/testsite

Another easier way to do this if you have a one user workstation is to change the Apache web user from _www to your account. That’s it! You now have the native AMP stack running on top of macOS Sierra.

Ref Link - https://coolestguidesontheplanet.com/get-apache-mysql-php-and-phpmyadmin-working-on-macos-sierra/#ssu

Twitter Bootstrap and ASP.NET GridView

Just for the record, I got borders in the table and to get rid of it I needed to set following properties in the GridView:

GridLines="None"
CellSpacing="-1"

How can I represent an infinite number in Python?

Also if you use SymPy you can use sympy.oo

>>> from sympy import oo
>>> oo + 1
oo
>>> oo - oo
nan

etc.

Store a closure as a variable in Swift

Depends on your needs there is an addition to accepted answer. You may also implement it like this:

var parseCompletion: (() ->Void)!

and later in some func assign to it

func someHavyFunc(completion: @escaping () -> Void){
    self.parseCompletion = completion
}

and in some second function use it

func someSecondFunc(){
    if let completion = self.parseCompletion {
        completion()
    }
}

note that @escaping parameter is a mandatory here

Batch file to perform start, run, %TEMP% and delete all

Just use

del /f /q C:\Users\%username%\AppData\Local\temp

And it will work.

Note: It will delete the whole folder however, Windows will remake it as it needs.

Creating a select box with a search option

Select2 http://select2.github.io may be even better and more active than Chosen.

See this comparison: http://sitepoint.com/jquery-select-box-components-chosen-vs-select2

I went for Select2 (a few months ago) because Chosen had an issue when using Chinese characters via an IME http://github.com/harvesthq/chosen/issues/2663 It works great.

What's the difference between window.location= and window.location.replace()?

TLDR;

use location.href or better use window.location.href;

However if you read this you will gain undeniable proof.

The truth is it's fine to use but why do things that are questionable. You should take the higher road and just do it the way that it probably should be done.

location = "#/mypath/otherside"
var sections = location.split('/')

This code is perfectly correct syntax-wise, logic wise, type-wise you know the only thing wrong with it?

it has location instead of location.href

what about this

var mystring = location = "#/some/spa/route"

what is the value of mystring? does anyone really know without doing some test. No one knows what exactly will happen here. Hell I just wrote this and I don't even know what it does. location is an object but I am assigning a string will it pass the string or pass the location object. Lets say there is some answer to how this should be implemented. Can you guarantee all browsers will do the same thing?

This i can pretty much guess all browsers will handle the same.

var mystring = location.href = "#/some/spa/route"

What about if you place this into typescript will it break because the type compiler will say this is suppose to be an object?

This conversation is so much deeper than just the location object however. What this conversion is about what kind of programmer you want to be?

If you take this short-cut, yea it might be okay today, ye it might be okay tomorrow, hell it might be okay forever, but you sir are now a bad programmer. It won't be okay for you and it will fail you.

There will be more objects. There will be new syntax.

You might define a getter that takes only a string but returns an object and the worst part is you will think you are doing something correct, you might think you are brilliant for this clever method because people here have shamefully led you astray.

var Person.name = {first:"John":last:"Doe"}
console.log(Person.name) // "John Doe"

With getters and setters this code would actually work, but just because it can be done doesn't mean it's 'WISE' to do so.

Most people who are programming love to program and love to get better. Over the last few years I have gotten quite good and learn a lot. The most important thing I know now especially when you write Libraries is consistency and predictability.

Do the things that you can consistently do.

+"2" <-- this right here parses the string to a number. should you use it? or should you use parseInt("2")?

what about var num =+"2"?

From what you have learn, from the minds of stackoverflow i am not too hopefully.

If you start following these 2 words consistent and predictable. You will know the right answer to a ton of questions on stackoverflow.

Let me show you how this pays off. Normally I place ; on every line of javascript i write. I know it's more expressive. I know it's more clear. I have followed my rules. One day i decided not to. Why? Because so many people are telling me that it is not needed anymore and JavaScript can do without it. So what i decided to do this. Now because I have become sure of my self as a programmer (as you should enjoy the fruit of mastering a language) i wrote something very simple and i didn't check it. I erased one comma and I didn't think I needed to re-test for such a simple thing as removing one comma.

I wrote something similar to this in es6 and babel

var a = "hello world"
(async function(){
  //do work
})()

This code fail and took forever to figure out. For some reason what it saw was

var a = "hello world"(async function(){})()

hidden deep within the source code it was telling me "hello world" is not a function.

For more fun node doesn't show the source maps of transpiled code.

Wasted so much stupid time. I was presenting to someone as well about how ES6 is brilliant and then I had to start debugging and demonstrate how headache free and better ES6 is. Not convincing is it.

I hope this answered your question. This being an old question it's more for the future generation, people who are still learning.

Question when people say it doesn't matter either way works. Chances are a wiser more experienced person will tell you other wise.

what if someone overwrite the location object. They will do a shim for older browsers. It will get some new feature that needs to be shimmed and your 3 year old code will fail.

My last note to ponder upon.

Writing clean, clear purposeful code does something for your code that can't be answer with right or wrong. What it does is it make your code an enabler.

You can use more things plugins, Libraries with out fear of interruption between the codes.

for the record. use

window.location.href

OSError: [Errno 2] No such file or directory while using python subprocess in Django

Can't upvote so I'll repost @jfs comment cause I think it should be more visible.

@AnneTheAgile: shell=True is not required. Moreover you should not use it unless it is necessary (see @ valid's comment). You should pass each command-line argument as a separate list item instead e.g., use ['command', 'arg 1', 'arg 2'] instead of "command 'arg 1' 'arg 2'". – jfs Mar 3 '15 at 10:02

How can I get the image url in a Wordpress theme?

get_template_directory_uri();

This function will help you retrieve theme directory URI, and can be used with your images, your example below:

<img src="<?php echo get_template_directory_uri(); ?>/images/mindset.jpg" />

How do I get the type of a variable?

You can use the typeid operator:

#include <typeinfo>
...
cout << typeid(variable).name() << endl;

How can I debug a .BAT script?

you can use cmd \k at the end of your script to see the error. it won't close your command prompt after the execution is done

How to run travis-ci locally

I'm not sure what was your original reason for running Travis locally, if you just wanted to play with it, then stop reading here as it's irrelevant for you.

If you already have experience with hosted Travis and you want to get the same experience in your own datacenter, read on.

Since Dec 2014 Travis CI offers an Enterprise on-premises version.

http://blog.travis-ci.com/2014-12-19-introducing-travis-ci-enterprise/

The pricing is part of the article as well:

The licensing is done per seats, where every license includes 20 users. Pricing starts at $6,000 per license, which includes 20 users and 5 concurrent builds. There's a premium option with unlimited builds for $8,500.

What are XAND and XOR

In most cases you won't find an Xand, Xor, nor, nand Logical operator in programming, but fear not in most cases you can simulate it with the other operators.

Since you didn't state any particular language. I won't do any specific language either. For my examples we'll use the following variables.

A = 3
B = 5
C = 7

and for code I'll put it in the code tag to make it easier to see what I did, I'll also follow the logic through the process to show what the end result will be.

NAND

Also known as Not And, can easily be simulated by using a Not operator, (normally indicated as ! )

You can do the following

if(!((A>B) && (B<C)))

if (!(F&&T))
if(!(F))
If(T)

In our example above it will be true, since both sides were not true. Thus giving us the desired result
Nand

NOR

Also known as Not OR, just like NAND we can simulate it with the not operator.
if(!((A>B) || (B<C)))

if (!(F||T))
if(!(T))
if(F)

Again this will give us the desired outcomes
Nor

XOR

Xor or Exlcusive OR only will be true when one is TRUE but the Other is FALSE

If (!(A > C && B > A) && (A > C || B > A) )

If (!(F && T) && (F || T) )
If (!(F) && (T) )
If (T && T )
If (T)

So that is an example of it working for just 1 or the other being true, I'll show if both are true it will be false.

If ( !(A < C && B > A) && (A < C || B > A) )

If ( !(T && T) && (T ||T) )
If ( !(T) && (T) )
If ( F && T )
If (F)

And both false

If (!(A > C && B < A) && (A > C || B < A) )

If (!(F && F) && (F || F) )
If (!(F) && (F) )
If (T && F )
If (F)


And the picture to help
XOR

XAND

And finally our Exclusive And, this will only return true if both are sides are false, or if both are true. Of course You could just call this a Not XOR (NXOR)

Both True If ( (A < C && B > A) || !(A < C || B > A) )

If ((T&&T) || !(T||T))
IF (T || !T)
If (T || F)
IF (T)

Both False If ( (A > C && B < A) || !(A > C || B < A) )

If ( (F && F) || !(F ||F))
If ( F || !F)
If ( F || T)
If (T)

And lastly 1 true and the other one false. If ((A > C && B > A) || !(A > C || B > A) )

If ((F && T) || ! (F || T) )
If (F||!(T))
If (F||F)
If (F)

Or if you want to go the NXOR route...
If (!(!(A > C && B > A) && (A > C || B > A)))

If (!(!(F && T) && (F || T)) )
If (!(!(F) && (T)) )
If (!(T && T) )
If (!(T))
If (F)

enter image description here

Of course everyone else's solutions probably state this as well, I am putting my own answer in here because the top answer didn't seem to understand that not all languages support XOR or XAND for example C uses ^ for XOR and XAND isn't even supported.

So I provided some examples of how to simulate it with the basic operators in the event your language doesn't support XOR or XAND as their own operators like Php if ($a XOR $B).

As for Xnot what is that? Exclusive not? so not not? I don't know how that would look in a logic gate, I think it doesn't exist. Since Not just inverts the output from a 1 to a 0 and 0 to a 1.

Anyway hope that helps.

What is the meaning of the term "thread-safe"?

Thread-safe-code works as specified, even when entered simultaneously by different threads. This often means, that internal data-structures or operations that should run uninterrupted are protected against different modifications at the same time.

How does DISTINCT work when using JPA and Hibernate

Update: See the top-voted answer please.

My own is currently obsolete. Only kept here for historical reasons.


Distinct in HQL is usually needed in Joins and not in simple examples like your own.

See also How do you create a Distinct query in HQL

How do I import material design library to Android Studio?

Goto

  1. File (Top Left Corner)
  2. Project Structure
  3. Under Module. Find the Dependence tab
  4. press plus button (+) at top right.
  5. You will find all the dependencies

What is the best workaround for the WCF client `using` block issue?

You could also use a DynamicProxy to extend the Dispose() method. This way you could do something like:

using (var wrapperdProxy = new Proxy<yourProxy>())
{
   // Do whatever and dispose of Proxy<yourProxy> will be called and work properly.
}

How can I send an xml body using requests library?

Just send xml bytes directly:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import requests

xml = """<?xml version='1.0' encoding='utf-8'?>
<a>?</a>"""
headers = {'Content-Type': 'application/xml'} # set what your server accepts
print requests.post('http://httpbin.org/post', data=xml, headers=headers).text

Output

{
  "origin": "x.x.x.x",
  "files": {},
  "form": {},
  "url": "http://httpbin.org/post",
  "args": {},
  "headers": {
    "Content-Length": "48",
    "Accept-Encoding": "identity, deflate, compress, gzip",
    "Connection": "keep-alive",
    "Accept": "*/*",
    "User-Agent": "python-requests/0.13.9 CPython/2.7.3 Linux/3.2.0-30-generic",
    "Host": "httpbin.org",
    "Content-Type": "application/xml"
  },
  "json": null,
  "data": "<?xml version='1.0' encoding='utf-8'?>\n<a>\u0431</a>"
}

Sorting using Comparator- Descending order (User defined classes)

String[] s = {"a", "x", "y"};
Arrays.sort(s, new Comparator<String>() {

    @Override
    public int compare(String o1, String o2) {
        return o2.compareTo(o1);
    }
});
System.out.println(Arrays.toString(s));

-> [y, x, a]

Now you have to implement the Comparator for your Person class. Something like (for ascending order): compare(Person a, Person b) = a.id < b.id ? -1 : (a.id == b.id) ? 0 : 1 or Integer.valueOf(a.id).compareTo(Integer.valueOf(b.id)).

To minimize confusion you should implement an ascending Comparator and convert it to a descending one with a wrapper (like this) new ReverseComparator<Person>(new PersonComparator()).

How to restart a single container with docker-compose

Simple 'docker' command knows nothing about 'worker' container. Use command like this

docker-compose -f docker-compose.yml restart worker

javascript find and remove object in array based on key value

You can simplify this, and there's really no need for using jquery here.

var id = 88;

for(var i = 0; i < data.length; i++) {
    if(data[i].id == id) {
        data.splice(i, 1);
        break;
    }
}

Just iterate through the list, find the matching id, splice, and then break to exit your loop

How would I check a string for a certain letter in Python?

Use the in keyword without is.

if "x" in dog:
    print "Yes!"

If you'd like to check for the non-existence of a character, use not in:

if "x" not in dog:
    print "No!"

intl extension: installing php_intl.dll

In my case adding PHP directory to PATH in user environment didn't work. After some testing I've found that it should be added to system PATH (I don't know what's the name of this part of system setting windows, 'couse I have Polish Windows).

Laravel 5.4 Specific Table Migration

First you should create one migration file for your table like:

public function up()
    {
        Schema::create('test', function (Blueprint $table) {
            $table->increments('id');
            $table->string('fname',255);
            $table->string('lname',255);
            $table->rememberToken();
            $table->timestamps();
        });
    }

After create test folder in migrations folder then newly created migration moved/copied in test folder and run below command in your terminal/cmd like:

php artisan migrate --path=/database/migrations/test/

Remove Android App Title Bar

It's obvious, but the App Theme selection in design is just for display a draft during layout edition, is not related to real app looking in cell phone.

Just change the manifest file (AndroidManifest.xml) is not enough because the style need to be predefined is styles.xml. Also is useless change the layout files.

All proposed solution in Java or Kotlin has failed for me. Some of them crash the app. And if one never (like me) uses the title bar in app, the static solution is cleaner.

For me the only solution that works in 2019 (Android Studio 3.4.1) is:

in styles.xml (under app/res/values) add the lines:

   <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

After in AndroidManifest.xml (under app/manifests)

Replace

android:theme="@style/AppTheme">

by

android:theme="@style/AppTheme.NoActionBar">

Oracle SQL escape character (for a '&')

Set the define character to something other than &

SET DEFINE ~
create table blah (x varchar(20));
insert into blah (x) values ('blah&amp');
select * from blah;

X                    
-------------------- 
blah&amp 

href overrides ng-click in Angular.js

Just write ng-click before href ..It worked for me

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
  <head>_x000D_
    <script data-require="[email protected]" data-semver="1.5.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>_x000D_
    <script>_x000D_
    angular.module("module",[])_x000D_
.controller("controller",function($scope){_x000D_
  _x000D_
  $scope.func =function(){_x000D_
    console.log("d");_x000D_
  }_x000D_
  _x000D_
})</script>_x000D_
  </head>_x000D_
_x000D_
  <body ng-app="module" ng-controller="controller">_x000D_
    <h1>Hello ..</h1>_x000D_
    <a ng-click="func()" href="someplace.html">Take me there</a>_x000D_
  </body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How does PHP 'foreach' actually work?

As per the documentation provided by PHP manual.

On each iteration, the value of the current element is assigned to $v and the internal
array pointer is advanced by one (so on the next iteration, you'll be looking at the next element).

So as per your first example:

$array = ['foo'=>1];
foreach($array as $k=>&$v)
{
   $array['bar']=2;
   echo($v);
}

$array have only single element, so as per the foreach execution, 1 assign to $v and it don't have any other element to move pointer

But in your second example:

$array = ['foo'=>1, 'bar'=>2];
foreach($array as $k=>&$v)
{
   $array['baz']=3;
   echo($v);
}

$array have two element, so now $array evaluate the zero indices and move the pointer by one. For first iteration of loop, added $array['baz']=3; as pass by reference.

How can I run MongoDB as a Windows service?

1) echo logpath=F:\mongodb\log\mongo.log > F:\mongodb\mongod.cfg

2) dbpath=F:\mongodb\data\db [add this to the next line in mongod.cfg]

C:\>F:\mongodb\bin\mongod.exe –config F:\mongodb\mongod.cfg –install

Reference

Rename multiple files based on pattern in Unix

Another possible parameter expansion:

for f in fgh*; do mv -- "$f" "jkl${f:3}"; done

How to position two elements side by side using CSS

You can use float:left to align div in one line.

Fiddle

How to solve “Microsoft Visual Studio (VS)” error “Unable to connect to the configured development Web server”

We solved this problem with deleting .vs folder on project folder and deleting temporary ASP.NET files.

1. Close the Visual Studio.
2. Delete .vs folder on project folder that includes applicationhost.config file.
3. Delete temporary ASP.NET Files located: C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root

Solving "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection" InvalidOperationException

Most of the other answers point to eager loading, but I found another solution.

In my case I had an EF object InventoryItem with a collection of InvActivity child objects.

class InventoryItem {
...
   // EF code first declaration of a cross table relationship
   public virtual List<InvActivity> ItemsActivity { get; set; }

   public GetLatestActivity()
   {
       return ItemActivity?.OrderByDescending(x => x.DateEntered).SingleOrDefault();
   }
...
}

And since I was pulling from the child object collection instead of a context query (with IQueryable), the Include() function was not available to implement eager loading. So instead my solution was to create a context from where I utilized GetLatestActivity() and attach() the returned object:

using (DBContext ctx = new DBContext())
{
    var latestAct = _item.GetLatestActivity();

    // attach the Entity object back to a usable database context
    ctx.InventoryActivity.Attach(latestAct);

    // your code that would make use of the latestAct's lazy loading
    // ie   latestAct.lazyLoadedChild.name = "foo";
}

Thus you aren't stuck with eager loading.

ERROR 403 in loading resources like CSS and JS in my index.php

Find out the web server user

open up terminal and type lsof -i tcp:80

This will show you the user of the web server process Here is an example from a raspberry pi running debian:

COMMAND   PID     USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
apache2  7478 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7664 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)
apache2  7794 www-data    3u  IPv4 450666      0t0  TCP *:http (LISTEN)

The user is www-data

If you give ownership of the web files to the web server:

chown www-data:www-data -R /opt/lamp/htdocs

And chmod 755 for good measure:

chmod 755 -R /opt/lamp/htdocs

Let me know how you go, maybe you need to use 'sudo' before the command, i.e. sudo chown www-data:www-data -R /opt/lamp/htdocs

if it doesn't work, please give us the output of: ls -al /opt/lamp/htdocs

How to get the current time in milliseconds from C in Linux?

Use gettimeofday() to get the time in seconds and microseconds. Combining and rounding to milliseconds is left as an exercise.

Setting width of spreadsheet cell using PHPExcel

autoSize for column width set as bellow. It works for me.

$spreadsheet->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);

What happens to a declared, uninitialized variable in C? Does it have a value?

As far as i had gone it is mostly depend on compiler but in general most cases the value is pre assumed as 0 by the compliers.
I got garbage value in case of VC++ while TC gave value as 0. I Print it like below

int i;
printf('%d',i);

Get all files that have been modified in git branch

What if it could be as easy as this?

git changed

If you're willing to assume that the main branch is called "master", and that you create your other branches from master, then you can add this alias to your ~/.gitconfig file to make it that easy:

cbranch = !"git branch | grep '*' | cut -f2 -d' '"
changed = !"git diff --name-only $(git cbranch) $(git merge-base $(git cbranch) master)"

Those assumptions will work for most people in most situations, but you must be aware that you're making them.

Also, you must use a shell that supports $(). It's very likely that your shell supports this.

Why doesn't Java allow overriding of static methods?

Answer of this question is simple, the method or variable marked as static belongs to the class only, So that static method cannot be inherited in the sub class because they belong to the super class only.

Could not resolve Spring property placeholder

the following property must be added in the gradle.build file

processResources {
    filesMatching("**/*.properties") {
        expand project.properties
    }
}

Additionally, if working with Intellij, the project must be re-imported.

List to array conversion to use ravel() function

create an int array and a list

from array import array
listA = list(range(0,50))
for item in listA:
    print(item)
arrayA = array("i", listA)
for item in arrayA:
    print(item)

JavaScript: replace last occurrence of text in a string

I know this is silly, but I'm feeling creative this morning:

'one two, one three, one four, one'
.split(' ') // array: ["one", "two,", "one", "three,", "one", "four,", "one"]
.reverse() // array: ["one", "four,", "one", "three,", "one", "two,", "one"]
.join(' ') // string: "one four, one three, one two, one"
.replace(/one/, 'finish') // string: "finish four, one three, one two, one"
.split(' ') // array: ["finish", "four,", "one", "three,", "one", "two,", "one"]
.reverse() // array: ["one", "two,", "one", "three,", "one", "four,", "finish"]
.join(' '); // final string: "one two, one three, one four, finish"

So really, all you'd need to do is add this function to the String prototype:

String.prototype.replaceLast = function (what, replacement) {
    return this.split(' ').reverse().join(' ').replace(new RegExp(what), replacement).split(' ').reverse().join(' ');
};

Then run it like so: str = str.replaceLast('one', 'finish');

One limitation you should know is that, since the function is splitting by space, you probably can't find/replace anything with a space.

Actually, now that I think of it, you could get around the 'space' problem by splitting with an empty token.

String.prototype.reverse = function () {
    return this.split('').reverse().join('');
};

String.prototype.replaceLast = function (what, replacement) {
    return this.reverse().replace(new RegExp(what.reverse()), replacement.reverse()).reverse();
};

str = str.replaceLast('one', 'finish');

Why doesn't [01-12] range work as expected?

You seem to have misunderstood how character classes definition works in regex.

To match any of the strings 01, 02, 03, 04, 05, 06, 07, 08, 09, 10, 11, or 12, something like this works:

0[1-9]|1[0-2]

References


Explanation

A character class, by itself, attempts to match one and exactly one character from the input string. [01-12] actually defines [012], a character class that matches one character from the input against any of the 3 characters 0, 1, or 2.

The - range definition goes from 1 to 1, which includes just 1. On the other hand, something like [1-9] includes 1, 2, 3, 4, 5, 6, 7, 8, 9.

Beginners often make the mistakes of defining things like [this|that]. This doesn't "work". This character definition defines [this|a], i.e. it matches one character from the input against any of 6 characters in t, h, i, s, | or a. More than likely (this|that) is what is intended.

References


How ranges are defined

So it's obvious now that a pattern like between [24-48] hours doesn't "work". The character class in this case is equivalent to [248].

That is, - in a character class definition doesn't define numeric range in the pattern. Regex engines doesn't really "understand" numbers in the pattern, with the exception of finite repetition syntax (e.g. a{3,5} matches between 3 and 5 a).

Range definition instead uses ASCII/Unicode encoding of the characters to define ranges. The character 0 is encoded in ASCII as decimal 48; 9 is 57. Thus, the character definition [0-9] includes all character whose values are between decimal 48 and 57 in the encoding. Rather sensibly, by design these are the characters 0, 1, ..., 9.

See also


Another example: A to Z

Let's take a look at another common character class definition [a-zA-Z]

In ASCII:

  • A = 65, Z = 90
  • a = 97, z = 122

This means that:

  • [a-zA-Z] and [A-Za-z] are equivalent
  • In most flavors, [a-Z] is likely to be an illegal character range
    • because a (97) is "greater than" than Z (90)
  • [A-z] is legal, but also includes these six characters:
    • [ (91), \ (92), ] (93), ^ (94), _ (95), ` (96)

Related questions

Remove Top Line of Text File with PowerShell

Another approach to remove the first line from file, using multiple assignment technique. Refer Link

 $firstLine, $restOfDocument = Get-Content -Path $filename 
 $modifiedContent = $restOfDocument 
 $modifiedContent | Out-String | Set-Content $filename

In c# what does 'where T : class' mean?

T represents an object type of, it implies that you can give any type of. IList : if IList s=new IList; Now s.add("Always accept string.").

scipy.misc module has no attribute imread?

For Python 3, it is best to use imread in matplotlib.pyplot:

from matplotlib.pyplot import imread

How do you determine what SQL Tables have an identity column programmatically

sys.columns.is_identity = 1

e.g.,

select o.name, c.name
from sys.objects o inner join sys.columns c on o.object_id = c.object_id
where c.is_identity = 1

Opening a remote machine's Windows C drive

If you need a drive letter (some applications don't like UNC style paths that start with a machine-name) you can "map a drive" to a UNC path. Right-click on "My Computer" and select Map Network Drive... or use this command line:

NET USE z: \server\c$\folder1\folder2

NET USE y: \server\d$

Note that you can map drive-to-drive or drill down and map to sub-folder.

Variable interpolation in the shell

Use curly braces around the variable name:

`tail -1 ${filepath}_newstap.sh`

What's the difference between tilde(~) and caret(^) in package.json?

Tilde (~)

major version is fixed, minor version is fixed, matches any build number

"express": "~4.13.3" 

~4.13.3 means it will check for 4.13.x where x is anything and 4.14.0

Caret (^)

major version is fixed, matches any minor version, matches any build number

"supertest": "^3.0.0"

^3.0.0 means it will check for 3.x.x where x is anything

Eclipse Java Missing required source folder: 'src'

In my case eclipse reported this in the Problems view on the parent project which does not have any code. I just delete the error whenever it is reported on this parent project where src folder is really not needed.

How to make a dropdown readonly using jquery?

I had the same problem, my solution was to disable all options not selected. Very easy with jQuery:

$('option:not(:selected)').attr('disabled', true);

Edit => If you have multiple dropdowns on same page, disable all not selected options on select-ID as below.

$('#select_field_id option:not(:selected)').attr('disabled', true);

Create thumbnail image

This is the code I'm using. Also works for .NET Core > 2.0 using System.Drawing.Common NuGet.

https://www.nuget.org/packages/System.Drawing.Common/

using System;
using System.Drawing;

class Program
{
    static void Main()
    {
        const string input = "C:\\background1.png";
        const string output = "C:\\thumbnail.png";

        // Load image.
        Image image = Image.FromFile(input);

        // Compute thumbnail size.
        Size thumbnailSize = GetThumbnailSize(image);

        // Get thumbnail.
        Image thumbnail = image.GetThumbnailImage(thumbnailSize.Width,
            thumbnailSize.Height, null, IntPtr.Zero);

        // Save thumbnail.
        thumbnail.Save(output);
    }

    static Size GetThumbnailSize(Image original)
    {
        // Maximum size of any dimension.
        const int maxPixels = 40;

        // Width and height.
        int originalWidth = original.Width;
        int originalHeight = original.Height;

        // Return original size if image is smaller than maxPixels
        if (originalWidth <= maxPixels || originalHeight <= maxPixels)
        {
            return new Size(originalWidth, originalHeight);
        }   

        // Compute best factor to scale entire image based on larger dimension.
        double factor;
        if (originalWidth > originalHeight)
        {
            factor = (double)maxPixels / originalWidth;
        }
        else
        {
            factor = (double)maxPixels / originalHeight;
        }

        // Return thumbnail size.
        return new Size((int)(originalWidth * factor), (int)(originalHeight * factor));
    }
}

Source:

https://www.dotnetperls.com/getthumbnailimage

Default values and initialization in Java

In the first case you are declaring "int a" as a local variable(as declared inside a method) and local varible do not get default value.

But instance variable are given default value both for static and non-static.

Default value for instance variable:

int = 0

float,double = 0.0

reference variable = null

char = 0 (space character)

boolean = false

Bootstrap 3 offset on right not left

Since Google seems to like this answer...

If you're looking to match Bootstrap 4's naming convention, i.e. offset-*-#, here's that modification:

.offset-right-12 {
  margin-right: 100%;
}
.offset-right-11 {
  margin-right: 91.66666667%;
}
.offset-right-10 {
  margin-right: 83.33333333%;
}
.offset-right-9 {
  margin-right: 75%;
}
.offset-right-8 {
  margin-right: 66.66666667%;
}
.offset-right-7 {
  margin-right: 58.33333333%;
}
.offset-right-6 {
  margin-right: 50%;
}
.offset-right-5 {
  margin-right: 41.66666667%;
}
.offset-right-4 {
  margin-right: 33.33333333%;
}
.offset-right-3 {
  margin-right: 25%;
}
.offset-right-2 {
  margin-right: 16.66666667%;
}
.offset-right-1 {
  margin-right: 8.33333333%;
}
.offset-right-0 {
  margin-right: 0;
}
@media (min-width: 576px) {
  .offset-sm-right-12 {
    margin-right: 100%;
  }
  .offset-sm-right-11 {
    margin-right: 91.66666667%;
  }
  .offset-sm-right-10 {
    margin-right: 83.33333333%;
  }
  .offset-sm-right-9 {
    margin-right: 75%;
  }
  .offset-sm-right-8 {
    margin-right: 66.66666667%;
  }
  .offset-sm-right-7 {
    margin-right: 58.33333333%;
  }
  .offset-sm-right-6 {
    margin-right: 50%;
  }
  .offset-sm-right-5 {
    margin-right: 41.66666667%;
  }
  .offset-sm-right-4 {
    margin-right: 33.33333333%;
  }
  .offset-sm-right-3 {
    margin-right: 25%;
  }
  .offset-sm-right-2 {
    margin-right: 16.66666667%;
  }
  .offset-sm-right-1 {
    margin-right: 8.33333333%;
  }
  .offset-sm-right-0 {
    margin-right: 0;
  }
}
@media (min-width: 768px) {
  .offset-md-right-12 {
    margin-right: 100%;
  }
  .offset-md-right-11 {
    margin-right: 91.66666667%;
  }
  .offset-md-right-10 {
    margin-right: 83.33333333%;
  }
  .offset-md-right-9 {
    margin-right: 75%;
  }
  .offset-md-right-8 {
    margin-right: 66.66666667%;
  }
  .offset-md-right-7 {
    margin-right: 58.33333333%;
  }
  .offset-md-right-6 {
    margin-right: 50%;
  }
  .offset-md-right-5 {
    margin-right: 41.66666667%;
  }
  .offset-md-right-4 {
    margin-right: 33.33333333%;
  }
  .offset-md-right-3 {
    margin-right: 25%;
  }
  .offset-md-right-2 {
    margin-right: 16.66666667%;
  }
  .offset-md-right-1 {
    margin-right: 8.33333333%;
  }
  .offset-md-right-0 {
    margin-right: 0;
  }
}
@media (min-width: 992px) {
  .offset-lg-right-12 {
    margin-right: 100%;
  }
  .offset-lg-right-11 {
    margin-right: 91.66666667%;
  }
  .offset-lg-right-10 {
    margin-right: 83.33333333%;
  }
  .offset-lg-right-9 {
    margin-right: 75%;
  }
  .offset-lg-right-8 {
    margin-right: 66.66666667%;
  }
  .offset-lg-right-7 {
    margin-right: 58.33333333%;
  }
  .offset-lg-right-6 {
    margin-right: 50%;
  }
  .offset-lg-right-5 {
    margin-right: 41.66666667%;
  }
  .offset-lg-right-4 {
    margin-right: 33.33333333%;
  }
  .offset-lg-right-3 {
    margin-right: 25%;
  }
  .offset-lg-right-2 {
    margin-right: 16.66666667%;
  }
  .offset-lg-right-1 {
    margin-right: 8.33333333%;
  }
  .offset-lg-right-0 {
    margin-right: 0;
  }
}
@media (min-width: 1200px) {
  .offset-xl-right-12 {
    margin-right: 100%;
  }
  .offset-xl-right-11 {
    margin-right: 91.66666667%;
  }
  .offset-xl-right-10 {
    margin-right: 83.33333333%;
  }
  .offset-xl-right-9 {
    margin-right: 75%;
  }
  .offset-xl-right-8 {
    margin-right: 66.66666667%;
  }
  .offset-xl-right-7 {
    margin-right: 58.33333333%;
  }
  .offset-xl-right-6 {
    margin-right: 50%;
  }
  .offset-xl-right-5 {
    margin-right: 41.66666667%;
  }
  .offset-xl-right-4 {
    margin-right: 33.33333333%;
  }
  .offset-xl-right-3 {
    margin-right: 25%;
  }
  .offset-xl-right-2 {
    margin-right: 16.66666667%;
  }
  .offset-xl-right-1 {
    margin-right: 8.33333333%;
  }
  .offset-xl-right-0 {
    margin-right: 0;
  }
}

Replace whole line containing a string using Sed

You can use the change command to replace the entire line, and the -i flag to make the changes in-place. For example, using GNU sed:

sed -i '/TEXT_TO_BE_REPLACED/c\This line is removed by the admin.' /tmp/foo

Java output formatting for Strings

EDIT: This is an extremely primitive answer but I can't delete it because it was accepted. See the answers below for a better solution though

Why not just generate a whitespace string dynamically to insert into the statement.

So if you want them all to start on the 50th character...

String key = "Name =";
String space = "";
for(int i; i<(50-key.length); i++)
{space = space + " ";}
String value = "Bob\n";
System.out.println(key+space+value);

Put all of that in a loop and initialize/set the "key" and "value" variables before each iteration and you're golden. I would also use the StringBuilder class too which is more efficient.

Get public/external IP address?

Answers based on using external web services are not exactly correct, because they do not actually answer the stated question:

... information on finding my routers public IP


Explanation

All online services return the external IP address, but it does not essentially mean, that this address is assigned to the user's router.

Router may be assigned with another local IP address of ISP infrastructure networks. Practically this means, that router can not host any services available on Internet. This may be good for safety of most home users, but not good for geeks who host servers at home.

Here's how to check if router has external IP:

trace route to web server behind ISP

According to Wikipedia article, the IP address ranges 10.0.0.0 – 10.255.255.255, 172.16.0.0 – 172.31.255.255 and 192.168.0.0 – 192.168.255.255 are used for private i.e. local networks.

See what happens when you trace route to some remote host with router being assigned with external IP address:

trace route to web server with external IP address

Gotcha! First hop starts from 31.* now. This clearly means that there's nothing between your router and Internet.


Solution

  1. Make Ping to some address with Ttl = 2
  2. Evaluate where response comes from.

TTL=2 must be not enough to reach remote host. Hop #1 host will emit "Reply from <ip address>: TTL expired in transit." revealing its IP address.

Implementation

try
{
    using (var ping = new Ping())
    {
        var pingResult = ping.Send("google.com");
        if (pingResult?.Status == IPStatus.Success)
        {
            pingResult = ping.Send(pingResult.Address, 3000, "ping".ToAsciiBytes(), new PingOptions { Ttl = 2 });

            var isRealIp = !Helpers.IsLocalIp(pingResult?.Address);

            Console.WriteLine(pingResult?.Address == null
                ? $"Has {(isRealIp ? string.Empty : "no ")}real IP, status: {pingResult?.Status}"
                : $"Has {(isRealIp ? string.Empty : "no ")}real IP, response from: {pingResult.Address}, status: {pingResult.Status}");

            Console.WriteLine($"ISP assigned REAL EXTERNAL IP to your router, response from: {pingResult?.Address}, status: {pingResult?.Status}");
        }
        else
        {
            Console.WriteLine($"Your router appears to be behind ISP networks, response from: {pingResult?.Address}, status: {pingResult?.Status}");
        }
    }
}
catch (Exception exc)
{
    Console.WriteLine("Failed to resolve external ip address by ping");
}

Small helper is used to check if IP belongs to private or public network:

public static bool IsLocalIp(IPAddress ip) {
    var ipParts = ip.ToString().Split(new [] { "." }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();

    return (ipParts[0] == 192 && ipParts[1] == 168) 
        || (ipParts[0] == 172 && ipParts[1] >= 16 && ipParts[1] <= 31) 
        ||  ipParts[0] == 10;
}

How to detect if a stored procedure already exists

If you are dealing only with stored procedures, the easiest thing to do is to probably drop the proc, then recreate it. You can generate all of the code to do this using the Generate Scripts wizard in SQL Server.

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[YourSproc]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[YourSproc]

CREATE PROCEDURE YourSproc...

How to convert a string variable containing time to time_t type in c++?

With C++11 you can now do

struct std::tm tm;
std::istringstream ss("16:35:12");
ss >> std::get_time(&tm, "%H:%M:%S"); // or just %T in this case
std::time_t time = mktime(&tm);

see std::get_time and strftime for reference

onCreateOptionsMenu inside Fragments

I tried the @Alexander Farber and @Sino Raj answers. Both answers are nice, but I couldn't use the onCreateOptionsMenu inside my fragment, until I discover what was missing:

Add setSupportActionBar(toolbar) in my Activity, like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.id.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
}

I hope this answer can be helpful for someone with the same problem.

Difference between readFile() and readFileSync()

readFileSync() is synchronous and blocks execution until finished. These return their results as return values. readFile() are asynchronous and return immediately while they function in the background. You pass a callback function which gets called when they finish. let's take an example for non-blocking.

following method read a file as a non-blocking way

var fs = require('fs');
fs.readFile(filename, "utf8", function(err, data) {
        if (err) throw err;
        console.log(data);
});

following is read a file as blocking or synchronous way.

var data = fs.readFileSync(filename);

LOL...If you don't want readFileSync() as blocking way then take reference from the following code. (Native)

var fs = require('fs');
function readFileAsSync(){
    new Promise((resolve, reject)=>{
        fs.readFile(filename, "utf8", function(err, data) {
                if (err) throw err;
                resolve(data);
        });
    });
}

async function callRead(){
    let data = await readFileAsSync();
    console.log(data);
}

callRead();

it's mean behind scenes readFileSync() work same as above(promise) base.

What is the path that Django uses for locating and loading templates?

basically BASE_DIR is your django project directory, same dir where manage.py is.

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]

Can you break from a Groovy "each" closure?

(1..10).each{

if (it < 5)

println it

else

return false

React - Component Full Screen (with height 100%)

try using !important in height. It is probably because of some other style affecting your html body.

{ height : 100% !important; }

also you can give values in VP which will set height to viee port pixel you mention likeheight : 700vp; but this wont be portable.

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

I ran into the same issue today, try running ur container with this command.

docker run --name mariadbtest -p 3306:3306 -e MYSQL_ROOT_PASSWORD=mypass -d mariadb/server:10.3

How to import an Excel file into SQL Server?

You can also use OPENROWSET to import excel file in sql server.

SELECT * INTO Your_Table FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
                        'Excel 12.0;Database=C:\temp\MySpreadsheet.xlsx',
                        'SELECT * FROM [Data$]')

SQL to Entity Framework Count Group-By

A useful extension is to collect the results in a Dictionary for fast lookup (e.g. in a loop):

var resultDict = _dbContext.Projects
    .Where(p => p.Status == ProjectStatus.Active)
    .GroupBy(f => f.Country)
    .Select(g => new { country = g.Key, count = g.Count() })
    .ToDictionary(k => k.country, i => i.count);

Originally found here: http://www.snippetsource.net/Snippet/140/groupby-and-count-with-ef-in-c

csv.Error: iterator should return strings, not bytes

I had this error when running an old python script developped with Python 2.6.4

When updating to 3.6.2, I had to remove all 'rb' parameters from open calls in order to fix this csv reading error.

How do I access the $scope variable in browser's console using AngularJS?

I usually use jQuery data() function for that:

$($0).data().$scope

The $0 is currently selected item in chrome DOM inspector. $1, $2 .. and so on are previously selected items.

How can I create a progress bar in Excel VBA?

In the past, with VBA projects, I've used a label control with the background colored and adjust the size based on the progress. Some examples with similar approaches can be found in the following links:

  1. http://oreilly.com/pub/h/2607
  2. http://www.ehow.com/how_7764247_create-progress-bar-vba.html
  3. http://spreadsheetpage.com/index.php/tip/displaying_a_progress_indicator/

Here is one that uses Excel's Autoshapes:

http://www.andypope.info/vba/pmeter.htm

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

In the below investigation as API, I use http://example.com instead of http://myApiUrl/login from your question, because this first one working.

I assume that your page is on http://my-site.local:8088.

The reason why you see different results is that Postman:

  • set header Host=example.com (your API)
  • NOT set header Origin

This is similar to browsers' way of sending requests when the site and API has the same domain (browsers also set the header item Referer=http://my-site.local:8088, however I don't see it in Postman). When Origin header is not set, usually servers allow such requests by default.

Enter image description here

This is the standard way how Postman sends requests. But a browser sends requests differently when your site and API have different domains, and then CORS occurs and the browser automatically:

  • sets header Host=example.com (yours as API)
  • sets header Origin=http://my-site.local:8088 (your site)

(The header Referer has the same value as Origin). And now in Chrome's Console & Networks tab you will see:

Enter image description here

Enter image description here

When you have Host != Origin this is CORS, and when the server detects such a request, it usually blocks it by default.

Origin=null is set when you open HTML content from a local directory, and it sends a request. The same situation is when you send a request inside an <iframe>, like in the below snippet (but here the Host header is not set at all) - in general, everywhere the HTML specification says opaque origin, you can translate that to Origin=null. More information about this you can find here.

_x000D_
_x000D_
fetch('http://example.com/api', {method: 'POST'});
_x000D_
Look on chrome-console > network tab
_x000D_
_x000D_
_x000D_

If you do not use a simple CORS request, usually the browser automatically also sends an OPTIONS request before sending the main request - more information is here. The snippet below shows it:

_x000D_
_x000D_
fetch('http://example.com/api', {_x000D_
  method: 'POST',_x000D_
  headers: { 'Content-Type': 'application/json'}_x000D_
});
_x000D_
Look in chrome-console -> network tab to 'api' request._x000D_
This is the OPTIONS request (the server does not allow sending a POST request)
_x000D_
_x000D_
_x000D_

You can change the configuration of your server to allow CORS requests.

Here is an example configuration which turns on CORS on nginx (nginx.conf file) - be very careful with setting always/"$http_origin" for nginx and "*" for Apache - this will unblock CORS from any domain.

_x000D_
_x000D_
location ~ ^/index\.php(/|$) {_x000D_
   ..._x000D_
    add_header 'Access-Control-Allow-Origin' "$http_origin" always;_x000D_
    add_header 'Access-Control-Allow-Credentials' 'true' always;_x000D_
    if ($request_method = OPTIONS) {_x000D_
        add_header 'Access-Control-Allow-Origin' "$http_origin"; # DO NOT remove THIS LINES (doubled with outside 'if' above)_x000D_
        add_header 'Access-Control-Allow-Credentials' 'true';_x000D_
        add_header 'Access-Control-Max-Age' 1728000; # cache preflight value for 20 days_x000D_
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';_x000D_
        add_header 'Access-Control-Allow-Headers' 'My-First-Header,My-Second-Header,Authorization,Content-Type,Accept,Origin';_x000D_
        add_header 'Content-Length' 0;_x000D_
        add_header 'Content-Type' 'text/plain charset=UTF-8';_x000D_
        return 204;_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

Here is an example configuration which turns on CORS on Apache (.htaccess file)

_x000D_
_x000D_
# ------------------------------------------------------------------------------_x000D_
# | Cross-domain Ajax requests                                                 |_x000D_
# ------------------------------------------------------------------------------_x000D_
_x000D_
# Enable cross-origin Ajax requests._x000D_
# http://code.google.com/p/html5security/wiki/CrossOriginRequestSecurity_x000D_
# http://enable-cors.org/_x000D_
_x000D_
# <IfModule mod_headers.c>_x000D_
#    Header set Access-Control-Allow-Origin "*"_x000D_
# </IfModule>_x000D_
_x000D_
# Header set Header set Access-Control-Allow-Origin "*"_x000D_
# Header always set Access-Control-Allow-Credentials "true"_x000D_
_x000D_
Access-Control-Allow-Origin "http://your-page.com:80"_x000D_
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"_x000D_
Header always set Access-Control-Allow-Headers "My-First-Header,My-Second-Header,Authorization, content-type, csrf-token"
_x000D_
_x000D_
_x000D_

How do I connect to my existing Git repository using Visual Studio Code?

  1. Open Visual Studio Code terminal (Ctrl + `)
  2. Write the Git clone command. For example,

    git clone https://github.com/angular/angular-phonecat.git
    
  3. Open the folder you have just cloned (menu FileOpen Folder)

    Enter image description here

Getting the current Fragment instance in the viewpager

If your pager is inside a Fragment then use this:

private fun getPagerCurrentFragment(): Fragment? {
    return childFragmentManager.findFragmentByTag("android:switcher:${R.id.myViewPagerId}:${myViewPager.currentItem}")
}

Where R.id.myViewPagerId is the id of your ViewPager inside the xml Layout.

SQLite UPSERT / UPDATE OR INSERT

To have a pure UPSERT with no holes (for programmers) that don't relay on unique and other keys:

UPDATE players SET user_name="gil", age=32 WHERE user_name='george'; 
SELECT changes();

SELECT changes() will return the number of updates done in the last inquire. Then check if return value from changes() is 0, if so execute:

INSERT INTO players (user_name, age) VALUES ('gil', 32); 

Add item to Listview control

I have done it like this and it seems to work:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string[] row = { textBox1.Text, textBox2.Text, textBox3.Text };
        var listViewItem = new ListViewItem(row); 
        listView1.Items.Add(listViewItem);
    }
}

How to find whether a number belongs to a particular range in Python?

To check whether some number n is in the inclusive range denoted by the two number a and b you do either

if   a <= n <= b:
    print "yes"
else:
    print "no"

use the replace >= and <= with > and < to check whether n is in the exclusive range denoted by a and b (i.e. a and b are not themselves members of the range).

Range will produce an arithmetic progression defined by the two (or three) arguments converted to integers. See the documentation. This is not what you want I guess.

Are PHP Variables passed by value or by reference?

For anyone who comes across this in the future, I want to share this gem from the PHP docs, posted by an anonymous user:

There seems to be some confusion here. The distinction between pointers and references is not particularly helpful. The behavior in some of the "comprehensive" examples already posted can be explained in simpler unifying terms. Hayley's code, for example, is doing EXACTLY what you should expect it should. (Using >= 5.3)

First principle: A pointer stores a memory address to access an object. Any time an object is assigned, a pointer is generated. (I haven't delved TOO deeply into the Zend engine yet, but as far as I can see, this applies)

2nd principle, and source of the most confusion: Passing a variable to a function is done by default as a value pass, ie, you are working with a copy. "But objects are passed by reference!" A common misconception both here and in the Java world. I never said a copy OF WHAT. The default passing is done by value. Always. WHAT is being copied and passed, however, is the pointer. When using the "->", you will of course be accessing the same internals as the original variable in the caller function. Just using "=" will only play with copies.

3rd principle: "&" automatically and permanently sets another variable name/pointer to the same memory address as something else until you decouple them. It is correct to use the term "alias" here. Think of it as joining two pointers at the hip until forcibly separated with "unset()". This functionality exists both in the same scope and when an argument is passed to a function. Often the passed argument is called a "reference," due to certain distinctions between "passing by value" and "passing by reference" that were clearer in C and C++.

Just remember: pointers to objects, not objects themselves, are passed to functions. These pointers are COPIES of the original unless you use "&" in your parameter list to actually pass the originals. Only when you dig into the internals of an object will the originals change.

And here's the example they provide:

<?php

//The two are meant to be the same
$a = "Clark Kent"; //a==Clark Kent
$b = &$a; //The two will now share the same fate.

$b="Superman"; // $a=="Superman" too.
echo $a;
echo $a="Clark Kent"; // $b=="Clark Kent" too.
unset($b); // $b divorced from $a
$b="Bizarro";
echo $a; // $a=="Clark Kent" still, since $b is a free agent pointer now.

//The two are NOT meant to be the same.
$c="King";
$d="Pretender to the Throne";
echo $c."\n"; // $c=="King"
echo $d."\n"; // $d=="Pretender to the Throne"
swapByValue($c, $d);
echo $c."\n"; // $c=="King"
echo $d."\n"; // $d=="Pretender to the Throne"
swapByRef($c, $d);
echo $c."\n"; // $c=="Pretender to the Throne"
echo $d."\n"; // $d=="King"

function swapByValue($x, $y){
$temp=$x;
$x=$y;
$y=$temp;
//All this beautiful work will disappear
//because it was done on COPIES of pointers.
//The originals pointers still point as they did.
}

function swapByRef(&$x, &$y){
$temp=$x;
$x=$y;
$y=$temp;
//Note the parameter list: now we switched 'em REAL good.
}

?>

I wrote an extensive, detailed blog post on this subject for JavaScript, but I believe it applies equally well to PHP, C++, and any other language where people seem to be confused about pass by value vs. pass by reference.

Clearly, PHP, like C++, is a language that does support pass by reference. By default, objects are passed by value. When working with variables that store objects, it helps to see those variables as pointers (because that is fundamentally what they are, at the assembly level). If you pass a pointer by value, you can still "trace" the pointer and modify the properties of the object being pointed to. What you cannot do is have it point to a different object. Only if you explicitly declare a parameter as being passed by reference will you be able to do that.

Why am I getting error CS0246: The type or namespace name could not be found?

Check your Web.Config and find namespace = . you can remove or if you need it you must create new

Send Email Intent

This code is working in my device

Intent mIntent = new Intent(Intent.ACTION_SENDTO);
mIntent.setData(Uri.parse("mailto:"));
mIntent.putExtra(Intent.EXTRA_EMAIL  , new String[] {"[email protected]"});
mIntent.putExtra(Intent.EXTRA_SUBJECT, "");
startActivity(Intent.createChooser(mIntent, "Send Email Using..."));

What is the OAuth 2.0 Bearer Token exactly?

Bearer Token
A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).

The Bearer Token is created for you by the Authentication server. When a user authenticates your application (client) the authentication server then goes and generates for you a Token. Bearer Tokens are the predominant type of access token used with OAuth 2.0. A Bearer token basically says "Give the bearer of this token access".

The Bearer Token is normally some kind of opaque value created by the authentication server. It isn't random; it is created based upon the user giving you access and the client your application getting access.

In order to access an API for example you need to use an Access Token. Access tokens are short lived (around an hour). You use the bearer token to get a new Access token. To get an access token you send the Authentication server this bearer token along with your client id. This way the server knows that the application using the bearer token is the same application that the bearer token was created for. Example: I can't just take a bearer token created for your application and use it with my application it wont work because it wasn't generated for me.

Google Refresh token looks something like this: 1/mZ1edKKACtPAb7zGlwSzvs72PvhAbGmB8K1ZrGxpcNM

copied from comment: I don't think there are any restrictions on the bearer tokens you supply. Only thing I can think of is that its nice to allow more than one. For example a user can authenticate the application up to 30 times and the old bearer tokens will still work. oh and if one hasn't been used for say 6 months I would remove it from your system. It's your authentication server that will have to generate them and validate them so how it's formatted is up to you.

Update:

A Bearer Token is set in the Authorization header of every Inline Action HTTP Request. For example:

POST /rsvp?eventId=123 HTTP/1.1
Host: events-organizer.com
Authorization: Bearer AbCdEf123456
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/1.0 (KHTML, like Gecko; Gmail Actions)

rsvpStatus=YES

The string "AbCdEf123456" in the example above is the bearer authorization token. This is a cryptographic token produced by the authentication server. All bearer tokens sent with actions have the issue field, with the audience field specifying the sender domain as a URL of the form https://. For example, if the email is from [email protected], the audience is https://example.com.

If using bearer tokens, verify that the request is coming from the authentication server and is intended for the the sender domain. If the token doesn't verify, the service should respond to the request with an HTTP response code 401 (Unauthorized).

Bearer Tokens are part of the OAuth V2 standard and widely adopted by many APIs.

Facebook API: Get fans of / people who like a page

According to the Facebook documentation it's not possible to get all the fans of a page:

Although you can't get a list of all the fans of a Facebook Page, you can find out whether a specific person has liked a Page.

How to check if type of a variable is string?

Lots of good suggestions provided by others here, but I don't see a good cross-platform summary. The following should be a good drop in for any Python program:

def isstring(s):
    # if we use Python 3
    if (sys.version_info[0] >= 3):
        return isinstance(s, str)
    # we use Python 2
    return isinstance(s, basestring)

In this function, we use isinstance(object, classinfo) to see if our input is a str in Python 3 or a basestring in Python 2.

Determining type of an object in ruby

The proper way to determine the "type" of an object, which is a wobbly term in the Ruby world, is to call object.class.

Since classes can inherit from other classes, if you want to determine if an object is "of a particular type" you might call object.is_a?(ClassName) to see if object is of type ClassName or derived from it.

Normally type checking is not done in Ruby, but instead objects are assessed based on their ability to respond to particular methods, commonly called "Duck typing". In other words, if it responds to the methods you want, there's no reason to be particular about the type.

For example, object.is_a?(String) is too rigid since another class might implement methods that convert it into a string, or make it behave identically to how String behaves. object.respond_to?(:to_s) would be a better way to test that the object in question does what you want.

How to change Jquery UI Slider handle

.ui-slider .ui-slider-handle{
    width:50px; 
    height:50px; 
    background:url(../images/slider_grabber.png) no-repeat; overflow: hidden; 
    position:absolute;
    top: -10px;
    border-style:none; 
}

Clearing my form inputs after submission

I used the following with jQuery $("#submitForm").val("");

where submitForm is the id for the input element in the html. I ran it AFTER my function to extract the value from the input field. That extractValue function below:

function extractValue() { var value = $("#submitForm").val().trim(); console.log(value); };

Also don't forget to include preventDefault(); method to stop the submit type form from refreshing your page!

jQuery get selected option value (not the text, but the attribute 'value')

you can use jquery as follows

SCRIPT

  $('#IDOfyourdropdown').change(function(){
    alert($(this).val());
  });

FIDDLE is here

Longer object length is not a multiple of shorter object length?

Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.

In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.

Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.

Set timeout for ajax (jQuery)

You could use the timeout setting in the ajax options like this:

$.ajax({
    url: "test.html",
    timeout: 3000,
    error: function(){
        //do something
    },
    success: function(){
        //do something
    }
});

Read all about the ajax options here: http://api.jquery.com/jQuery.ajax/

Remember that when a timeout occurs, the error handler is triggered and not the success handler :)

oracle SQL how to remove time from date

You can use TRUNC on DateTime to remove Time part of the DateTime. So your where clause can be:

AND TRUNC(p1.PA_VALUE) >= TO_DATE('25/10/2012', 'DD/MM/YYYY')

The TRUNCATE (datetime) function returns date with the time portion of the day truncated to the unit specified by the format model.

How to generate random float number in C

while it might not matter now here is a function which generate a float between 2 values.

#include <math.h>

float func_Uniform(float left, float right) {
    float randomNumber = sin(rand() * rand());
    return left + (right - left) * fabs(randomNumber);
}

TypeScript error: Type 'void' is not assignable to type 'boolean'

It means that the callback function you passed to this.dataStore.data.find should return a boolean and have 3 parameters, two of which can be optional:

  • value: Conversations
  • index: number
  • obj: Conversation[]

However, your callback function does not return anything (returns void). You should pass a callback function with the correct return value:

this.dataStore.data.find((element, index, obj) => {
    // ...

    return true; // or false
});

or:

this.dataStore.data.find(element => {
    // ...

    return true; // or false
});

Reason why it's this way: the function you pass to the find method is called a predicate. The predicate here defines a boolean outcome based on conditions defined in the function itself, so that the find method can determine which value to find.

In practice, this means that the predicate is called for each item in data, and the first item in data for which your predicate returns true is the value returned by find.

Is it ok to scrape data from Google results?

Google disallows automated access in their TOS, so if you accept their terms you would break them.

That said, I know of no lawsuit from Google against a scraper. Even Microsoft scraped Google, they powered their search engine Bing with it. They got caught in 2011 red handed :)

There are two options to scrape Google results:

1) Use their API

UPDATE 2020: Google has reprecated previous APIs (again) and has new prices and new limits. Now (https://developers.google.com/custom-search/v1/overview) you can query up to 10k results per day at 1,500 USD per month, more than that is not permitted and the results are not what they display in normal searches.

  • You can issue around 40 requests per hour You are limited to what they give you, it's not really useful if you want to track ranking positions or what a real user would see. That's something you are not allowed to gather.

  • If you want a higher amount of API requests you need to pay.

  • 60 requests per hour cost 2000 USD per year, more queries require a custom deal.

2) Scrape the normal result pages

  • Here comes the tricky part. It is possible to scrape the normal result pages. Google does not allow it.
  • If you scrape at a rate higher than 8 (updated from 15) keyword requests per hour you risk detection, higher than 10/h (updated from 20) will get you blocked from my experience.
  • By using multiple IPs you can up the rate, so with 100 IP addresses you can scrape up to 1000 requests per hour. (24k a day) (updated)
  • There is an open source search engine scraper written in PHP at http://scraping.compunect.com It allows to reliable scrape Google, parses the results properly and manages IP addresses, delays, etc. So if you can use PHP it's a nice kickstart, otherwise the code will still be useful to learn how it is done.

3) Alternatively use a scraping service (updated)

  • Recently a customer of mine had a huge search engine scraping requirement but it was not 'ongoing', it's more like one huge refresh per month.
    In this case I could not find a self-made solution that's 'economic'.
    I used the service at http://scraping.services instead. They also provide open source code and so far it's running well (several thousand resultpages per hour during the refreshes)
  • The downside is that such a service means that your solution is "bound" to one professional supplier, the upside is that it was a lot cheaper than the other options I evaluated (and faster in our case)
  • One option to reduce the dependency on one company is to make two approaches at the same time. Using the scraping service as primary source of data and falling back to a proxy based solution like described at 2) when required.

What is the difference between a stored procedure and a view?

Mahesh is not quite correct when he suggests that you can't alter the data in a view. So with patrick's view

CREATE View vw_user_profile AS 
Select A.user_id, B.profile_description
FROM tbl_user A left join tbl_profile B on A.user_id = b.user_id

I CAN update the data ... as an example I can do either of these ...

Update vw_user_profile Set profile_description='Manager' where user_id=4

or

Update tbl_profile Set profile_description='Manager' where user_id=4

You can't INSERT to this view as not all of the fields in all of the table are present and I'm assuming that PROFILE_ID is the primary key and can't be NULL. However you can sometimes INSERT into a view ...

I created a view on an existing table using ...

Create View Junk as SELECT * from [TableName]

THEN

Insert into junk (Code,name) values 
('glyn','Glyn Roberts'),
('Mary','Maryann Roberts')

and

DELETE from Junk Where ID>4

Both the INSERT and the DELETE worked in this case

Obviously you can't update any fields which are aggregated or calculated but any view which is just a straight view should be updateable.

If the view contains more than one table then you can't insert or delete but if the view is a subset of one table only then you usually can.

What does "Use of unassigned local variable" mean?

Give them a default value:

double lateFee=0.0;
double monthlyCharge = 0.0;
double annualRate = 0.0;

Basically, all possible paths don't initialize these variables.

How do I check if file exists in jQuery or pure JavaScript?

For a client computer this can be achieved by:

try
{
  var myObject, f;
  myObject = new ActiveXObject("Scripting.FileSystemObject");
  f =   myObject.GetFile("C:\\img.txt");
  f.Move("E:\\jarvis\\Images\\");
}
catch(err)
{
  alert("file does not exist")
}

This is my program to transfer a file to a specific location and shows alert if it does not exist

JQuery string contains check

var str1 = "ABCDEFGHIJKLMNOP";
var str2 = "DEFG";

sttr1.search(str2);

it will return the position of the match, or -1 if it isn't found.

I can't access http://localhost/phpmyadmin/

Or it could be that Skype is running on the same port (it does by default).

Disable Skype or configure Skype to use another port

Correct way to work with vector of arrays

Every element of your vector is a float[4], so when you resize every element needs to default initialized from a float[4]. I take it you tried to initialize with an int value like 0?

Try:

static float zeros[4] = {0.0, 0.0, 0.0, 0.0};
myvector.resize(newsize, zeros);

What does the 'b' character do in front of a string literal?

The b denotes a byte string.

Bytes are the actual data. Strings are an abstraction.

If you had multi-character string object and you took a single character, it would be a string, and it might be more than 1 byte in size depending on encoding.

If took 1 byte with a byte string, you'd get a single 8-bit value from 0-255 and it might not represent a complete character if those characters due to encoding were > 1 byte.

TBH I'd use strings unless I had some specific low level reason to use bytes.

counting the number of lines in a text file

I think your question is, "why am I getting one more line than there is in the file?"

Imagine a file:

line 1
line 2
line 3

The file may be represented in ASCII like this:

line 1\nline 2\nline 3\n

(Where \n is byte 0x10.)

Now let's see what happens before and after each getline call:

Before 1: line 1\nline 2\nline 3\n
  Stream: ^
After 1:  line 1\nline 2\nline 3\n
  Stream:         ^

Before 2: line 1\nline 2\nline 3\n
  Stream:         ^
After 2:  line 1\nline 2\nline 3\n
  Stream:                 ^

Before 2: line 1\nline 2\nline 3\n
  Stream:                 ^
After 2:  line 1\nline 2\nline 3\n
  Stream:                         ^

Now, you'd think the stream would mark eof to indicate the end of the file, right? Nope! This is because getline sets eof if the end-of-file marker is reached "during it's operation". Because getline terminates when it reaches \n, the end-of-file marker isn't read, and eof isn't flagged. Thus, myfile.eof() returns false, and the loop goes through another iteration:

Before 3: line 1\nline 2\nline 3\n
  Stream:                         ^
After 3:  line 1\nline 2\nline 3\n
  Stream:                         ^ EOF

How do you fix this? Instead of checking for eof(), see if .peek() returns EOF:

while(myfile.peek() != EOF){
    getline ...

You can also check the return value of getline (implicitly casting to bool):

while(getline(myfile,line)){
    cout<< ...

How does cellForRowAtIndexPath work?

I'll try and break it down (example from documention)

/* 
 *   The cellForRowAtIndexPath takes for argument the tableView (so if the same object
 *   is delegate for several tableViews it can identify which one is asking for a cell),
 *   and an indexPath which determines which row and section the cell is returned for. 
 */ 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    /*
     *   This is an important bit, it asks the table view if it has any available cells
     *   already created which it is not using (if they are offScreen), so that it can
     *   reuse them (saving the time of alloc/init/load from xib a new cell ).
     *   The identifier is there to differentiate between different types of cells
     *   (you can display different types of cells in the same table view)
     */

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];

    /*
     *   If the cell is nil it means no cell was available for reuse and that we should
     *   create a new one.
     */
    if (cell == nil) {

        /* 
         *   Actually create a new cell (with an identifier so that it can be dequeued). 
         */

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"] autorelease];

        cell.selectionStyle = UITableViewCellSelectionStyleNone;

    }

    /*
     *   Now that we have a cell we can configure it to display the data corresponding to
     *   this row/section
     */

    NSDictionary *item = (NSDictionary *)[self.content objectAtIndex:indexPath.row];
    cell.textLabel.text = [item objectForKey:@"mainTitleKey"];
    cell.detailTextLabel.text = [item objectForKey:@"secondaryTitleKey"];
    NSString *path = [[NSBundle mainBundle] pathForResource:[item objectForKey:@"imageKey"] ofType:@"png"];
    UIImage *theImage = [UIImage imageWithContentsOfFile:path];
    cell.imageView.image = theImage;

    /* Now that the cell is configured we return it to the table view so that it can display it */

    return cell;

}

This is a DataSource method so it will be called on whichever object has declared itself as the DataSource of the UITableView. It is called when the table view actually needs to display the cell onscreen, based on the number of rows and sections (which you specify in other DataSource methods).

Binding a WPF ComboBox to a custom list

I had what at first seemed to be an identical problem, but it turned out to be due to an NHibernate/WPF compatibility issue. The problem was caused by the way WPF checks for object equality. I was able to get my stuff to work by using the object ID property in the SelectedValue and SelectedValuePath properties.

<ComboBox Name="CategoryList"
          DisplayMemberPath="CategoryName"
          SelectedItem="{Binding Path=CategoryParent}"
          SelectedValue="{Binding Path=CategoryParent.ID}"
          SelectedValuePath="ID">

See the blog post from Chester, The WPF ComboBox - SelectedItem, SelectedValue, and SelectedValuePath with NHibernate, for details.

REST API - Use the "Accept: application/json" HTTP Header

Well Curl could be a better option for json representation but in that case it would be difficult to understand the structure of json because its in command line. if you want to get your json on browser you simply remove all the XML Annotations like -

@XmlRootElement(name="person")
@XmlAccessorType(XmlAccessType.NONE)
@XmlAttribute
@XmlElement

from your model class and than run the same url, you have used for xml representation.

Make sure that you have jacson-databind dependency in your pom.xml

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.4.1</version>
</dependency>

Blue and Purple Default links, how to remove?

Hey define color #000 into as like you and modify your css as like this

.navBtn { text-decoration: none; color:#000; }
.navBtn:visited { text-decoration: none; color:#000; }
.navBtn:hover { text-decoration: none; color:#000; }
.navBtn:focus { text-decoration: none; color:#000; }
.navBtn:hover, .navBtn:active { text-decoration: none; color:#000; }

or this

 li a { text-decoration: none; color:#000; }
 li a:visited { text-decoration: none; color:#000; }
 li a:hover { text-decoration: none; color:#000; }
 li a:focus { text-decoration: none; color:#000; }
 li a:hover, .navBtn:active { text-decoration: none; color:#000; }

Cocoa Touch: How To Change UIView's Border Color And Thickness?

@IBInspectable is working for me on iOS 9 , Swift 2.0

extension UIView {

@IBInspectable var borderWidth: CGFloat {
get {
        return layer.borderWidth
    }
    set(newValue) {
        layer.borderWidth = newValue
    }
}

@IBInspectable var cornerRadius: CGFloat {
    get {
        return layer.cornerRadius
    }
    set(newValue) {
        layer.cornerRadius = newValue
    }
}

@IBInspectable var borderColor: UIColor? {
    get {
        if let color = layer.borderColor {
            return UIColor(CGColor: color)
        }
        return nil
    }
    set(newValue) {
        layer.borderColor = newValue?.CGColor
    }
}

Printing everything except the first field with awk

awk '{ tmp = $1; sub(/^[^ ]+ +/, ""); print $0, tmp }'

If table exists drop table then create it, if it does not exist just create it

Just put DROP TABLE IF EXISTS `tablename`; before your CREATE TABLE statement.

That statement drops the table if it exists but will not throw an error if it does not.

Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile

Your Maven is reading Java version as 1.6.0_65, Where as the pom.xml says the version is 1.7.

Try installing the required verison.

If already installed check your $JAVA_HOME environment variable, it should contain the path of Java JDK 7. If you dont find it, fix your environment variable.

also remove the lines

 <fork>true</fork>
     <executable>${JAVA_1_7_HOME}/bin/javac</executable>

from the pom.xml

Can curl make a connection to any TCP ports, not just HTTP/HTTPS?

Of course:

curl http://example.com:11740
curl https://example.com:11740

Port 80 and 443 are just default port numbers.

Where IN clause in LINQ

This little bit different idea. But it will useful to you. I have used sub query to inside the linq main query.

Problem:

Let say we have document table. Schema as follows schema : document(name,version,auther,modifieddate) composite Keys : name,version

So we need to get latest versions of all documents.

soloution

 var result = (from t in Context.document
                          where ((from tt in Context.document where t.Name == tt.Name
                                orderby tt.Version descending select new {Vesion=tt.Version}).FirstOrDefault()).Vesion.Contains(t.Version)
                          select t).ToList();

Disable/enable an input with jQuery?

You can put this somewhere global in your code:

$.prototype.enable = function () {
    $.each(this, function (index, el) {
        $(el).removeAttr('disabled');
    });
}

$.prototype.disable = function () {
    $.each(this, function (index, el) {
        $(el).attr('disabled', 'disabled');
    });
}

And then you can write stuff like:

$(".myInputs").enable();
$("#otherInput").disable();

Converting ArrayList to Array in java

You don't need to reinvent the wheel, here's the toArray() method:

String []dsf = new String[al.size()];
al.toArray(dsf);

Override intranet compatibility mode IE8

I had struggled with this issue and wanted to help provide a unique solution and insight.

Certain AJAX based frameworks will inject javascripts and stylesheets at the beginning of the <head> and doing this seems to prevent the well-established meta tag solution from working properly. In this case I found that directly injecting into the HTTP response header, much like Andras Csehi's answer will solve the problem.

For those of us using Java Servlets however, a good way to solve this is to use a ServletFilter.

public class EmulateFilter implements Filter {

@Override
public void destroy() {
}

@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
        FilterChain arg2) throws IOException, ServletException {
    HttpServletResponse response = ((HttpServletResponse)arg1);
    response.addHeader("X-UA-Compatible", "IE=8");
    arg2.doFilter(arg0, arg1);
}

@Override
public void init(FilterConfig arg0) throws ServletException {
}

}

Tomcat view catalina.out log file

I found logs of Apache Tomcat/9.0.33 version in below path:

In tail -f /opt/tomcat/logs/catalina.out

Thanks.

Open Source Javascript PDF viewer

You can use the Google Docs PDF-viewing widget, if you don't mind having them host the "application" itself.

I had more suggestions, but stack overflow only lets me post one hyperlink as a new user, sorry.

How to do a Postgresql subquery in select clause with join in from clause like SQL Server?

select n1.name, n1.author_id, cast(count_1 as numeric)/total_count
  from (select id, name, author_id, count(1) as count_1
          from names
          group by id, name, author_id) n1
inner join (select distinct(author_id), count(1) as total_count
              from names) n2
  on (n2.author_id = n1.author_id)
Where true

used distinct if more inner join, because more join group performance is slow

What is aria-label and how should I use it?

Prerequisite:

Aria is used to improve the user experience of visually impaired users. Visually impaired users navigate though application using screen reader software like JAWS, NVDA,.. While navigating through the application, screen reader software announces content to users. Aria can be used to add content in the code which helps screen reader users understand role, state, label and purpose of the control

Aria does not change anything visually. (Aria is scared of designers too).

aria-label

aria-label attribute is used to communicate the label to screen reader users. Usually search input field does not have visual label (thanks to designers). aria-label can be used to communicate the label of control to screen reader users

How To Use:

<input type="edit" aria-label="search" placeholder="search">

There is no visual change in application. But screen readers can understand the purpose of control

aria-labelledby

Both aria-label and aria-labelledby is used to communicate the label. But aria-labelledby can be used to reference any label already present in the page whereas aria-label is used to communicate the label which i not displayed visually

Approach 1:

<span id="sd">Search</span>

<input type="text" aria-labelledby="sd">

Approach 2:

aria-labelledby can also be used to combine two labels for screen reader users

<span id="de">Billing Address</span>

<span id="sd">First Name</span>

<input type="text" aria-labelledby="de sd">

Is there a "not equal" operator in Python?

Use !=. See comparison operators. For comparing object identities, you can use the keyword is and its negation is not.

e.g.

1 == 1 #  -> True
1 != 1 #  -> False
[] is [] #-> False (distinct objects)
a = b = []; a is b # -> True (same object)

List All Google Map Marker Images

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

Detect change to ngModel on a select tag (Angular 2)

Update:

Separate the event and property bindings:

<select [ngModel]="selectedItem" (ngModelChange)="onChange($event)">
onChange(newValue) {
    console.log(newValue);
    this.selectedItem = newValue;  // don't forget to update the model here
    // ... do other stuff here ...
}

You could also use

<select [(ngModel)]="selectedItem" (ngModelChange)="onChange($event)">

and then you wouldn't have to update the model in the event handler, but I believe this causes two events to fire, so it is probably less efficient.


Old answer, before they fixed a bug in beta.1:

Create a local template variable and attach a (change) event:

<select [(ngModel)]="selectedItem" #item (change)="onChange(item.value)">

plunker

See also How can I get new selection in "select" in Angular 2?

How to prevent a click on a '#' link from jumping to top of page?

I have used:

<a href="javascript://nop/" class="someClass">Text</a>

String concatenation in MySQL

Use concat() function instead of + like this:

select concat(firstname, lastname) as "Name" from test.student

Unable to preventDefault inside passive event listener

In plain JS add { passive: false } as third argument

document.addEventListener('wheel', function(e) {
    e.preventDefault();
    doStuff(e);
}, { passive: false });

The tilde operator in Python

One should note that in the case of array indexing, array[~i] amounts to reversed_array[i]. It can be seen as indexing starting from the end of the array:

[0, 1, 2, 3, 4, 5, 6, 7, 8]
    ^                 ^
    i                ~i

Oracle - How to create a readonly user

It is not strictly possible in default db due to the many public executes that each user gains automatically through public.

How to find integer array size in java

The length of an array is available as

int l = array.length;

The size of a List is availabe as

int s = list.size();

How to completely hide the navigation bar in iPhone / HTML5

Simple javascript document navigation to "#" will do it.

window.onload = function()
{
document.location.href = "#";
}

This will force the navigation bar to remove itself on load.

How do you tell if caps lock is on using JavaScript?

So I found this page and didn't really like the solutions I found so I figured one out and am offering it up to all of you. For me, it only matters if the caps lock is on if I'm typing letters. This code solved the problem for me. Its quick and easy and gives you a capsIsOn variable to reference whenever you need it.

_x000D_
_x000D_
let capsIsOn=false;_x000D_
let capsChecked=false;_x000D_
_x000D_
let capsCheck=(e)=>{_x000D_
    let letter=e.key;_x000D_
    if(letter.length===1 && letter.match(/[A-Za-z]/)){_x000D_
        if(letter!==letter.toLowerCase()){_x000D_
          capsIsOn=true;_x000D_
          console.log('caps is on');_x000D_
        }else{_x000D_
          console.log('caps is off');_x000D_
        }_x000D_
        capsChecked=true;_x000D_
        window.removeEventListener("keyup",capsCheck);_x000D_
    }else{_x000D_
      console.log("not a letter, not capsCheck was performed");_x000D_
    }_x000D_
_x000D_
}_x000D_
_x000D_
window.addEventListener("keyup",capsCheck);_x000D_
_x000D_
window.addEventListener("keyup",(e)=>{_x000D_
  if(capsChecked && e.keyCode===20){_x000D_
    capsIsOn=!capsIsOn;_x000D_
  }_x000D_
});
_x000D_
_x000D_
_x000D_

Multi column forms with fieldsets

There are a couple of things that need to be adjusted in your layout:

  1. You are nesting col elements within form-group elements. This should be the other way around (the form-group should be within the col-sm-xx element).

  2. You should always use a row div for each new "row" in your design. In your case, you would need at least 5 rows (Username, Password and co, Title/First/Last name, email, Language). Otherwise, your problematic .col-sm-12 is still on the same row with the above 3 .col-sm-4 resulting in a total of columns greater than 12, and causing the overlap problem.

Here is a fixed demo.

And an excerpt of what the problematic section HTML should become:

<fieldset>
    <legend>Personal Information</legend>
    <div class='row'>
        <div class='col-sm-4'>    
            <div class='form-group'>
                <label for="user_title">Title</label>
                <input class="form-control" id="user_title" name="user[title]" size="30" type="text" />
            </div>
        </div>
        <div class='col-sm-4'>
            <div class='form-group'>
                <label for="user_firstname">First name</label>
                <input class="form-control" id="user_firstname" name="user[firstname]" required="true" size="30" type="text" />
            </div>
        </div>
        <div class='col-sm-4'>
            <div class='form-group'>
                <label for="user_lastname">Last name</label>
                <input class="form-control" id="user_lastname" name="user[lastname]" required="true" size="30" type="text" />
            </div>
        </div>
    </div>
    <div class='row'>
        <div class='col-sm-12'>
            <div class='form-group'>

                <label for="user_email">Email</label>
                <input class="form-control required email" id="user_email" name="user[email]" required="true" size="30" type="text" />
            </div>
        </div>
    </div>
</fieldset>

Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

Combining a few of the approaches already mentioned (the indexOf is obviously rather simple), I think these are the functions that will do the trick:

function regexIndexOf(string, regex, startpos) {
    var indexOf = string.substring(startpos || 0).search(regex);
    return (indexOf >= 0) ? (indexOf + (startpos || 0)) : indexOf;
}

function regexLastIndexOf(string, regex, startpos) {
    regex = (regex.global) ? regex : new RegExp(regex.source, "g" + (regex.ignoreCase ? "i" : "") + (regex.multiLine ? "m" : ""));
    if(typeof (startpos) == "undefined") {
        startpos = string.length;
    } else if(startpos < 0) {
        startpos = 0;
    }
    var stringToWorkWith = string.substring(0, startpos + 1);
    var lastIndexOf = -1;
    var nextStop = 0;
    while((result = regex.exec(stringToWorkWith)) != null) {
        lastIndexOf = result.index;
        regex.lastIndex = ++nextStop;
    }
    return lastIndexOf;
}

UPDATE: Edited regexLastIndexOf() so that is seems to mimic lastIndexOf() now. Please let me know if it still fails and under what circumstances.


UPDATE: Passes all tests found on in comments on this page, and my own. Of course, that doesn't mean it's bulletproof. Any feedback appreciated.

C# equivalent to Java's charAt()?

Simply use String.ElementAt(). It's quite similar to java's String.charAt(). Have fun coding!

Set port for php artisan.php serve

as this example you can change ip and port this works with me

php artisan serve --host=0.0.0.0 --port=8000

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

This code will return your Date object formatted with the browser timezone.

Date.prototype.timezone = function () {
    this.setHours(this.getHours() + (new Date().getTimezoneOffset() / 60));
    return this;
}

Edit:

To avoid to pollute the Date API, the above function can be transformed into a utility function. The function takes a Date object, and returns a mutated Date object.

function setTimeZone(date) {
    date.setHours(date.getHours() + (new Date().getTimezoneOffset() / 60));
    return date;
}

a page can have only one server-side form tag

Use only one server side form tag.

Check your Master page for <form runat="server"> - there should be only one.

Why do you need more than one?

Get Hours and Minutes (HH:MM) from date

You can easily use Format() function instead of all the casting for sql 2012 and above only

SELECT FORMAT(GETDATE(),'hh:mm')

This is by far the best way to do the required conversion.

How to detect if numpy is installed

The traditional method for checking for packages in Python is "it's better to beg forgiveness than ask permission", or rather, "it's better to catch an exception than test a condition."

try:
    import numpy
    HAS_NUMPY = True
except ImportError:
    HAS_NUMPY = False

How can I convert string to datetime with format specification in JavaScript?

Just for an updated answer here, there's a good js lib at http://www.datejs.com/

Datejs is an open source JavaScript Date library for parsing, formatting and processing.

'router-outlet' is not a known element

This issue was with me also. Simple trick for it.

 @NgModule({
  imports: [
   .....       
  ],
 declarations: [
  ......
 ],

 providers: [...],
 bootstrap: [...]
 })

use it as in above order.first imports then declarations.It worked for me.

Unable to set data attribute using jQuery Data() API

Had the same problem. Since you can still get data using the .data() method, you only have to figure out a way to write to the elements. This is the helper method I use. Like most people have said, you will have to use .attr. I have it replacing any _ with - as I know it does that. I'm not aware of any other characters it replaces...however I have not researched that.

function ExtendElementData(element, object){
    //element is what you want to set data on
    //object is a hash/js-object
    var keys = Object.keys(object);
    for (var i = 0; i < keys.length; i++){
        var key = keys[i];
        $(element).attr('data-'+key.replace("_", "-"), object[key]);
    }
}

EDIT: 5/1/2017

I found there were still instances where you could not get the correct data using built in methods so what I use now is as follows:

function setDomData(element, object){
    //object is a hash

    var keys = Object.keys(object);
    for (var i = 0; i < keys.length; i++){
        var key = keys[i];
        $(element).attr('data-'+key.replace("_", "-"), object[key]);
    }
};

function getDomData(element, key){
    var domObject = $(element).get(0);
    var attKeys = Object.keys(domObject.attributes);

    var values = null;
    if (key != null){
        values = $(element).attr('data-' + key);
    } else {
        values = {};

        var keys = [];
        for (var i = 0; i < attKeys.length; i++) {
            keys.push(domObject.attributes[attKeys[i]]);
        }

        for (var i = 0; i < keys.length; i++){
            if(!keys[i].match(/data-.*/)){
                values[keys[i]] = $(element).attr(keys[i]);
            }
        }
    }
    return values;
};

How to count lines of Java code using IntelliJ IDEA?

The Statistic plugin worked for me.

To install it from Intellij:

File - Settings - Plugins - Browse repositories... Find it on the list and double-click on it.

Access the 'statistic' toolbar via tabs in bottom left of project screen capture of statistic toolbar, bottom left

OLDER VERSIONS: Open statistics window from:

View -> Tool Windows -> Statistic

How do I clear the content of a div using JavaScript?

You can do it the DOM way as well:

var div = document.getElementById('cart_item');
while(div.firstChild){
    div.removeChild(div.firstChild);
}

Importing images from a directory (Python) to list or dictionary

I'd start by using glob:

from PIL import Image
import glob
image_list = []
for filename in glob.glob('yourpath/*.gif'): #assuming gif
    im=Image.open(filename)
    image_list.append(im)

then do what you need to do with your list of images (image_list).

Return Type for jdbcTemplate.queryForList(sql, object, classType)

A complete solution for JdbcTemplate, NamedParameterJdbcTemplate with or without RowMapper Example.

// Create a Employee table

create table employee(  
id number(10),  
name varchar2(100),  
salary number(10)  
);

======================================================================= //Employee.java

public class Employee {
private int id;  
private String name;  
private float salary;  

//no-arg and parameterized constructors  

public Employee(){};

public Employee(int  id, String name, float salary){
    this.id=id;
    this.name=name;
    this.salary=salary;
}

//getters and setters  
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public float getSalary() {
    return salary;
}
public void setSalary(float salary) {
    this.salary = salary;
}
public String toString(){  
   return id+" "+name+" "+salary;  
}   

}

========================================================================= //EmployeeDao.java

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

public class EmployeeDao {  
  private JdbcTemplate jdbcTemplate;  
  private NamedParameterJdbcTemplate nameTemplate;  

  public void setnameTemplate(NamedParameterJdbcTemplate template) {  
    this.nameTemplate = template;  
 }   

 public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {  
  this.jdbcTemplate = jdbcTemplate;  
 }  

 // BY using JdbcTemplate
 public int saveEmployee(Employee e){  
 int id = e.getId();
 String name = e.getName();
 float salary = e.getSalary();
 Object p[] = {id, name, salary};
    String query="insert into employee values(?,?,?)";
      return jdbcTemplate.update(query, p);
    /*String query="insert into employee     values('"+e.getId()+"','"+e.getName()+"','"+e.getSalary()+"')"; 
      return jdbcTemplate.update(query);
    */

}  

//By using NameParameterTemplate
public void insertEmploye(Employee e) {  
String query="insert into employee values (:id,:name,:salary)";  
Map<String,Object> map=new HashMap<String,Object>();  
map.put("id",e.getId());  
map.put("name",e.getName());  
map.put("salary",e.getSalary());  

nameTemplate.execute(query,map,new MyPreparedStatement());

 }
// Updating Employee
public int updateEmployee(Employee e){  
String query="update employee set  name='"+e.getName()+"',salary='"+e.getSalary()+"' where id='"+e.getId()+"' ";  
  return jdbcTemplate.update(query);  
 }
 // Deleting a Employee row
 public int deleteEmployee(Employee e){  
 String query="delete from employee where id='"+e.getId()+"' ";  
 return jdbcTemplate.update(query);  
 }  
 //Selecting Single row with condition and also all rows
    public int selectEmployee(Employee e){  
     //String query="select * from employee where id='"+e.getId()+"' ";
      String query="select * from employee";
      List<Map<String, Object>> rows = jdbcTemplate.queryForList(query);
       for(Map<String, Object> row : rows){
          String id = row.get("id").toString();
          String name = (String)row.get("name");
          String salary = row.get("salary").toString();
          System.out.println(id + " " + name + " " + salary );
        }

      return 1;
   }  

   // Can use MyrowMapper class an implementation class for RowMapper interface
    public void getAllEmployee()
    {

    String query="select * from employee";
    List<Employee> l = jdbcTemplate.query(query, new MyrowMapper());

    Iterator it=l.iterator();
    while(it.hasNext())
    {
      Employee e=(Employee)it.next();
      System.out.println(e.getId()+" "+e.getName()+" "+e.getSalary());
    }
   }  

  //Can use directly a RowMapper implementation class without an object creation
  public List<Employee> getAllEmployee1(){
    return jdbcTemplate.query("select * from employee",new RowMapper<Employee>(){  
      @Override  
      public Employee mapRow(ResultSet rs, int rownumber) throws  SQLException    {  
            Employee e=new Employee();  
            e.setId(rs.getInt(1));  
            e.setName(rs.getString(2));  
            e.setSalary(rs.getFloat(3));  
            return e;  
          }  
      });  
      }
     // End of all the function

     }

================================================================ //MyrowMapper.java

 import java.sql.ResultSet;
 import java.sql.SQLException;
 import org.springframework.jdbc.core.RowMapper;

 public class MyrowMapper implements RowMapper<Employee> {

  @Override  
  public Employee mapRow(ResultSet rs, int rownumber) throws SQLException 
   {  
    System.out.println("mapRow()====:"+rownumber);
    Employee e=new Employee();  
     e.setId(rs.getInt("id"));  
     e.setName(rs.getString("name"));  
     e.setSalary(rs.getFloat("salary"));  
     return e;  
      }
    } 

========================================================== //MyPreparedStatement.java

import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.PreparedStatementCallback;


 public class MyPreparedStatement implements  PreparedStatementCallback<Object> {

 @Override
 public Object doInPreparedStatement(PreparedStatement ps)
        throws SQLException, DataAccessException {

     return ps.executeUpdate(); 
  } 

 } 

===================================================================== //Test.java

import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {  

public static void main(String[] args) {  
 ApplicationContext ctx=new     ClassPathXmlApplicationContext("applicationContext.xml");  

 EmployeeDao dao=(EmployeeDao)ctx.getBean("edao"); 

  // By calling constructor for insert
 /* 
    int status=dao.saveEmployee(new Employee(103,"Ajay",35000));  
    System.out.println(status);  
 */
 // By calling PreparedStatement
  dao.insertEmploye(new Employee(103,"Roh",25000));


 // By calling setter-getter for update
 /* 
    Employee e=new Employee(); 
    e.setId(102);
    e.setName("Rohit");
    e.setSalary(8000000);
    int status=dao.updateEmployee(e);
*/
 // By calling constructor for update
 /*
    int status=dao.updateEmployee(new Employee(102,"Sadhan",15000)); 
    System.out.println(status); 
 */ 
 // Deleting a record 
 /*      
    Employee e=new Employee(); 
    e.setId(102); 
    int status=dao.deleteEmployee(e); 
    System.out.println(status);
 */
 // Selecting single or all rows
 /*
    Employee e=new Employee(); 
    e.setId(102);
    int status=dao.selectEmployee(e);
    System.out.println(status);
*/
// Can use MyrowMapper class an implementation class for RowMapper interface

    dao.getAllEmployee();

// Can use directly a RowMapper implementation class without an object creation
 /*
    List<Employee> list=dao.getAllEmployee1();  
    for(Employee e1:list)  
    System.out.println(e1);  
  */   
   }  

 } 

================================================================== //applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>  
<beans  
 xmlns="http://www.springframework.org/schema/beans"  
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
 xmlns:p="http://www.springframework.org/schema/p"  
 xsi:schemaLocation="http://www.springframework.org/schema/beans   
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  

<bean id="ds"        class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
 <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />  
 <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe" />  
 <property name="username" value="hr" />  
 <property name="password" value="hr" />  
 </bean>  

 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">  
 <property name="dataSource" ref="ds"></property>  
 </bean>  

<bean id="nameTemplate"   
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">  
<constructor-arg ref="ds"></constructor-arg>  
</bean>  

<bean id="edao" class="EmployeeDao"> 
<!-- Can use both --> 
<property name="nameTemplate" ref="nameTemplate"></property>
<property name="jdbcTemplate" ref="jdbcTemplate"></property> 
</bean>  

===================================================================

Warning:No JDK specified for module 'Myproject'.when run my project in Android studio

I was able to fix it using the answer here: https://stackoverflow.com/a/32176571/1174024 But I have 150 modules. So I would have had to perform this step 150 times.

So I needed to do it a different way.

So first close the existing project, then Import it again, In the first step of the wizard choose "Gradle" project. Then the next step of the wizard has the Gradle project properties. Here it's going to ask you for, among other things, the Java SDK to use. The default will be "Project SDK". Do not use this default, instead hand pick your Java SDK from the list. Then finish the import.

Now the problem should go away.

href="tel:" and mobile numbers

The BlackBerry browser and Safari for iOS (iPhone/iPod/iPad) automatically detect phone numbers and email addresses and convert them to links. If you don’t want this feature, you should use the following meta tags.

For Safari:

<meta name="format-detection" content="telephone=no">

For BlackBerry:

<meta http-equiv="x-rim-auto-match" content="none">

Source: mobilexweb.com

SQL Server Creating a temp table for this query

Like this. Make sure you drop the temp table (at the end of the code block, after you're done with it) or it will error on subsequent runs.

SELECT  
    tblMEP_Sites.Name AS SiteName, 
    convert(varchar(10),BillingMonth ,101) AS BillingMonth, 
    SUM(Consumption) AS Consumption
INTO 
    #MyTempTable
FROM 
    tblMEP_Projects
    JOIN tblMEP_Sites
        ON tblMEP_Projects.ID = tblMEP_Sites.ProjectID
    JOIN tblMEP_Meters
        ON tblMEP_Meters.SiteID = tblMEP_Sites.ID
    JOIN tblMEP_MonthlyData
        ON tblMEP_MonthlyData.MeterID = tblMEP_Meters.ID
    JOIN tblMEP_CustomerAccounts
        ON tblMEP_CustomerAccounts.ID = tblMEP_Meters.CustomerAccountID
    JOIN tblMEP_UtilityCompanies
        ON tblMEP_UtilityCompanies.ID = tblMEP_CustomerAccounts.UtilityCompanyID
    JOIN tblMEP_MeterTypes
        ON tblMEP_UtilityCompanies.UtilityTypeID = tblMEP_MeterTypes.ID
WHERE 
    tblMEP_Projects.ID = @ProjectID
    AND tblMEP_MonthlyData.BillingMonth Between @StartDate AND @EndDate
    AND tbLMEP_MeterTypes.ID = @MeterTypeID
GROUP BY 
    BillingMonth, tblMEP_Sites.Name

DROP TABLE #MyTempTable

How to get last key in an array?

Dont know if this is going to be faster or not, but it seems easier to do it this way, and you avoid the error by not passing in a function to end()...

it just needed a variable... not a big deal to write one more line of code, then unset it if you needed to.

$array = array(
    'first' => 123,
    'second' => 456,
    'last' => 789, 
);

$keys = array_keys($array);
$last = end($keys);

Get input value from TextField in iOS alert in Swift

Updated for Swift 3 and above:

//1. Create the alert controller.
let alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .alert)

//2. Add the text field. You can configure it however you need.
alert.addTextField { (textField) in
    textField.text = "Some default text"
}

// 3. Grab the value from the text field, and print it when the user clicks OK.
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
    let textField = alert.textFields![0] // Force unwrapping because we know it exists.
    print("Text field: \(textField.text)")
}))

// 4. Present the alert.
self.present(alert, animated: true, completion: nil)

Swift 2.x

Assuming you want an action alert on iOS:

//1. Create the alert controller.            
var alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .Alert)

//2. Add the text field. You can configure it however you need.
alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
    textField.text = "Some default text."
})

//3. Grab the value from the text field, and print it when the user clicks OK. 
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { [weak alert] (action) -> Void in
    let textField = alert.textFields![0] as UITextField
    println("Text field: \(textField.text)")
}))

// 4. Present the alert.
self.presentViewController(alert, animated: true, completion: nil)

Check if a row exists, otherwise insert

Take a look at MERGE command. You can do UPDATE, INSERT & DELETE in one statement.

Here is a working implementation on using MERGE
- It checks whether flight is full before doing an update, else does an insert.

if exists(select 1 from INFORMATION_SCHEMA.TABLES T 
              where T.TABLE_NAME = 'Bookings') 
begin
    drop table Bookings
end
GO

create table Bookings(
  FlightID    int identity(1, 1) primary key,
  TicketsMax    int not null,
  TicketsBooked int not null
)
GO

insert  Bookings(TicketsMax, TicketsBooked) select 1, 0
insert  Bookings(TicketsMax, TicketsBooked) select 2, 2
insert  Bookings(TicketsMax, TicketsBooked) select 3, 1
GO

select * from Bookings

And then ...

declare @FlightID int = 1
declare @TicketsToBook int = 2

--; This should add a new record
merge Bookings as T
using (select @FlightID as FlightID, @TicketsToBook as TicketsToBook) as S
    on  T.FlightID = S.FlightID
      and T.TicketsMax > (T.TicketsBooked + S.TicketsToBook)
  when matched then
    update set T.TicketsBooked = T.TicketsBooked + S.TicketsToBook
  when not matched then
    insert (TicketsMax, TicketsBooked) 
    values(S.TicketsToBook, S.TicketsToBook);

select * from Bookings

How do you tell if a checkbox is selected in Selenium for Java?

public boolean getcheckboxvalue(String element)
    {   
        WebElement webElement=driver.findElement(By.xpath(element));
        return webElement.isSelected();
    }

Default behavior of "git push" without a branch specified

I just committed my code to a branch and pushed it to github, like this:

git branch SimonLowMemoryExperiments
git checkout SimonLowMemoryExperiments
git add .
git commit -a -m "Lots of experimentation with identifying the memory problems"
git push origin SimonLowMemoryExperiments

MySQl Error #1064

In my case I was having the same error and later I come to know that the 'condition' is mysql reserved keyword and I used that as field name.

What is the difference between HTTP status code 200 (cache) vs status code 304?

For your last question, why ? I'll try to explain with what I know

A brief explanation of those three status codes in layman's terms.

  • 200 - success (browser requests and get file from server)

If caching is enabled in the server

  • 200 (from memory cache) - file found in browser, so browser is not going request from server
  • 304 - browser request a file but it is rejected by server

For some files browser is deciding to request from server and for some it's deciding to read from stored (cached) files. Why is this ? Every files has an expiry date, so

If a file is not expired then the browser will use from cache (200 cache).

If file is expired, browser requests server for a file. Server check file in both places (browser and server). If same file found, server refuses the request. As per protocol browser uses existing file.

look at this nginx configuration

location / {
    add_header Cache-Control must-revalidate;
    expires     60;
    etag on;

    ...
}

Here the expiry is set to 60 seconds, so all static files are cached for 60 seconds. So if u request a file again within 60 seconds browser will read from memory (200 memory). If u request after 60 seconds browser will request server (304).

I assumed that the file is not changed after 60 seconds, in that case you would get 200 (ie, updated file will be fetched from server).

So, if the servers are configured with different expiring and caching headers (policies), the status may differ.

In your case you are using cdn, the main purpose of cdn is high availability and fast delivery. Therefore they use multiple servers. Even though it seems like files are in same directory, cdn might use multiple servers to provide u content, if those servers have different configurations. Then these status can change. Hope it helps.

How to solve java.lang.NoClassDefFoundError?

I use the FileSync plugin for Eclipse so I can live debug on Tomcat & I received NoClassFoundError because I had added a sync entry for the bin directory in the Eclipse workspace => classes in the metadata for Tomcat but hadn't also added a folder sync for the extlib directory in Eclipse =>

C:\Users\Stuart\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\webapps\myApp\WEB-INF\lib

Where does npm install packages?

On windows I used npm list -g to find it out. By default my (global) packages were being installed to C:\Users\[Username]\AppData\Roaming\npm.

Multiple radio button groups in one form

in input field make name same like

<input type="radio" name="option" value="option1">
<input type="radio" name="option" value="option2" >
<input type="radio" name="option" value="option3" >
<input type="radio" name="option" value="option3" >

center MessageBox in parent form

But why stop with MessageBox-specific implementation? Use the class below like this:

    private void OnFormClosing(object sender, FormClosingEventArgs e)
    {
        DialogResult dg;
        using (DialogCenteringService centeringService = new DialogCenteringService(this)) // center message box
        {
            dg = MessageBox.Show(this, "Are you sure?", "Confirm exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        }

        if (dg == DialogResult.No)
        {
            e.Cancel = true;
        }
    }

The code that you can use with anything that shows dialog windows, even if they're owned by another thread (our app has multiple UI threads):

(Here is the updated code which takes monitor working areas into account, so that the dialog isn't centered between two monitors or is partly off-screen. With it you'll need enum SetWindowPosFlags, which is below)

public class DialogCenteringService : IDisposable
{
    private readonly IWin32Window owner;
    private readonly HookProc hookProc;
    private readonly IntPtr hHook = IntPtr.Zero;

    public DialogCenteringService(IWin32Window owner)
    {
        if (owner == null) throw new ArgumentNullException("owner");

        this.owner = owner;
        hookProc = DialogHookProc;

        hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, hookProc, IntPtr.Zero, GetCurrentThreadId());
    }

    private IntPtr DialogHookProc(int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode < 0)
        {
            return CallNextHookEx(hHook, nCode, wParam, lParam);
        }

        CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT));
        IntPtr hook = hHook;

        if (msg.message == (int)CbtHookAction.HCBT_ACTIVATE)
        {
            try
            {
                CenterWindow(msg.hwnd);
            }
            finally
            {
                UnhookWindowsHookEx(hHook);
            }
        }

        return CallNextHookEx(hook, nCode, wParam, lParam);
    }

    public void Dispose()
    {
        UnhookWindowsHookEx(hHook);
    }

    private void CenterWindow(IntPtr hChildWnd)
    {
        Rectangle recChild = new Rectangle(0, 0, 0, 0);
        bool success = GetWindowRect(hChildWnd, ref recChild);

        if (!success)
        {
            return;
        }

        int width = recChild.Width - recChild.X;
        int height = recChild.Height - recChild.Y;

        Rectangle recParent = new Rectangle(0, 0, 0, 0);
        success = GetWindowRect(owner.Handle, ref recParent);

        if (!success)
        {
            return;
        }

        Point ptCenter = new Point(0, 0);
        ptCenter.X = recParent.X + ((recParent.Width - recParent.X) / 2);
        ptCenter.Y = recParent.Y + ((recParent.Height - recParent.Y) / 2);


        Point ptStart = new Point(0, 0);
        ptStart.X = (ptCenter.X - (width / 2));
        ptStart.Y = (ptCenter.Y - (height / 2));

        //MoveWindow(hChildWnd, ptStart.X, ptStart.Y, width, height, false);
        Task.Factory.StartNew(() => SetWindowPos(hChildWnd, (IntPtr)0, ptStart.X, ptStart.Y, width, height, SetWindowPosFlags.SWP_ASYNCWINDOWPOS | SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_NOOWNERZORDER | SetWindowPosFlags.SWP_NOZORDER));
    }

    // some p/invoke

    // ReSharper disable InconsistentNaming
    public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);

    public delegate void TimerProc(IntPtr hWnd, uint uMsg, UIntPtr nIDEvent, uint dwTime);

    private const int WH_CALLWNDPROCRET = 12;

    // ReSharper disable EnumUnderlyingTypeIsInt
    private enum CbtHookAction : int
    // ReSharper restore EnumUnderlyingTypeIsInt
    {
        // ReSharper disable UnusedMember.Local
        HCBT_MOVESIZE = 0,
        HCBT_MINMAX = 1,
        HCBT_QS = 2,
        HCBT_CREATEWND = 3,
        HCBT_DESTROYWND = 4,
        HCBT_ACTIVATE = 5,
        HCBT_CLICKSKIPPED = 6,
        HCBT_KEYSKIPPED = 7,
        HCBT_SYSCOMMAND = 8,
        HCBT_SETFOCUS = 9
        // ReSharper restore UnusedMember.Local
    }

    [DllImport("kernel32.dll")]
    static extern int GetCurrentThreadId();

    [DllImport("user32.dll")]
    private static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle lpRect);

    [DllImport("user32.dll")]
    private static extern int MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, SetWindowPosFlags uFlags);

    [DllImport("User32.dll")]
    public static extern UIntPtr SetTimer(IntPtr hWnd, UIntPtr nIDEvent, uint uElapse, TimerProc lpTimerFunc);

    [DllImport("User32.dll")]
    public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll")]
    public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);

    [DllImport("user32.dll")]
    public static extern int UnhookWindowsHookEx(IntPtr idHook);

    [DllImport("user32.dll")]
    public static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll")]
    public static extern int GetWindowTextLength(IntPtr hWnd);

    [DllImport("user32.dll")]
    public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength);

    [DllImport("user32.dll")]
    public static extern int EndDialog(IntPtr hDlg, IntPtr nResult);

    [StructLayout(LayoutKind.Sequential)]
    public struct CWPRETSTRUCT
    {
        public IntPtr lResult;
        public IntPtr lParam;
        public IntPtr wParam;
        public uint message;
        public IntPtr hwnd;
    };
    // ReSharper restore InconsistentNaming
}

[Flags]
public enum SetWindowPosFlags : uint
{
    // ReSharper disable InconsistentNaming

    /// <summary>
    ///     If the calling thread and the thread that owns the window are attached to different input queues, the system posts the request to the thread that owns the window. This prevents the calling thread from blocking its execution while other threads process the request.
    /// </summary>
    SWP_ASYNCWINDOWPOS = 0x4000,

    /// <summary>
    ///     Prevents generation of the WM_SYNCPAINT message.
    /// </summary>
    SWP_DEFERERASE = 0x2000,

    /// <summary>
    ///     Draws a frame (defined in the window's class description) around the window.
    /// </summary>
    SWP_DRAWFRAME = 0x0020,

    /// <summary>
    ///     Applies new frame styles set using the SetWindowLong function. Sends a WM_NCCALCSIZE message to the window, even if the window's size is not being changed. If this flag is not specified, WM_NCCALCSIZE is sent only when the window's size is being changed.
    /// </summary>
    SWP_FRAMECHANGED = 0x0020,

    /// <summary>
    ///     Hides the window.
    /// </summary>
    SWP_HIDEWINDOW = 0x0080,

    /// <summary>
    ///     Does not activate the window. If this flag is not set, the window is activated and moved to the top of either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter parameter).
    /// </summary>
    SWP_NOACTIVATE = 0x0010,

    /// <summary>
    ///     Discards the entire contents of the client area. If this flag is not specified, the valid contents of the client area are saved and copied back into the client area after the window is sized or repositioned.
    /// </summary>
    SWP_NOCOPYBITS = 0x0100,

    /// <summary>
    ///     Retains the current position (ignores X and Y parameters).
    /// </summary>
    SWP_NOMOVE = 0x0002,

    /// <summary>
    ///     Does not change the owner window's position in the Z order.
    /// </summary>
    SWP_NOOWNERZORDER = 0x0200,

    /// <summary>
    ///     Does not redraw changes. If this flag is set, no repainting of any kind occurs. This applies to the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent window uncovered as a result of the window being moved. When this flag is set, the application must explicitly invalidate or redraw any parts of the window and parent window that need redrawing.
    /// </summary>
    SWP_NOREDRAW = 0x0008,

    /// <summary>
    ///     Same as the SWP_NOOWNERZORDER flag.
    /// </summary>
    SWP_NOREPOSITION = 0x0200,

    /// <summary>
    ///     Prevents the window from receiving the WM_WINDOWPOSCHANGING message.
    /// </summary>
    SWP_NOSENDCHANGING = 0x0400,

    /// <summary>
    ///     Retains the current size (ignores the cx and cy parameters).
    /// </summary>
    SWP_NOSIZE = 0x0001,

    /// <summary>
    ///     Retains the current Z order (ignores the hWndInsertAfter parameter).
    /// </summary>
    SWP_NOZORDER = 0x0004,

    /// <summary>
    ///     Displays the window.
    /// </summary>
    SWP_SHOWWINDOW = 0x0040,

    // ReSharper restore InconsistentNaming
}

Javascript array search and remove string?

use:

array.splice(2, 1);

This removes one item from the array, starting at index 2 (3rd item)

How to make EditText not editable through XML in Android?

They made "editable" deprecated but didn't provide a working corresponding one in inputType.

By the way, does inputType="none" has any effect? Using it or not does not make any difference as far as I see.

For example, the default editText is said to be single line. But you have to select an inputType for it to be single line. And if you select "none", it is still multiline.

Create mysql table directly from CSV file using the CSV Storage engine?

MySQL for excel plugin can help you.

http://dev.mysql.com/doc/refman/5.6/en/mysql-for-excel.html

Open your CSV file in excel. You can use this plugin to export excel data into a new table of remote or local mysql server. It will analyze your data (top 100 to 1000 rows) and create a corresponding table schema.

Rename all files in directory from $filename_h to $filename_half?

Although the answer set is complete, I need to add another missing one.

for i in *_h.png;
  do name=`echo "$i" | cut -d'_' -f1`
  echo "Executing of name $name" 
  mv "$i" "${name}_half.png"
done

Python: Figure out local timezone

Avoiding non-standard module (seems to be a missing method of datetime module):

from datetime import datetime
utcOffset_min = int(round((datetime.now() - datetime.utcnow()).total_seconds())) / 60   # round for taking time twice
utcOffset_h = utcOffset_min / 60
assert(utcOffset_min == utcOffset_h * 60)   # we do not handle 1/2 h timezone offsets

print 'Local time offset is %i h to UTC.' % (utcOffset_h)

PostgreSQL function for last inserted ID

I had this issue with Java and Postgres. I fixed it by updating a new Connector-J version.

postgresql-9.2-1002.jdbc4.jar

https://jdbc.postgresql.org/download.html: Version 42.2.12

https://jdbc.postgresql.org/download/postgresql-42.2.12.jar

Fastest check if row exists in PostgreSQL

I would like to propose another thought to specifically address your sentence: "So I want to check if a single row from the batch exists in the table because then I know they all were inserted."

You are making things efficient by inserting in "batches" but then doing existence checks one record at a time? This seems counter intuitive to me. So when you say "inserts are always done in batches" I take it you mean you are inserting multiple records with one insert statement. You need to realize that Postgres is ACID compliant. If you are inserting multiple records (a batch of data) with one insert statement, there is no need to check if some were inserted or not. The statement either passes or it will fail. All records will be inserted or none.

On the other hand, if your C# code is simply doing a "set" separate insert statements, for example, in a loop, and in your mind, this is a "batch" .. then you should not in fact describe it as "inserts are always done in batches". The fact that you expect that part of what you call a "batch", may actually not be inserted, and hence feel the need for a check, strongly suggests this is the case, in which case you have a more fundamental problem. You need change your paradigm to actually insert multiple records with one insert, and forego checking if the individual records made it.

Consider this example:

CREATE TABLE temp_test (
    id SERIAL PRIMARY KEY,
    sometext TEXT,
    userid INT,
    somethingtomakeitfail INT unique
)
-- insert a batch of 3 rows
;;
INSERT INTO temp_test (sometext, userid, somethingtomakeitfail) VALUES
('foo', 1, 1),
('bar', 2, 2),
('baz', 3, 3)
;;
-- inspect the data of what we inserted
SELECT * FROM temp_test
;;
-- this entire statement will fail .. no need to check which one made it
INSERT INTO temp_test (sometext, userid, somethingtomakeitfail) VALUES
('foo', 2, 4),
('bar', 2, 5),
('baz', 3, 3)  -- <<--(deliberately simulate a failure)
;;
-- check it ... everything is the same from the last successful insert ..
-- no need to check which records from the 2nd insert may have made it in
SELECT * FROM temp_test

This is in fact the paradigm for any ACID compliant DB .. not just Postgresql. In other words you are better off if you fix your "batch" concept and avoid having to do any row by row checks in the first place.

How to Call Controller Actions using JQuery in ASP.NET MVC

the previous response is ASP.NET only

you need a reference to jquery (perhaps from a CDN): http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js

and then a similar block of code but simpler...

$.ajax({ url: '/Controller/Action/Id',
         success: function(data) { alert(data); }, 
         statusCode : {
             404: function(content) { alert('cannot find resource'); },
             500: function(content) { alert('internal server error'); }
         }, 
         error: function(req, status, errorObj) {
               // handle status === "timeout"
               // handle other errors
         }
});

I've added some necessary handlers, 404 and 500 happen all the time if you are debugging code. Also, a lot of other errors, such as timeout, will filter out through the error handler.

ASP.NET MVC Controllers handle requests, so you just need to request the correct URL and the controller will pick it up. This code sample with work in environments other than ASP.NET

Add class to <html> with Javascript?

Like this:

var root = document.getElementsByTagName( 'html' )[0]; // '0' to assign the first (and only `HTML` tag)

root.setAttribute( 'class', 'myCssClass' );

Or use this as your 'setter' line to preserve any previously applied classes: (thanks @ama2)

root.className += ' myCssClass';

Or, depending on the required browser support, you can use the classList.add() method:

root.classList.add('myCssClass');

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList http://caniuse.com/#feat=classlist

UPDATE:

A more elegant solution for referencing the HTML element might be this:

var root = document.documentElement;
root.className += ' myCssClass';
// ... or:
//  root.classList.add('myCssClass');
//

Make a phone call programmatically

Probably the mymobileNO.titleLabel.text value doesn't include the scheme tel://

Your code should look like this:

NSString *phoneNumber = [@"tel://" stringByAppendingString:mymobileNO.titleLabel.text];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];

Plot multiple lines (data series) each with unique color in R

If you would like a ggplot2 solution, you can do this if you can shape your data to this format (see example below)

# dummy data
set.seed(45)
df <- data.frame(x=rep(1:5, 9), val=sample(1:100, 45), 
                   variable=rep(paste0("category", 1:9), each=5))
# plot
ggplot(data = df, aes(x=x, y=val)) + geom_line(aes(colour=variable))

ggplot2_geom_line

Using % for host when creating a MySQL user

Going to provide a slightly different answer to those provided so far.

If you have a row for an anonymous user from localhost in your users table ''@'localhost' then this will be treated as more specific than your user with wildcard'd host 'user'@'%'. This is why it is necessary to also provide 'user'@'localhost'.

You can see this explained in more detail at the bottom of this page.

Selection with .loc in python

It's a pandas data-frame and it's using label base selection tool with df.loc and in it, there are two inputs, one for the row and the other one for the column, so in the row input it's selecting all those row values where the value saved in the column class is versicolor, and in the column input it's selecting the column with label class, and assigning Iris-versicolor value to them. So basically it's replacing all the cells of column class with value versicolor with Iris-versicolor.

Why I get 411 Length required error?

I had the same error when I imported web requests from fiddler captured sessions to Visual Studio webtests. Some POST requests did not have a StringHttpBody tag. I added an empty one to them and the error was gone. Add this after the Headers tag:

    <StringHttpBody ContentType="" InsertByteOrderMark="False">
  </StringHttpBody>

Creating a class object in c++

Example example;

This is a declaration of a variable named example of type Example. This will default-initialize the object which involves calling its default constructor. The object will have automatic storage duration which means that it will be destroyed when it goes out of scope.

Example* example;

This is a declaration of a variable named example which is a pointer to an Example. In this case, default-initialization leaves it uninitialized - the pointer is pointing nowhere in particular. There is no Example object here. The pointer object has automatic storage duration.

Example* example = new Example();

This is a declaration of a variable named example which is a pointer to an Example. This pointer object, as above, has automatic storage duration. It is then initialized with the result of new Example();. This new expression creates an Example object with dynamic storage duration and then returns a pointer to it. So the example pointer is now pointing to that dynamically allocated object. The Example object is value-initialized which will call a user-provided constructor if there is one or otherwise initialise all members to 0.

Example* example = new Example;

This is similar to the previous line. The difference is that the Example object is default-initialized, which will call the default constructor of Example (or leave it uninitialized if it is not of class type).

A dynamically allocated object must be deleted (probably with delete example;).

How can I use LEFT & RIGHT Functions in SQL to get last 3 characters?

select right(rtrim('94342KMR'),3)

This will fetch the last 3 right string.

select substring(rtrim('94342KMR'),1,len('94342KMR')-3)

This will fetch the remaining Characters.

JavaScript Chart.js - Custom data formatting to display on tooltip

tooltips: {
    callbacks: {
        label: function (tooltipItem) {
            return (new Intl.NumberFormat('en-US', {
                style: 'currency',
                currency: 'USD',
            })).format(tooltipItem.value);
        }
    }
}

Cast object to interface in TypeScript

Here's another way to force a type-cast even between incompatible types and interfaces where TS compiler normally complains:

export function forceCast<T>(input: any): T {

  // ... do runtime checks here

  // @ts-ignore <-- forces TS compiler to compile this as-is
  return input;
}

Then you can use it to force cast objects to a certain type:

import { forceCast } from './forceCast';

const randomObject: any = {};
const typedObject = forceCast<IToDoDto>(randomObject);

Note that I left out the part you are supposed to do runtime checks before casting for the sake of reducing complexity. What I do in my project is compiling all my .d.ts interface files into JSON schemas and using ajv to validate in runtime.

Android - Get value from HashMap

HashMap<String, String> meMap=new HashMap<String, String>();
meMap.put("Color1","Red");
meMap.put("Color2","Blue");
meMap.put("Color3","Green");
meMap.put("Color4","White");
Iterator iterator = meMap.keySet().iterator();
while( iterator. hasNext() ){
    Toast.makeText(getBaseContext(), meMap.get(iterator.next().toString()), 
    Toast.LENGTH_SHORT).show();
}

HTML - how can I show tooltip ONLY when ellipsis is activated

Here's a pure CSS solution. No need for jQuery. It won't show a tooltip, instead it'll just expand the content to its full length on mouseover.

Works great if you have content that gets replaced. Then you don't have to run a jQuery function every time.

.might-overflow {
    text-overflow: ellipsis;
    overflow : hidden;
    white-space: nowrap;
}

.might-overflow:hover {
    text-overflow: clip;
    white-space: normal;
    word-break: break-all;
}

Identify if a string is a number

UPDATE of Kunal Noel Answer

stringTest.All(char.IsDigit);
// This returns true if all characters of the string are digits.

But, for this case we have that empty strings will pass that test, so, you can:

if (!string.IsNullOrEmpty(stringTest) && stringTest.All(char.IsDigit)){
   // Do your logic here
}

How can I change the default width of a Twitter Bootstrap modal box?

Less-based solution (no js) for Bootstrap 2:

.modal-width(@modalWidth) {
    width: @modalWidth;
    margin-left: -@modalWidth/2;

    @media (max-width: @modalWidth) {
        position: fixed;
        top:   20px;
        left:  20px;
        right: 20px;
        width: auto;
        margin: 0;
        &.fade  { top: -100px; }
        &.fade.in { top: 20px; }
    }
}

Then wherever you want to specify a modal width:

#myModal {
    .modal-width(700px);
}

Why aren't programs written in Assembly more often?

People seem to forget that there is also the other direction.

Why are you writing in Assembler in the first place? Why not write the program in a truly low level language?

Instead of

mov eax, 0x123
add eax, 0x456
push eax
call printInt

you could just as well write

B823010000
0556040000
50 
FF15.....

That has so many advantages, you know the exact size of your program, you can reuse the value of instructions as input for other instructions and you do not even need an assembler to write it, you can use any text editor...

And the reason you still prefer Assembler about this, is the reason other people prefer C...

Setting onClickListener for the Drawable right of an EditText

public class CustomEditText extends androidx.appcompat.widget.AppCompatEditText {

    private Drawable drawableRight;
    private Drawable drawableLeft;
    private Drawable drawableTop;
    private Drawable drawableBottom;

    int actionX, actionY;

    private DrawableClickListener clickListener;

    public CustomEditText (Context context, AttributeSet attrs) {
        super(context, attrs);
        // this Contructure required when you are using this view in xml
    }

    public CustomEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);        
    }

    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
    }

    @Override
    public void setCompoundDrawables(Drawable left, Drawable top,
            Drawable right, Drawable bottom) {
        if (left != null) {
            drawableLeft = left;
        }
        if (right != null) {
            drawableRight = right;
        }
        if (top != null) {
            drawableTop = top;
        }
        if (bottom != null) {
            drawableBottom = bottom;
        }
        super.setCompoundDrawables(left, top, right, bottom);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Rect bounds;
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            actionX = (int) event.getX();
            actionY = (int) event.getY();
            if (drawableBottom != null
                    && drawableBottom.getBounds().contains(actionX, actionY)) {
                clickListener.onClick(DrawablePosition.BOTTOM);
                return super.onTouchEvent(event);
            }

            if (drawableTop != null
                    && drawableTop.getBounds().contains(actionX, actionY)) {
                clickListener.onClick(DrawablePosition.TOP);
                return super.onTouchEvent(event);
            }

            // this works for left since container shares 0,0 origin with bounds
            if (drawableLeft != null) {
                bounds = null;
                bounds = drawableLeft.getBounds();

                int x, y;
                int extraTapArea = (int) (13 * getResources().getDisplayMetrics().density  + 0.5);

                x = actionX;
                y = actionY;

                if (!bounds.contains(actionX, actionY)) {
                    /** Gives the +20 area for tapping. */
                    x = (int) (actionX - extraTapArea);
                    y = (int) (actionY - extraTapArea);

                    if (x <= 0)
                        x = actionX;
                    if (y <= 0)
                        y = actionY;

                    /** Creates square from the smallest value */
                    if (x < y) {
                        y = x;
                    }
                }

                if (bounds.contains(x, y) && clickListener != null) {
                    clickListener
                            .onClick(DrawableClickListener.DrawablePosition.LEFT);
                    event.setAction(MotionEvent.ACTION_CANCEL);
                    return false;

                }
            }

            if (drawableRight != null) {

                bounds = null;
                bounds = drawableRight.getBounds();

                int x, y;
                int extraTapArea = 13;

                /**
                 * IF USER CLICKS JUST OUT SIDE THE RECTANGLE OF THE DRAWABLE
                 * THAN ADD X AND SUBTRACT THE Y WITH SOME VALUE SO THAT AFTER
                 * CALCULATING X AND Y CO-ORDINATE LIES INTO THE DRAWBABLE
                 * BOUND. - this process help to increase the tappable area of
                 * the rectangle.
                 */
                x = (int) (actionX + extraTapArea);
                y = (int) (actionY - extraTapArea);

                /**Since this is right drawable subtract the value of x from the width 
                * of view. so that width - tappedarea will result in x co-ordinate in drawable bound. 
                */
                x = getWidth() - x;
                
                 /*x can be negative if user taps at x co-ordinate just near the width.
                 * e.g views width = 300 and user taps 290. Then as per previous calculation
                 * 290 + 13 = 303. So subtract X from getWidth() will result in negative value.
                 * So to avoid this add the value previous added when x goes negative.
                 */
                 
                if(x <= 0){
                    x += extraTapArea;
                }
                
                 /* If result after calculating for extra tappable area is negative.
                 * assign the original value so that after subtracting
                 * extratapping area value doesn't go into negative value.
                 */               
                 
                if (y <= 0)
                    y = actionY;                

                /**If drawble bounds contains the x and y points then move ahead.*/
                if (bounds.contains(x, y) && clickListener != null) {
                    clickListener
                            .onClick(DrawableClickListener.DrawablePosition.RIGHT);
                    event.setAction(MotionEvent.ACTION_CANCEL);
                    return false;
                }
                return super.onTouchEvent(event);
            }           

        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void finalize() throws Throwable {
        drawableRight = null;
        drawableBottom = null;
        drawableLeft = null;
        drawableTop = null;
        super.finalize();
    }

    public void setDrawableClickListener(DrawableClickListener listener) {
        this.clickListener = listener;
    }

}

Also Create an Interface with

public interface DrawableClickListener {

    public static enum DrawablePosition { TOP, BOTTOM, LEFT, RIGHT };
    public void onClick(DrawablePosition target); 
    }

Still if u need any help, comment

Also set the drawableClickListener on the view in activity file.

editText.setDrawableClickListener(new DrawableClickListener() {
        
         
        public void onClick(DrawablePosition target) {
            switch (target) {
            case LEFT:
                //Do something here
                break;

            default:
                break;
            }
        }
        
    });

return in for loop or outside loop

Some people argue that a method should have a single point of exit (e.g., only one return). Personally, I think that trying to stick to that rule produces code that's harder to read. In your example, as soon as you find what you were looking for, return it immediately, it's clear and it's efficient.

Quoting the C2 wiki:

The original significance of having a single entry and single exit for a function is that it was part of the original definition of StructuredProgramming as opposed to undisciplined goto SpaghettiCode, and allowed a clean mathematical analysis on that basis.

Now that structured programming has long since won the day, no one particularly cares about that anymore, and the rest of the page is largely about best practices and aesthetics and such, not about mathematical analysis of structured programming constructs.

How to get elements with multiple classes

AND (both classes)

var list = document.getElementsByClassName("class1 class2");
var list = document.querySelectorAll(".class1.class2");

OR (at least one class)

var list = document.querySelectorAll(".class1,.class2");

XOR (one class but not the other)

var list = document.querySelectorAll(".class1:not(.class2),.class2:not(.class1)");

NAND (not both classes)

var list = document.querySelectorAll(":not(.class1),:not(.class2)");

NOR (not any of the two classes)

var list = document.querySelectorAll(":not(.class1):not(.class2)");

How to trigger ngClick programmatically

Simple sample:

HTML

<div id='player'>
    <div id="my-button" ng-click="someFuntion()">Someone</div>
</div>

JavaScript

$timeout(function() {
    angular.element('#my-button').triggerHandler('click');
}, 0);

What this does is look for the button's id and perform a click action. Voila.

Source: https://techiedan.com/angularjs-how-to-trigger-click/

OperationalError: database is locked

A very unusual scenario, which happened to me.

There was infinite recursion, which kept creating the objects.

More specifically, using DRF, I was overriding create method in a view, and I did

def create(self, request, *args, **kwargs):
    ....
    ....

    return self.create(request, *args, **kwargs)