Programs & Examples On #Null uniqueidentifier

Can you break from a Groovy "each" closure?

I agree with other answers not to use an exception to break an each. I also do not prefer to create an extra closure eachWithBreak, instead of this I prefer a modern approach: let's use the each to iterate over the collection, as requested, but refine the collection to contain only those elements to be iterated, for example with findAll:

collection.findAll { !endCondition }.each { doSomething() }

For example, if we what to break when the counter == 3 we can write this code (already suggested):

(0..5)
    .findAll { it < 3  }
    .each { println it }

This will output

0
1
2

So far so good, but you will notice a small discrepancy though. Our end condition, negation of counter == 3 is not quite correct because !(counter==3) is not equivalent with it < 3. This is necessary to make the code work since findAll does not actually break the loop but continues until the end.

To emulate a real situation, let's say we have this code:

for (n in 0..5) {
    if (n == 3)
        break
    println n
}

but we want to use each, so let's rewrite it using a function to simulate a break condition:

def breakWhen(nr) { nr == 3 }
(0..5)
    .findAll { !breakWhen(it) }
    .each { println it }

with the output:

0
1
2
4
5

now you see the problem with findAll. This does not stop, but ignores that element where the condition is not met.

To solve this issues, we need an extra variable to remember when the breaking condition become true. After this moment, findAll must ignore all remaining elements.

This is how it should look like:

def breakWhen(nr) { nr == 3 }
def loop = true
(0..5)
    .findAll {
        if (breakWhen(it))
            loop = false
        !breakWhen(it) && loop
    } .each {
        println it
    }

with the output:

0
1
2

That's what we want!

Notification not showing in Oreo

Android Notification Demo App for Android O as well as lower API versions. Here is best demo app on GitHub-Demo 1 and GitHub-Demo 2.

enter image description here

How does numpy.histogram() work?

import numpy as np    
hist, bin_edges = np.histogram([1, 1, 2, 2, 2, 2, 3], bins = range(5))

Below, hist indicates that there are 0 items in bin #0, 2 in bin #1, 4 in bin #3, 1 in bin #4.

print(hist)
# array([0, 2, 4, 1])   

bin_edges indicates that bin #0 is the interval [0,1), bin #1 is [1,2), ..., bin #3 is [3,4).

print (bin_edges)
# array([0, 1, 2, 3, 4]))  

Play with the above code, change the input to np.histogram and see how it works.


But a picture is worth a thousand words:

import matplotlib.pyplot as plt
plt.bar(bin_edges[:-1], hist, width = 1)
plt.xlim(min(bin_edges), max(bin_edges))
plt.show()   

enter image description here

Cannot hide status bar in iOS7

To hide Status Bar on a Single view, you should use:

[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];

At first, this didn't work for me, and then a saw in the documentation of this method that says: // Setting statusBarHidden does nothing if your application is using the default UIViewController-based status bar system.

This has to be done on the plist file, adding the key View controller-based status bar appearance set to NO. And then it worked.

How to revert a "git rm -r ."?

I had an identical situation. In my case the solution was:

git checkout -- .

Excel: Use a cell value as a parameter for a SQL query

I had the same problem as you, Noboby can understand me, But I solved it in this way.

SELECT NAME, TELEFONE, DATA
FROM   [sheet1$a1:q633]
WHERE  NAME IN (SELECT * FROM  [sheet2$a1:a2])

you need insert a parameter in other sheet, the SQL will consider that information like as database, then you can select the information and compare them into parameter you like.

SQL Server - Convert varchar to another collation (code page) to fix character encoding

We may need more information. Here is what I did to reproduce on SQL Server 2008:

CREATE DATABASE [Test] ON  PRIMARY 
    ( 
    NAME = N'Test'
    , FILENAME = N'...Test.mdf' 
    , SIZE = 3072KB 
    , FILEGROWTH = 1024KB 
    )
    LOG ON 
    ( 
    NAME = N'Test_log'
    , FILENAME = N'...Test_log.ldf' 
    , SIZE = 1024KB 
    , FILEGROWTH = 10%
    )
    COLLATE SQL_Latin1_General_CP850_BIN2
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[MyTable]
    (
    [SomeCol] [varchar](50) NULL
    ) ON [PRIMARY]
GO
Insert MyTable( SomeCol )
Select '±' Collate SQL_Latin1_General_CP1_CI_AS
GO
Select SomeCol, SomeCol Collate SQL_Latin1_General_CP1_CI_AS
From MyTable

Results show the original character. Declaring collation in the query should return the proper character from SQL Server's perspective however it may be the case that the presentation layer is then converting to something yet different like UTF-8.

Open button in new window?

Opens a new window with the url you supplied :)

<button class="button" onClick="window.open('http://www.example.com');">
     <span class="icon">Open</span>
</button>

hope that helps :)

Import data.sql MySQL Docker Container

you can copy the export file for e.g dump.sql using docker cp into the container and then import the db. if you need full instructions, let me know and I will provide

jQuery: checking if the value of a field is null (empty)

I would also trim the input field, cause a space could make it look like filled

if ($.trim($('#person_data[document_type]').val()) != '')
{

}

How to center a Window in Java?

Note that both the setLocationRelativeTo(null) and Tookit.getDefaultToolkit().getScreenSize() techniques work only for the primary monitor. If you are in a multi-monitor environment, you may need to get information about the specific monitor the window is on before doing this kind of calculation.

Sometimes important, sometimes not...

See GraphicsEnvironment javadocs for more info on how to get this.

Can't use SURF, SIFT in OpenCV

You can proceed in this way. It must work for you as well!

Step 1:

virtualenv venv 
source venv/bin/activate

Step 2:

sudo python3 -m pip install opencv-python==3.4.2.16 
sudo python3 -m pip install opencv-contrib-python==3.4.2.16

Step 3:

import cv2
sift = cv2.xfeatures2d.SIFT_create()

Don't use cv2.SIFT() . It will raise an exception.

How do I get a TextBox to only accept numeric input in WPF?

The event handler is previewing text input. Here a regular expression matches the text input only if it is not a number, and then it is not made to entry textbox.

If you want only letters then replace the regular expression as [^a-zA-Z].

XAML

<TextBox Name="NumberTextBox" PreviewTextInput="NumberValidationTextBox"/>

XAML.CS FILE

using System.Text.RegularExpressions;
private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
{
    Regex regex = new Regex("[^0-9]+");
    e.Handled = regex.IsMatch(e.Text);
}

The requested URL /about was not found on this server

On my MacOS Catalina machine I discovered that an additional file had been created at /etc/apache2/users/my-username.conf where the default was

AllowOverride none

Changing that to All finally got things working for me. The challenge with Mac is that its hard to get to these directories with Finder so its easy not to spot this file

Get the generated SQL statement from a SqlCommand object?

needed to cover non-Stored procedures too so I augmented CommandAsSql library (see comments under @Flapper's answer above) with this logic:

    private static void CommandAsSql_Text(this SqlCommand command, System.Text.StringBuilder sql)
    {
        string query = command.CommandText;

        foreach (SqlParameter p in command.Parameters)
            query = Regex.Replace(query, "\\B" + p.ParameterName + "\\b", p.ParameterValueForSQL()); //the first one is \B, the 2nd one is \b, since ParameterName starts with @ which is a non-word character in RegEx (see https://stackoverflow.com/a/2544661)

        sql.AppendLine(query);
    }

the pull request is at: https://github.com/jphellemons/CommandAsSql/pull/3/commits/527d696dc6055c5bcf858b9700b83dc863f04896

the Regex idea was based on @stambikk's and EvZ's comments above and the "Update:" section of https://stackoverflow.com/a/2544661/903783 that mentions "negative look-behind assertion". The use of \B instead of \b for word boundary detection at the start of the regular expression is because the p.parameterName will always start with a "@" which is not a word character.

note that ParameterValueForSQL() is an extension method defined at the CommandAsSql library to handle issues like single-quoting string parameter values etc.

Makefiles with source files in different directories

I think it's better to point out that using Make (recursive or not) is something that usually you may want to avoid, because compared to today tools, it's difficult to learn, maintain and scale.

It's a wonderful tool but it's direct use should be considered obsolete in 2010+.

Unless, of course, you're working in a special environment i.e. with a legacy project etc.

Use an IDE, CMake or, if you're hard cored, the Autotools.

(edited due to downvotes, ty Honza for pointing out)

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object?

Make sure you are sending the proper parameters too. This happened to me after switching to UI-Router.

To fix it, I changed $routeParams to use $stateParams in my controller. The main issue was that $stateParams was no longer sending a proper parameter to the resource.

Android ADB devices unauthorized

for anyone encountering this later this may also help. I encountered this exact issue trying to use adb from a user command prompt and the answers above did not help, but the problem went away with an "adb kill-server" when running in an administrator command prompt.

Is there a numpy builtin to reject outliers from a list

An alternative is to make a robust estimation of the standard deviation (assuming Gaussian statistics). Looking up online calculators, I see that the 90% percentile corresponds to 1.2815σ and the 95% is 1.645σ (http://vassarstats.net/tabs.html?#z)

As a simple example:

import numpy as np

# Create some random numbers
x = np.random.normal(5, 2, 1000)

# Calculate the statistics
print("Mean= ", np.mean(x))
print("Median= ", np.median(x))
print("Max/Min=", x.max(), " ", x.min())
print("StdDev=", np.std(x))
print("90th Percentile", np.percentile(x, 90))

# Add a few large points
x[10] += 1000
x[20] += 2000
x[30] += 1500

# Recalculate the statistics
print()
print("Mean= ", np.mean(x))
print("Median= ", np.median(x))
print("Max/Min=", x.max(), " ", x.min())
print("StdDev=", np.std(x))
print("90th Percentile", np.percentile(x, 90))

# Measure the percentile intervals and then estimate Standard Deviation of the distribution, both from median to the 90th percentile and from the 10th to 90th percentile
p90 = np.percentile(x, 90)
p10 = np.percentile(x, 10)
p50 = np.median(x)
# p50 to p90 is 1.2815 sigma
rSig = (p90-p50)/1.2815
print("Robust Sigma=", rSig)

rSig = (p90-p10)/(2*1.2815)
print("Robust Sigma=", rSig)

The output I get is:

Mean=  4.99760520022
Median=  4.95395274981
Max/Min= 11.1226494654   -2.15388472011
Sigma= 1.976629928
90th Percentile 7.52065379649

Mean=  9.64760520022
Median=  4.95667658782
Max/Min= 2205.43861943   -2.15388472011
Sigma= 88.6263902244
90th Percentile 7.60646688694

Robust Sigma= 2.06772555531
Robust Sigma= 1.99878292462

Which is close to the expected value of 2.

If we want to remove points above/below 5 standard deviations (with 1000 points we would expect 1 value > 3 standard deviations):

y = x[abs(x - p50) < rSig*5]

# Print the statistics again
print("Mean= ", np.mean(y))
print("Median= ", np.median(y))
print("Max/Min=", y.max(), " ", y.min())
print("StdDev=", np.std(y))

Which gives:

Mean=  4.99755359935
Median=  4.95213030447
Max/Min= 11.1226494654   -2.15388472011
StdDev= 1.97692712883

I have no idea which approach is the more efficent/robust

convert datetime to date format dd/mm/yyyy

It's simple--tostring() accepts a parameter with this format...

DateTime.ToString("dd/MM/yyyy");

Convert PDF to PNG using ImageMagick

when you set the density to 96, doesn't it look good?

when i tried it i saw that saving as jpg resulted with better quality, but larger file size

How to define custom sort function in javascript?

or shorter

_x000D_
_x000D_
function sortBy(field) {_x000D_
  return function(a, b) {_x000D_
    return (a[field] > b[field]) - (a[field] < b[field])_x000D_
  };_x000D_
}_x000D_
_x000D_
let myArray = [_x000D_
    {tabid: 6237, url: 'https://reddit.com/r/znation'},_x000D_
    {tabid: 8430, url: 'https://reddit.com/r/soccer'},_x000D_
    {tabid: 1400, url: 'https://reddit.com/r/askreddit'},_x000D_
    {tabid: 3620, url: 'https://reddit.com/r/tacobell'},_x000D_
    {tabid: 5753, url: 'https://reddit.com/r/reddevils'},_x000D_
]_x000D_
_x000D_
myArray.sort(sortBy('url'));_x000D_
console.log(myArray);
_x000D_
_x000D_
_x000D_

YAML equivalent of array of objects in JSON

Great answer above. Another way is to use the great yaml jq wrapper tool, yq at https://github.com/kislyuk/yq

Save your JSON example to a file, say ex.json and then

yq -y '.' ex.json

AAPL:
- shares: -75.088
  date: 11/27/2015
- shares: 75.088
  date: 11/26/2015

Check if Cookie Exists

public static class CookieHelper
{
    /// <summary>
    /// Checks whether a cookie exists.
    /// </summary>
    /// <param name="cookieCollection">A CookieCollection, such as Response.Cookies.</param>
    /// <param name="name">The cookie name to delete.</param>
    /// <returns>A bool indicating whether a cookie exists.</returns>
    public static bool Exists(this HttpCookieCollection cookieCollection, string name)
    {
        if (cookieCollection == null)
        {
            throw new ArgumentNullException("cookieCollection");
        }

        return cookieCollection[name] != null;
    }
}

Usage:

Request.Cookies.Exists("MyCookie")

How do I disable form fields using CSS?

It's very curious that you have visible and display properties in CSS but not enable/disable.

It's very curious that you think that's very curious. You're misunderstanding the purpose of CSS. CSS is not meant to change the behavior of form elements. It's meant to change their style only. Hiding a text field doesn't mean the text field is no longer there or that the browser won't send its data when you submit the form. All it does is hide it from the user's eyes.

To actually disable your fields, you must use the disabled attribute in HTML or the disabled DOM property in JavaScript.

Troubleshooting "Illegal mix of collations" error in mysql

This code needs to be put inside Run SQL query/queries on database

SQL QUERY WINDOW

ALTER TABLE `table_name` CHANGE `column_name` `column_name`   VARCHAR(128) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL;

Please replace table_name and column_name with appropriate name.

Python/BeautifulSoup - how to remove all tags from an element?

Use get_text(), it returns all the text in a document or beneath a tag, as a single Unicode string.

For instance, remove all different script tags from the following text:

<td><a href="http://www.irit.fr/SC">Signal et Communication</a>
<br/><a href="http://www.irit.fr/IRT">Ingénierie Réseaux et Télécommunications</a>
</td>

The expected result is:

Signal et Communication
Ingénierie Réseaux et Télécommunications

Here is the source code:

#!/usr/bin/env python3
from bs4 import BeautifulSoup

text = '''
<td><a href="http://www.irit.fr/SC">Signal et Communication</a>
<br/><a href="http://www.irit.fr/IRT">Ingénierie Réseaux et Télécommunications</a>
</td>
'''
soup = BeautifulSoup(text)

print(soup.get_text())

Want to make Font Awesome icons clickable

I found this worked best for my usecase:

<i class="btn btn-light fa fa-dribbble fa-4x" href="#"></i>
<i class="btn btn-light fa fa-behance-square fa-4x" href="#"></i>
<i class="btn btn-light fa fa-linkedin-square fa-4x" href="#"></i>
<i class="btn btn-light fa fa-twitter-square fa-4x" href="#"></i>
<i class="btn btn-light fa fa-facebook-square fa-4x" href="#"></i>

Error in eval(expr, envir, enclos) : object not found

i use colname(train) = paste("A", colname(train)) and it turns out to the same problem as yours.

I finally figure out that randomForest is more stingy than rpart, it can't recognize the colname with space, comma or other specific punctuation.

paste function will prepend "A" and " " as seperator with each colname. so we need to avert the space and use this sentence instead:

colname(train) = paste("A", colname(train), sep = "")

this will prepend string without space.

Execute SQL script to create tables and rows

If you have password for your dB then

mysql -u <username> -p <DBName> < yourfile.sql

How can I alter a primary key constraint using SQL syntax?

Performance wise there is no point to keep non clustered indexes during this as they will get re-updated on drop and create. If it is a big data set you should consider renaming the table (if possible , any security settings on it?), re-creating an empty table with the correct keys migrate all data there. You have to make sure you have enough space for this.

How to make PDF file downloadable in HTML link?

Instead of linking to the .PDF file, instead do something like

<a href="pdf_server.php?file=pdffilename">Download my eBook</a>

which outputs a custom header, opens the PDF (binary safe) and prints the data to the user's browser, then they can choose to save the PDF despite their browser settings. The pdf_server.php should look like this:

header("Content-Type: application/octet-stream");

$file = $_GET["file"] .".pdf";
header("Content-Disposition: attachment; filename=" . urlencode($file));   
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");            
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
$fp = fopen($file, "r");
while (!feof($fp))
{
    echo fread($fp, 65536);
    flush(); // this is essential for large downloads
} 
fclose($fp); 

PS: and obviously run some sanity checks on the "file" variable to prevent people from stealing your files such as don't accept file extensions, deny slashes, add .pdf to the value

Operator overloading on class templates

This helped me with the exact same problem.

Solution:

  1. Forward declare the friend function before the definition of the class itself. For example:

       template<typename T> class MyClass;  // pre-declare the template class itself
       template<typename T> std::ostream& operator<< (std::ostream& o, const MyClass <T>& x);
    
  2. Declare your friend function in your class with "<>" appended to the function name.

       friend std::ostream& operator<< <> (std::ostream& o, const Foo<T>& x);
    

how does multiplication differ for NumPy Matrix vs Array classes?

Reference from http://docs.scipy.org/doc/scipy/reference/tutorial/linalg.html

..., the use of the numpy.matrix class is discouraged, since it adds nothing that cannot be accomplished with 2D numpy.ndarray objects, and may lead to a confusion of which class is being used. For example,

>>> import numpy as np
>>> from scipy import linalg
>>> A = np.array([[1,2],[3,4]])
>>> A
    array([[1, 2],
           [3, 4]])
>>> linalg.inv(A)
array([[-2. ,  1. ],
      [ 1.5, -0.5]])
>>> b = np.array([[5,6]]) #2D array
>>> b
array([[5, 6]])
>>> b.T
array([[5],
      [6]])
>>> A*b #not matrix multiplication!
array([[ 5, 12],
      [15, 24]])
>>> A.dot(b.T) #matrix multiplication
array([[17],
      [39]])
>>> b = np.array([5,6]) #1D array
>>> b
array([5, 6])
>>> b.T  #not matrix transpose!
array([5, 6])
>>> A.dot(b)  #does not matter for multiplication
array([17, 39])

scipy.linalg operations can be applied equally to numpy.matrix or to 2D numpy.ndarray objects.

Perl: function to trim string leading and trailing whitespace

Here's one approach using a regular expression:

$string =~ s/^\s+|\s+$//g ;     # remove both leading and trailing whitespace

Perl 6 will include a trim function:

$string .= trim;

Source: Wikipedia

How to replace master branch in Git, entirely, from another branch?

What about using git branch -m to rename the master branch to another one, then rename seotweaks branch to master? Something like this:

git branch -m master old-master
git branch -m seotweaks master
git push -f origin master

This might remove commits in origin master, please check your origin master before running git push -f origin master.

Lining up labels with radio buttons in bootstrap

If you add the 'radio inline' class to the control label in the solution provided by user1938475 it should line up correctly with the other labels. Or if you're only using 'radio' like your 2nd example just include the 'radio' class.

<label class="radio control-label">Some label</label>

OR for 'radio inline'

<label class="radio-inline control-label">Some label</label>

How do I know the script file name in a Bash script?

You can use $0 to determine your script name (with full path) - to get the script name only you can trim that variable with

basename $0

How can I get the count of milliseconds since midnight for the current?

I tried a few ones above but they seem to reset @ 1000

This one definately works, and should also take year into consideration

long millisStart = Calendar.getInstance().getTimeInMillis();

and then do the same for end time if needed.

How To Set Text In An EditText

You need to:

  1. Declare the EditText in the xml file
  2. Find the EditText in the activity
  3. Set the text in the EditText

How to stop asynctask thread in android?

You may also have to use it in onPause or onDestroy of Activity Life Cycle:

//you may call the cancel() method but if it is not handled in doInBackground() method
if (loginTask != null && loginTask.getStatus() != AsyncTask.Status.FINISHED)
    loginTask.cancel(true);

where loginTask is object of your AsyncTask

Thank you.

RSA encryption and decryption in Python

# coding: utf-8
from __future__ import unicode_literals
import base64
import os

import six
from Crypto import Random
from Crypto.PublicKey import RSA


class PublicKeyFileExists(Exception): pass


class RSAEncryption(object):
    PRIVATE_KEY_FILE_PATH = None
    PUBLIC_KEY_FILE_PATH = None

    def encrypt(self, message):
        public_key = self._get_public_key()
        public_key_object = RSA.importKey(public_key)
        random_phrase = 'M'
        encrypted_message = public_key_object.encrypt(self._to_format_for_encrypt(message), random_phrase)[0]
        # use base64 for save encrypted_message in database without problems with encoding
        return base64.b64encode(encrypted_message)

    def decrypt(self, encoded_encrypted_message):
        encrypted_message = base64.b64decode(encoded_encrypted_message)
        private_key = self._get_private_key()
        private_key_object = RSA.importKey(private_key)
        decrypted_message = private_key_object.decrypt(encrypted_message)
        return six.text_type(decrypted_message, encoding='utf8')

    def generate_keys(self):
        """Be careful rewrite your keys"""
        random_generator = Random.new().read
        key = RSA.generate(1024, random_generator)
        private, public = key.exportKey(), key.publickey().exportKey()

        if os.path.isfile(self.PUBLIC_KEY_FILE_PATH):
            raise PublicKeyFileExists('???? ? ????????? ?????? ??????????. ??????? ????')
        self.create_directories()

        with open(self.PRIVATE_KEY_FILE_PATH, 'w') as private_file:
            private_file.write(private)
        with open(self.PUBLIC_KEY_FILE_PATH, 'w') as public_file:
            public_file.write(public)
        return private, public

    def create_directories(self, for_private_key=True):
        public_key_path = self.PUBLIC_KEY_FILE_PATH.rsplit('/', 1)
        if not os.path.exists(public_key_path):
            os.makedirs(public_key_path)
        if for_private_key:
            private_key_path = self.PRIVATE_KEY_FILE_PATH.rsplit('/', 1)
            if not os.path.exists(private_key_path):
                os.makedirs(private_key_path)

    def _get_public_key(self):
        """run generate_keys() before get keys """
        with open(self.PUBLIC_KEY_FILE_PATH, 'r') as _file:
            return _file.read()

    def _get_private_key(self):
        """run generate_keys() before get keys """
        with open(self.PRIVATE_KEY_FILE_PATH, 'r') as _file:
            return _file.read()

    def _to_format_for_encrypt(value):
        if isinstance(value, int):
            return six.binary_type(value)
        for str_type in six.string_types:
            if isinstance(value, str_type):
                return value.encode('utf8')
        if isinstance(value, six.binary_type):
            return value

And use

KEYS_DIRECTORY = settings.SURVEY_DIR_WITH_ENCRYPTED_KEYS

class TestingEncryption(RSAEncryption):
    PRIVATE_KEY_FILE_PATH = KEYS_DIRECTORY + 'private.key'
    PUBLIC_KEY_FILE_PATH = KEYS_DIRECTORY + 'public.key'


# django/flask
from django.core.files import File

class ProductionEncryption(RSAEncryption):
    PUBLIC_KEY_FILE_PATH = settings.SURVEY_DIR_WITH_ENCRYPTED_KEYS + 'public.key'

    def _get_private_key(self):
        """run generate_keys() before get keys """
        from corportal.utils import global_elements
        private_key = global_elements.request.FILES.get('private_key')
        if private_key:
            private_key_file = File(private_key)
            return private_key_file.read()

message = 'Hello ??? friend'
encrypted_mes = ProductionEncryption().encrypt(message)
decrypted_mes = ProductionEncryption().decrypt(message)

How to load all modules in a folder?

Using importlib the only thing you've got to add is

from importlib import import_module
from pathlib import Path

__all__ = [
    import_module(f".{f.stem}", __package__)
    for f in Path(__file__).parent.glob("*.py")
    if "__" not in f.stem
]
del import_module, Path

What should be the package name of android app?

Package name is the reversed domain name, it is a unique name for each application on Playstore. You can't upload two apps with the same package name. You can check package name of the app from playstore url

https://play.google.com/store/apps/details?id=package_name

so you can easily check on playstore that this package name is in used by some other app or not before uploading it.

Swift programmatically navigate to another view controller/scene

Swift 5

The default modal presentation style is a card. This shows the previous view controller at the top and allows the user to swipe away the presented view controller.

To retain the old style you need to modify the view controller you will be presenting like this:

newViewController.modalPresentationStyle = .fullScreen

This is the same for both programmatically created and storyboard created controllers.

Swift 3

With a programmatically created Controller

If you want to navigate to Controller created Programmatically, then do this:

let newViewController = NewViewController()
self.navigationController?.pushViewController(newViewController, animated: true)

With a StoryBoard created Controller

If you want to navigate to Controller on StoryBoard with Identifier "newViewController", then do this:

let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let newViewController = storyBoard.instantiateViewController(withIdentifier: "newViewController") as! NewViewController
        self.present(newViewController, animated: true, completion: nil)

Clear form fields with jQuery

if you use selectors and make values to empty values, it is not resetting the form, it's making all fields empty. Reset is to make form as it was before any edit actions from user after the load of form from server side. If there is an input with name "username" and that username was prefilled from server side, most of solutions on this page will delete that value from input, not reset it to the value how it was before user's changes. If you need to reset the form, use this:

$('#myform')[0].reset();

if you need not to reset the form, but fill all inputs with some value, for example empty value, then you can use most of the solutions from other comments.

How to make a website secured with https

@balalakshmi mentioned about the correct authentication settings. Authentication is only half of the problem, the other half is authorization.

If you're using Forms Authentication and standard controls like <asp:Login> there are a couple of things you'll need to do to ensure that only your authenticated users can access secured pages.

In web.config, under the <system.web> section you'll need to disable anonymous access by default:

<authorization>
 <deny users="?" />
</authorization>

Any pages that will be accessed anonymously (such as the Login.aspx page itself) will need to have an override that re-allows anonymous access. This requires a <location> element and must be located at the <configuration> level (outside the <system.web> section), like this:

<!-- Anonymous files -->
<location path="Login.aspx">
 <system.web>
  <authorization>
   <allow users="*" />
  </authorization>
 </system.web>
</location>

Note that you'll also need to allow anonymous access to any style sheets or scripts that are used by the anonymous pages:

<!-- Anonymous folders -->
<location path="styles">
 <system.web>
  <authorization>
   <allow users="*" />
  </authorization>
 </system.web>
</location>

Be aware that the location's path attribute is relative to the web.config folder and cannot have a ~/ prefix, unlike most other path-type configuration attributes.

Turning multiple lines into one comma separated line

sed -n 's/.*/&,/;H;$x;$s/,\n/,/g;$s/\n\(.*\)/\1/;$s/\(.*\),/\1/;$p'

How to edit incorrect commit message in Mercurial?

In TortoiseHg, right-click on the revision you want to modify. Choose Modify History->Import MQ. That will convert all the revisions up to and including the selected revision from Mercurial changesets into Mercurial Queue patches. Select the Patch you want to modify the message for, and it should automatically change the screen to the MQ editor. Edit the message which is in the middle of the screen, then click QRefresh. Finally, right click on the patch and choose Modify History->Finish Patch, which will convert it from a patch back into a change set.

Oh, this assumes that MQ is an active extension for TortoiseHG on this repository. If not, you should be able to click File->Settings, click Extensions, and click the mq checkbox. It should warn you that you have to close TortoiseHg before the extension is active, so close and reopen.

In Git, what is the difference between origin/master vs origin master?

origin/master is the remote master branch

Usually after doing a git fetch origin to bring all the changes from the server, you would do a git rebase origin/master, to rebase your changes and move the branch to the latest index. Here, origin/master is referring to the remote branch, because you are basically telling GIT to rebase the origin/master branch onto the current branch.

You would use origin master when pushing, for example. git push origin master is simply telling GIT to push to the remote repository the local master branch.

How to convert string to string[]?

If you want to convert a string like "Mohammad" to String[] that contains all characters as String, this may help you:

"Mohammad".ToCharArray().Select(c => c.ToString()).ToArray()

How to use GNU Make on Windows?

While make itself is available as a standalone executable (gnuwin32.sourceforge.net package make), using it in a proper development environment means using msys2.

Git 2.24 (Q4 2019) illustrates that:

See commit 4668931, commit b35304b, commit ab7d854, commit be5d88e, commit 5d65ad1, commit 030a628, commit 61d1d92, commit e4347c9, commit ed712ef, commit 5b8f9e2, commit 41616ef, commit c097b95 (04 Oct 2019), and commit dbcd970 (30 Sep 2019) by Johannes Schindelin (dscho).
(Merged by Junio C Hamano -- gitster -- in commit 6d5291b, 15 Oct 2019)

test-tool run-command: learn to run (parts of) the testsuite

Signed-off-by: Johannes Schindelin

Git for Windows jumps through hoops to provide a development environment that allows to build Git and to run its test suite.

To that end, an entire MSYS2 system, including GNU make and GCC is offered as "the Git for Windows SDK".
It does come at a price: an initial download of said SDK weighs in with several hundreds of megabytes, and the unpacked SDK occupies ~2GB of disk space.

A much more native development environment on Windows is Visual Studio. To help contributors use that environment, we already have a Makefile target vcxproj that generates a commit with project files (and other generated files), and Git for Windows' vs/master branch is continuously re-generated using that target.

The idea is to allow building Git in Visual Studio, and to run individual tests using a Portable Git.

What does servletcontext.getRealPath("/") mean and when should I use it

There is also a change between Java 7 and Java 8. Admittedly it involves the a deprecated call, but I had to add a "/" to get our program working! Here is the link discussing it Why does servletContext.getRealPath returns null on tomcat 8?

SQL Server: Cannot insert an explicit value into a timestamp column

There is some good information in these answers. Suppose you are dealing with databases which you can't alter, and that you are copying data from one version of the table to another, or from the same table in one database to another. Suppose also that there are lots of columns, and you either need data from all the columns, or the columns which you don't need don't have default values. You need to write a query with all the column names.

Here is a query which returns all the non-timestamp column names for a table, which you can cut and paste into your insert query. FYI: 189 is the type ID for timestamp.

declare @TableName nvarchar(50) = 'Product';

select stuff(
    (select 
        ', ' + columns.name
    from 
        (select id from sysobjects where xtype = 'U' and name = @TableName) tables
        inner join syscolumns columns on tables.id = columns.id
    where columns.xtype <> 189
    for xml path('')), 1, 2, '')

Just change the name of the table at the top from 'Product' to your table name. The query will return a list of column names:

ProductID, Name, ProductNumber, MakeFlag, FinishedGoodsFlag, Color, SafetyStockLevel, ReorderPoint, StandardCost, ListPrice, Size, SizeUnitMeasureCode, WeightUnitMeasureCode, Weight, DaysToManufacture, ProductLine, Class, Style, ProductSubcategoryID, ProductModelID, SellStartDate, SellEndDate, DiscontinuedDate, rowguid, ModifiedDate

If you are copying data from one database (DB1) to another database(DB2) you could use this query.

insert DB2.dbo.Product (ProductID, Name, ProductNumber, MakeFlag, FinishedGoodsFlag, Color, SafetyStockLevel, ReorderPoint, StandardCost, ListPrice, Size, SizeUnitMeasureCode, WeightUnitMeasureCode, Weight, DaysToManufacture, ProductLine, Class, Style, ProductSubcategoryID, ProductModelID, SellStartDate, SellEndDate, DiscontinuedDate, rowguid, ModifiedDate)
select ProductID, Name, ProductNumber, MakeFlag, FinishedGoodsFlag, Color, SafetyStockLevel, ReorderPoint, StandardCost, ListPrice, Size, SizeUnitMeasureCode, WeightUnitMeasureCode, Weight, DaysToManufacture, ProductLine, Class, Style, ProductSubcategoryID, ProductModelID, SellStartDate, SellEndDate, DiscontinuedDate, rowguid, ModifiedDate 
from DB1.dbo.Product

Using PowerShell to remove lines from a text file if it contains a string

The pipe character | has a special meaning in regular expressions. a|b means "match either a or b". If you want to match a literal | character, you need to escape it:

... | Select-String -Pattern 'H\|159' -NotMatch | ...

How to use variables in SQL statement in Python?

Different implementations of the Python DB-API are allowed to use different placeholders, so you'll need to find out which one you're using -- it could be (e.g. with MySQLdb):

cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))

or (e.g. with sqlite3 from the Python standard library):

cursor.execute("INSERT INTO table VALUES (?, ?, ?)", (var1, var2, var3))

or others yet (after VALUES you could have (:1, :2, :3) , or "named styles" (:fee, :fie, :fo) or (%(fee)s, %(fie)s, %(fo)s) where you pass a dict instead of a map as the second argument to execute). Check the paramstyle string constant in the DB API module you're using, and look for paramstyle at http://www.python.org/dev/peps/pep-0249/ to see what all the parameter-passing styles are!

Window.open and pass parameters by post method

I completely agree with mercenary's answer posted above and created this function for me which works for me. It's not an answer, it's a comment on above post by mercenary

function openWindowWithPostRequest() {
  var winName='MyWindow';
  var winURL='search.action';
  var windowoption='resizable=yes,height=600,width=800,location=0,menubar=0,scrollbars=1';
  var params = { 'param1' : '1','param2' :'2'};         
  var form = document.createElement("form");
  form.setAttribute("method", "post");
  form.setAttribute("action", winURL);
  form.setAttribute("target",winName);  
  for (var i in params) {
    if (params.hasOwnProperty(i)) {
      var input = document.createElement('input');
      input.type = 'hidden';
      input.name = i;
      input.value = params[i];
      form.appendChild(input);
    }
  }              
  document.body.appendChild(form);                       
  window.open('', winName,windowoption);
  form.target = winName;
  form.submit();                 
  document.body.removeChild(form);           
}

Android - How to decode and decompile any APK file?

To decompile APK Use APKTool.
You can learn how APKTool works on http://www.decompileandroid.com/ or by reading the documentation.

Check whether a value exists in JSON object

iterate through the array and check its name value.

How to create timer events using C++ 11?

This is the code I have so far:

I am using VC++ 2012 (no variadic templates)

//header
#include <thread>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <chrono>
#include <memory>
#include <algorithm>

template<class T>
class TimerThread
{
  typedef std::chrono::high_resolution_clock clock_t;

  struct TimerInfo
  {
    clock_t::time_point m_TimePoint;
    T m_User;

    template <class TArg1>
    TimerInfo(clock_t::time_point tp, TArg1 && arg1)
      : m_TimePoint(tp)
      , m_User(std::forward<TArg1>(arg1))
    {
    }

    template <class TArg1, class TArg2>
    TimerInfo(clock_t::time_point tp, TArg1 && arg1, TArg2 && arg2)
      : m_TimePoint(tp)
      , m_User(std::forward<TArg1>(arg1), std::forward<TArg2>(arg2))
    {
    }
  };

  std::unique_ptr<std::thread> m_Thread;
  std::vector<TimerInfo>       m_Timers;
  std::mutex                   m_Mutex;
  std::condition_variable      m_Condition;
  bool                         m_Sort;
  bool                         m_Stop;

  void TimerLoop()
  {
    for (;;)
    {
      std::unique_lock<std::mutex>  lock(m_Mutex);

      while (!m_Stop && m_Timers.empty())
      {
        m_Condition.wait(lock);
      }

      if (m_Stop)
      {
        return;
      }

      if (m_Sort)
      {
        //Sort could be done at insert
        //but probabily this thread has time to do
        std::sort(m_Timers.begin(),
                  m_Timers.end(),
                  [](const TimerInfo & ti1, const TimerInfo & ti2)
        {
          return ti1.m_TimePoint > ti2.m_TimePoint;
        });
        m_Sort = false;
      }

      auto now = clock_t::now();
      auto expire = m_Timers.back().m_TimePoint;

      if (expire > now) //can I take a nap?
      {
        auto napTime = expire - now;
        m_Condition.wait_for(lock, napTime);

        //check again
        auto expire = m_Timers.back().m_TimePoint;
        auto now = clock_t::now();

        if (expire <= now)
        {
          TimerCall(m_Timers.back().m_User);
          m_Timers.pop_back();
        }
      }
      else
      {
        TimerCall(m_Timers.back().m_User);
        m_Timers.pop_back();
      }
    }
  }

  template<class T, class TArg1>
  friend void CreateTimer(TimerThread<T>& timerThread, int ms, TArg1 && arg1);

  template<class T, class TArg1, class TArg2>
  friend void CreateTimer(TimerThread<T>& timerThread, int ms, TArg1 && arg1, TArg2 && arg2);

public:
  TimerThread() : m_Stop(false), m_Sort(false)
  {
    m_Thread.reset(new std::thread(std::bind(&TimerThread::TimerLoop, this)));
  }

  ~TimerThread()
  {
    m_Stop = true;
    m_Condition.notify_all();
    m_Thread->join();
  }
};

template<class T, class TArg1>
void CreateTimer(TimerThread<T>& timerThread, int ms, TArg1 && arg1)
{
  {
    std::unique_lock<std::mutex> lock(timerThread.m_Mutex);
    timerThread.m_Timers.emplace_back(TimerThread<T>::TimerInfo(TimerThread<T>::clock_t::now() + std::chrono::milliseconds(ms),
                                      std::forward<TArg1>(arg1)));
    timerThread.m_Sort = true;
  }
  // wake up
  timerThread.m_Condition.notify_one();
}

template<class T, class TArg1, class TArg2>
void CreateTimer(TimerThread<T>& timerThread, int ms, TArg1 && arg1, TArg2 && arg2)
{
  {
    std::unique_lock<std::mutex> lock(timerThread.m_Mutex);
    timerThread.m_Timers.emplace_back(TimerThread<T>::TimerInfo(TimerThread<T>::clock_t::now() + std::chrono::milliseconds(ms),
                                      std::forward<TArg1>(arg1),
                                      std::forward<TArg2>(arg2)));
    timerThread.m_Sort = true;
  }
  // wake up
  timerThread.m_Condition.notify_one();
}

//sample
#include <iostream>
#include <string>

void TimerCall(int i)
{
  std::cout << i << std::endl;
}

int main()
{
  std::cout << "start" << std::endl;
  TimerThread<int> timers;

  CreateTimer(timers, 2000, 1);
  CreateTimer(timers, 5000, 2);
  CreateTimer(timers, 100, 3);

  std::this_thread::sleep_for(std::chrono::seconds(5));
  std::cout << "end" << std::endl;
}

How to check if a variable is equal to one string or another string?

Two separate checks. Also, use == rather than is to check for equality rather than identity.

 if var=='stringone' or var=='stringtwo':
     dosomething()

How to hide .php extension in .htaccess

The other option for using PHP scripts sans extension is

Options +MultiViews

Or even just following in the directories .htaccess:

DefaultType application/x-httpd-php

The latter allows having all filenames without extension script being treated as PHP scripts. While MultiViews makes the webserver look for alternatives, when just the basename is provided (there's a performance hit with that however).

How/When does Execute Shell mark a build as failure in Jenkins?

In my opinion, turning off the -e option to your shell is a really bad idea. Eventually one of the commands in your script will fail due to transient conditions like out of disk space or network errors. Without -e Jenkins won't notice and will continue along happily. If you've got Jenkins set up to do deployment, that may result in bad code getting pushed and bringing down your site.

If you have a line in your script where failure is expected, like a grep or a find, then just add || true to the end of that line. That ensures that line will always return success.

If you need to use that exit code, you can either hoist the command into your if statement:

grep foo bar; if [ $? == 0 ]; then ...    -->   if grep foo bar; then ...

Or you can capture the return code in your || clause:

grep foo bar || ret=$?

Convert dd-mm-yyyy string to date

Use this format: myDate = new Date('2011-01-03'); // Mon Jan 03 2011 00:00:00

Java sending and receiving file (byte[]) over sockets

Adding up on EJP's answer; use this for more fluidity. Make sure you don't put his code inside a bigger try catch with more code between the .read and the catch block, it may return an exception and jump all the way to the outer catch block, safest bet is to place EJPS's while loop inside a try catch, and then continue the code after it, like:

int count;
byte[] bytes = new byte[4096];
try {
    while ((count = is.read(bytes)) > 0) {
        System.out.println(count);
        bos.write(bytes, 0, count);
    }
} catch ( Exception e )
{
    //It will land here....
}
// Then continue from here

EDIT: ^This happened to me cuz I didn't realize you need to put socket.shutDownOutput() if it's a client-to-server stream!

Hope this post solves any of your issues

How can I use Async with ForEach?

List<T>.ForEach doesn't play particularly well with async (neither does LINQ-to-objects, for the same reasons).

In this case, I recommend projecting each element into an asynchronous operation, and you can then (asynchronously) wait for them all to complete.

using (DataContext db = new DataLayer.DataContext())
{
    var tasks = db.Groups.ToList().Select(i => GetAdminsFromGroupAsync(i.Gid));
    var results = await Task.WhenAll(tasks);
}

The benefits of this approach over giving an async delegate to ForEach are:

  1. Error handling is more proper. Exceptions from async void cannot be caught with catch; this approach will propagate exceptions at the await Task.WhenAll line, allowing natural exception handling.
  2. You know that the tasks are complete at the end of this method, since it does an await Task.WhenAll. If you use async void, you cannot easily tell when the operations have completed.
  3. This approach has a natural syntax for retrieving the results. GetAdminsFromGroupAsync sounds like it's an operation that produces a result (the admins), and such code is more natural if such operations can return their results rather than setting a value as a side effect.

How to delete last item in list?

If I understood the question correctly, you can use the slicing notation to keep everything except the last item:

record = record[:-1]

But a better way is to delete the item directly:

del record[-1]

Note 1: Note that using record = record[:-1] does not really remove the last element, but assign the sublist to record. This makes a difference if you run it inside a function and record is a parameter. With record = record[:-1] the original list (outside the function) is unchanged, with del record[-1] or record.pop() the list is changed. (as stated by @pltrdy in the comments)

Note 2: The code could use some Python idioms. I highly recommend reading this:
Code Like a Pythonista: Idiomatic Python (via wayback machine archive).

How to Get the HTTP Post data in C#?

In the web browser, open up developer console (F12 in Chrome and IE), then open network tab and watch the request and response data. Another option - use Fiddler (http://fiddler2.com/).

When you get to see the POST request as it is being sent to your page, look into query string and headers. You will see whether your data comes in query string or as form - or maybe it is not being sent to your page at all.

UPDATE: sorry, had to look at MailGun APIs first, they do not go through your browser, requests come directly from their server. You'll have to debug and examine all members of Request.Params when you get the POST from MailGun.

Can you append strings to variables in PHP?

PHP syntax is little different in case of concatenation from JavaScript. Instead of (+) plus a (.) period is used for string concatenation.

<?php

$selectBox = '<select name="number">';
for ($i=1;$i<=100;$i++)
{
    $selectBox += '<option value="' . $i . '">' . $i . '</option>'; // <-- (Wrong) Replace + with .
    $selectBox .= '<option value="' . $i . '">' . $i . '</option>'; // <-- (Correct) Here + is replaced .
}
$selectBox += '</select>'; // <-- (Wrong) Replace + with .
$selectBox .= '</select>'; // <-- (Correct) Here + is replaced .
echo $selectBox;

?>

JMS Topic vs Queues

If you have N consumers then:

JMS Topics deliver messages to N of N JMS Queues deliver messages to 1 of N

You said you are "looking to have a 'thing' that will send a copy of the message to each subscriber in the same sequence as that in which the message was received by the ActiveMQ broker."

So you want to use a Topic in order that all N subscribers get a copy of the message.

get everything between <tag> and </tag> with php

you can use /<code>([\s\S]*)<\/code>/msU this catch NEWLINES too!

Controller not a function, got undefined, while defining controllers globally

These errors occurred, in my case, preceeded by syntax errors at list.find() fuction; 'find' method of a list not recognized by IE11, so has to replace by Filter method, which works for both IE11 and chrome. refer https://github.com/flrs/visavail/issues/19

Generate PDF from HTML using pdfMake in Angularjs

I know its not relevant to this post but might help others converting HTML to PDF on client side. This is a simple solution if you use kendo. It also preserves the css (most of the cases).

_x000D_
_x000D_
var generatePDF = function() {_x000D_
  kendo.drawing.drawDOM($("#formConfirmation")).then(function(group) {_x000D_
    kendo.drawing.pdf.saveAs(group, "Converted PDF.pdf");_x000D_
  });_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
  <!-- Latest compiled and minified CSS -->_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <!-- Optional theme -->_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
  <!-- Latest compiled and minified JavaScript -->_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
  <script src="//kendo.cdn.telerik.com/2016.3.914/js/kendo.all.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <br/>_x000D_
  <button class="btn btn-primary" onclick="generatePDF()"><i class="fa fa-save"></i> Save as PDF</button>_x000D_
  <br/>_x000D_
  <br/>_x000D_
  <div id="formConfirmation">_x000D_
_x000D_
    <div class="container theme-showcase" role="main">_x000D_
      <!-- Main jumbotron for a primary marketing message or call to action -->_x000D_
      <div class="jumbotron">_x000D_
        <h1>Theme example</h1>_x000D_
        <p>This is a template showcasing the optional theme stylesheet included in Bootstrap. Use it as a starting point to create something more unique by building on or modifying it.</p>_x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>Buttons</h1>_x000D_
      </div>_x000D_
      <p>_x000D_
        <button type="button" class="btn btn-lg btn-default">Default</button>_x000D_
        <button type="button" class="btn btn-lg btn-primary">Primary</button>_x000D_
        <button type="button" class="btn btn-lg btn-success">Success</button>_x000D_
        <button type="button" class="btn btn-lg btn-info">Info</button>_x000D_
        <button type="button" class="btn btn-lg btn-warning">Warning</button>_x000D_
        <button type="button" class="btn btn-lg btn-danger">Danger</button>_x000D_
        <button type="button" class="btn btn-lg btn-link">Link</button>_x000D_
      </p>_x000D_
      <p>_x000D_
        <button type="button" class="btn btn-default">Default</button>_x000D_
        <button type="button" class="btn btn-primary">Primary</button>_x000D_
        <button type="button" class="btn btn-success">Success</button>_x000D_
        <button type="button" class="btn btn-info">Info</button>_x000D_
        <button type="button" class="btn btn-warning">Warning</button>_x000D_
        <button type="button" class="btn btn-danger">Danger</button>_x000D_
        <button type="button" class="btn btn-link">Link</button>_x000D_
      </p>_x000D_
      <p>_x000D_
        <button type="button" class="btn btn-sm btn-default">Default</button>_x000D_
        <button type="button" class="btn btn-sm btn-primary">Primary</button>_x000D_
        <button type="button" class="btn btn-sm btn-success">Success</button>_x000D_
        <button type="button" class="btn btn-sm btn-info">Info</button>_x000D_
        <button type="button" class="btn btn-sm btn-warning">Warning</button>_x000D_
        <button type="button" class="btn btn-sm btn-danger">Danger</button>_x000D_
        <button type="button" class="btn btn-sm btn-link">Link</button>_x000D_
      </p>_x000D_
      <p>_x000D_
        <button type="button" class="btn btn-xs btn-default">Default</button>_x000D_
        <button type="button" class="btn btn-xs btn-primary">Primary</button>_x000D_
        <button type="button" class="btn btn-xs btn-success">Success</button>_x000D_
        <button type="button" class="btn btn-xs btn-info">Info</button>_x000D_
        <button type="button" class="btn btn-xs btn-warning">Warning</button>_x000D_
        <button type="button" class="btn btn-xs btn-danger">Danger</button>_x000D_
        <button type="button" class="btn btn-xs btn-link">Link</button>_x000D_
      </p>_x000D_
      <div class="page-header">_x000D_
        <h1>Tables</h1>_x000D_
      </div>_x000D_
      <div class="row">_x000D_
        <div class="col-md-6">_x000D_
          <table class="table">_x000D_
            <thead>_x000D_
              <tr>_x000D_
                <th>#</th>_x000D_
                <th>First Name</th>_x000D_
                <th>Last Name</th>_x000D_
                <th>Username</th>_x000D_
              </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
              <tr>_x000D_
                <td>1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>3</td>_x000D_
                <td>Larry</td>_x000D_
                <td>the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
              </tr>_x000D_
            </tbody>_x000D_
          </table>_x000D_
        </div>_x000D_
        <div class="col-md-6">_x000D_
          <table class="table table-striped">_x000D_
            <thead>_x000D_
              <tr>_x000D_
                <th>#</th>_x000D_
                <th>First Name</th>_x000D_
                <th>Last Name</th>_x000D_
                <th>Username</th>_x000D_
              </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
              <tr>_x000D_
                <td>1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>3</td>_x000D_
                <td>Larry</td>_x000D_
                <td>the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
              </tr>_x000D_
            </tbody>_x000D_
          </table>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="row">_x000D_
        <div class="col-md-6">_x000D_
          <table class="table table-bordered">_x000D_
            <thead>_x000D_
              <tr>_x000D_
                <th>#</th>_x000D_
                <th>First Name</th>_x000D_
                <th>Last Name</th>_x000D_
                <th>Username</th>_x000D_
              </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
              <tr>_x000D_
                <td rowspan="2">1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@TwBootstrap</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>3</td>_x000D_
                <td colspan="2">Larry the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
              </tr>_x000D_
            </tbody>_x000D_
          </table>_x000D_
        </div>_x000D_
        <div class="col-md-6">_x000D_
          <table class="table table-condensed">_x000D_
            <thead>_x000D_
              <tr>_x000D_
                <th>#</th>_x000D_
                <th>First Name</th>_x000D_
                <th>Last Name</th>_x000D_
                <th>Username</th>_x000D_
              </tr>_x000D_
            </thead>_x000D_
            <tbody>_x000D_
              <tr>_x000D_
                <td>1</td>_x000D_
                <td>Mark</td>_x000D_
                <td>Otto</td>_x000D_
                <td>@mdo</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>2</td>_x000D_
                <td>Jacob</td>_x000D_
                <td>Thornton</td>_x000D_
                <td>@fat</td>_x000D_
              </tr>_x000D_
              <tr>_x000D_
                <td>3</td>_x000D_
                <td colspan="2">Larry the Bird</td>_x000D_
                <td>@twitter</td>_x000D_
              </tr>_x000D_
            </tbody>_x000D_
          </table>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>Thumbnails</h1>_x000D_
      </div>_x000D_
      <img data-src="holder.js/200x200" class="img-thumbnail" alt="A generic square placeholder image with a white border around it, making it resemble a photograph taken with an old instant camera">_x000D_
      <div class="page-header">_x000D_
        <h1>Labels</h1>_x000D_
      </div>_x000D_
      <h1>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h1>_x000D_
      <h2>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h2>_x000D_
      <h3>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h3>_x000D_
      <h4>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h4>_x000D_
      <h5>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h5>_x000D_
      <h6>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </h6>_x000D_
      <p>_x000D_
        <span class="label label-default">Default</span>_x000D_
        <span class="label label-primary">Primary</span>_x000D_
        <span class="label label-success">Success</span>_x000D_
        <span class="label label-info">Info</span>_x000D_
        <span class="label label-warning">Warning</span>_x000D_
        <span class="label label-danger">Danger</span>_x000D_
      </p>_x000D_
      <div class="page-header">_x000D_
        <h1>Badges</h1>_x000D_
      </div>_x000D_
      <p>_x000D_
        <a href="#">Inbox <span class="badge">42</span></a>_x000D_
      </p>_x000D_
      <ul class="nav nav-pills" role="tablist">_x000D_
        <li role="presentation" class="active"><a href="#">Home <span class="badge">42</span></a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Profile</a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Messages <span class="badge">3</span></a>_x000D_
        </li>_x000D_
      </ul>_x000D_
      <div class="page-header">_x000D_
        <h1>Dropdown menus</h1>_x000D_
      </div>_x000D_
      <div class="dropdown theme-dropdown clearfix">_x000D_
        <a id="dropdownMenu1" href="#" class="sr-only dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>_x000D_
        <ul class="dropdown-menu" aria-labelledby="dropdownMenu1">_x000D_
          <li class="active"><a href="#">Action</a>_x000D_
          </li>_x000D_
          <li><a href="#">Another action</a>_x000D_
          </li>_x000D_
          <li><a href="#">Something else here</a>_x000D_
          </li>_x000D_
          <li role="separator" class="divider"></li>_x000D_
          <li><a href="#">Separated link</a>_x000D_
          </li>_x000D_
        </ul>_x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>Navs</h1>_x000D_
      </div>_x000D_
      <ul class="nav nav-tabs" role="tablist">_x000D_
        <li role="presentation" class="active"><a href="#">Home</a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Profile</a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Messages</a>_x000D_
        </li>_x000D_
      </ul>_x000D_
      <ul class="nav nav-pills" role="tablist">_x000D_
        <li role="presentation" class="active"><a href="#">Home</a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Profile</a>_x000D_
        </li>_x000D_
        <li role="presentation"><a href="#">Messages</a>_x000D_
        </li>_x000D_
      </ul>_x000D_
      <div class="page-header">_x000D_
        <h1>Navbars</h1>_x000D_
      </div>_x000D_
      <nav class="navbar navbar-default">_x000D_
        <div class="container">_x000D_
          <div class="navbar-header">_x000D_
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
              <span class="sr-only">Toggle navigation</span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
            </button>_x000D_
            <a class="navbar-brand" href="#">Project name</a>_x000D_
          </div>_x000D_
          <div class="navbar-collapse collapse">_x000D_
            <ul class="nav navbar-nav">_x000D_
              <li class="active"><a href="#">Home</a>_x000D_
              </li>_x000D_
              <li><a href="#about">About</a>_x000D_
              </li>_x000D_
              <li><a href="#contact">Contact</a>_x000D_
              </li>_x000D_
              <li class="dropdown">_x000D_
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>_x000D_
                <ul class="dropdown-menu">_x000D_
                  <li><a href="#">Action</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">Another action</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">Something else here</a>_x000D_
                  </li>_x000D_
                  <li role="separator" class="divider"></li>_x000D_
                  <li class="dropdown-header">Nav header</li>_x000D_
                  <li><a href="#">Separated link</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">One more separated link</a>_x000D_
                  </li>_x000D_
                </ul>_x000D_
              </li>_x000D_
            </ul>_x000D_
          </div>_x000D_
          <!--/.nav-collapse -->_x000D_
        </div>_x000D_
      </nav>_x000D_
      <nav class="navbar navbar-inverse">_x000D_
        <div class="container">_x000D_
          <div class="navbar-header">_x000D_
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
              <span class="sr-only">Toggle navigation</span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
              <span class="icon-bar"></span>_x000D_
            </button>_x000D_
            <a class="navbar-brand" href="#">Project name</a>_x000D_
          </div>_x000D_
          <div class="navbar-collapse collapse">_x000D_
            <ul class="nav navbar-nav">_x000D_
              <li class="active"><a href="#">Home</a>_x000D_
              </li>_x000D_
              <li><a href="#about">About</a>_x000D_
              </li>_x000D_
              <li><a href="#contact">Contact</a>_x000D_
              </li>_x000D_
              <li class="dropdown">_x000D_
                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>_x000D_
                <ul class="dropdown-menu">_x000D_
                  <li><a href="#">Action</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">Another action</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">Something else here</a>_x000D_
                  </li>_x000D_
                  <li role="separator" class="divider"></li>_x000D_
                  <li class="dropdown-header">Nav header</li>_x000D_
                  <li><a href="#">Separated link</a>_x000D_
                  </li>_x000D_
                  <li><a href="#">One more separated link</a>_x000D_
                  </li>_x000D_
                </ul>_x000D_
              </li>_x000D_
            </ul>_x000D_
          </div>_x000D_
          <!--/.nav-collapse -->_x000D_
        </div>_x000D_
      </nav>_x000D_
      <div class="page-header">_x000D_
        <h1>Alerts</h1>_x000D_
      </div>_x000D_
      <div class="alert alert-success" role="alert">_x000D_
        <strong>Well done!</strong> You successfully read this important alert message._x000D_
      </div>_x000D_
      <div class="alert alert-info" role="alert">_x000D_
        <strong>Heads up!</strong> This alert needs your attention, but it's not super important._x000D_
      </div>_x000D_
      <div class="alert alert-warning" role="alert">_x000D_
        <strong>Warning!</strong> Best check yo self, you're not looking too good._x000D_
      </div>_x000D_
      <div class="alert alert-danger" role="alert">_x000D_
        <strong>Oh snap!</strong> Change a few things up and try submitting again._x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>Progress bars</h1>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%;"><span class="sr-only">60% Complete</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 40%"><span class="sr-only">40% Complete (success)</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 20%"><span class="sr-only">20% Complete</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%"><span class="sr-only">60% Complete (warning)</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-danger" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="width: 80%"><span class="sr-only">80% Complete (danger)</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-striped" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%"><span class="sr-only">60% Complete</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="progress">_x000D_
        <div class="progress-bar progress-bar-success" style="width: 35%"><span class="sr-only">35% Complete (success)</span>_x000D_
        </div>_x000D_
        <div class="progress-bar progress-bar-warning" style="width: 20%"><span class="sr-only">20% Complete (warning)</span>_x000D_
        </div>_x000D_
        <div class="progress-bar progress-bar-danger" style="width: 10%"><span class="sr-only">10% Complete (danger)</span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>List groups</h1>_x000D_
      </div>_x000D_
      <div class="row">_x000D_
        <div class="col-sm-4">_x000D_
          <ul class="list-group">_x000D_
            <li class="list-group-item">Cras justo odio</li>_x000D_
            <li class="list-group-item">Dapibus ac facilisis in</li>_x000D_
            <li class="list-group-item">Morbi leo risus</li>_x000D_
            <li class="list-group-item">Porta ac consectetur ac</li>_x000D_
            <li class="list-group-item">Vestibulum at eros</li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
        <div class="col-sm-4">_x000D_
          <div class="list-group">_x000D_
            <a href="#" class="list-group-item active">_x000D_
              Cras justo odio_x000D_
            </a>_x000D_
            <a href="#" class="list-group-item">Dapibus ac facilisis in</a>_x000D_
            <a href="#" class="list-group-item">Morbi leo risus</a>_x000D_
            <a href="#" class="list-group-item">Porta ac consectetur ac</a>_x000D_
            <a href="#" class="list-group-item">Vestibulum at eros</a>_x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
        <div class="col-sm-4">_x000D_
          <div class="list-group">_x000D_
            <a href="#" class="list-group-item active">_x000D_
              <h4 class="list-group-item-heading">List group item heading</h4>_x000D_
              <p class="list-group-item-text">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p>_x000D_
            </a>_x000D_
            <a href="#" class="list-group-item">_x000D_
              <h4 class="list-group-item-heading">List group item heading</h4>_x000D_
              <p class="list-group-item-text">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p>_x000D_
            </a>_x000D_
            <a href="#" class="list-group-item">_x000D_
              <h4 class="list-group-item-heading">List group item heading</h4>_x000D_
              <p class="list-group-item-text">Donec id elit non mi porta gravida at eget metus. Maecenas sed diam eget risus varius blandit.</p>_x000D_
            </a>_x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
      </div>_x000D_
      <div class="page-header">_x000D_
        <h1>Panels</h1>_x000D_
      </div>_x000D_
      <div class="row">_x000D_
        <div class="col-sm-4">_x000D_
          <div class="panel panel-default">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
          <div class="panel panel-primary">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
        <div class="col-sm-4">_x000D_
          <div class="panel panel-success">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
          <div class="panel panel-info">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
        <div class="col-sm-4">_x000D_
          <div class="panel panel-warning">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
          <div class="panel panel-danger">_x000D_
            <div class="panel-heading">_x000D_
              <h3 class="panel-title">Panel title</h3>_x000D_
            </div>_x000D_
            <div class="panel-body">_x000D_
              Panel content_x000D_
            </div>_x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- /.col-sm-4 -->_x000D_
      </div>_x000D_
    </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

MySQL CREATE TABLE IF NOT EXISTS in PHPmyadmin import

Depending on what you want to accomplish, you might replace INSERT with INSERT IGNORE in your file. This will avoid generating an error for the rows that you are trying to insert and already exist.

See http://dev.mysql.com/doc/refman/5.5/en/insert.html.

How to pass value from <option><select> to form action

You don't have to use jQuery or Javascript.

Use the name tag of the select and let the form do it's job.

<select name="agent_id" id="agent_id">

Simulating a click in jQuery/JavaScript on a link

Try this

function submitRequest(buttonId) {
    if (document.getElementById(buttonId) == null
            || document.getElementById(buttonId) == undefined) {
        return;
    }
    if (document.getElementById(buttonId).dispatchEvent) {
        var e = document.createEvent("MouseEvents");
        e.initEvent("click", true, true);
        document.getElementById(buttonId).dispatchEvent(e);
    } else {
        document.getElementById(buttonId).click();
    }
}

and you can use it like

submitRequest("target-element-id");

HTTP get with headers using RestTemplate

The RestTemplate getForObject() method does not support setting headers. The solution is to use the exchange() method.

So instead of restTemplate.getForObject(url, String.class, param) (which has no headers), use

HttpHeaders headers = new HttpHeaders();
headers.set("Header", "value");
headers.set("Other-Header", "othervalue");
...

HttpEntity entity = new HttpEntity(headers);

ResponseEntity<String> response = restTemplate.exchange(
    url, HttpMethod.GET, entity, String.class, param);

Finally, use response.getBody() to get your result.

This question is similar to this question.

How to create a box when mouse over text in pure CSS?

You can easily make this CSS Tool Tip through simple code :-

    <!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
a.info{
    position:relative; /*this is the key*/
    color:#000;
    top:100px;
    left:50px;
    text-decoration:none;
    text-align:center;
  }



a.info span{display: none}

a.info:hover span{ /*the span will display just on :hover state*/
    display:block;
    position:absolute;
    top:-60px;
    width:15em;
    border:5px solid #0cf;
    background-color:#cff; color:#000;
    text-align: center;
    padding:10px;
  }

  a.info:hover span:after{ /*the span will display just on :hover state*/
    content:'';
    position:absolute;
    bottom:-11px;
    width:10px;
    height:10px;
    border-bottom:5px solid #0cf;
    border-right:5px solid #0cf;
    background:#cff;
    left:50%;
    margin-left:-5px;
    -moz-transform:rotate(45deg);
    -webkit-transform:rotate(45deg);
    transform:rotate(45deg);
  }


</style>
</head>
<body>
<a href="#" class="info">Shailender Arora <span>TOOLTIP</span></a>
  </div>
</body>
</html>

http://jsbin.com/ebucoz/25/edit

How to detect current state within directive

Also you can use ui-sref-active directive:

<ul>
  <li ui-sref-active="active" class="item">
    <a href ui-sref="app.user({user: 'bilbobaggins'})">@bilbobaggins</a>
  </li>
  <!-- ... -->
</ul>

Or filters: "stateName" | isState & "stateName" | includedByState

Populate nested array in mongoose

That works for me:

 Project.find(query)
  .lean()
  .populate({ path: 'pages' })
  .exec(function(err, docs) {

    var options = {
      path: 'pages.components',
      model: 'Component'
    };

    if (err) return res.json(500);
    Project.populate(docs, options, function (err, projects) {
      res.json(projects);
    });
  });

Documentation: Model.populate

How can I detect when an Android application is running in the emulator?

Well Android id does not work for me, I'm currently using:

"google_sdk".equals( Build.PRODUCT );

How to get element value in jQuery

Most probably, you want something like this:

$("#list li").click(function() {
        var selected = $(this).html();
        alert(selected);
});

Getting "unixtime" in Java

Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.

As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.

long unixTime = System.currentTimeMillis() / 1000L;

How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

If you're already using Boost, you can do it with boost string algorithms + boost lexical cast:

#include <boost/algorithm/string/predicate.hpp>
#include <boost/lexical_cast.hpp>

try {    
    if (boost::starts_with(argv[1], "--foo="))
        foo_value = boost::lexical_cast<int>(argv[1]+6);
} catch (boost::bad_lexical_cast) {
    // bad parameter
}

This kind of approach, like many of the other answers provided here is ok for very simple tasks, but in the long run you are usually better off using a command line parsing library. Boost has one (Boost.Program_options), which may make sense if you happen to be using Boost already.

Otherwise a search for "c++ command line parser" will yield a number of options.

javax.servlet.ServletException cannot be resolved to a type in spring web app

import javax.servlet

STEP 1

Go to properties of your project ( with Alt+Enter or righ-click )

STEP 2

check on Apache Tomcat v7.0 under Targeted Runtime and it works.

source: https://stackoverflow.com/a/9287149

How Do I Upload Eclipse Projects to GitHub?

You need a git client to upload your project to git servers. For eclipse EGIT is a nice plugin to use GIT.

to learn the basic of git , see here // i think you should have the basic first

How to display errors on laravel 4?

Maybe not on Laravel 4 this time, but on L5.2* I had similar issue:

I simply changed the ownership of the storage/logs directory to www-data with:

# chown -R www-data:www-data logs

PS: This is on Ubuntu 15 and with apache.

My logs directory now looks like:

drwxrwxr-x  2 www-data   www-data 4096 jaan  23 09:39 logs/

What is the recommended way to delete a large number of items from DynamoDB?

The answer of this question depends on the number of items and their size and your budget. Depends on that we have following 3 cases:

1- The number of items and size of items in the table are not very much. then as Steffen Opel said you can Use Query rather than Scan to retrieve all items for user_id and then loop over all returned items and either facilitate DeleteItem or BatchWriteItem. But keep in mind you may burn a lot of throughput capacity here. For example, consider a situation where you need delete 1000 items from a DynamoDB table. Assume that each item is 1 KB in size, resulting in Around 1MB of data. This bulk-deleting task will require a total of 2000 write capacity units for query and delete. To perform this data load within 10 seconds (which is not even considered as fast in some applications), you would need to set the provisioned write throughput of the table to 200 write capacity units. As you can see its doable to use this way if its for less number of items or small size items.

2- We have a lot of items or very large items in the table and we can store them according to the time into different tables. Then as jonathan Said you can just delete the table. this is much better but I don't think it is matched with your case. As you want to delete all of users data no matter what is the time of creation of logs, so in this case you can't delete a particular table. if you wanna have a separate table for each user then I guess if number of users are high then its so expensive and it is not practical for your case.

3- If you have a lot of data and you can't divide your hot and cold data into different tables and you need to do large scale delete frequently then unfortunately DynamoDB is not a good option for you at all. It may become more expensive or very slow(depends on your budget). In these cases I recommend to find another database for your data.

PHP case-insensitive in_array function

you can use preg_grep():

$a= array(
 'one',
 'two',
 'three',
 'four'
);

print_r( preg_grep( "/ONe/i" , $a ) );

How do you join on the same table, twice, in mysql?

Given the following tables..

Domain Table
dom_id | dom_url

Review Table
rev_id | rev_dom_from | rev_dom_for

Try this sql... (It's pretty much the same thing that Stephen Wrighton wrote above) The trick is that you are basically selecting from the domain table twice in the same query and joining the results.

Select d1.dom_url, d2.dom_id from
review r, domain d1, domain d2
where d1.dom_id = r.rev_dom_from
and d2.dom_id = r.rev_dom_for

If you are still stuck, please be more specific with exactly it is that you don't understand.

What is the easiest way to encrypt a password when I save it to the registry?

This is what you would like to do:

OurKey.SetValue("Password", StringEncryptor.EncryptString(textBoxPassword.Text));
OurKey.GetValue("Password", StringEncryptor.DecryptString(textBoxPassword.Text));

You can do that with this the following classes. This class is a generic class is the client endpoint. It enables IOC of various encryption algorithms using Ninject.

public class StringEncryptor
{
    private static IKernel _kernel;

    static StringEncryptor()
    {
        _kernel = new StandardKernel(new EncryptionModule());
    }

    public static string EncryptString(string plainText)
    {
        return _kernel.Get<IStringEncryptor>().EncryptString(plainText);
    }

    public static string DecryptString(string encryptedText)
    {
        return _kernel.Get<IStringEncryptor>().DecryptString(encryptedText);
    }
}

This next class is the ninject class that allows you to inject the various algorithms:

public class EncryptionModule : StandardModule
{
    public override void Load()
    {
        Bind<IStringEncryptor>().To<TripleDESStringEncryptor>();
    }
}

This is the interface that any algorithm needs to implement to encrypt/decrypt strings:

public interface IStringEncryptor
{
    string EncryptString(string plainText);
    string DecryptString(string encryptedText);
}

This is a implementation using the TripleDES algorithm:

public class TripleDESStringEncryptor : IStringEncryptor
{
    private byte[] _key;
    private byte[] _iv;
    private TripleDESCryptoServiceProvider _provider;

    public TripleDESStringEncryptor()
    {
        _key = System.Text.ASCIIEncoding.ASCII.GetBytes("GSYAHAGCBDUUADIADKOPAAAW");
        _iv = System.Text.ASCIIEncoding.ASCII.GetBytes("USAZBGAW");
        _provider = new TripleDESCryptoServiceProvider();
    }

    #region IStringEncryptor Members

    public string EncryptString(string plainText)
    {
        return Transform(plainText, _provider.CreateEncryptor(_key, _iv));
    }

    public string DecryptString(string encryptedText)
    {
        return Transform(encryptedText, _provider.CreateDecryptor(_key, _iv));
    }

    #endregion

    private string Transform(string text, ICryptoTransform transform)
    {
        if (text == null)
        {
            return null;
        }
        using (MemoryStream stream = new MemoryStream())
        {
            using (CryptoStream cryptoStream = new CryptoStream(stream, transform, CryptoStreamMode.Write))
            {
                byte[] input = Encoding.Default.GetBytes(text);
                cryptoStream.Write(input, 0, input.Length);
                cryptoStream.FlushFinalBlock();

                return Encoding.Default.GetString(stream.ToArray());
            }
        }
    }
}

You can watch my video and download the code for this at : http://www.wrightin.gs/2008/11/how-to-encryptdecrypt-sensitive-column-contents-in-nhibernateactive-record-video.html

How to get back Lost phpMyAdmin Password, XAMPP

There is a batch file called resetroot.bat located in the xammp folders 'C:\xampp\mysql' run this and it will delete the phpmyadmin passwords. Then all you need to do is start the MySQL service in xamp and click the admin button.

How to count check-boxes using jQuery?

The following code worked for me.

$('input[name="chkGender[]"]:checked').length;

100% Min Height CSS layout

First you should create a div with id='footer' after your content div and then simply do this.

Your HTML should look like this:

<html>
    <body>
        <div id="content">
            ...
        </div>
        <div id="footer"></div>
    </body>
</html>

And the CSS:

?html, body {
    height: 100%;   
}
#content {
    height: 100%;
}
#footer {
    clear: both;        
}

SQL Server 2008- Get table constraints

You Can Get With This Query

Unique Constraint,

Default Constraint With Value,

Foreign Key With referenced Table And Column

And Primary Key Constraint.

Select C.*, (Select definition From sys.default_constraints Where object_id = C.object_id) As dk_definition,
(Select definition From sys.check_constraints Where object_id = C.object_id) As ck_definition,
(Select name From sys.objects Where object_id = D.referenced_object_id) As fk_table,
(Select name From sys.columns Where column_id = D.parent_column_id And object_id = D.parent_object_id) As fk_col
From sys.objects As C
Left Join (Select * From sys.foreign_key_columns) As D On D.constraint_object_id = C.object_id 
Where C.parent_object_id = (Select object_id From sys.objects Where type = 'U'
And name = 'Table Name Here');

How to get named excel sheets while exporting from SSRS

To add tab names while exporting to excel, I used the following method:

  • On the report design window, select the tablix object.
  • Open properties window of the tablix object.
  • Add the required tab name to the PageName property.
  • Run the report
  • Export the report to Excel.
  • Now the worksheet name is the same as the PageName property of the tablix object.

Django - Did you forget to register or load this tag?

In gameprofile.html please change the tag {% endblock content %} to {% endblock %} then it works otherwise django will not load the endblock and give error.

How to fix Python indentation

On most UNIX-like systems, you can also run:

expand -t4 oldfilename.py > newfilename.py

from the command line, changing the number if you want to replace tabs with a number of spaces other than 4. You can easily write a shell script to do this with a bunch of files at once, retaining the original file names.

How to send image to PHP file using Ajax?

Jquery code which contains simple ajax :

   $("#product").on("input", function(event) {
      var data=$("#nameform").serialize();
    $.post("./__partails/search-productbyCat.php",data,function(e){
       $(".result").empty().append(e);

     });


    });

Html elements you can use any element:

     <form id="nameform">
     <input type="text" name="product" id="product">
     </form>

php Code:

  $pdo=new PDO("mysql:host=localhost;dbname=onlineshooping","root","");
  $Catagoryf=$_POST['product'];

 $pricef=$_POST['price'];
  $colorf=$_POST['color'];

  $stmtcat=$pdo->prepare('SELECT * from products where Catagory =?');
  $stmtcat->execute(array($Catagoryf));

  while($result=$stmtcat->fetch(PDO::FETCH_ASSOC)){
  $iddb=$result['ID'];
     $namedb=$result['Name'];
    $pricedb=$result['Price'];
     $colordb=$result['Color'];

   echo "<tr>";
   echo "<td><a href=./pages/productsinfo.php?id=".$iddb."> $namedb</a> </td>".'<br>'; 
   echo "<td><pre>$pricedb</pre></td>";
   echo "<td><pre>    $colordb</pre>";
   echo "</tr>";

The easy way

if...else within JSP or JSTL

<c:choose>
<c:when test="${not empty userid and userid ne null}">
      <sql:query dataSource="${dbsource}" var="usersql">
                SELECT * FROM newuser WHERE ID = ?;
                <sql:param value="${param.userid}" />
      </sql:query>
 </c:when>
 <c:otherwise >
       <sql:query dataSource="${dbsource}" var="usersql">
                 SELECT * FROM newuser WHERE username = ?;
                 <sql:param value="${param.username}" />
       </sql:query>                              
  </c:otherwise>

html5 <input type="file" accept="image/*" capture="camera"> display as image rather than "choose file" button

I know this is an old question but I came across it while trying to solve this same issue. I thought it'd be worth sharing this solution I hadn't found anywhere else.

Basically the solution is to use CSS to hide the <input> element and style a <label> around it to look like a button. Click the 'Run code snippet' button to see the results.

I had used a JavaScript solution before that worked fine too but it is nice to solve a 'presentation' issue with just CSS.

_x000D_
_x000D_
label.cameraButton {_x000D_
  display: inline-block;_x000D_
  margin: 1em 0;_x000D_
_x000D_
  /* Styles to make it look like a button */_x000D_
  padding: 0.5em;_x000D_
  border: 2px solid #666;_x000D_
  border-color: #EEE #CCC #CCC #EEE;_x000D_
  background-color: #DDD;_x000D_
}_x000D_
_x000D_
/* Look like a clicked/depressed button */_x000D_
label.cameraButton:active {_x000D_
  border-color: #CCC #EEE #EEE #CCC;_x000D_
}_x000D_
_x000D_
/* This is the part that actually hides the 'Choose file' text box for camera inputs */_x000D_
label.cameraButton input[accept*="camera"] {_x000D_
  display: none;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <title>Nice image capture button</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <label class="cameraButton">Take a picture_x000D_
    <input type="file" accept="image/*;capture=camera">_x000D_
  </label>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Select default option value from typescript angular 6

You may use bellow like in angular 9

 <select [(ngModel)]="itemId"  formControlName="itemId" class="form-control" >
          <option [ngValue]="" disabled>Choose Gender</option>             
          <option *ngFor="let item of items"  [ngValue]="item .id" [selected]="item .id == this.id"  >
             {{item.name}}
          </option>
   </select>

Install Visual Studio 2013 on Windows 7

The minimum requirements are based on the Express edition you're attempting to install:

Express for Web (Web sites and HTML5 applications) - Windows 7 SP1 (With IE 10)
Express for Windows (Windows 8 Apps) - Windows 8.1
Express for Windows Desktop (Windows Programs) - Windows 7 SP1 (With IE 10)
Express for Windows Phone (Windows Phone Apps) - Windows 8

It sounds like you're trying to install the "Express 2013 for Windows" edition, which is for developing Windows 8 "Modern UI" apps, or the Windows Phone edition.

The similarly named version that is compatible with Windows 7 SP1 is "Express 2013 for Windows Desktop"

Source

How to install MySQLdb package? (ImportError: No module named setuptools)

#!/usr/bin/env python

import os
import sys
from **distutils.core** import setup, Extension

if sys.version_info < (2, 3):
    raise Error("Python-2.3 or newer is required")

if os.name == "posix":
    from setup_posix import get_config
else: # assume windows
    from setup_windows import get_config

metadata, options = get_config()
metadata['ext_modules'] = [Extension(sources=['_mysql.c'], **options)]
metadata['long_description'] = metadata['long_description'].replace(r'\n', '')
setup(**metadata)

Data truncation: Data too long for column 'logo' at row 1

Following solution worked for me. When connecting to the db, specify that data should be truncated if they are too long (jdbcCompliantTruncation). My link looks like this:

jdbc:mysql://SERVER:PORT_NO/SCHEMA?sessionVariables=sql_mode='NO_ENGINE_SUBSTITUTION'&jdbcCompliantTruncation=false

If you increase the size of the strings, you may face the same problem in future if the string you are attempting to store into the DB is longer than the new size.

EDIT: STRICT_TRANS_TABLES has to be removed from sql_mode as well.

How to symbolicate crash log Xcode?

For me the .crash file was enough. Without .dSYM file and .app file.

I ran these two commands on the mac where I build the archive and it worked:

export DEVELOPER_DIR="/Applications/Xcode.app/Contents/Developer" 

/Applications/Xcode.app/Contents/SharedFrameworks/DVTFoundation.framework/Versions/A/Resources/symbolicatecrash  /yourPath/crash1.crash > /yourPath/crash1_symbolicated.crash

App.Config Transformation for projects which are not Web Projects in Visual Studio?

Another solution I've found is NOT to use the transformations but just have a separate config file, e.g. app.Release.config. Then add this line to your csproj file.

  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
    <AppConfig>App.Release.config</AppConfig>
  </PropertyGroup>

This will not only generate the right myprogram.exe.config file but if you're using Setup and Deployment Project in Visual Studio to generate MSI, it'll force the deployment project to use the correct config file when packaging.

Converting date between DD/MM/YYYY and YYYY-MM-DD?

I am new to programming. I wanted to convert from yyyy-mm-dd to dd/mm/yyyy to print out a date in the format that people in my part of the world use and recognise.

The accepted answer above got me on the right track.

The answer I ended up with to my problem is:

import datetime

today_date = datetime.date.today()
print(today_date)

new_today_date = today_date.strftime("%d/%m/%Y")
print (new_today_date)

The first two lines after the import statement gives today's date in the USA format (2017-01-26). The last two lines convert this to the format recognised in the UK and other countries (26/01/2017).

You can shorten this code, but I left it as is because it is helpful to me as a beginner. I hope this helps other beginner programmers starting out!

How to get POST data in WebAPI?

After spending a good bit of time today trying to wrap my brain around the (significant but powerful) paradigm shift between old ways of processing web form data and how it is done with WebAPI, I thought I'd add my 2 cents to this discussion.

What I wanted to do (which is pretty common for web form processing of a POST) is to be able to grab any of the form values I want, in any order. Say like you can do if you have your data in a System.Collections.Specialized.NameValueCollection. But turns out, in WebAPI, the data from a POST comes back at you as a stream. So you can't directly do that.

But there is a cool little class named FormDataCollection (in System.Net.Http.Formatting) and what it will let you do is iterate through your collection once.

So I wrote a simple utility method that will run through the FormDataCollection once and stick all the values into a NameValueCollection. Once this is done, you can jump all around the data to your hearts content.

So in my ApiController derived class, I have a post method like this:

    public void Post(FormDataCollection formData)
    {
        NameValueCollection valueMap = WebAPIUtils.Convert(formData);

        ... my code that uses the data in the NameValueCollection
    }

The Convert method in my static WebAPIUtils class looks like this:

    /// <summary>
    /// Copy the values contained in the given FormDataCollection into 
    /// a NameValueCollection instance.
    /// </summary>
    /// <param name="formDataCollection">The FormDataCollection instance. (required, but can be empty)</param>
    /// <returns>The NameValueCollection. Never returned null, but may be empty.</returns>
    public static NameValueCollection Convert(FormDataCollection formDataCollection)
    {
        Validate.IsNotNull("formDataCollection", formDataCollection);

        IEnumerator<KeyValuePair<string, string>> pairs = formDataCollection.GetEnumerator();

        NameValueCollection collection = new NameValueCollection();

        while (pairs.MoveNext())
        {
            KeyValuePair<string, string> pair = pairs.Current;

            collection.Add(pair.Key, pair.Value);
        }

        return collection;
     }

Hope this helps!

matplotlib: how to change data points color based on some variable

If you want to plot lines instead of points, see this example, modified here to plot good/bad points representing a function as a black/red as appropriate:

def plot(xx, yy, good):
    """Plot data

    Good parts are plotted as black, bad parts as red.

    Parameters
    ----------
    xx, yy : 1D arrays
        Data to plot.
    good : `numpy.ndarray`, boolean
        Boolean array indicating if point is good.
    """
    import numpy as np
    import matplotlib.pyplot as plt
    fig, ax = plt.subplots()
    from matplotlib.colors import from_levels_and_colors
    from matplotlib.collections import LineCollection
    cmap, norm = from_levels_and_colors([0.0, 0.5, 1.5], ['red', 'black'])
    points = np.array([xx, yy]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    lines = LineCollection(segments, cmap=cmap, norm=norm)
    lines.set_array(good.astype(int))
    ax.add_collection(lines)
    plt.show()

VBA copy cells value and format

Following on from jpw it might be good to encapsulate his solution in a small subroutine to save on having lots of lines of code:

Private Sub CommandButton1_Click()
Dim i As Integer
Dim a As Integer
a = 15
For i = 11 To 32
  If Worksheets(1).Cells(i, 3) <> "" Then
    call copValuesAndFormat(i,3,a,15)        
    call copValuesAndFormat(i,5,a,17) 
    call copValuesAndFormat(i,6,a,18) 
    call copValuesAndFormat(i,7,a,19) 
    call copValuesAndFormat(i,8,a,20) 
    call copValuesAndFormat(i,9,a,21) 
    a = a + 1
  End If
Next i
end sub

sub copValuesAndFormat(x1 as integer, y1 as integer, x2 as integer, y2 as integer)
  Worksheets(1).Cells(x1, y1).Copy
  Worksheets(2).Cells(x2, y2).PasteSpecial Paste:=xlPasteFormats
  Worksheets(2).Cells(x2, y2).PasteSpecial Paste:=xlPasteValues
end sub

(I do not have Excel in current location so please excuse bugs as not tested)

How to hide/show more text within a certain length (like youtube)

Show More, Show Less (Only when needed) No JQuery

I needed this functionality for an RSS feed on our company's website. This is what I came up with:

_x000D_
_x000D_
// Create Variables_x000D_
var allOSB = [];_x000D_
var mxh = '';_x000D_
_x000D_
window.onload = function() {_x000D_
  // Set Variables_x000D_
  allOSB = document.getElementsByClassName("only-so-big");_x000D_
  _x000D_
  if (allOSB.length > 0) {_x000D_
    mxh = window.getComputedStyle(allOSB[0]).getPropertyValue('max-height');_x000D_
    mxh = parseInt(mxh.replace('px', ''));_x000D_
    _x000D_
    // Add read-more button to each OSB section_x000D_
    for (var i = 0; i < allOSB.length; i++) {_x000D_
      var el = document.createElement("button");_x000D_
      el.innerHTML = "Read More";_x000D_
      el.setAttribute("type", "button");_x000D_
      el.setAttribute("class", "read-more hid");_x000D_
      _x000D_
      insertAfter(allOSB[i], el);_x000D_
    }_x000D_
  }_x000D_
_x000D_
  // Add click function to buttons_x000D_
  var readMoreButtons = document.getElementsByClassName("read-more");_x000D_
  for (var i = 0; i < readMoreButtons.length; i++) {_x000D_
    readMoreButtons[i].addEventListener("click", function() { _x000D_
      revealThis(this);_x000D_
    }, false);_x000D_
  }_x000D_
  _x000D_
  // Update buttons so only the needed ones show_x000D_
  updateReadMore();_x000D_
}_x000D_
// Update on resize_x000D_
window.onresize = function() {_x000D_
  updateReadMore();_x000D_
}_x000D_
_x000D_
// show only the necessary read-more buttons_x000D_
function updateReadMore() {_x000D_
  if (allOSB.length > 0) {_x000D_
    for (var i = 0; i < allOSB.length; i++) {_x000D_
      if (allOSB[i].scrollHeight > mxh) {_x000D_
        if (allOSB[i].hasAttribute("style")) {_x000D_
          updateHeight(allOSB[i]);_x000D_
        }_x000D_
        allOSB[i].nextElementSibling.className = "read-more";_x000D_
      } else {_x000D_
        allOSB[i].nextElementSibling.className = "read-more hid";_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
}_x000D_
_x000D_
function revealThis(current) {_x000D_
  var el = current.previousElementSibling;_x000D_
  if (el.hasAttribute("style")) {_x000D_
    current.innerHTML = "Read More";_x000D_
    el.removeAttribute("style");_x000D_
  } else {_x000D_
    updateHeight(el);_x000D_
    current.innerHTML = "Show Less";_x000D_
  }_x000D_
}_x000D_
_x000D_
function updateHeight(el) {_x000D_
  el.style.maxHeight = el.scrollHeight + "px";_x000D_
}_x000D_
_x000D_
// thanks to karim79 for this function_x000D_
// http://stackoverflow.com/a/4793630/5667951_x000D_
function insertAfter(referenceNode, newNode) {_x000D_
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);_x000D_
}
_x000D_
@import url('https://fonts.googleapis.com/css?family=Open+Sans:600');_x000D_
_x000D_
*,_x000D_
*:before,_x000D_
*:after {_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
html,_x000D_
body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  width: 100%;_x000D_
}_x000D_
body {_x000D_
  font-family: 'Open Sans', sans-serif;_x000D_
}_x000D_
h1 {_x000D_
  text-align: center;_x000D_
}_x000D_
.main-container {_x000D_
  margin: 30px auto;_x000D_
  max-width: 1000px;_x000D_
  padding: 20px;_x000D_
}_x000D_
.only-so-big p {_x000D_
  padding: 0;_x000D_
  margin: 0;_x000D_
}_x000D_
p {_x000D_
  font-size: 15px;_x000D_
  line-height: 20px;_x000D_
}_x000D_
hr {_x000D_
  background: #ccc;_x000D_
  display: block;_x000D_
  height: 1px;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
_x000D_
/*_x000D_
  NECESSARY SECTION_x000D_
*/_x000D_
.only-so-big {_x000D_
  background: rgba(178, 252, 255, .3);_x000D_
  height: 100%;_x000D_
  max-height: 100px;_x000D_
  overflow: hidden;_x000D_
  -webkit-transition: max-height .75s;_x000D_
  transition: max-height .75s;_x000D_
}_x000D_
_x000D_
.read-more {_x000D_
  background: none;_x000D_
  border: none;_x000D_
  color: #1199f9;_x000D_
  cursor: pointer;_x000D_
  font-size: 1em;_x000D_
  outline: none; _x000D_
}_x000D_
.read-more:hover {_x000D_
  text-decoration: underline;_x000D_
}_x000D_
.read-more:focus {_x000D_
  outline: none;_x000D_
}_x000D_
.read-more::-moz-focus-inner {_x000D_
  border: 0;_x000D_
}_x000D_
.hid {_x000D_
  display: none;_x000D_
}
_x000D_
<div class="main-container">_x000D_
      <h1>Controlling Different Content Size</h1>_x000D_
      <p>We're working with an RSS feed and have had issues with some being much larger than others (content wise). I only want to show the "Read More" button if it's needed.</p>_x000D_
      <div class="only-so-big">_x000D_
        <p>This is just a short guy. No need for the read more button.</p>_x000D_
      </div>_x000D_
      <hr>_x000D_
      <div class="only-so-big">_x000D_
        <p>This one has way too much content to show. Best be saving it for those who want to read everything in here.</p>_x000D_
        <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia_x000D_
          voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi THE END!</p>_x000D_
      </div>_x000D_
      <hr>_x000D_
      <div class="only-so-big">_x000D_
        <p>Another small section with not a lot of content</p>_x000D_
      </div>_x000D_
      <hr>_x000D_
      <div class="only-so-big">_x000D_
        <p>Make Window smaller to show "Read More" button.<br> totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed?</p>_x000D_
      </div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

Move SQL data from one table to another

All these answers run the same query for the INSERT and DELETE. As mentioned previously, this risks the DELETE picking up records inserted between statements and could be slow if the query is complex (although clever engines "should" make the second call fast).

The correct way (assuming the INSERT is into a fresh table) is to do the DELETE against table1 using the key field of table2.

The delete should be:

DELETE FROM tbl_OldTableName WHERE id in (SELECT id FROM tbl_NewTableName)

Excuse my syntax, I'm jumping between engines but you get the idea.

How to make join queries using Sequelize on Node.js

While the accepted answer isn't technically wrong, it doesn't answer the original question nor the follow up question in the comments, which was what I came here looking for. But I figured it out, so here goes.

If you want to find all Posts that have Users (and only the ones that have users) where the SQL would look like this:

SELECT * FROM posts INNER JOIN users ON posts.user_id = users.id

Which is semantically the same thing as the OP's original SQL:

SELECT * FROM posts, users WHERE posts.user_id = users.id

then this is what you want:

Posts.findAll({
  include: [{
    model: User,
    required: true
   }]
}).then(posts => {
  /* ... */
});

Setting required to true is the key to producing an inner join. If you want a left outer join (where you get all Posts, regardless of whether there's a user linked) then change required to false, or leave it off since that's the default:

Posts.findAll({
  include: [{
    model: User,
//  required: false
   }]
}).then(posts => {
  /* ... */
});

If you want to find all Posts belonging to users whose birth year is in 1984, you'd want:

Posts.findAll({
  include: [{
    model: User,
    where: {year_birth: 1984}
   }]
}).then(posts => {
  /* ... */
});

Note that required is true by default as soon as you add a where clause in.

If you want all Posts, regardless of whether there's a user attached but if there is a user then only the ones born in 1984, then add the required field back in:

Posts.findAll({
  include: [{
    model: User,
    where: {year_birth: 1984}
    required: false,
   }]
}).then(posts => {
  /* ... */
});

If you want all Posts where the name is "Sunshine" and only if it belongs to a user that was born in 1984, you'd do this:

Posts.findAll({
  where: {name: "Sunshine"},
  include: [{
    model: User,
    where: {year_birth: 1984}
   }]
}).then(posts => {
  /* ... */
});

If you want all Posts where the name is "Sunshine" and only if it belongs to a user that was born in the same year that matches the post_year attribute on the post, you'd do this:

Posts.findAll({
  where: {name: "Sunshine"},
  include: [{
    model: User,
    where: ["year_birth = post_year"]
   }]
}).then(posts => {
  /* ... */
});

I know, it doesn't make sense that somebody would make a post the year they were born, but it's just an example - go with it. :)

I figured this out (mostly) from this doc:

removing bold styling from part of a header

Better one: Instead of using extra span tags in html and increasing html code, you can do as below:

<div id="sc-nav-display">
    <table class="sc-nav-table">
      <tr>
        <th class="nav-invent-head">Inventory</th>
        <th class="nav-orders-head">Orders</th>
      </tr>
    </table>
  </div> 

Here, you can use CSS as below:

#sc-nav-display th{
    font-weight: normal;
}

You just need to use ID assigned to the respected div tag of table. I used "#sc-nav-display" with "th" in CSS, so that, every other table headings will remain BOLD until and unless you do the same to all others table head as I said.

Load Image from javascript

this worked for me though... i wanted to display the image after the pencil icon is being clicked... and i wanted it seamless.. and this was my approach..

pencil button to display image

i created an input[file] element and made it hidden,

<input type="file" id="upl" style="display:none"/>

this input-file's click event will be trigged by the getImage function.

<a href="javascript:;" onclick="getImage()"/>
    <img src="/assets/pen.png"/>
</a>

<script>
     function getImage(){
       $('#upl').click();
     }
</script>

this is done while listening to the change event of the input-file element with ID of #upl.

_x000D_
_x000D_
   $(document).ready(function(){_x000D_
     _x000D_
       $('#upl').bind('change', function(evt){_x000D_
         _x000D_
    var preview = $('#logodiv').find('img');_x000D_
    var file    = evt.target.files[0];_x000D_
    var reader  = new FileReader();_x000D_
  _x000D_
    reader.onloadend = function () {_x000D_
   $('#logodiv > img')_x000D_
    .prop('src',reader.result)  //set the scr prop._x000D_
    .prop('width', 216);  //set the width of the image_x000D_
    .prop('height',200);  //set the height of the image_x000D_
    }_x000D_
  _x000D_
    if (file) {_x000D_
   reader.readAsDataURL(file);_x000D_
    } else {_x000D_
   preview.src = "";_x000D_
    }_x000D_
  _x000D_
    });_x000D_
_x000D_
   })
_x000D_
_x000D_
_x000D_

and BOOM!!! - it WORKS....

Getting a HeadlessException: No X11 DISPLAY variable was set

I assume you're trying to tunnel into some unix box.

Make sure X11 forwarding is enabled in your PuTTY settings.

enter image description here

Disable firefox same origin policy

As of September 2016 this addon is the best to disable CORS: https://github.com/fredericlb/Force-CORS/releases

In the options panel you can configure which header to inject and specific website to have it enabled automatically.

enter image description here

MVC controller : get JSON object from HTTP body?

Once you define a class (MyDTOClass) indicating what you expect to receive it should be as simple as...

public ActionResult Post([FromBody]MyDTOClass inputData){
 ... do something with input data ...
}

Thx to Julias:

Parsing Json .Net Web Api

Make sure your request is sent with the http header:

Content-Type: application/json

How do you parse and process HTML/XML in PHP?

I recommend PHP Simple HTML DOM Parser.

It really has nice features, like:

foreach($html->find('img') as $element)
       echo $element->src . '<br>';

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

If you don't use the NDK, unset the environment variable ANDROID_NDK_HOME.

graphing an equation with matplotlib

This is because in line

graph(x**3+2*x-4, range(-10, 11))

x is not defined.

The easiest way is to pass the function you want to plot as a string and use eval to evaluate it as an expression.

So your code with minimal modifications will be

import numpy as np  
import matplotlib.pyplot as plt  
def graph(formula, x_range):  
    x = np.array(x_range)  
    y = eval(formula)
    plt.plot(x, y)  
    plt.show()

and you can call it as

graph('x**3+2*x-4', range(-10, 11))

Installing mysql-python on Centos

Step 1 - Install package

# yum install MySQL-python
Loaded plugins: auto-update-debuginfo, langpacks, presto, refresh-packagekit
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package MySQL-python.i686 0:1.2.3-3.fc15 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================
 Package              Arch         Version                 Repository      Size
================================================================================
Installing:
 MySQL-python         i686         1.2.3-3.fc15            fedora          78 k

Transaction Summary
================================================================================
Install       1 Package(s)

Total download size: 78 k
Installed size: 220 k
Is this ok [y/N]: y
Downloading Packages:
Setting up and reading Presto delta metadata
Processing delta metadata
Package(s) data still to download: 78 k
MySQL-python-1.2.3-3.fc15.i686.rpm                       |  78 kB     00:00     
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
  Installing : MySQL-python-1.2.3-3.fc15.i686                               1/1 

Installed:
  MySQL-python.i686 0:1.2.3-3.fc15                                              

Complete!

Step 2 - Test working

import MySQLdb
db = MySQLdb.connect("localhost","myusername","mypassword","mydb" )
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()    
print "Database version : %s " % data    
db.close()

Ouput:

Database version : 5.5.20 

Spring RestTemplate - how to enable full debugging/logging of requests/responses?

Adding to above discussion this only represents Happy scenarios. probably you will not be able to log the response if an Error comes .

In this case plus all the cases above you must override DefaultResponseErrorHandler and set it like below

restTemplate.setErrorHandler(new DefaultResponseErrorHandlerImpl());

Using the Web.Config to set up my SQL database connection string?

Web.config file

<connectionStrings>
  <add name="MyConnectionString" connectionString="Data Source=SERGIO-DESKTOP\SQLEXPRESS;    Initial Catalog=YourDatabaseName;Integrated Security=True;"/>
</connectionStrings>

.cs file

System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

How to use "not" in xpath?

you can use not(expression) function

or

expression != true()

MongoDB distinct aggregation

Distinct and the aggregation framework are not inter-operable.

Instead you just want:

db.zips.aggregate([ 
    {$group:{_id:{city:'$city', state:'$state'}, numberOfzipcodes:{$sum:1}}}, 
    {$sort:{numberOfzipcodes:-1}},
    {$group:{_id:'$_id.state', city:{$first:'$_id.city'}, 
              numberOfzipcode:{$first:'$numberOfzipcodes'}}}
]);

iOS8 Beta Ad-Hoc App Download (itms-services)

I was struggling with this, my app was installing but not complete (almost 60% I can say) in iOS8, but in iOS7.1 it was working as expected. The error message popped was:

"Cannot install at this time". 

Finally Zillan's link helped me to get apple documentation. So, check:

  1. make sure the internet reachability in your device as you will be in local network/ intranet.
  2. Also make sure the address ax.init.itunes.apple.com is not getting blocked by your firewall/proxy (Just type this address in safari, a blank page must load).

As soon as I changed the proxy it installed completely. Hope it will help someone.

Passing arguments forward to another javascript function

If you want to only pass certain arguments, you can do so like this:

Foo.bar(TheClass, 'theMethod', 'arg1', 'arg2')

Foo.js

bar (obj, method, ...args) {
  obj[method](...args)
}

obj and method are used by the bar() method, while the rest of args are passed to the actual call.

make: Nothing to be done for `all'

I arrived at this peculiar, hard-to-debug error through a different route. My trouble ended up being that I was using a pattern rule in a build step when the target and the dependency were located in distinct directories. Something like this:

foo/apple.o: bar/apple.c $(FOODEPS)

%.o: %.c
    $(CC) $< -o $@

I had several dependencies set up this way, and was trying to use one pattern recipe for them all. Clearly, a single substitution for "%" isn't going to work here. I made explicit rules for each dependency, and I found myself back among the puppies and unicorns!

foo/apple.o: bar/apple.c $(FOODEPS)
    $(CC) $< -o $@

Hope this helps someone!

How to use querySelectorAll only for elements that have a specific attribute set?

Extra Tips:

Multiple "nots", input that is NOT hidden and NOT disabled:

:not([type="hidden"]):not([disabled])

Also did you know you can do this:

node.parentNode.querySelectorAll('div');

This is equivelent to jQuery's:

$(node).parent().find('div');

Which will effectively find all divs in "node" and below recursively, HOT DAMN!

How can I trigger a Bootstrap modal programmatically?

In order to manually show the modal pop up you have to do this

$('#myModal').modal('show');

You previously need to initialize it with show: false so it won't show until you manually do it.

$('#myModal').modal({ show: false})

Where myModal is the id of the modal container.

Understanding the results of Execute Explain Plan in Oracle SQL Developer

Here is a reference for using EXPLAIN PLAN with Oracle: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/ex_plan.htm), with specific information about the columns found here: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/ex_plan.htm#i18300

Your mention of 'FULL' indicates to me that the query is doing a full-table scan to find your data. This is okay, in certain situations, otherwise an indicator of poor indexing / query writing.

Generally, with explain plans, you want to ensure your query is utilizing keys, thus Oracle can find the data you're looking for with accessing the least number of rows possible. Ultimately, you can sometime only get so far with the architecture of your tables. If the costs remain too high, you may have to think about adjusting the layout of your schema to be more performance based.

How to disable phone number linking in Mobile Safari?

Break the number down into separate blocks of text

301 <div style="display:inline-block">441</div> 3909

android: data binding error: cannot find symbol class

I was calling my onClick wrong, which caused this error. So I changed

android:onClick="@{listener.onDogClicked()}"

to

android:onClick="@{listener::onDogClicked}"

How can I stop float left?

A standard approach is to add a clearing div between the two floating block level elements:

<div style="clear:both;"></div>

T-SQL How to select only Second row from a table?

Certainly TOP will surfice if you simply want the TOP 2, but if you need them individually so that you can do something with those values then use the ROW_NUMBER which will give you more control over the rows you want to select

ps. I did this as i'm not sure if the OP is after a simple TOP 2 in a select. (I may be wrong!)

-- Get first row, same as TOP 1
SELECT [Id] FROM 
(
    SELECT [Id], ROW_NUMBER() OVER (ORDER BY [Id]) AS Rownumber
    FROM table
) results
WHERE results.Rownumber = 1

-- Get second row only
SELECT [Id] FROM 
(
    SELECT [Id], ROW_NUMBER() OVER (ORDER BY [Id]) AS Rownumber
    FROM table
) results
WHERE results.Rownumber = 2

How to predict input image using trained model in Keras?

keras predict_classes (docs) outputs A numpy array of class predictions. Which in your model case, the index of neuron of highest activation from your last(softmax) layer. [[0]] means that your model predicted that your test data is class 0. (usually you will be passing multiple image, and the result will look like [[0], [1], [1], [0]] )

You must convert your actual label (e.g. 'cancer', 'not cancer') into binary encoding (0 for 'cancer', 1 for 'not cancer') for binary classification. Then you will interpret your sequence output of [[0]] as having class label 'cancer'

How to read a file and write into a text file?

    An example of reading a file:
Dim sFileText as String
Dim iFileNo as Integer
iFileNo = FreeFile
'open the file for reading
Open "C:\Test.txt" For Input As #iFileNo
'change this filename to an existing file! (or run the example below first)

'read the file until we reach the end
Do While Not EOF(iFileNo)
Input #iFileNo, sFileText
'show the text (you will probably want to replace this line as appropriate to your program!)
MsgBox sFileText
Loop

'close the file (if you dont do this, you wont be able to open it again!)
Close #iFileNo
(note: an alternative to Input # is Line Input # , which reads whole lines).


An example of writing a file:
Dim sFileText as String
Dim iFileNo as Integer
iFileNo = FreeFile
'open the file for writing
Open "C:\Test.txt" For Output As #iFileNo
'please note, if this file already exists it will be overwritten!

'write some example text to the file
Print #iFileNo, "first line of text"
Print #iFileNo, " second line of text"
Print #iFileNo, "" 'blank line
Print #iFileNo, "some more text!"

'close the file (if you dont do this, you wont be able to open it again!)
Close #iFileNo

From Here

How to 'insert if not exists' in MySQL?

Something worth noting is that INSERT IGNORE will still increment the primary key whether the statement was a success or not just like a normal INSERT would.

This will cause gaps in your primary keys that might make a programmer mentally unstable. Or if your application is poorly designed and depends on perfect incremental primary keys, it might become a headache.

Look into innodb_autoinc_lock_mode = 0 (server setting, and comes with a slight performance hit), or use a SELECT first to make sure your query will not fail (which also comes with a performance hit and extra code).

Using LINQ to concatenate strings

I blogged about this a while ago, what I did seams to be exactly what you're looking for:

http://ondevelopment.blogspot.com/2009/02/string-concatenation-made-easy.html

In the blog post describe how to implement extension methods that works on IEnumerable and are named Concatenate, this will let you write things like:

var sequence = new string[] { "foo", "bar" };
string result = sequence.Concatenate();

Or more elaborate things like:

var methodNames = typeof(IFoo).GetMethods().Select(x => x.Name);
string result = methodNames.Concatenate(", ");

How to copy files across computers using SSH and MAC OS X Terminal

You can do this with the scp command, which uses the ssh protocol to copy files across machines. It extends the syntax of cp to allow references to other systems:

scp username1@hostname1:/path/to/file username2@hostname2:/path/to/other/file

Copy something from this machine to some other machine:

scp /path/to/local/file username@hostname:/path/to/remote/file

Copy something from another machine to this machine:

scp username@hostname:/path/to/remote/file /path/to/local/file

Copy with a port number specified:

scp -P 1234 username@hostname:/path/to/remote/file /path/to/local/file

Can't bind to 'ngForOf' since it isn't a known property of 'tr' (final release)

I have encountered a similar error (*ngIf) even if all my imports were OK and the component was rendered without any other error + routing was OK.

In my case AppModule was not including that specific module. The strange thing is that it did not complain about this, but this might be related with how Ivy works with ng serve (kind of loads modules according to routing, but its dependencies are not considered).

How to set custom JsonSerializerSettings for Json.NET in ASP.NET Web API?

You can specify JsonSerializerSettings for each JsonConvert, and you can set a global default.

Single JsonConvert with an overload:

// Option #1.
JsonSerializerSettings config = new JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore };
this.json = JsonConvert.SerializeObject(YourObject, Formatting.Indented, config);

// Option #2 (inline).
JsonConvert.SerializeObject(YourObject, Formatting.Indented,
    new JsonSerializerSettings() {
        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
    }
);

Global Setting with code in Application_Start() in Global.asax.cs:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
     Formatting = Newtonsoft.Json.Formatting.Indented,
     ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
};

Reference: https://github.com/JamesNK/Newtonsoft.Json/issues/78

MS Excel showing the formula in a cell instead of the resulting value

Check for spaces in your formula before the "=". example' =A1' instean '=A1'

How to scroll UITableView to specific position

Simply single line of code:

self.tblViewMessages.scrollToRow(at: IndexPath.init(row: arrayChat.count-1, section: 0), at: .bottom, animated: isAnimeted)

Is optimisation level -O3 dangerous in g++?

Recently I experienced a problem using optimization with g++. The problem was related to a PCI card, where the registers (for command and data) were repreented by a memory address. My driver mapped the physical address to a pointer within the application and gave it to the called process, which worked with it like this:

unsigned int * pciMemory;
askDriverForMapping( & pciMemory );
...
pciMemory[ 0 ] = someCommandIdx;
pciMemory[ 0 ] = someCommandLength;
for ( int i = 0; i < sizeof( someCommand ); i++ )
    pciMemory[ 0 ] = someCommand[ i ];

The card didn't act as expected. When I saw the assembly I understood that the compiler only wrote someCommand[ the last ] into pciMemory, omitting all preceding writes.

In conclusion: be accurate and attentive with optimization.

How to read a value from the Windows registry

const CString REG_SW_GROUP_I_WANT = _T("SOFTWARE\\My Corporation\\My Package\\Group I want");
const CString REG_KEY_I_WANT= _T("Key Name");

CRegKey regKey;
DWORD   dwValue = 0;

if(ERROR_SUCCESS != regKey.Open(HKEY_LOCAL_MACHINE, REG_SW_GROUP_I_WANT))
{
  m_pobLogger->LogError(_T("CRegKey::Open failed in Method"));
  regKey.Close();
  goto Function_Exit;
}
if( ERROR_SUCCESS != regKey.QueryValue( dwValue, REG_KEY_I_WANT))
{
  m_pobLogger->LogError(_T("CRegKey::QueryValue Failed in Method"));
  regKey.Close();
  goto Function_Exit;
}

// dwValue has the stuff now - use for further processing

Android List View Drag and Drop sort

Am adding this answer for the purpose of those who google about this..

There was an episode of DevBytes (ListView Cell Dragging and Rearranging) recently which explains how to do this

You can find it here also the sample code is available here.

What this code basically does is that it creates a dynamic listview by the extension of listview that supports cell dragging and swapping. So that you can use the DynamicListView instead of your basic ListView and that's it you have implemented a ListView with Drag and Drop.

ITextSharp HTML to PDF?

2020 UPDATE:

Converting HTML to PDF is very simple to do now. All you have to do is use NuGet to install itext7 and itext7.pdfhtml. You can do this in Visual Studio by going to "Project" > "Manage NuGet Packages..."

Make sure to include this dependency:

using iText.Html2pdf;

Now literally just paste this one liner and you're done:

HtmlConverter.ConvertToPdf(new FileInfo(@"temp.html"), new FileInfo(@"report.pdf"));

If you're running this example in visual studio, your html file should be in the /bin/Debug directory.

If you're interested, here's a good resource. Also, note that itext7 is licensed under AGPL.

How do I comment out a block of tags in XML?

Syntax for XML : <!--Your comment-->

eg.

   <?xml version = "1.0" encoding = "UTF-8" ?>
   <!--here is your comment :) -->
   <class_list>   
   <student>
   <name></name>
   <grade>A</grade>
   </student>
   </class_list>

XML Comments Rules

Comments cannot appear before XML declaration.
Comments may appear anywhere in a document.
Comments must not appear within attribute values.
Comments cannot be nested inside the other comments.

How to install npm peer dependencies automatically?

The automatic install of peer dependencies was explicitly removed with npm 3, as it cause more problems than it tried to solve. You can read about it here for example:

So no, for the reasons given, you cannot install them automatically with npm 3 upwards.

NPM V7

NPM v7 has reintroduced the automatic peerDependencies installation. They had made some changes to fix old problems as version compatibility across multiple dependants. You can see the discussion here and the announcement here

Now in V7, as in versions before V3, you only need to do an npm i and all peerDependences should be automatically installed.

How can I resolve the error "The security token included in the request is invalid" when running aws iam upload-server-certificate?

If switching from using temporary IAM role credentials to using IAM user credentials, don't forget to ensure AWS_SESSION_TOKEN, which is only used for temporary credentials, no longer has a value:

unset AWS_SESSION_TOKEN # unset the environment variable

Marker in leaflet, click event

Here's a jsfiddle with a function call: https://jsfiddle.net/8282emwn/

var marker = new L.Marker([46.947, 7.4448]).on('click', markerOnClick).addTo(map);

function markerOnClick(e)
{
  alert("hi. you clicked the marker at " + e.latlng);
}

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its dependencies could not be resolved

I had the same problem but with an other cause. The solution was to deactivate Avira Browser Protection (in german Browser-Schutz). I took the solusion from m2e cannot transfer metadata from nexus, but maven command line can. It can be activated again ones maven has the needed plugin.

what does the __file__ variable mean/do?

When a module is loaded from a file in Python, __file__ is set to its path. You can then use that with other functions to find the directory that the file is located in.

Taking your examples one at a time:

A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.

B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where the program resides.

C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where the program resides.

You can see the various values returned from these here:

import os
print(__file__)
print(os.path.join(os.path.dirname(__file__), '..'))
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.dirname(__file__)))

and make sure you run it from different locations (such as ./text.py, ~/python/text.py and so forth) to see what difference that makes.


I just want to address some confusion first. __file__ is not a wildcard it is an attribute. Double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.

http://docs.python.org/reference/datamodel.html shows many of the special methods and attributes, if not all of them.

In this case __file__ is an attribute of a module (a module object). In Python a .py file is a module. So import amodule will have an attribute of __file__ which means different things under difference circumstances.

Taken from the docs:

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

In your case the module is accessing it's own __file__ attribute in the global namespace.

To see this in action try:

# file: test.py

print globals()
print __file__

And run:

python test.py

{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__':
 'test_print__file__.py', '__doc__': None, '__package__': None}
test_print__file__.py

PHP/MySQL insert row then get 'id'

As @NaturalBornCamper said, mysql_insert_id is now deprecated and should not be used. The options are now to use either PDO or mysqli. NaturalBornCamper explained PDO in his answer, so I'll show how to do it with MySQLi (MySQL Improved) using mysqli_insert_id.

// First, connect to your database with the usual info...
$db = new mysqli($hostname, $username, $password, $databaseName);
// Let's assume we have a table called 'people' which has a column
// called 'people_id' which is the PK and is auto-incremented...
$db->query("INSERT INTO people (people_name) VALUES ('Mr. X')");
// We've now entered in a new row, which has automatically been 
// given a new people_id. We can get it simply with:
$lastInsertedPeopleId = $db->insert_id;
// OR
$lastInsertedPeopleId = mysqli_insert_id($db);

Check out the PHP documentation for more examples: http://php.net/manual/en/mysqli.insert-id.php

Classes vs. Functions

i know it is a controversial topic, and likely i get burned now. but here are my thoughts.

For myself i figured that it is best to avoid classes as long as possible. If i need a complex datatype I use simple struct (C/C++), dict (python), JSON (js), or similar, i.e. no constructor, no class methods, no operator overloading, no inheritance, etc. When using class, you can get carried away by OOP itself (What Design pattern, what should be private, bla bla), and loose focus on the essential stuff you wanted to code in the first place.

If your project grows big and messy, then OOP starts to make sense because some sort of helicopter-view system architecture is needed. "function vs class" also depends on the task ahead of you.

function

  • purpose: process data, manipulate data, create result sets.
  • when to use: always code a function if you want to do this: “y=f(x)”

struct/dict/json/etc (instead of class)

  • purpose: store attr./param., maintain attr./param., reuse attr./param., use attr./param. later.
  • when to use: if you deal with a set of attributes/params (preferably not mutable)
  • different languages same thing: struct (C/C++), JSON (js), dict (python), etc.
  • always prefer simple struct/dict/json/etc over complicated classes (keep it simple!)

class (if it is a new data type)

  • a simple perspective: is a struct (C), dict (python), json (js), etc. with methods attached.
  • The method should only make sense in combination with the data/param stored in the class.
  • my advice: never code complex stuff inside class methods (call an external function instead)
  • warning: do not misuse classes as fake namespace for functions! (this happens very often!)
  • other use cases: if you want to do a lot of operator overloading then use classes (e.g. your own matrix/vector multiplication class)
  • ask yourself: is it really a new “data type”? (Yes => class | No => can you avoid using a class)

array/vector/list (to store a lot of data)

  • purpose: store a lot of homogeneous data of the same data type, e.g. time series
  • advice#1: just use what your programming language already have. do not reinvent it
  • advice#2: if you really want your “class mysupercooldatacontainer”, then overload an existing array/vector/list/etc class (e.g. “class mycontainer : public std::vector…”)

enum (enum class)

  • i just mention it
  • advice#1: use enum plus switch-case instead of overcomplicated OOP design patterns
  • advice#2: use finite state machines

Deleting all files from a folder using PHP?

If you want to delete everything from folder (including subfolders) use this combination of array_map, unlink and glob:

array_map( 'unlink', array_filter((array) glob("path/to/temp/*") ) );

This call can also handle empty directories ( thanks for the tip, @mojuba!)

Git - deleted some files locally, how do I get them from a remote repository

Since git is a distributed VCS, your local repository contains all of the information. No downloading is necessary; you just need to extract the content you want from the repo at your fingertips.

If you haven't committed the deletion, just check out the files from your current commit:

git checkout HEAD <path>

If you have committed the deletion, you need to check out the files from a commit that has them. Presumably it would be the previous commit:

git checkout HEAD^ <path>

but if it's n commits ago, use HEAD~n, or simply fire up gitk, find the SHA1 of the appropriate commit, and paste it in.

HTTP Error 500.22 - Internal Server Error (An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.)

This worked for me:

  1. Delete the originally created site.
  2. Recreate the site in IIS
  3. Clean solution
  4. Build solution

Seems like something went south when I originally created the site. I hate solutions that are similar to "Restart your machine, then reinstall windows" without knowing what caused the error. But, this worked for me. Quick and simple. Hope it helps someone else.

CSS Outside Border

Way late, but I just ran into a similar issue.
My solution was pseudo elements - no additional markup, and you get to draw the border without affecting the width.
Position the pseudo element absolutely (with the main positioned relatively) and whammo.

See below, JSFiddle here.

.hello {
    position: relative;
    /* Styling not important */
    background: black;
    color: white;
    padding: 20px;
    width: 200px;
    height: 200px;
}

.hello::before {
    content: "";
    position: absolute;
    display: block;
    top: 0;
    left: -5px;
    right: -5px;
    bottom: 0;
    border-left: 5px solid red;
    border-right: 5px solid red;
    z-index: -1;
}

Twitter Bootstrap 3 Sticky Footer

Here is my updated solution to this issue.

 /* Sticky footer styles
-------------------------------------------------- */
html {
  position: relative;
  min-height: 100%;
}


body {
  /* Margin bottom by footer height */
  margin-bottom: 60px;
}
.footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  /* Set the fixed height of the footer here */
  height: 60px;
  background-color: #f5f5f5;

  border-top: 1px solid #eee;
  text-align: center;
}

.site-footer-links {
  font-size: 12px;
  line-height: 1.5;
  color: #777;
  padding-top: 20px;
  display: block;
  text-align: center;
  float: center;
  margin: 0;
  list-style: none;
} 

And use it like this:

<div class="footer">
 <div class="site-footer">
  <ul class="site-footer-links">
        <li>© Zee and Company<span></span></li>
  </ul>
 </div>

</div>

Or

html, body {
  height: 100%;
}
.page-wrap {
  min-height: 100%;
  /* equal to footer height */
  margin-bottom: -142px; 
}
.page-wrap:after {
  content: "";
  display: block;
}
.site-footer, .page-wrap:after {
  height: 142px; 
}
.site-footer {
  background: orange;
}

Parsing PDF files (especially with tables) with PDFBox

For anyone wanting to do the same thing as OP (as I do), after days of research Amazon Textract is the best option (if your volume is low free tier might be enough).

Not unique table/alias

 select persons.personsid,name,info.id,address
    -> from persons
    -> inner join persons on info.infoid = info.info.id;

How to split a string in Java

From the documentation:

public String[] split(String regex,int limit) Splits this string around matches of the given regular expression. The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.

Basically you can do something like this:

String s = "123-456-789-123"; // The String to be split
String[] array = s.split("-"); // Split according to the hyphen and put them in an array
for(String subString : array){ // Cycle through the array
   System.out.println(subString);
}

Output:

123
456
789
123

How to support different screen size in android

Adding to @ud_an

It is not a good practice to create different folders for layouts. Create your layout such that it works fine with all the screen sizes. To achieve this, play with the layout attributes. You only need to have different images for hdpi, mdpi and ldpi types. The rest will be managed by android OS.

ReferenceError: describe is not defined NodeJs

OP asked about running from node not from mocha. This is a very common use case, see Using Mocha Programatically

This is what injected describe and it into my tests.

mocha.ui('bdd').run(function (failures) {
    process.on('exit', function () {
      process.exit(failures);
    });
  });

I tried tdd like in the docs, but that didn't work, bdd worked though.

Get my phone number in android

If the function you called returns null, it means your phone number is not registered in your contact list.

If instead of the phone number you just need an unique number, you may use the sim card's serial number:

    TelephonyManager telemamanger = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
    String getSimSerialNumber = telemamanger.getSimSerialNumber();  

SyntaxError: non-default argument follows default argument

Let me clarify two points here :

  • Firstly non-default argument should not follow the default argument, it means you can't define (a = 'b',c) in function. The correct order of defining parameter in function are :
  • positional parameter or non-default parameter i.e (a,b,c)
  • keyword parameter or default parameter i.e (a = 'b',r= 'j')
  • keyword-only parameter i.e (*args)
  • var-keyword parameter i.e (**kwargs)

def example(a, b, c=None, r="w" , d=[], *ae, **ab):

(a,b) are positional parameter

(c=none) is optional parameter

(r="w") is keyword parameter

(d=[]) is list parameter

(*ae) is keyword-only

(*ab) is var-keyword parameter

so first re-arrange your parameters

  • now the second thing is you have to define len1 when you are doing hgt=len1 the len1 argument is not defined when default values are saved, Python computes and saves default values when you define the function len1 is not defined, does not exist when this happens (it exists only when the function is executed)

so second remove this "len1 = hgt" it's not allowed in python.

keep in mind the difference between argument and parameters.

Conda uninstall one package and one package only

You can use conda remove --force.

The documentation says:

--force               Forces removal of a package without removing packages
                      that depend on it. Using this option will usually
                      leave your environment in a broken and inconsistent
                      state

browser.msie error after update to jQuery 1.9.1

You can use :

var MSIE = jQuery.support.leadingWhitespace; // This property is not supported by ie 6-8

$(document).ready(function(){

if (MSIE){
    if (navigator.vendor == 'Apple Computer, Inc.'){
        // some code for this navigator
    } else {
       // some code for others browsers
    }

} else {
    // default code

}});

Python; urllib error: AttributeError: 'bytes' object has no attribute 'read'

Use json.loads not json.load.

(load loads from a file-like object, loads from a string. So you could just as well omit the .read() call instead.)

How can I check for IsPostBack in JavaScript?

Lots of options here.

For a pure JS solution, have your page submit to itself, but with additional URL parameter (mypage.html?postback=true) - you can then get the page url with window.location.href, and parse that using a split or regex to look for your variable.

The much easier one, assuming you sending back to some sort of scripting language to proces the page (php/perl/asp/cf et. al), is to have them echo a line of javascript in the page setting a variable:

<html>

<?php
if ($_POST['myVar']) {
    //postback
    echo '<script>var postingBack = true;</script>';
    //Do other processing
} else {
    echo '<script>var postingBack = false;</script>'
 } ?>
<script>
function myLoader() {
     if (postingBack == false) {
          //Do stuff
     }
 }

<body onLoad="myLoader():"> ...

Sublime Text 2 multiple line edit

I was facing the same problem on Linux, what I did was to select all the content (ctrl-A) and then press ctrl+shift+L, It gives you a cursor on each line and then you can add similar content to each column.

Also you can perform other operations like cut, copy and paste column wise.

PS :- If you want to select a rectangular set of data from text, you can also press shift and hold Right Mouse button and then select data in a rectangular fashion. Then press CTRL+SHIFT+L to get the cursor on each line.

How do I combine 2 select statements into one?

I think that's what you're looking for:

SELECT CASE WHEN BoolField05 = 1 THEN Status ELSE 'DELETED' END AS MyStatus, t1.*
FROM WorkItems t1
WHERE (TextField01, TimeStamp) IN(
  SELECT TextField01, MAX(TimeStamp)
  FROM WorkItems t2
  GROUP BY t2.TextField01
  )
AND TimeStamp > '2009-02-12 18:00:00'

If you're in Oracle or in MS SQL 2005 and above, then you could do:

SELECT *
FROM (
  SELECT CASE WHEN BoolField05 = 1 THEN Status ELSE 'DELETED' END AS MyStatus, t1.*,
     ROW_NUMBER() OVER (PARTITION BY TextField01 ORDER BY TimeStamp DESC) AS rn
  FROM WorkItems t1
) to
WHERE rn = 1

, it's more efficient.

Using jQuery to center a DIV on the screen

i use this:

$(function() {
   $('#divId').css({
    'left' : '50%',
    'top' : '50%',
    'position' : 'absolute',
    'margin-left' : -$('#divId').outerWidth()/2,
    'margin-top' : -$('#divId').outerHeight()/2
  });
});

Python webbrowser.open() to open Chrome browser

If you have set the default browser in windows then you can do this:

open_google = webbrowser.get('windows-default').open('https://google.com')

// OR

open_google = webbrowser.open('https://google.com')

Calling C/C++ from Python?

For modern C++, use cppyy: http://cppyy.readthedocs.io/en/latest/

It's based on Cling, the C++ interpreter for Clang/LLVM. Bindings are at run-time and no additional intermediate language is necessary. Thanks to Clang, it supports C++17.

Install it using pip:

    $ pip install cppyy

For small projects, simply load the relevant library and the headers that you are interested in. E.g. take the code from the ctypes example is this thread, but split in header and code sections:

    $ cat foo.h
    class Foo {
    public:
        void bar();
    };

    $ cat foo.cpp
    #include "foo.h"
    #include <iostream>

    void Foo::bar() { std::cout << "Hello" << std::endl; }

Compile it:

    $ g++ -c -fPIC foo.cpp -o foo.o
    $ g++ -shared -Wl,-soname,libfoo.so -o libfoo.so  foo.o

and use it:

    $ python
    >>> import cppyy
    >>> cppyy.include("foo.h")
    >>> cppyy.load_library("foo")
    >>> from cppyy.gbl import Foo
    >>> f = Foo()
    >>> f.bar()
    Hello
    >>>

Large projects are supported with auto-loading of prepared reflection information and the cmake fragments to create them, so that users of installed packages can simply run:

    $ python
    >>> import cppyy
    >>> f = cppyy.gbl.Foo()
    >>> f.bar()
    Hello
    >>>

Thanks to LLVM, advanced features are possible, such as automatic template instantiation. To continue the example:

    >>> v = cppyy.gbl.std.vector[cppyy.gbl.Foo]()
    >>> v.push_back(f)
    >>> len(v)
    1
    >>> v[0].bar()
    Hello
    >>>

Note: I'm the author of cppyy.

Check if table exists in SQL Server

Please see the below approaches,

Approach 1: Using INFORMATION_SCHEMA.TABLES view

We can write a query like below to check if a Customers Table exists in the current database.

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'Customers')
BEGIN
    PRINT 'Table Exists'
END

Approach 2: Using OBJECT_ID() function

We can use OBJECT_ID() function like below to check if a Customers Table exists in the current database.

IF OBJECT_ID(N'dbo.Customers', N'U') IS NOT NULL
BEGIN
    PRINT 'Table Exists'
END

Approach 3: Using sys.Objects Catalog View

We can use the Sys.Objects catalog view to check the existence of the Table as shown below:

IF EXISTS(SELECT 1 FROM sys.Objects WHERE  Object_id = OBJECT_ID(N'dbo.Customers') AND Type = N'U')
BEGIN
   PRINT 'Table Exists'
END

Approach 4: Using sys.Tables Catalog View

We can use the Sys.Tables catalog view to check the existence of the Table as shown below:

 IF EXISTS(SELECT 1 FROM sys.Tables WHERE  Name = N'Customers' AND Type = N'U')
 BEGIN
      PRINT 'Table Exists'
 END

Approach 5: Avoid Using sys.sysobjects System table

We should avoid using sys.sysobjects System Table directly, direct access to it will be deprecated in some future versions of the Sql Server. As per Microsoft BOL link, Microsoft is suggesting to use the catalog views sys.objects/sys.tables instead of sys.sysobjects system table directly.

  IF EXISTS(SELECT name FROM sys.sysobjects WHERE Name = N'Customers' AND xtype = N'U')
  BEGIN
     PRINT 'Table Exists'
  END

referred from: http://sqlhints.com/2014/04/13/how-to-check-if-a-table-exists-in-sql-server/

'any' vs 'Object'

Adding to Alex's answer and simplifying it:

Objects are more strict with their use and hence gives the programmer more compile time "evaluation" power and hence in a lot of cases provide more "checking capability" and coould prevent any leaks, whereas any is a more generic term and a lot of compile time checks might hence be ignored.

Way to get all alphabetic chars in an array in PHP?

range for A-Z but if you want to go for example from A to DU then:

 function generateAlphabet($na) {
        $sa = "";
        while ($na >= 0) {
            $sa = chr($na % 26 + 65) . $sa;
            $na = floor($na / 26) - 1;
        }
        return $sa;
    }

    $alphabet = Array();
    for ($na = 0; $na < 125; $na++) {
        $alphabet[]=generateAlphabet($na);
    }

    print_r($alphabet);

your answer will look like:

Array ( [0] => A [1] => B [2] => C [3] => D [4] => E [5] => F [6] => G [7] => H [8] => I [9] => J [10] => K [11] => L [12] => M [13] => N [14] => O [15] => P [16] => Q [17] => R [18] => S [19] => T [20] => U [21] => V [22] => W [23] => X [24] => Y [25] => Z [26] => AA [27] => AB [28] => AC [29] => AD [30] => AE [31] => AF [32] => AG [33] => AH [34] => AI [35] => AJ [36] => AK [37] => AL [38] => AM [39] => AN [40] => AO [41] => AP [42] => AQ [43] => AR [44] => AS [45] => AT [46] => AU [47] => AV [48] => AW [49] => AX [50] => AY [51] => AZ [52] => BA [53] => BB [54] => BC [55] => BD [56] => BE [57] => BF [58] => BG [59] => BH [60] => BI [61] => BJ [62] => BK [63] => BL [64] => BM [65] => BN [66] => BO [67] => BP [68] => BQ [69] => BR [70] => BS [71] => BT [72] => BU [73] => BV [74] => BW [75] => BX [76] => BY [77] => BZ [78] => CA [79] => CB [80] => CC [81] => CD [82] => CE [83] => CF [84] => CG [85] => CH [86] => CI [87] => CJ [88] => CK [89] => CL [90] => CM [91] => CN [92] => CO [93] => CP [94] => CQ [95] => CR [96] => CS [97] => CT [98] => CU [99] => CV [100] => CW [101] => CX [102] => CY [103] => CZ [104] => DA [105] => DB [106] => DC [107] => DD [108] => DE [109] => DF [110] => DG [111] => DH [112] => DI [113] => DJ [114] => DK [115] => DL [116] => DM [117] => DN [118] => DO [119] => DP [120] => DQ [121] => DR [122] => DS [123] => DT [124] => DU ) 

How can we generate getters and setters in Visual Studio?

Enter image description here

On behalf of the Visual Studio tool, we can easily generate C# properties using an online tool called C# property generator.

Watch multiple $scope attributes

Beginning with AngularJS 1.1.4 you can use $watchCollection:

$scope.$watchCollection('[item1, item2]', function(newValues, oldValues){
    // do stuff here
    // newValues and oldValues contain the new and respectively old value
    // of the observed collection array
});

Plunker example here

Documentation here

How many bytes does one Unicode character take?

Well I just pulled up the Wikipedia page on it too, and in the intro portion I saw "Unicode can be implemented by different character encodings. The most commonly used encodings are UTF-8 (which uses one byte for any ASCII characters, which have the same code values in both UTF-8 and ASCII encoding, and up to four bytes for other characters), the now-obsolete UCS-2 (which uses two bytes for each character but cannot encode every character in the current Unicode standard)"

As this quote demonstrates, your problem is that you are assuming Unicode is a single way of encoding characters. There are actually multiple forms of Unicode, and, again in that quote, one of them even has 1 byte per character just like what you are used to.

So your simple answer that you want is that it varies.

PHP substring extraction. Get the string before the first '/' or the whole string

One-line version of the accepted answer:

$out=explode("/", $mystring, 2)[0];

Should work in php 5.4+

What is the difference between an annotated and unannotated tag?

The big difference is perfectly explained here.

Basically, lightweight tags are just pointers to specific commits. No further information is saved; on the other hand, annotated tags are regular objects, which have an author and a date and can be referred because they have their own SHA key.

If knowing who tagged what and when is relevant for you, then use annotated tags. If you just want to tag a specific point in your development, no matter who and when did that, then lightweight tags are good enough.

Normally you'd go for annotated tags, but it is really up to the Git master of the project.

What is the Python equivalent for a case/switch statement?

While the official docs are happy not to provide switch, I have seen a solution using dictionaries.

For example:

# define the function blocks
def zero():
    print "You typed zero.\n"

def sqr():
    print "n is a perfect square\n"

def even():
    print "n is an even number\n"

def prime():
    print "n is a prime number\n"

# map the inputs to the function blocks
options = {0 : zero,
           1 : sqr,
           4 : sqr,
           9 : sqr,
           2 : even,
           3 : prime,
           5 : prime,
           7 : prime,
}

Then the equivalent switch block is invoked:

options[num]()

This begins to fall apart if you heavily depend on fall through.

Deleting a SQL row ignoring all foreign keys and constraints

Temporarily disable constraints on a table T-SQL, SQL Server

MSSQL

  ALTER TABLE TableName NOCHECK CONSTRAINT ALL
  
  ALTER TABLE TableName CHECK CONSTRAINT ALL
  
  ALTER TABLE TableName NOCHECK CONSTRAINT FK_Table_RefTable
  
  ALTER TABLE TableName CHECK CONSTRAINT FK_Table_RefTable

ref

  DELETE FROM TableName
  
  DBCC CHECKIDENT ('TableName', RESEED, 0)

MySql

  SET FOREIGN_KEY_CHECKS = 0; -- Disable foreign key checking. 

  TRUNCATE TABLE [YOUR TABLE]; 

  SET FOREIGN_KEY_CHECKS = 1;

Deprecated: mysql_connect()

This warning is displayed because a new extension has appeared. It suppouse that you still can use the old one but in some cases it´s impossible.

I show you how I do the connection with database. You need just change the values of the variables.

My connection file: connection.php

<?php    
 $host='IP or Server Name (usually "localhost") ';
 $user='Database user';
 $password='Database password';
 $db='Database name';

 //PHP 5.4 o earlier (DEPRECATED)
 $con = mysql_connect($host,$user,$password) or exit("Connection Error");
 $connection = mysql_select_db($db, $con);

 //PHP 5.5 (New method)
 $connection =  mysqli_connect($host,$user,$password,$db);
?>

The extension changes too when performing a query.

Query File: "example.php"

<?php
 //First I call for the connection
 require("connection.php");

 // ... Here code if you need do something ...

 $query = "Here the query you are going to perform";

 //QUERY PHP 5.4 o earlier (DEPRECATED)
 $result = mysql_query ($query) or exit("The query could not be performed");

 //QUERY PHP 5.5 (NEW EXTENSION)
 $result = mysqli_query ($query) or exit("The query could not be performed");    
?>

This way is using MySQL Improved Extension, but you can use PDO (PHP Data Objects).

First method can be used only with MySQL databases, but PDO can manage different types of databases.

I'm going to put an example but it´s necessary to say that I only use the first one, so please correct me if there is any error.

My PDO connection file: "PDOconnection.php"

<?php
 $hostDb='mysql:host= "Here IP or Server Name";dbname="Database name" ';
 $user='Database user';
 $password='Database password';

 $connection = new PDO($hostDb, $user, $password);
?>

Query File (PDO): "example.php"

<?php
 $query = "Here the query you are going to perform";
 $result=$connection->$query;
?>

To finish just say that of course you can hide the warning but it´s not a good idea because can help you in future save time if an error happens (all of us knows the theory but if you work a lot of hours sometimes... brain is not there ^^ ).

How to request Administrator access inside a batch file

@echo off 
Net session >nul 2>&1 || (PowerShell start -verb runas '%~0' &exit /b)
Echo Administrative privileges have been got. & pause

The above works on my Windows 10 Version 1903

Jackson enum Serializing and DeSerializer

You should create a static factory method which takes single argument and annotate it with @JsonCreator (available since Jackson 1.2)

@JsonCreator
public static Event forValue(String value) { ... }

Read more about JsonCreator annotation here.

ASP.NET MVC: Html.EditorFor and multi-line text boxes

Use data type 'MultilineText':

[DataType(DataType.MultilineText)]
public string Text { get; set; }

See ASP.NET MVC3 - textarea with @Html.EditorFor

Bitwise operation and usage

One typical usage:

| is used to set a certain bit to 1

& is used to test or clear a certain bit

  • Set a bit (where n is the bit number, and 0 is the least significant bit):

    unsigned char a |= (1 << n);

  • Clear a bit:

    unsigned char b &= ~(1 << n);

  • Toggle a bit:

    unsigned char c ^= (1 << n);

  • Test a bit:

    unsigned char e = d & (1 << n);

Take the case of your list for example:

x | 2 is used to set bit 1 of x to 1

x & 1 is used to test if bit 0 of x is 1 or 0

Remove a parameter to the URL with JavaScript

Try this. Just pass in the param you want to remove from the URL and the original URL value, and the function will strip it out for you.

function removeParam(key, sourceURL) {
    var rtn = sourceURL.split("?")[0],
        param,
        params_arr = [],
        queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
    if (queryString !== "") {
        params_arr = queryString.split("&");
        for (var i = params_arr.length - 1; i >= 0; i -= 1) {
            param = params_arr[i].split("=")[0];
            if (param === key) {
                params_arr.splice(i, 1);
            }
        }
        if (params_arr.length) rtn = rtn + "?" + params_arr.join("&");
    }
    return rtn;
}

To use it, simply do something like this:

var originalURL = "http://yourewebsite.com?id=10&color_id=1";
var alteredURL = removeParam("color_id", originalURL);

The var alteredURL will be the output you desire.

Hope it helps!

How to access POST form fields

Express v4.17.0

app.use(express.urlencoded( {extended: true} ))

app.post('/userlogin', (req, res) => {    

   console.log(req.body) // object

   var email = req.body.email;

}

Demo Form

Another Answer Related

PHP - iterate on string characters

Expanded from @SeaBrightSystems answer, you could try this:

$s1 = "textasstringwoohoo";
$arr = str_split($s1); //$arr now has character array

Excel - Shading entire row based on change of value

I have found a simple solution to banding by content at Pearson Software Consulting: Let's say the header is from A1 to B1, table data is from A2 to B5, the controling cell is in the A column

  1. Make a new column, C
  2. At first the first row to color make the formula =true in the C2 cell
  3. In the second row make the formula =IF(A3=A2,C2,NOT(C2))
  4. Fill the column down to the last row
  5. Select the data range
  6. Select conditional formatting, choose Use a formula... and put =$C2 as the formula

Why am I getting 'Assembly '*.dll' must be strong signed in order to be marked as a prerequisite.'?

See this answer.

Go to the publish page and click on "Application Files". From there you should see a list of your DLL's. Ensure that the ones that are giving you trouble have their Publish Status marked as "Include" rather than "Prerequisite".