Programs & Examples On #Usernametoken

Example of SOAP request authenticated with WS-UsernameToken

Check this one (Password should be password):

<wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="SecurityToken-6138db82-5a4c-4bf7-915f-af7a10d9ae96">
  <wsse:Username>user</wsse:Username>
  <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">CBb7a2itQDgxVkqYnFtggUxtuqk=</wsse:Password>
  <wsse:Nonce>5ABcqPZWb6ImI2E6tob8MQ==</wsse:Nonce>
  <wsu:Created>2010-06-08T07:26:50Z</wsu:Created>
</wsse:UsernameToken>

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

In BIDS or SSDT-BI, do the following:

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

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

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

npm install doesn't create node_modules directory

my problem was to copy the whole source files contains .idea directory and my webstorm terminal commands were run on the original directory of the source
I delete the .idea directory and it worked fine

Unity 2d jumping script

Usually for jumping people use Rigidbody2D.AddForce with Forcemode.Impulse. It may seem like your object is pushed once in Y axis and it will fall down automatically due to gravity.

Example:

rigidbody2D.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);

Get driving directions using Google Maps API v2

I just release my latest library for Google Maps Direction API on Android https://github.com/akexorcist/Android-GoogleDirectionLibrary

How can I get screen resolution in java?

int screenResolution = Toolkit.getDefaultToolkit().getScreenResolution();
System.out.println(""+screenResolution);

Using Gradle to build a jar with dependencies

If you want the jar task to behave normally and also have an additional fatJar task, use the following:

task fatJar(type: Jar) {
    classifier = 'all'
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
    with jar
}

The important part is with jar. Without it, the classes of this project are not included.

Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project

Some great help found here. However, I still could not make it to work despite loading JAR properly. I found out later that I accidentally created module in the file structure instead of regular folder and this very module was pre-selected in the project setting.

Here is the footprint:

File -> Project Structure -> Modules -> (select proper module if you have more) -> Dependencies -> + -> JAR or Libraries

Determine the path of the executing BASH script

For the relative path (i.e. the direct equivalent of Windows' %~dp0):

MY_PATH="`dirname \"$0\"`"
echo "$MY_PATH"

For the absolute, normalized path:

MY_PATH="`dirname \"$0\"`"              # relative
MY_PATH="`( cd \"$MY_PATH\" && pwd )`"  # absolutized and normalized
if [ -z "$MY_PATH" ] ; then
  # error; for some reason, the path is not accessible
  # to the script (e.g. permissions re-evaled after suid)
  exit 1  # fail
fi
echo "$MY_PATH"

How to get document height and width without using jquery

var height = document.body.clientHeight;
var width = document.body.clientWidth;

Check: this article for better explanation.

System.Data.OracleClient requires Oracle client software version 8.1.7

Update 1: It is possible for different users to have different path. But its not the likely problem here. There is more chance that the user that the iwam user doesn't have permission to the oracle client directory.

Update 0: Its suppose to work. Check for environment variable ( That are needed to find the oracle client and tnsnames.ora ). Also, Maybe you have a 32/64 bit issues. Also, consider using the Oracle Data Provider for .NET ( search for odp.net)

How to solve COM Exception Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))?

My problem and the solution

I have a 32 bit third party dll which i have installed in 2008 R2 machine which is 64 bit.

I have a wcf service created in .net 4.5 framework which calls the 32 bit third party dll for process. Now i have build property set to target 'any' cpu and deployed it to the 64 bit machine.

when i tried to invoke the wcf service got error "80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG"

Now i used ProcMon.exe to trace the com registry issue and identified that the process is looking for the registry entry at HKLM\CLSID and HKCR\CLSID where there is no entry.

Came to know that Microsoft will not register the 32 bit com components to the paths HKLM\CLSID, HKCR\CLSID in 64 bit machine rather it places the entry in HKLM\Wow6432Node\CLSID and HKCR\Wow6432Node\CLSID paths.

Now the conflict is 64 bit process trying to invoke 32 bit process in 64 bit machine which will look for the registry entry in HKLM\CLSID, HKCR\CLSID. The solution is we have to force the 64 bit process to look at the registry entry at HKLM\Wow6432Node\CLSID and HKCR\Wow6432Node\CLSID.

This can be achieved by configuring the wcf service project properties to target to 'X86' machine instead of 'Any'.

After deploying the 'X86' version to the 2008 R2 server got the issue "System.BadImageFormatException: Could not load file or assembly"

Solution to this badimageformatexception is setting the 'Enable32bitApplications' to 'True' in IIS Apppool properties for the right apppool.

How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required?

As jcoder and Matt mentioned, PowerShell made it easy, and it could even be embedded in the batch script without creating a new script.

I modified Matt's script:

:: Check privileges 
net file 1>NUL 2>NUL
if not '%errorlevel%' == '0' (
    powershell Start-Process -FilePath "%0" -ArgumentList "%cd%" -verb runas >NUL 2>&1
    exit /b
)

:: Change directory with passed argument. Processes started with
:: "runas" start with forced C:\Windows\System32 workdir
cd /d %1

:: Actual work

Installing SetupTools on 64-bit Windows

Problem: you have 64-bit Python, and a 32-bit installer. This will cause problems for extension modules.

The reasons why the installer doesn't finds Python is the transparent 32-bit emulation from Windows 7. 64-bit and 32-bit programs will write to different parts of the Windows registry.

64-bit: HKLM|HKCU\SOFTWARE\

32-bit: HKLM|HKCU\SOFTWARE\wow6432node\.

This means that the 64-bit Python installer writes to HKLM\SOFTWARE\Python, but the 32-bit setuptools installer looks at HKLM\SOFTWARE\wow6432node\Python (this is handled by windows automatically, programs don't notice). This is expected behavior and not a bug.

Usually, you have these choices:

  • the "clean" way: use 32-bit Python if you have to use 32-bit modules or extensions
  • the other "clean" way: only use 64-bit installers when using 64-bit Python (see below)
  • what the answer above suggests: copy HKLM\SOFTWARE\Python to HKLM\SOFTWARE\wow6432node\Python, but this will cause problems with binary distributions, as 64-bit Python can't load 32-bit compiled modules (do NOT do this!)
  • install pure Python modules with setuptools instead of the distutils installer (easy_install or pip)

For setuptools itself, for example, you can't use a 32-bit installer for 64-bit Python as it includes binary files. But there's a 64-bit installer at http://www.lfd.uci.edu/~gohlke/pythonlibs/ (has many installers for other modules too). Nowadays, many packages on PyPi have binary distributions, so you can install them via pip.

How to initialise memory with new operator in C++?

std::fill is one way. Takes two iterators and a value to fill the region with. That, or the for loop, would (I suppose) be the more C++ way.

For setting an array of primitive integer types to 0 specifically, memset is fine, though it may raise eyebrows. Consider also calloc, though it's a bit inconvenient to use from C++ because of the cast.

For my part, I pretty much always use a loop.

(I don't like to second-guess people's intentions, but it is true that std::vector is, all things being equal, preferable to using new[].)

apache mod_rewrite is not working or not enabled

On centOS7 I changed the file /etc/httpd/conf/httpd.conf

from AllowOverride None to AllowOverride All

How to convert numbers to words without using num2word library?

I know that this is a very old post and I am probably very late to the party, but hopefully this will help someone else. This has worked for me.

phone_words = input('Phone: ')
numbered_words = {
    '0': 'zero',
    '1': 'one',
    '2': 'two',
    '3': 'three',
    '4': 'four',
    '5': 'five',
    '6': 'six',
    '7': 'seven',
    '8': 'eight',
    '9': 'nine'
}
output = ""
for ch in phone_words:
    output += numbered_words.get(ch, "!") + " "
phone_words = numbered_words

print(output)

Display names of all constraints for a table in Oracle SQL

Use either of the two commands below. Everything must be in uppercase. The table name must be wrapped in quotation marks:

--SEE THE CONSTRAINTS ON A TABLE
SELECT COLUMN_NAME, CONSTRAINT_NAME FROM USER_CONS_COLUMNS WHERE TABLE_NAME = 'TBL_CUSTOMER';

--OR FOR LESS DETAIL
SELECT CONSTRAINT_NAME FROM USER_CONSTRAINTS WHERE TABLE_NAME = 'TBL_CUSTOMER';

Decorators with parameters?

Here is a slightly modified version of t.dubrownik's answer. Why?

  1. As a general template, you should return the return value from the original function.
  2. This changes the name of the function, which could affect other decorators / code.

So use @functools.wraps():

from functools import wraps

def decorator(argument):
    def real_decorator(function):
        @wraps(function)
        def wrapper(*args, **kwargs):
            funny_stuff()
            something_with_argument(argument)
            retval = function(*args, **kwargs)
            more_funny_stuff()
            return retval
        return wrapper
    return real_decorator

Where value in column containing comma delimited values

The solution tbaxter120 suggested worked for me but I needed something that will be supported both in MySQL & Oracle & MSSQL, and here it is:

WHERE (CONCAT(',' ,CONCAT(RTRIM(MyColumn), ','))) LIKE CONCAT('%,' , CONCAT(@search , ',%'))

How to calculate cumulative normal distribution?

To build upon Unknown's example, the Python equivalent of the function normdist() implemented in a lot of libraries would be:

def normcdf(x, mu, sigma):
    t = x-mu;
    y = 0.5*erfcc(-t/(sigma*sqrt(2.0)));
    if y>1.0:
        y = 1.0;
    return y

def normpdf(x, mu, sigma):
    u = (x-mu)/abs(sigma)
    y = (1/(sqrt(2*pi)*abs(sigma)))*exp(-u*u/2)
    return y

def normdist(x, mu, sigma, f):
    if f:
        y = normcdf(x,mu,sigma)
    else:
        y = normpdf(x,mu,sigma)
    return y

Why can I not create a wheel in python?

I also ran into the error message invalid command 'bdist_wheel'

It turns out the package setup.py used distutils rather than setuptools. Changing it as follows enabled me to build the wheel.

#from distutils.core import setup
from setuptools import setup

Python: Continuing to next iteration in outer loop

for ii in range(200):
    for jj in range(200, 400):
        ...block0...
        if something:
            break
    else:
        ...block1...

Break will break the inner loop, and block1 won't be executed (it will run only if the inner loop is exited normally).

Duplicate symbols for architecture x86_64 under Xcode

I found the accepted answer touches on the problem but didn't help me solve it, hopefully this answer will help with this very frustrating issue.

duplicate symbol _OBJC_IVAR_$_BLoginViewController._hud in:

17 duplicate symbols for architecture x86_64

"Means that you have loaded same functions twice. As the issue disappear after removing -ObjC from Other Linker Flags, this means that this option result that functions loads twice:"

In layman's terms this means we have two files in our project with exactly the same name. Maybe you are combining one project into another one? Have a look at the errors above the "duplicate symbols" error to see which folder is duplicated, in my case it was BLoginViewController.

For example, in the image below you can see I have two BImageViewControllers, for me this is what was causing the issue.

As soon as I deleted one then the issue vanished :)

enter image description here

How can I solve the error 'TS2532: Object is possibly 'undefined'?

With the release of TypeScript 3.7, optional chaining (the ? operator) is now officially available.

As such, you can simplify your expression to the following:

const data = change?.after?.data();

You may read more about it from that version's release notes, which cover other interesting features released on that version.

Run the following to install the latest stable release of TypeScript.

npm install typescript

That being said, Optional Chaining can be used alongside Nullish Coalescing to provide a fallback value when dealing with null or undefined values

const data = change?.after?.data() ?? someOtherData();

How do I get interactive plots again in Spyder/IPython/matplotlib?

This is actually pretty easy to fix and doesn't take any coding:

1.Click on the Plots tab above the console. 2.Then at the top right corner of the plots screen click on the options button. 3.Lastly uncheck the "Mute inline plotting" button

Now re-run your script and your graphs should show up in the console.

Cheers.

PHP Get name of current directory

$myVar = str_replace('/', '', $_SERVER[REQUEST_URI]);

libs/images/index.php
Result: images

Indexing vectors and arrays with +:

Description and examples can be found in IEEE Std 1800-2017 § 11.5.1 "Vector bit-select and part-select addressing". First IEEE appearance is IEEE 1364-2001 (Verilog) § 4.2.1 "Vector bit-select and part-select addressing". Here is an direct example from the LRM:

logic [31: 0] a_vect;
logic [0 :31] b_vect;
logic [63: 0] dword;
integer sel;
a_vect[ 0 +: 8] // == a_vect[ 7 : 0]
a_vect[15 -: 8] // == a_vect[15 : 8]
b_vect[ 0 +: 8] // == b_vect[0 : 7]
b_vect[15 -: 8] // == b_vect[8 :15]
dword[8*sel +: 8] // variable part-select with fixed width

If sel is 0 then dword[8*(0) +: 8] == dword[7:0]
If sel is 7 then dword[8*(7) +: 8] == dword[63:56]

The value to the left always the starting index. The number to the right is the width and must be a positive constant. the + and - indicates to select the bits of a higher or lower index value then the starting index.

Assuming address is in little endian ([msb:lsb]) format, then if(address[2*pointer+:2]) is the equivalent of if({address[2*pointer+1],address[2*pointer]})

Remove a specific string from an array of string

You can't remove anything from an array - they're always fixed length. Once you've created an array of length 3, that array will always have length 3.

You'd be better off with a List<String>, e.g. an ArrayList<String>:

List<String> list = new ArrayList<String>();
list.add("google");
list.add("microsoft");
list.add("apple");
System.out.println(list.size()); // 3

list.remove("apple");
System.out.println(list.size()); // 2

Collections like this are generally much more flexible than working with arrays directly.

EDIT: For removal:

void removeRandomElement(List<?> list, Random random)
{
    int index = random.nextInt(list.size());
    list.remove(index);
}

How do I expand the output display to see more columns of a pandas DataFrame?

You can adjust pandas print options with set_printoptions.

In [3]: df.describe()
Out[3]: 
<class 'pandas.core.frame.DataFrame'>
Index: 8 entries, count to max
Data columns:
x1    8  non-null values
x2    8  non-null values
x3    8  non-null values
x4    8  non-null values
x5    8  non-null values
x6    8  non-null values
x7    8  non-null values
dtypes: float64(7)

In [4]: pd.set_printoptions(precision=2)

In [5]: df.describe()
Out[5]: 
            x1       x2       x3       x4       x5       x6       x7
count      8.0      8.0      8.0      8.0      8.0      8.0      8.0
mean   69024.5  69025.5  69026.5  69027.5  69028.5  69029.5  69030.5
std       17.1     17.1     17.1     17.1     17.1     17.1     17.1
min    69000.0  69001.0  69002.0  69003.0  69004.0  69005.0  69006.0
25%    69012.2  69013.2  69014.2  69015.2  69016.2  69017.2  69018.2
50%    69024.5  69025.5  69026.5  69027.5  69028.5  69029.5  69030.5
75%    69036.8  69037.8  69038.8  69039.8  69040.8  69041.8  69042.8
max    69049.0  69050.0  69051.0  69052.0  69053.0  69054.0  69055.0

However this will not work in all cases as pandas detects your console width and it will only use to_string if the output fits in the console (see the docstring of set_printoptions). In this case you can explicitly call to_string as answered by BrenBarn.

Update

With version 0.10 the way wide dataframes are printed changed:

In [3]: df.describe()
Out[3]: 
                 x1            x2            x3            x4            x5  \
count      8.000000      8.000000      8.000000      8.000000      8.000000   
mean   59832.361578  27356.711336  49317.281222  51214.837838  51254.839690   
std    22600.723536  26867.192716  28071.737509  21012.422793  33831.515761   
min    31906.695474   1648.359160     56.378115  16278.322271     43.745574   
25%    45264.625201  12799.540572  41429.628749  40374.273582  29789.643875   
50%    56340.214856  18666.456293  51995.661512  54894.562656  47667.684422   
75%    75587.003417  31375.610322  61069.190523  67811.893435  76014.884048   
max    98136.474782  84544.484627  91743.983895  75154.587156  99012.695717   

                 x6            x7  
count      8.000000      8.000000  
mean   41863.000717  33950.235126  
std    38709.468281  29075.745673  
min     3590.990740   1833.464154  
25%    15145.759625   6879.523949  
50%    22139.243042  33706.029946  
75%    72038.983496  51449.893980  
max    98601.190488  83309.051963  

Further more the API for setting pandas options changed:

In [4]: pd.set_option('display.precision', 2)

In [5]: df.describe()
Out[5]: 
            x1       x2       x3       x4       x5       x6       x7
count      8.0      8.0      8.0      8.0      8.0      8.0      8.0
mean   59832.4  27356.7  49317.3  51214.8  51254.8  41863.0  33950.2
std    22600.7  26867.2  28071.7  21012.4  33831.5  38709.5  29075.7
min    31906.7   1648.4     56.4  16278.3     43.7   3591.0   1833.5
25%    45264.6  12799.5  41429.6  40374.3  29789.6  15145.8   6879.5
50%    56340.2  18666.5  51995.7  54894.6  47667.7  22139.2  33706.0
75%    75587.0  31375.6  61069.2  67811.9  76014.9  72039.0  51449.9
max    98136.5  84544.5  91744.0  75154.6  99012.7  98601.2  83309.1

Onclick javascript to make browser go back to previous page?

history.back()

or

history.go(-1)

Put this to the button onclick handle. It should look like this:

<input name="action" onclick="history.back()" type="submit" value="Cancel"/>

Rendering a template variable as HTML

The simplest way is to use the safe filter:

{{ message|safe }}

Check out the Django documentation for the safe filter for more information.

Escaping ampersand character in SQL string

I wrote a regex to help find and replace "&" within an INSERT, I hope that this helps someone.

The trick was to make sure that the "&" was with other text.

Find “(\'[^\']*(?=\&))(\&)([^\']*\')”

Replace “$1' || chr(38) || '$3”

How to make the window full screen with Javascript (stretching all over the screen)

This may support

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default5.aspx.cs" Inherits="PRODUCTION_Default5" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Untitled Page</title>
        <script type="text/javascript">
            function max()
            {
               window.open("", "_self", "fullscreen=yes, scrollbars=auto"); 
            }
        </script>
    </head>
    <body onload="max()">
        <form id="form1" runat="server">
        <div>
        This is Test Page
        </div>
        </form>
    </body>
    </html>

Java ResultSet how to check if there are any results

Why not use rs.getRow()?

int getRow()
           throws SQLException
Retrieves the current row number. The first row is number 1, the second number 2, and so on.
Note:Support for the getRow method is optional for ResultSets with a result set type of TYPE_FORWARD_ONLY

Returns:
the current row number; 0 if there is no current row
Throws:
SQLException - if a database access error occurs or this method is called on a closed result set
SQLFeatureNotSupportedException - if the JDBC driver does not support this method
Since:
1.2

For me check "if (rs.getRow() != 0)" seems to work just fine.

What is the simplest method of inter-process communication between 2 C# processes?

The easiest solution in C# for inter-process communication when security is not a concern and given your constraints (two C# processes on the same machine) is the Remoting API. Now Remoting is a legacy technology (not the same as deprecated) and not encouraged for use in new projects, but it does work well and does not require a lot of pomp and circumstance to get working.

There is an excellent article on MSDN for using the class IpcChannel from the Remoting framework (credit to Greg Beech for the find here) for setting up a simple remoting server and client.

I Would suggest trying this approach first, and then try to port your code to WCF (Windows Communication Framework). Which has several advantages (better security, cross-platform), but is necessarily more complex. Luckily MSDN has a very good article for porting code from Remoting to WCF.

If you want to dive in right away with WCF there is a great tutorial here.

C# how to change data in DataTable?

Try the SetField method:

table.Rows[i].SetField(column, value);
table.Rows[i].SetField(columnIndex, value);
table.Rows[i].SetField(columnName, value);

This should get the job done and is a bit "cleaner" than using Rows[i][j].

C++ equivalent of Java's toString?

As an extension to what John said, if you want to extract the string representation and store it in a std::string do this:

#include <sstream>    
// ...
// Suppose a class A
A a;
std::stringstream sstream;
sstream << a;
std::string s = sstream.str(); // or you could use sstream >> s but that would skip out whitespace

std::stringstream is located in the <sstream> header.

Visual studio code terminal, how to run a command with administrator rights?

Here's what I get.

I'm using Visual Studio Code and its Terminal to execute the 'npm' commands.

Visual Studio Code (not as administrator)
PS g:\labs\myproject> npm install bootstrap@3

Results in scandir and/or permission errors.

Visual Studio Code (as Administrator)
Run this command after I've run something like 'ng serve'

PS g:\labs\myproject> npm install bootstrap@3

Results in scandir and/or permission errors.

Visual Studio Code (as Administrator - closing and opening the IDE)
If I have already executed other commands that would impact node modules I decided to try closing Visual Studio Code first, opening it up as Administrator then running the command:

PS g:\labs\myproject> npm install bootstrap@3

Result I get then is: + [email protected]
added 115 packages and updated 1 package in 24.685s

This is not a permanent solution since I don't want to continue closing down VS Code every time I want to execute an npm command, but it did resolve the issue to a point.

Inserting records into a MySQL table using Java

no that cannot work(not with real data):

String sql = "INSERT INTO course " +
        "VALUES (course_code, course_desc, course_chair)";
    stmt.executeUpdate(sql);

change it to:

String sql = "INSERT INTO course (course_code, course_desc, course_chair)" +
        "VALUES (?, ?, ?)";

Create a PreparedStatment with that sql and insert the values with index:

PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, "Test");
preparedStatement.setString(2, "Test2");
preparedStatement.setString(3, "Test3");
preparedStatement.executeUpdate(); 

How to resize Image in Android?

resized = Bitmap.createScaledBitmap(yourImageBitmap,(int)(yourImageBitmap.getWidth()*0.9), (int)(yourBitmap.getHeight()*0.9), true);

Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id}

Try this.

public class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        var json = config.Formatters.JsonFormatter;
        json.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"));
        config.Formatters.Remove(config.Formatters.XmlFormatter);

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional , Action =RouteParameter.Optional }

        );
    }
}

Selenium using Python - Geckodriver executable needs to be in PATH

On Windows 10 it works for me downloading the geckodriver.exe. I just had to update Firefox.

Below the code that I used:

from selenium import webdriver
driver = webdriver.Firefox(
    executable_path=r'C:\Users\Usuario\Desktop\Automate the boring stuff with python exercises\Web Scraping\geckodriver.exe')
driver.get('http://inventwithpython.com')

Python Pandas - Find difference between two data frames

A slight variation of the nice @liangli's solution that does not require to change the index of existing dataframes:

newdf = df1.drop(df1.join(df2.set_index('Name').index))

How to install pip for Python 3 on Mac OS X?

Install Python3 on mac

1. brew install python3
2. curl https://bootstrap.pypa.io/get-pip.py | python3
3. python3

Use pip3 to install modules

1. pip3 install ipython
2. python3 -m IPython

:)

How can I inspect element in an Android browser?

Had to debug a site for native Android browser and came here. So I tried weinre on an OS X 10.9 (as weinre server) with Firefox 30.0 (weinre client) and an Android 4.1.2 (target). I'm really, really surprised of the result.

  1. Download and install node runtime from http://nodejs.org/download/
  2. Install weinre: sudo npm -g install weinre
  3. Find out your current IP address at Settings > Network
  4. Setup a weinre server on your machine: weinre --boundHost YOUR.IP.ADDRESS.HERE
  5. In your browser call: http://YOUR.IP.ADRESS.HERE:8080
  6. You'll see a script snippet, place it into your site: <script src="http://YOUR.IP.ADDRESS.HERE:8080/target/target-script-min.js"></script>
  7. Open the debug client in your local browser: http://YOUR.IP.ADDRESS.HERE:8080/client
  8. Finally on your Android: call the site you want to inspect (the one with the script inside) and see how it appears as "Target" in your local browser. Now you can open "Elements" or whatever you want.

Maybe 8080 isn't your default port. Then in step 4 you have to call weinre --httpPort YOURPORT --boundHost YOUR.IP.ADRESS.HERE.

And I don't remember exactly when it was, maybe somewhere after step 5, I had to accept incoming connections prompt, of course.

Happy debugging

P.S. I'm still overwhelmed how good that works. Even elements-highlighting work

How to add a line to a multiline TextBox?

@Casperah pointed out that i'm thinking about it wrong:

  • A TextBox doesn't have lines
  • it has text
  • that text can be split on the CRLF into lines, if requested
  • but there is no notion of lines

The question then is how to accomplish what i want, rather than what WinForms lets me.

There are subtle bugs in the other given variants:

  • textBox1.AppendText("Hello" + Environment.NewLine);
  • textBox1.AppendText("Hello" + "\r\n");
  • textBox1.Text += "Hello\r\n"
  • textbox1.Text += System.Environment.NewLine + "brown";

They either append or prepend a newline when one (might) not be required.

So, extension helper:

public static class WinFormsExtensions
{
   public static void AppendLine(this TextBox source, string value)
   {
      if (source.Text.Length==0)
         source.Text = value;
      else
         source.AppendText("\r\n"+value);
   }
}

So now:

textBox1.Clear();
textBox1.AppendLine("red");
textBox1.AppendLine("green");
textBox1.AppendLine("blue");

and

textBox1.AppendLine(String.Format("Processing file {0}", filename));

Note: Any code is released into the public domain. No attribution required.

How to trigger a click on a link using jQuery

Sorry, but the event handler is really not needed. What you do need is another element within the tag to click on.

<a id="test1" href="javascript:alert('test1')">TEST1</a>
<a id="test2" href="javascript:alert('test2')"><span>TEST2</span></a>

Jquery:

$('#test1').trigger('click'); // Nothing
$('#test2').find('span').trigger('click'); // Works
$('#test2 span').trigger('click'); // Also Works

This is all about what you are clicking and it is not the tag but the thing within it. Unfortunately, bare text does not seem to be recognised by JQuery, but it is by vanilla javascript:

document.getElementById('test1').click(); // Works!

Or by accessing the jQuery object as an array

$('#test1')[0].click(); // Works too!!!

Convert date from String to Date format in Dataframes

I have personally found some errors in when using unix_timestamp based date converstions from dd-MMM-yyyy format to yyyy-mm-dd, using spark 1.6, but this may extend into recent versions. Below I explain a way to solve the problem using java.time that should work in all versions of spark:

I've seen errors when doing:

from_unixtime(unix_timestamp(StockMarketClosingDate, 'dd-MMM-yyyy'), 'yyyy-MM-dd') as FormattedDate

Below is code to illustrate the error, and my solution to fix it. First I read in stock market data, in a common standard file format:

    import sys.process._
    import org.apache.spark.sql.SQLContext
    import org.apache.spark.sql.functions.udf
    import org.apache.spark.sql.types.{StructType, StructField, StringType, IntegerType, DateType}
    import sqlContext.implicits._

    val EODSchema = StructType(Array(
        StructField("Symbol"                , StringType, true),     //$1       
        StructField("Date"                  , StringType, true),     //$2       
        StructField("Open"                  , StringType, true),     //$3       
        StructField("High"                  , StringType, true),     //$4
        StructField("Low"                   , StringType, true),     //$5
        StructField("Close"                 , StringType, true),     //$6
        StructField("Volume"                , StringType, true)      //$7
        ))

    val textFileName = "/user/feeds/eoddata/INDEX/INDEX_19*.csv"

    // below is code to read using later versions of spark
    //val eoddata = spark.read.format("csv").option("sep", ",").schema(EODSchema).option("header", "true").load(textFileName)


    // here is code to read using 1.6, via, "com.databricks:spark-csv_2.10:1.2.0"

    val eoddata = sqlContext.read
                               .format("com.databricks.spark.csv")
                               .option("header", "true")                               // Use first line of all files as header
                               .option("delimiter", ",")                               //.option("dateFormat", "dd-MMM-yyyy") failed to work
                               .schema(EODSchema)
                               .load(textFileName)

    eoddata.registerTempTable("eoddata")

And here is the date conversions having issues:

%sql 
-- notice there are errors around the turn of the year
Select 
    e.Date as StringDate
,   cast(from_unixtime(unix_timestamp(e.Date, "dd-MMM-yyyy"), 'YYYY-MM-dd') as Date)  as ProperDate
,   e.Close
from eoddata e
where e.Symbol = 'SPX.IDX'
order by cast(from_unixtime(unix_timestamp(e.Date, "dd-MMM-yyyy"), 'YYYY-MM-dd') as Date)
limit 1000

A chart made in zeppelin shows spikes, which are errors.

Errors in date conversion seen as spikes

and here is the check that shows the date conversion errors:

// shows the unix_timestamp conversion approach can create errors
val result =  sqlContext.sql("""
Select errors.* from
(
    Select 
    t.*
    , substring(t.OriginalStringDate, 8, 11) as String_Year_yyyy 
    , substring(t.ConvertedCloseDate, 0, 4)  as Converted_Date_Year_yyyy
    from
    (        Select
                Symbol
            ,   cast(from_unixtime(unix_timestamp(e.Date, "dd-MMM-yyyy"), 'YYYY-MM-dd') as Date)  as ConvertedCloseDate
            ,   e.Date as OriginalStringDate
            ,   Close
            from eoddata e
            where e.Symbol = 'SPX.IDX'
    ) t 
) errors
where String_Year_yyyy <> Converted_Date_Year_yyyy
""")


//df.withColumn("tx_date", to_date(unix_timestamp($"date", "M/dd/yyyy").cast("timestamp")))


result.registerTempTable("SPX")
result.cache()
result.show(100)
result: org.apache.spark.sql.DataFrame = [Symbol: string, ConvertedCloseDate: date, OriginalStringDate: string, Close: string, String_Year_yyyy: string, Converted_Date_Year_yyyy: string]
res53: result.type = [Symbol: string, ConvertedCloseDate: date, OriginalStringDate: string, Close: string, String_Year_yyyy: string, Converted_Date_Year_yyyy: string]
+-------+------------------+------------------+-------+----------------+------------------------+
| Symbol|ConvertedCloseDate|OriginalStringDate|  Close|String_Year_yyyy|Converted_Date_Year_yyyy|
+-------+------------------+------------------+-------+----------------+------------------------+
|SPX.IDX|        1997-12-30|       30-Dec-1996| 753.85|            1996|                    1997|
|SPX.IDX|        1997-12-31|       31-Dec-1996| 740.74|            1996|                    1997|
|SPX.IDX|        1998-12-29|       29-Dec-1997| 953.36|            1997|                    1998|
|SPX.IDX|        1998-12-30|       30-Dec-1997| 970.84|            1997|                    1998|
|SPX.IDX|        1998-12-31|       31-Dec-1997| 970.43|            1997|                    1998|
|SPX.IDX|        1998-01-01|       01-Jan-1999|1229.23|            1999|                    1998|
+-------+------------------+------------------+-------+----------------+------------------------+
FINISHED   

After this result, I switched to java.time conversions with a UDF like this, which worked for me:

// now we will create a UDF that uses the very nice java.time library to properly convert the silly stockmarket dates
// start by importing the specific java.time libraries that superceded the joda.time ones
import java.time.LocalDate
import java.time.format.DateTimeFormatter

// now define a specific data conversion function we want

def fromEODDate (YourStringDate: String): String = {

    val formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy")
    var   retDate = LocalDate.parse(YourStringDate, formatter)

    // this should return a proper yyyy-MM-dd date from the silly dd-MMM-yyyy formats
    // now we format this true local date with a formatter to the desired yyyy-MM-dd format

    val retStringDate = retDate.format(DateTimeFormatter.ISO_LOCAL_DATE)
    return(retStringDate)
}

Now I register it as a function for use in sql:

sqlContext.udf.register("fromEODDate", fromEODDate(_:String))

and check the results, and rerun test:

val results = sqlContext.sql("""
    Select
        e.Symbol    as Symbol
    ,   e.Date      as OrigStringDate
    ,   Cast(fromEODDate(e.Date) as Date) as ConvertedDate
    ,   e.Open
    ,   e.High
    ,   e.Low
    ,   e.Close
    from eoddata e
    order by Cast(fromEODDate(e.Date) as Date)
""")

results.printSchema()
results.cache()
results.registerTempTable("results")
results.show(10)
results: org.apache.spark.sql.DataFrame = [Symbol: string, OrigStringDate: string, ConvertedDate: date, Open: string, High: string, Low: string, Close: string]
root
 |-- Symbol: string (nullable = true)
 |-- OrigStringDate: string (nullable = true)
 |-- ConvertedDate: date (nullable = true)
 |-- Open: string (nullable = true)
 |-- High: string (nullable = true)
 |-- Low: string (nullable = true)
 |-- Close: string (nullable = true)
res79: results.type = [Symbol: string, OrigStringDate: string, ConvertedDate: date, Open: string, High: string, Low: string, Close: string]
+--------+--------------+-------------+-------+-------+-------+-------+
|  Symbol|OrigStringDate|ConvertedDate|   Open|   High|    Low|  Close|
+--------+--------------+-------------+-------+-------+-------+-------+
|ADVA.IDX|   01-Jan-1996|   1996-01-01|    364|    364|    364|    364|
|ADVN.IDX|   01-Jan-1996|   1996-01-01|   1527|   1527|   1527|   1527|
|ADVQ.IDX|   01-Jan-1996|   1996-01-01|   1283|   1283|   1283|   1283|
|BANK.IDX|   01-Jan-1996|   1996-01-01|1009.41|1009.41|1009.41|1009.41|
| BKX.IDX|   01-Jan-1996|   1996-01-01|  39.39|  39.39|  39.39|  39.39|
|COMP.IDX|   01-Jan-1996|   1996-01-01|1052.13|1052.13|1052.13|1052.13|
| CPR.IDX|   01-Jan-1996|   1996-01-01|  1.261|  1.261|  1.261|  1.261|
|DECA.IDX|   01-Jan-1996|   1996-01-01|    205|    205|    205|    205|
|DECN.IDX|   01-Jan-1996|   1996-01-01|    825|    825|    825|    825|
|DECQ.IDX|   01-Jan-1996|   1996-01-01|    754|    754|    754|    754|
+--------+--------------+-------------+-------+-------+-------+-------+
only showing top 10 rows

which looks ok, and I rerun my chart, to see if there are errors/spikes:

enter image description here

As you can see, no more spikes or errors. I now use a UDF as I've shown to apply my date format transformations to a standard yyyy-MM-dd format, and have not had spurious errors since. :-)

Number format in excel: Showing % value without multiplying with 100

Here's a simple way:

=NUMBERVALUE( CONCAT(5.66,"%") )

Just concatenate a % symbol after the number. By itself, this output would be text, so we also tuck the CONCAT function inside the NUMBERVALUE function.

p.s., in old excel, you might need to type the full word "CONCATENATE"

Add image in title bar

Add this in the head section of your html

<link rel="icon" type="image/gif/png" href="mouse_select_left.png">

Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence

Peters' python 2 workaround fails on an edge case:

d = {u'keyword': u'bad credit  \xe7redit cards'}
with io.open('filename', 'w', encoding='utf8') as json_file:
    data = json.dumps(d, ensure_ascii=False).decode('utf8')
    try:
        json_file.write(data)
    except TypeError:
        # Decode data to Unicode first
        json_file.write(data.decode('utf8'))

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in position 25: ordinal not in range(128)

It was crashing on the .decode('utf8') part of line 3. I fixed the problem by making the program much simpler by avoiding that step as well as the special casing of ascii:

with io.open('filename', 'w', encoding='utf8') as json_file:
  data = json.dumps(d, ensure_ascii=False, encoding='utf8')
  json_file.write(unicode(data))

cat filename
{"keyword": "bad credit  çredit cards"}

How to enable support of CPU virtualization on Macbook Pro?

Here is a way to check is virtualization is enabled or disabled by the firmware as suggested by this link in parallels.com.

How to check that Intel VT-x is supported in CPU:

  1. Open Terminal application from Application/Utilities

  2. Copy/paste command bellow

sysctl -a | grep machdep.cpu.features

  1. You may see output similar to:

Mac:~ user$ sysctl -a | grep machdep.cpu.features kern.exec: unknown type returned machdep.cpu.features: FPU VME DE PSE TSC MSR PAE MCE CX8 APIC SEP MTRR PGE MCA CMOV PAT CLFSH DS ACPI MMX FXSR SSE SSE2 SS HTT TM SSE3 MON VMX EST TM2 TPR PDCM

If you see VMX entry then CPU supports Intel VT-x feature, but it still may be disabled.

Refer to this link on Apple.com to enable hardware support for virtualization:

Resetting remote to a certain commit

On GitLab, you may have to set your branch to unprotected before doing this. You can do this in [repo] > Settings > Repository > Protected Branches. Then the method from Mark's answer works.

git reset --hard <commit-hash>
git push -f origin master

Center image horizontally within a div

Add this to your CSS:

#artiststhumbnail a img {
   display: block;
   margin-left: auto;
   margin-right: auto;
}

Just referencing a child element which in that case is the image.

How can I read a large text file line by line using Java?

Java 9:

try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
    stream.forEach(System.out::println);
}

batch file to check 64bit or 32bit OS

If $SYSTEM_os_arch==x86 ( 
  Echo OS is 32bit
 ) else ( 
  ECHO OS is 64bit
)

Addressing localhost from a VirtualBox virtual machine

You need to edit your hosts file on your Windows Virtual machine the same way you do for your local host machine:

C:\WINDOWS\system32\drivers\etc\hosts

And link your virtual hosts to 10.0.2.2, If you are just using localhost then replace

127.0.0.1 localhost with 10.0.2.2 localhost

For example:

10.0.2.2 localhost
10.0.2.2 local.site1.com
10.0.2.2 local.site2.com

This tells your virtual machine to point to your local machine for those domain names.

S3 Static Website Hosting Route All Paths to Index.html

I see 4 solutions to this problem. The first 3 were already covered in answers and the last one is my contribution.

  1. Set the error document to index.html.
    Problem: the response body will be correct, but the status code will be 404, which hurts SEO.

  2. Set the redirection rules.
    Problem: URL polluted with #! and page flashes when loaded.

  3. Configure CloudFront.
    Problem: all pages will return 404 from origin, so you need to chose if you won't cache anything (TTL 0 as suggested) or if you will cache and have issues when updating the site.

  4. Prerender all pages.
    Problem: additional work to prerender pages, specially when the pages changes frequently. For example, a news website.

My suggestion is to use option 4. If you prerender all pages, there will be no 404 errors for expected pages. The page will load fine and the framework will take control and act normally as a SPA. You can also set the error document to display a generic error.html page and a redirection rule to redirect 404 errors to a 404.html page (without the hashbang).

Regarding 403 Forbidden errors, I don't let them happen at all. In my application, I consider that all files within the host bucket are public and I set this with the everyone option with the read permission. If your site have pages that are private, letting the user to see the HTML layout should not be an issue. What you need to protect is the data and this is done in the backend.

Also, if you have private assets, like user photos, you can save them in another bucket. Because private assets need the same care as data and can't be compared to the asset files that are used to host the app.

How to get list of dates between two dates in mysql select query

Try:

select * from 
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'

-for date ranges up to nearly 300 years in the future.

[Corrected following a suggested edit by UrvishAtSynapse.]

UIView's frame, bounds, center, origin, when to use what?

Marco's answer above is correct, but just to expand on the question of "under what context"...

frame - this is the property you most often use for normal iPhone applications. most controls will be laid out relative to the "containing" control so the frame.origin will directly correspond to where the control needs to display, and frame.size will determine how big to make the control.

center - this is the property you will likely focus on for sprite based games and animations where movement or scaling may occur. By default animation and rotation will be based on the center of the UIView. It rarely makes sense to try and manage such objects by the frame property.

bounds - this property is not a positioning property, but defines the drawable area of the UIView "relative" to the frame. By default this property is usually (0, 0, width, height). Changing this property will allow you to draw outside of the frame or restrict drawing to a smaller area within the frame. A good discussion of this can be found at the link below. It is uncommon for this property to be manipulated unless there is specific need to adjust the drawing region. The only exception is that most programs will use the [[UIScreen mainScreen] bounds] on startup to determine the visible area for the application and setup their initial UIView's frame accordingly.

Why is there an frame rectangle and an bounds rectangle in an UIView?

Hopefully this helps clarify the circumstances where each property might get used.

Function for Factorial in Python

Another way to do it is to use np.prod shown below:

def factorial(n):
    if n == 0:
        return 1
    else:
         return np.prod(np.arange(1,n+1))

How to convert list of numpy arrays into single numpy array?

I checked some of the methods for speed performance and find that there is no difference! The only difference is that using some methods you must carefully check dimension.

Timing:

|------------|----------------|-------------------|
|            | shape (10000)  |  shape (1,10000)  |
|------------|----------------|-------------------|
| np.concat  |    0.18280     |      0.17960      |
|------------|----------------|-------------------|
|  np.stack  |    0.21501     |      0.16465      |
|------------|----------------|-------------------|
| np.vstack  |    0.21501     |      0.17181      |
|------------|----------------|-------------------|
|  np.array  |    0.21656     |      0.16833      |
|------------|----------------|-------------------|

As you can see I tried 2 experiments - using np.random.rand(10000) and np.random.rand(1, 10000) And if we use 2d arrays than np.stack and np.array create additional dimension - result.shape is (1,10000,10000) and (10000,1,10000) so they need additional actions to avoid this.

Code:

from time import perf_counter
from tqdm import tqdm_notebook
import numpy as np
l = []
for i in tqdm_notebook(range(10000)):
    new_np = np.random.rand(10000)
    l.append(new_np)



start = perf_counter()
stack = np.stack(l, axis=0 )
print(f'np.stack: {perf_counter() - start:.5f}')

start = perf_counter()
vstack = np.vstack(l)
print(f'np.vstack: {perf_counter() - start:.5f}')

start = perf_counter()
wrap = np.array(l)
print(f'np.array: {perf_counter() - start:.5f}')

start = perf_counter()
l = [el.reshape(1,-1) for el in l]
conc = np.concatenate(l, axis=0 )
print(f'np.concatenate: {perf_counter() - start:.5f}')

How to hide 'Back' button on navigation bar on iPhone?

Don't forget that we have the slide to back gesture now. You probably want to remove this as well. Don't forget to enable it back again if necessary.

if ([self.navigationItem respondsToSelector:@selector(hidesBackButton)]) {
    self.navigationItem.hidesBackButton = YES;
}

if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}

Android: Use a SWITCH statement with setOnClickListener/onClick for more than 1 button?

For my example :first 'MainActivity' implements 'View.OnClickListener' than start the code ....

@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    init();}


public void init(){

    foryou = (Button) this.findViewById(R.id.btn_foryou);
    following = (Button) findViewById(R.id.btn_following);
    popular = (Button) findViewById(R.id.btn_popular);
    watching = (Button) findViewById(R.id.btn_continuewatching);
    mProgress = (ProgressBar) findViewById(R.id.pb);

    foryou.setOnClickListener(this);
    following.setOnClickListener(this);
    popular.setOnClickListener(this);
    watching.setOnClickListener(this);
    mProgress.setOnClickListener(this);
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btn_foryou:
            foryou.setPaintFlags(foryou.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

            break;
        case R.id.btn_following:
            following.setPaintFlags(following.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

            break;
        case R.id.btn_popular:
            popular.setPaintFlags(popular.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

            break;
        case R.id.btn_continuewatching:
            watching.setPaintFlags(watching.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

            break;
        case R.id.btn_5:
            // foryou.setPaintFlags(foryou.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

            break;
        default:
            foryou.setPaintFlags(foryou.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

    }
}

Converting ArrayList to Array in java

List<String> list=new ArrayList<String>();
list.add("sravan");
list.add("vasu");
list.add("raki"); 
String names[]=list.toArray(new String[0]);

if you see the last line (new String[0]), you don't have to give the size, there are time when we don't know the length of the list, so to start with giving it as 0 , the constructed array will resize.

How to fix Hibernate LazyInitializationException: failed to lazily initialize a collection of roles, could not initialize proxy - no Session

Your Custom AuthenticationProvider class should be annotated with the following:

@Transactional

This will make sure the presence of the hibernate session there as well.

Add php variable inside echo statement as href link address?

Basically like this,

<?php
$link = ""; // Link goes here!
print "<a href="'.$link.'">Link</a>";
?>

Error when using scp command "bash: scp: command not found"

Make sure the scp command is available on both sides - both on the client and on the server.

If this is Fedora or Red Hat Enterprise Linux and clones (CentOS), make sure this package is installed:

    yum -y install openssh-clients

If you work with Debian or Ubuntu and clones, install this package:

    apt-get install openssh-client

Again, you need to do this both on the server and the client, otherwise you can encounter "weird" error messages on your client: scp: command not found or similar although you have it locally. This already confused thousands of people, I guess :)

How can I debug a HTTP POST in Chrome?

You can filter for HTTP POST requests with the Chrome DevTools. Just do the following:

  1. Open Chrome DevTools (Cmd+Opt+I on Mac, Ctrl+Shift+I or F12 on Windows) and click on the "Network" tab
  2. Click on the "Filter" icon
  3. Enter your filter method: method:POST
  4. Select the request you want to debug
  5. View the details of the request you want to debug

Screenshot

Chrome DevTools

Tested with Chrome Version 53.

Importing xsd into wsdl

import vs. include

The primary purpose of an import is to import a namespace. A more common use of the XSD import statement is to import a namespace which appears in another file. You might be gathering the namespace information from the file, but don't forget that it's the namespace that you're importing, not the file (don't confuse an import statement with an include statement).

Another area of confusion is how to specify the location or path of the included .xsd file: An XSD import statement has an optional attribute named schemaLocation but it is not necessary if the namespace of the import statement is at the same location (in the same file) as the import statement itself.

When you do chose to use an external .xsd file for your WSDL, the schemaLocation attribute becomes necessary. Be very sure that the namespace you use in the import statement is the same as the targetNamespace of the schema you are importing. That is, all 3 occurrences must be identical:

WSDL:

xs:import namespace="urn:listing3" schemaLocation="listing3.xsd"/>

XSD:

<xsd:schema targetNamespace="urn:listing3"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 

Another approach to letting know the WSDL about the XSD is through Maven's pom.xml:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>xmlbeans-maven-plugin</artifactId>
  <executions>
    <execution>
      <id>generate-sources-xmlbeans</id>
      <phase>generate-sources</phase>
      <goals>
    <goal>xmlbeans</goal>
      </goals>
    </execution>
  </executions>
  <version>2.3.3</version>
  <inherited>true</inherited>
  <configuration>
    <schemaDirectory>${basedir}/src/main/xsd</schemaDirectory>
  </configuration>
</plugin>

You can read more on this in this great IBM article. It has typos such as xsd:import instead of xs:import but otherwise it's fine.

How do I Merge two Arrays in VBA?

Or even a way that either variable can be uninitialised or an empty array or an array of objects (eg Dictionary objects). Only handles one dimension at a time, though. Also, it APPENDS arr2 to arr1 rather than merges.

Function appendArray(ByVal arr1 As Variant, ByVal arr2 As Variant) As Variant
    Dim holdarr As Variant
    Dim ub1 As Long
    Dim ub2 As Long
    Dim i As Long
    Dim newind As Long

                            ' Allows for one or both variants to not be arrays
    If IsEmpty(arr1) Or Not IsArray(arr1) Then
        arr1 = Array()
    End If

    If IsEmpty(arr2) Or Not IsArray(arr2) Then
        arr2 = Array()
    End If
                            ' Now we assume we DO have two ARRAYS, even if one or the other
                            ' has no elements
    ub1 = UBound(arr1)
    ub2 = UBound(arr2)

    If ub1 = -1 Then
        appendArray = arr2
        Exit Function
    End If

    If ub2 = -1 Then
        appendArray = arr1
        Exit Function
    End If

            ' Copy the first array. We know it is not empty.
    holdarr = arr1

            ' Grow it to the final size we need, keeping the current contents
    ReDim Preserve holdarr(ub1 + ub2 + 1)

            ' Set the starting new index
    newind = UBound(arr1) + 1

            ' Append the second array, allowing that it might be an array of objects
    For i = 0 To ub2
        If VarType(arr2(i)) = vbObject Then
            Set holdarr(newind) = arr2(i)
        Else
            holdarr(newind) = arr2(i)
        End If
        newind = newind + 1
    Next i
            ' Return the appended array
    appendArray = holdarr
End Function

What does "javascript:void(0)" mean?

There is a huge difference in the behaviour of # vs javascript:void(0);.

# scrolls you to the top of the page but javascript:void(0); does not.

This is very important if you are coding dynamic pages because the user does not want to go back to the top when they click a link on the page.

$(document).ready(function(){ Uncaught ReferenceError: $ is not defined

Put this code in the <head></head> tags:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>

Dark color scheme for Eclipse

In response to this comment I made a filter for Color Filter plugin for Compiz.

Here's what I got:

Howto:

  1. Go to /usr/share/compiz/filters/
  2. Create new file "negative-low-contrast" (as root)
  3. Insert the attached code into it.
  4. Go to System->Preferences->CompizConfig ...
  5. Enter Color Filter Plugin
  6. Enable it and add newly created filter to the list Profeet!!

Filter code:

!!ARBfp1.0
TEMP temp, neg;

# Dunno what's this... but every other filter starts with this :) ;
TEX temp, fragment.texcoord[0], texture[0], RECT;

# Applying negative filter ;
RCP neg.a, temp.a;
MAD temp.rgb, -neg.a, temp, 1.0;
MUL temp.rgb, temp.a, temp;
MUL temp, fragment.color, temp;

# Lowering contrast and shifting brightness ;
MUL temp.rgb, temp, 0.8;
ADD temp.rgb, temp, 0.25;

MOV result.color, temp;
END

You also can play with the filter. May be you will get something more facinating :) Feel free to share!

Explaining the 'find -mtime' command

To find all files modified in the last 24 hours use the one below. The -1 here means changed 1 day or less ago.

find . -mtime -1 -ls

Darken CSS background image?

You can use the CSS3 Linear Gradient property along with your background-image like this:

#landing-wrapper {
    display:table;
    width:100%;
    background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('landingpagepic.jpg');
    background-position:center top;
    height:350px;
}

Here's a demo:

_x000D_
_x000D_
#landing-wrapper {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
  background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('http://placehold.it/350x150');_x000D_
  background-position: center top;_x000D_
  height: 350px;_x000D_
  color: white;_x000D_
}
_x000D_
<div id="landing-wrapper">Lorem ipsum dolor ismet.</div>
_x000D_
_x000D_
_x000D_

How to see the changes between two commits without commits in-between?

My alias settings in ~/.zshrc file for git diff:

alias gdf='git diff HEAD{'^',}' # diff between your recent tow commits

Thanks @Jinmiao Luo


git diff HEAD~2 HEAD

complete change between latest 2nd commit and current.

HEAD is convenient

MSIE and addEventListener Problem in Javascript?

In IE you have to use attachEvent rather than the standard addEventListener.

A common practice is to check if the addEventListener method is available and use it, otherwise use attachEvent:

if (el.addEventListener){
  el.addEventListener('click', modifyText, false); 
} else if (el.attachEvent){
  el.attachEvent('onclick', modifyText);
}

You can make a function to do it:

function bindEvent(el, eventName, eventHandler) {
  if (el.addEventListener){
    el.addEventListener(eventName, eventHandler, false); 
  } else if (el.attachEvent){
    el.attachEvent('on'+eventName, eventHandler);
  }
}
// ...
bindEvent(document.getElementById('myElement'), 'click', function () {
  alert('element clicked');
});

You can run an example of the above code here.

The third argument of addEventListener is useCapture; if true, it indicates that the user wishes to initiate event capturing.

Using jQuery to see if a div has a child with a certain class

If it's a direct child you can do as below if it could be nested deeper remove the >

$("#text-field").keydown(function(event) {
    if($('#popup>p.filled-text').length !== 0) {
        console.log("Found");
     }
});

MySQL Query to select data from last week?

Probably the most simple way would be:

SELECT id
FROM table
WHERE date >= current_date - 7

For 8 days (i.e. Monday - Monday)

Tooltip with HTML content without JavaScript

This one is very interesting,

HTML and CSS only

_x000D_
_x000D_
.help-tip {_x000D_
  position: absolute;_x000D_
  top: 18px;_x000D_
  left: 18px;_x000D_
  text-align: center;_x000D_
  background-color: #BCDBEA;_x000D_
  border-radius: 50%;_x000D_
  width: 24px;_x000D_
  height: 24px;_x000D_
  font-size: 14px;_x000D_
  line-height: 26px;_x000D_
  cursor: default;_x000D_
}_x000D_
_x000D_
.help-tip:before {_x000D_
  content: '?';_x000D_
  font-weight: bold;_x000D_
  color: #fff;_x000D_
}_x000D_
_x000D_
.help-tip:hover span {_x000D_
  display: block;_x000D_
  transform-origin: 100% 0%;_x000D_
  -webkit-animation: fadeIn 0.3s ease-in-out;_x000D_
  animation: fadeIn 0.3s ease-in-out;_x000D_
}_x000D_
_x000D_
.help-tip span {_x000D_
  display: none;_x000D_
  text-align: left;_x000D_
  background-color: #1E2021;_x000D_
  padding: 5px;_x000D_
  width: 200px;_x000D_
  position: absolute;_x000D_
  border-radius: 3px;_x000D_
  box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.2);_x000D_
  left: -4px;_x000D_
  color: #FFF;_x000D_
  font-size: 13px;_x000D_
  line-height: 1.4;_x000D_
}_x000D_
_x000D_
.help-tip span:before {_x000D_
  position: absolute;_x000D_
  content: '';_x000D_
  width: 0;_x000D_
  height: 0;_x000D_
  border: 6px solid transparent;_x000D_
  border-bottom-color: #1E2021;_x000D_
  left: 10px;_x000D_
  top: -12px;_x000D_
}_x000D_
_x000D_
.help-tip span:after {_x000D_
  width: 100%;_x000D_
  height: 40px;_x000D_
  content: '';_x000D_
  position: absolute;_x000D_
  top: -40px;_x000D_
  left: 0;_x000D_
}
_x000D_
<span class="help-tip">_x000D_
     <span > This is the inline help tip! </span>_x000D_
</span>
_x000D_
_x000D_
_x000D_

How to select specific form element in jQuery?

$("#name", '#form2').val("Hello World")

How to check if element is visible after scrolling?

The only plugin which works consistently for me for doing this, is: https://github.com/customd/jquery-visible

I ported this plugin to GWT recently since I didn't want to add jquery as a dependency just for using the plugin. Here's my (simple) port (just including the functionality that I need for my use case):

public static boolean isVisible(Element e)
{
    //vp = viewPort, b = bottom, l = left, t = top, r = right
    int vpWidth   = Window.getClientWidth();
    int vpHeight = Window.getClientHeight();


    boolean tViz = ( e.getAbsoluteTop() >= 0 && e.getAbsoluteTop()<  vpHeight);
    boolean bViz = (e.getAbsoluteBottom() >  0 && e.getAbsoluteBottom() <= vpHeight);
    boolean lViz = (e.getAbsoluteLeft() >= 0 && e.getAbsoluteLeft() < vpWidth);
    boolean rViz = (e.getAbsoluteRight()  >  0 && e.getAbsoluteRight()  <= vpWidth);

    boolean vVisible   = tViz && bViz;
    boolean hVisible   = lViz && rViz;

    return hVisible && vVisible;
}

How to randomize (shuffle) a JavaScript array?

NEW!

Shorter & probably *faster Fisher-Yates shuffle algorithm

  1. it uses while---
  2. bitwise to floor (numbers up to 10 decimal digits (32bit))
  3. removed unecessary closures & other stuff

function fy(a,b,c,d){//array,placeholder,placeholder,placeholder
 c=a.length;while(c)b=Math.random()*(--c+1)|0,d=a[c],a[c]=a[b],a[b]=d
}

script size (with fy as function name): 90bytes

DEMO http://jsfiddle.net/vvpoma8w/

*faster probably on all browsers except chrome.

If you have any questions just ask.

EDIT

yes it is faster

PERFORMANCE: http://jsperf.com/fyshuffle

using the top voted functions.

EDIT There was a calculation in excess (don't need --c+1) and noone noticed

shorter(4bytes)&faster(test it!).

function fy(a,b,c,d){//array,placeholder,placeholder,placeholder
 c=a.length;while(c)b=Math.random()*c--|0,d=a[c],a[c]=a[b],a[b]=d
}

Caching somewhere else var rnd=Math.random and then use rnd() would also increase slightly the performance on big arrays.

http://jsfiddle.net/vvpoma8w/2/

Readable version (use the original version. this is slower, vars are useless, like the closures & ";", the code itself is also shorter ... maybe read this How to 'minify' Javascript code , btw you are not able to compress the following code in a javascript minifiers like the above one.)

function fisherYates( array ){
 var count = array.length,
     randomnumber,
     temp;
 while( count ){
  randomnumber = Math.random() * count-- | 0;
  temp = array[count];
  array[count] = array[randomnumber];
  array[randomnumber] = temp
 }
}

How to generate and validate a software license key?

The C# / .NET engine we use for licence key generation is now maintained as open source:

https://github.com/appsoftware/.NET-Licence-Key-Generator.

It's based on a "Partial Key Verification" system which means only a subset of the key that you use to generate the key has to be compiled into your distributable. You create the keys your self, so the licence implementation is unique to your software.

As stated above, if your code can be decompiled, it's relatively easy to circumvent most licencing systems.

Getting Data from Android Play Store

There's an unofficial open-source API for the Android Market you may try to use to get the information you need. Hope this helps.

How to upload files to server using Putty (ssh)

Use WinSCP for file transfer over SSH, putty is only for SSH commands.

Can someone explain mappedBy in JPA and Hibernate?

You started with ManyToOne mapping , then you put OneToMany mapping as well for BiDirectional way. Then at OneToMany side (usually your parent table/class), you have to mention "mappedBy" (mapping is done by and in child table/class), so hibernate will not create EXTRA mapping table in DB (like TableName = parent_child).

Multiple types were found that match the controller named 'Home'

i just deleted folder 'Bin' from server and copy my bin to server, and my problem solved.

Javascript to Select Multiple options

This type of thing should be done server-side, so as to limit the amount of resources used on the client for such trivial tasks. That being said, if you were to do it on the front-end, I would encourage you to consider using something like underscore.js to keep the code clean and concise:

var values = ["Red", "Green"],
    colors = document.getElementById("colors");

_.each(colors.options, function (option) {
    option.selected = ~_.indexOf(values, option.text);
});

If you're using jQuery, it could be even more terse:

var values = ["Red", "Green"];

$("#colors option").prop("selected", function () {
    return ~$.inArray(this.text, values);
});

If you were to do this without a tool like underscore.js or jQuery, you would have a bit more to write, and may find it to be a bit more complicated:

var color, i, j,
    values = ["Red", "Green"],
    options = document.getElementById("colors").options;

for ( i = 0; i < values.length; i++ ) {
    for ( j = 0, color = values[i]; j < options.length; j++ ) {
        options[j].selected = options[j].selected || color === options[j].text;
    }
}

String format currency

Personally i'm against using culture specific code, i suggest doing:

@String.Format(CultureInfo.CurrentCulture, "{0:C}", @price)

and in your web.config do:

<system.web>
    <globalization culture="en-GB" uiCulture="en-US" />
</system.web>

Additional info: https://msdn.microsoft.com/en-us/library/syy068tk(v=vs.90).aspx

Getting list of lists into pandas DataFrame

With approach explained by EdChum above, the values in the list are shown as rows. To show the values of lists as columns in DataFrame instead, simply use transpose() as following:

table = [[1 , 2], [3, 4]]
df = pd.DataFrame(table)
df = df.transpose()
df.columns = ['Heading1', 'Heading2']

The output then is:

      Heading1  Heading2
0         1        3
1         2        4

Easy way to turn JavaScript array into comma-separated list?

The Array.prototype.join() method:

_x000D_
_x000D_
var arr = ["Zero", "One", "Two"];_x000D_
_x000D_
document.write(arr.join(", "));
_x000D_
_x000D_
_x000D_

How to create/make rounded corner buttons in WPF?

Well the best way to get round corners fast and with standard animation is to create a copy of the control template with Blend. Once you get a copy set the corner radius on the Grid tag and you should be able to have your control with full animation functionality and applyable to any button control. look this is the code:

<ControlTemplate x:Key="ButtonControlTemplate" TargetType="Button">        
    <Grid x:Name="RootGrid" Background="{TemplateBinding Background}"
          CornerRadius="8,8,8,8">
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
                <VisualState x:Name="Normal">
                    <Storyboard>
                        <PointerUpThemeAnimation Storyboard.TargetName="RootGrid" />
                    </Storyboard>
                </VisualState>
                <VisualState x:Name="PointerOver">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RootGrid" Storyboard.TargetProperty="Background">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBackgroundPointerOver}" />
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="BorderBrush">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBorderBrushPressed}" />
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonForegroundPointerOver}" />
                        </ObjectAnimationUsingKeyFrames>
                        <PointerUpThemeAnimation Storyboard.TargetName="RootGrid" />
                    </Storyboard>
                </VisualState>
                <VisualState x:Name="Pressed">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RootGrid" Storyboard.TargetProperty="Background">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBackgroundPressed}" />
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="BorderBrush">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBorderBrushPressed}" />
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonForegroundPressed}" />
                        </ObjectAnimationUsingKeyFrames>
                        <PointerDownThemeAnimation Storyboard.TargetName="RootGrid" />
                    </Storyboard>
                </VisualState>
                <VisualState x:Name="Disabled">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RootGrid" Storyboard.TargetProperty="Background">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBackgroundDisabled}" />
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="BorderBrush">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBorderBrushDisabled}" />
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonForegroundDisabled}" />
                        </ObjectAnimationUsingKeyFrames>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
        <!--<Border CornerRadius="8,8,8,8"
                        Background="#002060"
                        BorderBrush="Red"
                        BorderThickness="2">-->
            <ContentPresenter x:Name="ContentPresenter"
                              BorderBrush="{TemplateBinding BorderBrush}"
                              BorderThickness="{TemplateBinding BorderThickness}"
                              Content="{TemplateBinding Content}"
                              ContentTransitions="{TemplateBinding ContentTransitions}"
                              ContentTemplate="{TemplateBinding ContentTemplate}"
                              Padding="{TemplateBinding Padding}"
                              HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
                              VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
                              AutomationProperties.AccessibilityView="Raw"/>
        <!--</Border>-->
    </Grid>        
</ControlTemplate>

I also edited the VisualState="PointerOver" specifically at Storyboard.TargetName="BorderBrush", because its ThemeResource get squared corners whenever PointerOver triggers.

Then you should be able to apply it to your control style like this:

<Style TargetType="ContentControl" x:Key="ButtonLoginStyle"
       BasedOn="{StaticResource CommonLoginStyleMobile}">
    <Setter Property="FontWeight" Value="Bold"/>
    <Setter Property="Background" Value="#002060"/>
    <Setter Property="Template" Value="{StaticResource ButtonControlTemplate}"/>        
</Style>

So you can apply your styles to any Button.

Call static method with reflection

Class that will call the methods:

namespace myNamespace
{
    public class myClass
    {
        public static void voidMethodWithoutParameters()
        {
            // code here
        }
        public static string stringReturnMethodWithParameters(string param1, string param2)
        {
            // code here
            return "output";
        }
    }
}

Calling myClass static methods using Reflection:

var myClassType = Assembly.GetExecutingAssembly().GetType(GetType().Namespace + ".myClass");
                    
// calling my void Method that has no parameters.
myClassType.GetMethod("voidMethodWithoutParameters", BindingFlags.Public | BindingFlags.Static).Invoke(null, null);

// calling my string returning Method & passing to it two string parameters.
Object methodOutput = myClassType.GetMethod("stringReturnMethodWithParameters", BindingFlags.Public | BindingFlags.Static).Invoke(null, new object[] { "value1", "value1" });
Console.WriteLine(methodOutput.ToString());

Note: I don't need to instantiate an object of myClass to use it's methods, as the methods I'm using are static.

Great resources:

MongoDB Show all contents from all collections

I prefer another approach if you are using mongo shell:

First as the another answers: use my_database_name then:

db.getCollectionNames().map( (name) => ({[name]: db[name].find().toArray().length}) )

This query will show you something like this:

[
        {
                "agreements" : 60
        },
        {
                "libraries" : 45
        },
        {
                "templates" : 9
        },
        {
                "users" : 19
        }
]

You can use similar approach with db.getCollectionInfos() it is pretty useful if you have so much data & helpful as well.

How to read the Stock CPU Usage data

As other answers have pointed, on UNIX systems the numbers represent CPU load averages over 1/5/15 minute periods. But on Linux (and consequently Android), what it represents is something different.

After a kernel patch dating back to 1993 (a great in-depth article on the subject), in Linux the load average numbers no longer strictly represent the CPU load: as the calculation accounts not only for CPU bound processes, but also for processes in uninterruptible wait state - the original goal was to account for I/O bound processes this way, to represent more of a "system load" than just CPU load. The issue is that since 1993 the usage of uninterruptible state has grown in Linux kernel, and it no longer typically represents an I/O bound process. The problem is further exacerbated by some Linux devs using uninterruptible waits as an easy wait to avoid accommodating signals in their implementations. As a result, in Linux (and Android) we can see skewed high load average numbers that do not objectively represent the real load. There are Android user reports about unreasonable high load averages contrasting low CPU utilization. For example, my old Android phone (with 2 CPU cores) normally shown average load of ~12 even when the system and CPUs were idle. Hence, average load numbers in Linux (Android) does not turn out to be a reliable performance metric.

How to convert JSON object to JavaScript array?

function json2array(json){
    var result = [];
    var keys = Object.keys(json);
    keys.forEach(function(key){
        result.push(json[key]);
    });
    return result;
}

See this complete explanation: http://book.mixu.net/node/ch5.html

How do I convert a datetime to date?

You can convert a datetime object to a date with the date() method of the date time object, as follows:

<datetime_object>.date()

How to round the double value to 2 decimal points?

public static double addDoubles(double a, double b) {
        BigDecimal A = new BigDecimal(a + "");
        BigDecimal B = new BigDecimal(b + "");
        return A.add(B).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

Concatenate multiple result rows of one column into one, group by another column

You can use array_agg function for that:

SELECT "Movie",
array_to_string(array_agg(distinct "Actor"),',') AS Actor
FROM Table1
GROUP BY "Movie";

Result:

MOVIE ACTOR
A 1,2,3
B 4

See this SQLFiddle

For more See 9.18. Aggregate Functions

How do I get the current Date/time in DD/MM/YYYY HH:MM format?

require 'date'

current_time = DateTime.now

current_time.strftime "%d/%m/%Y %H:%M"
# => "14/09/2011 17:02"

current_time.next_month.strftime "%d/%m/%Y %H:%M"
# => "14/10/2011 17:02"

Search text in fields in every table of a MySQL database

In case 23 answers is not enough, here are 2 more... Depending on database structure and content, you may find one them to actually be a quick and simple solution.

For fans of shell one-liners, here is a long one (actually on 2 lines to use variables):

cmd='mysql -u Username -pYour_Password -D Your_Database' # <-- Adapt this

$cmd -s -e 'SHOW TABLES' | while read table; do echo "=== $table ==="; $cmd -B -s -e "SELECT * FROM $table" | grep 'Your_Search'; done

Or on multiple lines to make it more readable:

$cmd -s -e 'SHOW TABLES' \
| while read table; do
    echo "=== $table ===";
    $cmd -B -s -e "SELECT * FROM $table" \
    | grep 'Your_Search';
  done
  • -s (--silent) is to suppress the column name headers

  • -B (--batch) escapes special characters like newlines, so we get the whole record when using grep

And for Perl fans, this will let you use regular expressions:

# perl -MDBI -le '($db,$u,$p)=@ARGV; $dbh=DBI->connect("dbi:mysql:dbname=$db",$u,$p); foreach $table ($dbh->tables()) {print "$table\n"; foreach $r ($dbh->selectall_array("SELECT * FROM $table")) {$_=join("\t", @$r); print $_ if (/Your_Regex/);}}' Your_Database Username Your_Password

Which in a "real" Perl script could be something like this:

#!/usr/bin/perl

use strict;
use open qw(:std :utf8);

use DBI;

my $db_host  = 'localhost';
my $db       = 'Your_Database';
my $db_user  = 'Username';
my $db_pass  = 'Your_Password';

my $search    = qr/Your_regex_Search/;


# https://metacpan.org/pod/DBD::mysql
my $dbh = DBI->connect( "dbi:mysql:dbname=$db;host=$db_host", $db_user, $db_pass,
                        { mysql_enable_utf8mb4 => 1 }
) or die "Can't connect: $DBI::errstr\n";


foreach my $table ( $dbh->tables() ) {
    my $sth = $dbh->prepare("SELECT * FROM $table")
        or die "Can't prepare: ", $dbh->errstr;

    $sth->execute
        or die "Can't execute: ", $sth->errstr;

    my @results;

    while (my @row = $sth->fetchrow()) {
        local $_ = join("\t", @row);
        if ( /$search/ ) {
            push @results, $_;
        }
    }

    $sth->finish;

    next unless @results;

    print "*** TABLE $table :\n",
          join("\n---------------\n", @results),
          "\n" . "=" x 20 . "\n";
}

$dbh->disconnect;

Pass variables to AngularJS controller, best practice?

You could use ng-init in an outer div:

<div ng-init="param='value';">
    <div ng-controller="BasketController" >
        <label>param: {{value}}</label>
    </div>
</div>  

The parameter will then be available in your controller's scope:

function BasketController($scope) {
        console.log($scope.param);
}

How to get JSON objects value if its name contains dots?

What you want is:

var smth = mydata.list[0]["points.bean.pointsBase"][0].time;

In JavaScript, any field you can access using the . operator, you can access using [] with a string version of the field name.

Center text in div?

I've looked around and the

display: table-cell;
vertical-align: middle;

seems to be the most popular solution

Multiple inputs with same name through POST in php

Eric answer is correct, but the problem is the fields are not grouped. Imagine you have multiple streets and cities which belong together:

<h1>First Address</h1>
<input name="street[]" value="Hauptstr" />
<input name="city[]" value="Berlin"  />

<h2>Second Address</h2>
<input name="street[]" value="Wallstreet" />
<input name="city[]" value="New York" />

The outcome would be

$POST = [ 'street' => [ 'Hauptstr', 'Wallstreet'], 
          'city' => [ 'Berlin' , 'New York'] ];

To group them by address, I would rather recommend to use what Eric also mentioned in the comment section:

<h1>First Address</h1>
<input name="address[1][street]" value="Hauptstr" />
<input name="address[1][city]" value="Berlin"  />

<h2>Second Address</h2>
<input name="address[2][street]" value="Wallstreet" />
<input name="address[2][city]" value="New York" />

The outcome would be

$POST = [ 'address' => [ 
                 1 => ['street' => 'Hauptstr', 'city' => 'Berlin'],
                 2 => ['street' => 'Wallstreet', 'city' => 'New York'],
              ]
        ]

SSIS cannot convert because a potential loss of data

This might not be the best method, but you can ignore the conversion error if all else fails. Mine was an issue of nulls not converting properly, so I just ignored the error and the dates came in as dates and the nulls came in as nulls, so no data quality issues--not that this would always be the case. To do this, right click on your source, click Edit, then Error Output. Go to the column that's giving you grief and under Error change it to Ignore Failure.

Is there a sleep function in JavaScript?

A naive, CPU-intensive method to block execution for a number of milliseconds:

/**
* Delay for a number of milliseconds
*/
function sleep(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}

error: expected class-name before ‘{’ token

If you forward-declare Flight and Landing in Event.h, then you should be fixed.

Remember to #include "Flight.h" and #include "Landing.h" in your implementation file for Event.

The general rule of thumb is: if you derive from it, or compose from it, or use it by value, the compiler must know its full definition at the time of declaration. If you compose from a pointer-to-it, the compiler will know how big a pointer is. Similarly, if you pass a reference to it, the compiler will know how big the reference is, too.

What is (x & 1) and (x >>= 1)?

These are Bitwise Operators (reference).

x & 1 produces a value that is either 1 or 0, depending on the least significant bit of x: if the last bit is 1, the result of x & 1 is 1; otherwise, it is 0. This is a bitwise AND operation.

x >>= 1 means "set x to itself shifted by one bit to the right". The expression evaluates to the new value of x after the shift.

Note: The value of the most significant bit after the shift is zero for values of unsigned type. For values of signed type the most significant bit is copied from the sign bit of the value prior to shifting as part of sign extension, so the loop will never finish if x is a signed type, and the initial value is negative.

SQL like search string starts with

COLLATE UTF8_GENERAL_CI will work as ignore-case. USE:

SELECT * from games WHERE title COLLATE UTF8_GENERAL_CI LIKE 'age of empires III%';

or

SELECT * from games WHERE LOWER(title) LIKE 'age of empires III%';

What does it mean by command cd /d %~dp0 in Windows

Let's dissect it. There are three parts:

  1. cd -- This is change directory command.
  2. /d -- This switch makes cd change both drive and directory at once. Without it you would have to do cd %~d0 & cd %~p0. (%~d0 Changs active drive, cd %~p0 change the directory).
  3. %~dp0 -- This can be dissected further into three parts:
    1. %0 -- This represents zeroth parameter of your batch script. It expands into the name of the batch file itself.
    2. %~0 -- The ~ there strips double quotes (") around the expanded argument.
    3. %dp0 -- The d and p there are modifiers of the expansion. The d forces addition of a drive letter and the p adds full path.

How to print out a variable in makefile

If you simply want some output, you want to use $(info) by itself. You can do that anywhere in a Makefile, and it will show when that line is evaluated:

$(info VAR="$(VAR)")

Will output VAR="<value of VAR>" whenever make processes that line. This behavior is very position dependent, so you must make sure that the $(info) expansion happens AFTER everything that could modify $(VAR) has already happened!

A more generic option is to create a special rule for printing the value of a variable. Generally speaking, rules are executed after variables are assigned, so this will show you the value that is actually being used. (Though, it is possible for a rule to change a variable.) Good formatting will help clarify what a variable is set to, and the $(flavor) function will tell you what kind of a variable something is. So in this rule:

print-% : ; $(info $* is a $(flavor $*) variable set to [$($*)]) @true
  • $* expands to the stem that the % pattern matched in the rule.
  • $($*) expands to the value of the variable whose name is given by by $*.
  • The [ and ] clearly delineate the variable expansion. You could also use " and " or similar.
  • $(flavor $*) tells you what kind of variable it is. NOTE: $(flavor) takes a variable name, and not its expansion. So if you say make print-LDFLAGS, you get $(flavor LDFLAGS), which is what you want.
  • $(info text) provides output. Make prints text on its stdout as a side-effect of the expansion. The expansion of $(info) though is empty. You can think of it like @echo, but importantly it doesn't use the shell, so you don't have to worry about shell quoting rules.
  • @true is there just to provide a command for the rule. Without that, make will also output print-blah is up to date. I feel @true makes it more clear that it's meant to be a no-op.

Running it, you get

$ make print-LDFLAGS
LDFLAGS is a recursive variable set to [-L/Users/...]

WSDL vs REST Pros and Cons

This probably really belongs as comments in several of the above posts, but I don't yet have the rep to do that, so here goes.

I think it is interesting that a lot of the pros and cons often cited for SOAP and REST have (IMO) very little to do with the actual values or limits of the two technologies. Probably the most cited pro for REST is that it is "light-weight" or tends to be more "human readable". At one level this is certainly true, REST does have a lower barrier to entry - there is less required structure than SOAP (though I agree with those who have said that good tooling is largely the answer here - too bad much of the SOAP tooling is pretty dreadful).

Beyond that initial entry cost however, I think the REST impression comes from a combination of the form of the request URLs and the complexity of the data exchanged by most REST services. REST tends to encourage simpler, more human readable request URLs and the data tends to be more digestable as well. To what extent however are these inherent to REST and to what extent are they merely accidental. The simpler URL structure is a direct result of the architecture - but it could be equally well applied to SOAP based services. The more digestable data is more likely to be a result of the lack of any defined structure. This means you'd better keep your data formats simple or you are going to be in for a lot of work. So here SOAP's additional structure, which should be a benefit is actually enabling sloppy design and that sloppy design then gets used as a dig against the technology.

So for use in the exchange of structured data between computer systems I'm not sure that REST is inherently better than SOAP (or visa-versa), they are just different. I think the comparison above of REST vs SOAP to dynamic vs. static typing is a good one. Where dyanmic languages tend to run in to trouble is in long term maintenance and upkeep of a system (and by long term I'm not talking a year or 2, I'm talking 5 or 10). It will be interesting to see if REST runs into the same challenges over time. I tend to think it will so if I were building a distributed, information processing system I would gravitate to SOAP as the communication mechanism (also because of the tranmission and application protocol layering and flexibility that it affords as has been mentioned above).

In other places though REST seems more appropriate. AJAX between the client and its server (regardless of payload) is one major example. I don't have much care for the longevity of this type of connection and ease of use and flexibility are at a premimum. Similarly if I needed quick access to some external service and I didn't think I was going to care about the maintainability of the interaction over time (again I'm assuming this is where REST is going to end up costing me more, one way or another), then I might choose REST just so I could get in and out quickly.

Anyway, they are both viable technologies and depending on what tradeoffs you want to make for a given application they can serve you well (or poorly).

CSS Disabled scrolling

Try using the following code snippet. This should solve your issue.

body, html { 
    overflow-x: hidden; 
    overflow-y: auto;
}

ASP MVC in IIS 7 results in: HTTP Error 403.14 - Forbidden

I tried everything here; nothing worked. Problem was in my Web.config file, somehow dependent assembly binding got changed from minimum 1 to minimum 0.

<!-- was -->
<runtime>
    <assemblyBinding>
        <dependentAssembly>
            <assemblyIdentity name="System.Web.Mvc" />
                <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />


<!-- should have been -->
                <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />

How do I replace all line breaks in a string with <br /> elements?

This worked for me when value came from a TextBox:

string.replace(/\n|\r\n|\r/g, '<br/>');

Using Gulp to Concatenate and Uglify files

we are using below configuration to do something similar

    var gulp = require('gulp'),
    async = require("async"),
    less = require('gulp-less'),
    minifyCSS = require('gulp-minify-css'),
    uglify = require('gulp-uglify'),
    concat = require('gulp-concat'),
    gulpDS = require("./gulpDS"),
    del = require('del');

// CSS & Less
var jsarr = [gulpDS.jsbundle.mobile, gulpDS.jsbundle.desktop, gulpDS.jsbundle.common];
var cssarr = [gulpDS.cssbundle];

var generateJS = function() {

    jsarr.forEach(function(gulpDSObject) {
        async.map(Object.keys(gulpDSObject), function(key) {
            var val = gulpDSObject[key]
            execGulp(val, key);
        });

    })
}

var generateCSS = function() {
    cssarr.forEach(function(gulpDSObject) {
        async.map(Object.keys(gulpDSObject), function(key) {
            var val = gulpDSObject[key];
            execCSSGulp(val, key);
        })
    })
}

var execGulp = function(arrayOfItems, dest) {
    var destSplit = dest.split("/");
    var file = destSplit.pop();
    del.sync([dest])
    gulp.src(arrayOfItems)
        .pipe(concat(file))
        .pipe(uglify())
        .pipe(gulp.dest(destSplit.join("/")));
}

var execCSSGulp = function(arrayOfItems, dest) {
    var destSplit = dest.split("/");
    var file = destSplit.pop();
    del.sync([dest])
    gulp.src(arrayOfItems)
        .pipe(less())
        .pipe(concat(file))
        .pipe(minifyCSS())
        .pipe(gulp.dest(destSplit.join("/")));
}

gulp.task('css', generateCSS);
gulp.task('js', generateJS);

gulp.task('default', ['css', 'js']);

sample GulpDS file is below:

{

    jsbundle: {
        "mobile": {
            "public/javascripts/sample.min.js": ["public/javascripts/a.js", "public/javascripts/mobile/b.js"]
           },
        "desktop": {
            'public/javascripts/sample1.js': ["public/javascripts/c.js", "public/javascripts/d.js"]},
        "common": {
            'public/javascripts/responsive/sample2.js': ['public/javascripts/n.js']
           }
    },
    cssbundle: {
        "public/stylesheets/a.css": "public/stylesheets/less/a.less",
        }
}

Call to getLayoutInflater() in places not in activity

or

View.inflate(context, layout, parent)

How to get all files under a specific directory in MATLAB?

You can use regexp or strcmp to eliminate . and .. Or you could use the isdir field if you only want files in the directory, not folders.

list=dir(pwd);  %get info of files/folders in current directory
isfile=~[list.isdir]; %determine index of files vs folders
filenames={list(isfile).name}; %create cell array of file names

or combine the last two lines:

filenames={list(~[list.isdir]).name};

For a list of folders in the directory excluding . and ..

dirnames={list([list.isdir]).name};
dirnames=dirnames(~(strcmp('.',dirnames)|strcmp('..',dirnames)));

From this point, you should be able to throw the code in a nested for loop, and continue searching each subfolder until your dirnames returns an empty cell for each subdirectory.

I want to align the text in a <td> to the top

you can use valign="top" on the td tag it is working perfectly for me.

How to speed up insertion performance in PostgreSQL

I spent around 6 hours on the same issue today. Inserts go at a 'regular' speed (less than 3sec per 100K) up until to 5MI (out of total 30MI) rows and then the performance sinks drastically (all the way down to 1min per 100K).

I will not list all of the things that did not work and cut straight to the meat.

I dropped a primary key on the target table (which was a GUID) and my 30MI or rows happily flowed to their destination at a constant speed of less than 3sec per 100K.

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

I would just do

int pnSize = primeNumber.size();
for (int i = 0; i < pnSize; i++)
    cout << primeNumber[i] << ' ';

How to Add a Dotted Underline Beneath HTML Text

You can try this method:

<h2 style="text-decoration: underline; text-underline-position: under; text-decoration-style: dotted">Hello World!</h2>

Please note that without text-underline-position: under; you still will have a dotted underline but this property will give it more breathing space.

This is assuming you want to embed everything inside an HTML file using inline styling and not to use a separate CSS file or tag.

How to not wrap contents of a div?

If your div has a fixed-width it shouldn't expand, because you've fixed its width. However, modern browsers support a min-width CSS property.

You can emulate the min-width property in old IE browsers by using CSS expressions or by using auto width and having a spacer object in the container. This solution isn't elegant but may do the trick:

<div id="container" style="float: left">
  <div id="spacer" style="height: 1px; width: 300px"></div>
  <button>Button 1 text</button>
  <button>Button 2 text</button>
</div>

Disable spell-checking on HTML textfields

If you have created your HTML element dynamically, you'll want to disable the attribute via JS. There is a little trap however:

When setting elem.contentEditable you can use either the boolean false or the string "false". But when you set elem.spellcheck, you can only use the boolean - for some reason. Your options are thus:

elem.spellcheck = false;

Or the option Mac provided in his answer:

elem.setAttribute("spellcheck", "false"); // Both string and boolean work here. 

Why shouldn't `&apos;` be used to escape single quotes?

&quot; is on the official list of valid HTML 4 entities, but &apos; is not.

From C.16. The Named Character Reference ':

The named character reference &apos; (the apostrophe, U+0027) was introduced in XML 1.0 but does not appear in HTML. Authors should therefore use &#39; instead of &apos; to work as expected in HTML 4 user agents.

Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

I found this solution for my project
I just set the minimum SDK version to 21 and that solves my problem

android {
    defaultConfig {
        ...
        minSdkVersion 21 //set the minimum sdk version 21
        targetSdkVersion 29
    }
    ...
}

if your minSdkVersion is 21 or higher multidex is enabled by default, and you do not need the multidex support library. To read more about multidex https://developer.android.com/studio/build/multidex.html

Getting android.content.res.Resources$NotFoundException: exception even when the resource is present in android

Make sure that the R you are pointing to is the correct one. I had a problem very similar to this, where an import got inserted by Eclipse that pointed to the System R file rather than the project one. It took a lot of head scratching. Hope this helps.

Java - Check if input is a positive integer, negative integer, natural number and so on.

If you really have to avoid operators then use Math.signum()

Returns the signum function of the argument; zero if the argument is zero, 1.0 if the argument is greater than zero, -1.0 if the argument is less than zero.

EDIT : As per the comments, this works for only double and float values. For integer values you can use the method:

Integer.signum(int i)

Binary Data Posting with curl

You don't need --header "Content-Length: $LENGTH".

curl --request POST --data-binary "@template_entry.xml" $URL

Note that GET request does not support content body widely.

Also remember that POST request have 2 different coding schema. This is first form:

  $ nc -l -p 6666 &
  $ curl  --request POST --data-binary "@README" http://localhost:6666

POST / HTTP/1.1
User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6
Host: localhost:6666
Accept: */*
Content-Length: 9309
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

.. -*- mode: rst; coding: cp1251; fill-column: 80 -*-
.. rst2html.py README README.html
.. contents::

You probably request this:

-F/--form name=content
           (HTTP) This lets curl emulate a filled-in form in
              which a user has pressed the submit button. This
              causes curl to POST data using the Content- Type
              multipart/form-data according to RFC2388. This
              enables uploading of binary files etc. To force the
              'content' part to be a file, prefix the file name
              with an @ sign. To just get the content part from a
              file, prefix the file name with the symbol <. The
              difference between @ and < is then that @ makes a
              file get attached in the post as a file upload,
              while the < makes a text field and just get the
              contents for that text field from a file.

Perl - Multiple condition if statement without duplicating code?

if (   ($name eq "tom" and $password eq "123!")
    or ($name eq "frank" and $password eq "321!")) {

    print "You have gained access.";
}
else {
    print "Access denied!";
}

Update ViewPager dynamically?

for those who still face the same problem which i faced before when i have a ViewPager with 7 fragments. the default for these fragments to load the English content from API service but the problem here that i want to change the language from settings activity and after finish settings activity i want ViewPager in main activity to refresh the fragments to match the language selection from the user and load the Arabic content if user chooses Arabic here what i did to work from the first time

1- You must use FragmentStatePagerAdapter as mentioned above.

2- on mainActivity i override the onResume and did the following

if (!(mPagerAdapter == null)) {
    mPagerAdapter.notifyDataSetChanged();
}

3-i overrided the getItemPosition() in mPagerAdapter and make it return POSITION_NONE.

@Override
public int getItemPosition(Object object) {
    return POSITION_NONE;
}

works like charm

Correct way to initialize empty slice

The two alternative you gave are semantically identical, but using make([]int, 0) will result in an internal call to runtime.makeslice (Go 1.14).

You also have the option to leave it with a nil value:

var myslice []int

As written in the Golang.org blog:

a nil slice is functionally equivalent to a zero-length slice, even though it points to nothing. It has length zero and can be appended to, with allocation.

A nil slice will however json.Marshal() into "null" whereas an empty slice will marshal into "[]", as pointed out by @farwayer.

None of the above options will cause any allocation, as pointed out by @ArmanOrdookhani.

Accessing localhost of PC from USB connected Android mobile device

How to Easily access LocalHost in Actual Android Device -> Connect your pc with the android device via USB

  1. Go to Chrome inspection click 'f12' or Control+Shift+C

Chrome Inspection tool

  1. Check the bottom of the chrome inspection tool.

  2. Now go to settings in Remote Device Tab.

Remote Devices Tab

  1. check on "Discover USB Device" option as well as check on "Port Forwarding" option.

  2. Now Click on Add Rules, Enter Any Device Port e.g(4880) and in Local Address Enter the Actual Address of the local host in my case e.g (127.0.0.1:480)

  3. After Adding the Rule go to your android studio -> inside your code URL(http://127.0.0.1:4880). Remember to change the port from 480 -> 4880.

  4. Go to Remote Device Tab in Chrome and Click on your connected Device. Add New URL(127.0.0.1:4880) Inspect the Android Device Chrome Browser

Check your Actual Device Chrome Browser and start Debugging the code on Actual Android device.

How to smooth a curve in the right way?

EDIT: look at this answer. Using np.cumsum is much faster than np.convolve

A quick and dirty way to smooth data I use, based on a moving average box (by convolution):

x = np.linspace(0,2*np.pi,100)
y = np.sin(x) + np.random.random(100) * 0.8

def smooth(y, box_pts):
    box = np.ones(box_pts)/box_pts
    y_smooth = np.convolve(y, box, mode='same')
    return y_smooth

plot(x, y,'o')
plot(x, smooth(y,3), 'r-', lw=2)
plot(x, smooth(y,19), 'g-', lw=2)

enter image description here

jQuery on window resize

Here's an example using jQuery, javascript and css to handle resize events.
(css if your best bet if you're just stylizing things on resize (media queries))
http://jsfiddle.net/CoryDanielson/LAF4G/

css

.footer 
{
    /* default styles applied first */
}

@media screen and (min-height: 820px) /* height >= 820 px */
{
    .footer {
        position: absolute;
        bottom: 3px;
        left: 0px;
        /* more styles */
    }
}

javascript

window.onresize = function() {
    if (window.innerHeight >= 820) { /* ... */ }
    if (window.innerWidth <= 1280) {  /* ... */ }
}

jQuery

$(window).on('resize', function(){
    var win = $(this); //this = window
    if (win.height() >= 820) { /* ... */ }
    if (win.width() >= 1280) { /* ... */ }
});

How do I stop my resize code from executing so often!?

This is the first problem you'll notice when binding to resize. The resize code gets called a LOT when the user is resizing the browser manually, and can feel pretty janky.

To limit how often your resize code is called, you can use the debounce or throttle methods from the underscore & lowdash libraries.

  • debounce will only execute your resize code X number of milliseconds after the LAST resize event. This is ideal when you only want to call your resize code once, after the user is done resizing the browser. It's good for updating graphs, charts and layouts that may be expensive to update every single resize event.
  • throttle will only execute your resize code every X number of milliseconds. It "throttles" how often the code is called. This isn't used as often with resize events, but it's worth being aware of.

If you don't have underscore or lowdash, you can implement a similar solution yourself: JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?

How can I declare a global variable in Angular 2 / Typescript?

I like the solution from @supercobra too. I just would like to improve it slightly. If you export an object which contains all the constants, you could simply use es6 import the module without using require.

I also used Object.freeze to make the properties become true constants. If you are interested in the topic, you could read this post.

// global.ts

 export const GlobalVariable = Object.freeze({
     BASE_API_URL: 'http://example.com/',
     //... more of your variables
 });

Refer the module using import.

//anotherfile.ts that refers to global constants
import { GlobalVariable } from './path/global';

export class HeroService {
    private baseApiUrl = GlobalVariable.BASE_API_URL;

    //... more code
}

Convert bytes to bits in python

Operations are much faster when you work at the integer level. In particular, converting to a string as suggested here is really slow.

If you want bit 7 and 8 only, use e.g.

val = (byte >> 6) & 3

(this is: shift the byte 6 bits to the right - dropping them. Then keep only the last two bits 3 is the number with the first two bits set...)

These can easily be translated into simple CPU operations that are super fast.

Is there shorthand for returning a default value if None in Python?

x or "default"

works best — i can even use a function call inline, without executing it twice or using extra variable:

self.lineEdit_path.setText( self.getDir(basepath) or basepath )

I use it when opening Qt's dialog.getExistingDirectory() and canceling, which returns empty string.

Centering the image in Bootstrap

Update 2018

Bootstrap 2.x

You could create a new CSS class such as:

.img-center {margin:0 auto;}

And then, add this to each IMG:

 <img src="images/2.png" class="img-responsive img-center">

OR, just override the .img-responsive if you're going to center all images..

 .img-responsive {margin:0 auto;}

Demo: http://bootply.com/86123

Bootstrap 3.x

EDIT - With the release of Bootstrap 3.0.1, the center-block class can now be used without any additional CSS..

 <img src="images/2.png" class="img-responsive center-block">

Bootstrap 4

In Bootstrap 4, the mx-auto class (auto x-axis margins) can be used to center images that are display:block. However, img is display:inline by default so text-center can be used on the parent.

<div class="container">
    <div class="row">
        <div class="col-12">
            <img class="mx-auto d-block" src="//placehold.it/200">  
        </div>
    </div>
    <div class="row">
        <div class="col-12 text-center">
            <img src="//placehold.it/200">  
        </div>
    </div>
</div>

Bootsrap 4 - center image demo

Django: Redirect to previous page after login

See django docs for views.login(), you supply a 'next' value (as a hidden field) on the input form to redirect to after a successful login.

Remove excess whitespace from within a string

If you want to replace only multiple spaces in a string, for Example: "this string have lots of space . " And you expect the answer to be "this string have lots of space", you can use the following solution:

$strng = "this string                        have lots of                        space  .   ";

$strng = trim(preg_replace('/\s+/',' ', $strng));

echo $strng;

UITableView set to static cells. Is it possible to hide some of the cells programmatically?

In > Swift 2.2, I've combined few answers here.

Make an outlet from storyboard to link to your staticCell.

@IBOutlet weak var updateStaticCell: UITableViewCell!

override func viewDidLoad() {
    ...
    updateStaticCell.hidden = true
}

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    if indexPath.row == 0 {
        return 0
    } else {
        return super.tableView(tableView, heightForRowAtIndexPath: indexPath)
    }
}

I want to hide my first cell so I set the height to 0 as described above.

How to group subarrays by a column value?

function array_group_by($arr, array $keys) {

if (!is_array($arr)) {
    trigger_error('array_group_by(): The first argument should be an array', E_USER_ERROR);
}
if (count($keys)==0) {
    trigger_error('array_group_by(): The Second argument Array can not be empty', E_USER_ERROR);
}

// Load the new array, splitting by the target key
$grouped = [];
foreach ($arr as $value) {
    $grouped[$value[$keys[0]]][] = $value;
}

// Recursively build a nested grouping if more parameters are supplied
// Each grouped array value is grouped according to the next sequential key
if (count($keys) > 1) {
        foreach ($grouped as $key => $value) {
       $parms = array_merge([$value], [array_slice($keys, 1,count($keys))]);
       $grouped[$key] = call_user_func_array('array_group_by', $parms);

    }
}
return $grouped;

}

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

With BeautifulStoneSoup gone in bs4, it's even simpler in Python3

from bs4 import BeautifulSoup

soup = BeautifulSoup(html)
text = soup.get_text()
print(text)

Remove URL parameters without refreshing page

if I have a special tag at the end of my URL like: http://domain.com/?tag=12345 Here is the below code to remove that tag whenever it presents in the URL:

<script>
// Remove URL Tag Parameter from Address Bar
if (window.parent.location.href.match(/tag=/)){
    if (typeof (history.pushState) != "undefined") {
        var obj = { Title: document.title, Url: window.parent.location.pathname };
        history.pushState(obj, obj.Title, obj.Url);
    } else {
        window.parent.location = window.parent.location.pathname;
    }
}
</script>

This gives the idea to remove one or more (or all) parameters from URL

With window.location.pathname you basically get everything before '?' in the url.

var pathname = window.location.pathname; // Returns path only

var url = window.location.href; // Returns full URL

Make code in LaTeX look *nice*

For simple document, I sometimes use verbatim, but listing is nice for big chunk of code.

How to display Base64 images in HTML?

This will show image of base 64 data:

<style>
.logo {
      width: 290px;
      height: 63px;
      background: url(data:image/png;base64,copy-paste-base64-data-here) no-repeat;
}
</style>

<div class="logo"></div>

Background color in input and text fields

You want to restrict to input fields that are of type text so use the selector input[type=text] rather than input (which will apply to all input fields (e.g. those of type submit as well)).

How can I make a multipart/form-data POST request using Java?

I found this sample in Apache's Quickstart Guide. It's for version 4.5:

/**
 * Example how to use multipart/form encoded POST request.
 */
public class ClientMultipartFormPost {

    public static void main(String[] args) throws Exception {
        if (args.length != 1)  {
            System.out.println("File path not given");
            System.exit(1);
        }
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPost httppost = new HttpPost("http://localhost:8080" +
                    "/servlets-examples/servlet/RequestInfoExample");

            FileBody bin = new FileBody(new File(args[0]));
            StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

            HttpEntity reqEntity = MultipartEntityBuilder.create()
                    .addPart("bin", bin)
                    .addPart("comment", comment)
                    .build();


            httppost.setEntity(reqEntity);

            System.out.println("executing request " + httppost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content length: " + resEntity.getContentLength());
                }
                EntityUtils.consume(resEntity);
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }
}

Output (echo/print) everything from a PHP Array

I think you are looking for print_r which will print out the array as text. You can't control the formatting though, it's more for debugging. If you want cool formatting you'll need to do it manually.

html5: display video inside canvas

You need to update currentTime video element and then draw the frame in canvas. Don't init play() event on the video.

You can also use for ex. this plugin https://github.com/tstabla/stVideo

Detect & Record Audio in Python

You might want to look at csounds, also. It has several API's, including Python. It might be able to interact with an A-D interface and gather sound samples.

How do I set <table> border width with CSS?

<table style="border: 5px solid black">

This only adds a border around the table.

If you want same border through CSS then add this rule:

table tr td { border: 5px solid black; }

and one thing for HTML table to avoid spaces

<table cellspacing="0" cellpadding="0">

How to find GCD, LCM on a set of numbers

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n0 = input.nextInt(); // number of intended input.
        int [] MyList = new int [n0];

        for (int i = 0; i < n0; i++)
            MyList[i] = input.nextInt();
            //input values stored in an array
        int i = 0;
        int count = 0;
            int gcd = 1; // Initial gcd is 1
            int k = 2; // Possible gcd
            while (k <= MyList[i] && k <= MyList[i]) {
                if (MyList[i] % k == 0 && MyList[i] % k == 0)
                    gcd = k; // Update gcd
                k++;
                count++; //checking array for gcd
            }
           // int i = 0;
            MyList [i] = gcd;
            for (int e: MyList) {
                System.out.println(e);

            }

            }

        }

What is the most compatible way to install python modules on a Mac?

You may already have pip3 pre-installed, so just try it!

Printing Batch file results to a text file

For showing result of batch file in text file, you can use

this command

chdir > test.txt

This command will redirect result to test.txt.

When you open test.txt you will found current path of directory in test.txt

failed to open stream: No such file or directory in

include() needs a full file path, relative to the file system's root directory.

This should work:

 include_once("C:/xampp/htdocs/PoliticalForum/headerSite.php");

Writing List of Strings to Excel CSV File in Python

I know I'm a little late, but something I found that works (and doesn't require using csv) is to write a for loop that writes to your file for every element in your list.

# Define Data
RESULTS = ['apple','cherry','orange','pineapple','strawberry']

# Open File
resultFyle = open("output.csv",'w')

# Write data to file
for r in RESULTS:
    resultFyle.write(r + "\n")
resultFyle.close()

I don't know if this solution is any better than the ones already offered, but it more closely reflects your original logic so I thought I'd share.

Removing duplicates in the lists

I didn't see answers for non-hashable values, one liner, n log n, standard-library only, so here's my answer:

list(map(operator.itemgetter(0), itertools.groupby(sorted(items))))

Or as a generator function:

def unique(items: Iterable[T]) -> Iterable[T]:
    """For unhashable items (can't use set to unique) with a partial order"""
    yield from map(operator.itemgetter(0), itertools.groupby(sorted(items)))

How to count objects in PowerShell?

@($output).Count does not always produce correct results. I used the ($output | Measure).Count method.

I found this with VMware Get-VmQuestion cmdlet:

$output = Get-VmQuestion -VM vm1
@($output).Count

The answer it gave is one, whereas

$output

produced no output (the correct answer was 0 as produced with the Measure method).

This only seemed to be the case with 0 and 1. Anything above 1 was correct with limited testing.

How to determine if .NET Core is installed

Great question, and the answer is not a simple one. There is no "show me all .net core versions" command, but there's hope.

EDIT:

I'm not sure when it was added, but the info command now includes this information in its output. It will print out the installed runtimes and SDKs, as well as some other info:

dotnet --info

If you only want to see the SDKs: dotnet --list-sdks

If you only want to see installed runtimes: dotnet --list-runtimes

I'm on Windows, but I'd guess that would work on Mac or Linux as well with a current version.

Also, you can reference the .NET Core Download Archive to help you decipher the SDK versions.


OLDER INFORMATION: Everything below this point is old information, which is less relevant, but may still be useful.

See installed Runtimes:

Open C:\Program Files\dotnet\shared\Microsoft.NETCore.App in Windows Explorer

See installed SDKs:

Open C:\Program Files\dotnet\sdk in Windows Explorer

(Source for the locations: A developer's blog)


In addition, you can see the latest Runtime and SDK versions installed by issuing these commands at the command prompt:

dotnet Latest Runtime version is the first thing listed. DISCLAIMER: This no longer works, but may work for older versions.

dotnet --version Latest SDK version DISCLAIMER: Apparently the result of this may be affected by any global.json config files.


On macOS you could check .net core version by using below command.

ls /usr/local/share/dotnet/shared/Microsoft.NETCore.App/

On Ubuntu or Alpine:

ls /usr/share/dotnet/shared/Microsoft.NETCore.App/

It will list down the folder with installed version name.

Is there a reason for C#'s reuse of the variable in a foreach?

The compiler declares the variable in a way that makes it highly prone to an error that is often difficult to find and debug, while producing no perceivable benefits.

Your criticism is entirely justified.

I discuss this problem in detail here:

Closing over the loop variable considered harmful

Is there something you can do with foreach loops this way that you couldn't if they were compiled with an inner-scoped variable? or is this just an arbitrary choice that was made before anonymous methods and lambda expressions were available or common, and which hasn't been revised since then?

The latter. The C# 1.0 specification actually did not say whether the loop variable was inside or outside the loop body, as it made no observable difference. When closure semantics were introduced in C# 2.0, the choice was made to put the loop variable outside the loop, consistent with the "for" loop.

I think it is fair to say that all regret that decision. This is one of the worst "gotchas" in C#, and we are going to take the breaking change to fix it. In C# 5 the foreach loop variable will be logically inside the body of the loop, and therefore closures will get a fresh copy every time.

The for loop will not be changed, and the change will not be "back ported" to previous versions of C#. You should therefore continue to be careful when using this idiom.

Find if value in column A contains value from column B?

You can use VLOOKUP, but this requires a wrapper function to return True or False. Not to mention it is (relatively) slow. Use COUNTIF or MATCH instead.

Fill down this formula in column K next to the existing values in column I (from I1 to I2691):

=COUNTIF(<entire column E range>,<single column I value>)>0
=COUNTIF($E$1:$E$99504,$I1)>0

You can also use MATCH:

=NOT(ISNA(MATCH(<single column I value>,<entire column E range>)))
=NOT(ISNA(MATCH($I1,$E$1:$E$99504,0)))

Git - What is the difference between push.default "matching" and "simple"

From GIT documentation: Git Docs

Below gives the full information. In short, simple will only push the current working branch and even then only if it also has the same name on the remote. This is a very good setting for beginners and will become the default in GIT 2.0

Whereas matching will push all branches locally that have the same name on the remote. (Without regard to your current working branch ). This means potentially many different branches will be pushed, including those that you might not even want to share.

In my personal usage, I generally use a different option: current which pushes the current working branch, (because I always branch for any changes). But for a beginner I'd suggest simple

push.default
Defines the action git push should take if no refspec is explicitly given. Different values are well-suited for specific workflows; for instance, in a purely central workflow (i.e. the fetch source is equal to the push destination), upstream is probably what you want. Possible values are:

nothing - do not push anything (error out) unless a refspec is explicitly given. This is primarily meant for people who want to avoid mistakes by always being explicit.

current - push the current branch to update a branch with the same name on the receiving end. Works in both central and non-central workflows.

upstream - push the current branch back to the branch whose changes are usually integrated into the current branch (which is called @{upstream}). This mode only makes sense if you are pushing to the same repository you would normally pull from (i.e. central workflow).

simple - in centralized workflow, work like upstream with an added safety to refuse to push if the upstream branch's name is different from the local one.

When pushing to a remote that is different from the remote you normally pull from, work as current. This is the safest option and is suited for beginners.

This mode will become the default in Git 2.0.

matching - push all branches having the same name on both ends. This makes the repository you are pushing to remember the set of branches that will be pushed out (e.g. if you always push maint and master there and no other branches, the repository you push to will have these two branches, and your local maint and master will be pushed there).

To use this mode effectively, you have to make sure all the branches you would push out are ready to be pushed out before running git push, as the whole point of this mode is to allow you to push all of the branches in one go. If you usually finish work on only one branch and push out the result, while other branches are unfinished, this mode is not for you. Also this mode is not suitable for pushing into a shared central repository, as other people may add new branches there, or update the tip of existing branches outside your control.

This is currently the default, but Git 2.0 will change the default to simple.

PHP MySQL Google Chart JSON - Complete Example

use this, it realy works:

data.addColumn no of your key, you can add more columns or remove

<?php
$con=mysql_connect("localhost","USername","Password") or die("Failed to connect with database!!!!");
mysql_select_db("Database Name", $con); 
// The Chart table contain two fields: Weekly_task and percentage
//this example will display a pie chart.if u need other charts such as Bar chart, u will need to change little bit to make work with bar chart and others charts
$sth = mysql_query("SELECT * FROM chart");

while($r = mysql_fetch_assoc($sth)) {
$arr2=array_keys($r);
$arr1=array_values($r);

}

for($i=0;$i<count($arr1);$i++)
{
    $chart_array[$i]=array((string)$arr2[$i],intval($arr1[$i]));
}
echo "<pre>";
$data=json_encode($chart_array);
?>

<html>
  <head>
    <!--Load the AJAX API-->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript">

    // Load the Visualization API and the piechart package.
    google.load('visualization', '1', {'packages':['corechart']});

    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);

    function drawChart() {

      // Create our data table out of JSON data loaded from server.
     var data = new google.visualization.DataTable();
        data.addColumn("string", "YEAR");
        data.addColumn("number", "NO of record");

        data.addRows(<?php $data ?>);

        ]); 
      var options = {
           title: 'My Weekly Plan',
          is3D: 'true',
          width: 800,
          height: 600
        };
      // Instantiate and draw our chart, passing in some options.
      //do not forget to check ur div ID
      var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }
    </script>
  </head>

  <body>
    <!--Div that will hold the pie chart-->
    <div id="chart_div"></div>
  </body>
</html>

Cache an HTTP 'Get' service response in AngularJS?

I think there's an even easier way now. This enables basic caching for all $http requests (which $resource inherits):

 var app = angular.module('myApp',[])
      .config(['$httpProvider', function ($httpProvider) {
            // enable http caching
           $httpProvider.defaults.cache = true;
      }])

'python3' is not recognized as an internal or external command, operable program or batch file

Python3.exe is not defined in windows

Specify the path for required version of python when you need to used it by creating virtual environment for your project

Python 3

virtualenv --python=C:\PATH_TO_PYTHON\python.exe environment

Python2

virtualenv --python=C:\PATH_TO_PYTHON\python.exe environment

then activate the environment using

.\environment\Scripts\activate.ps1

Get resultset from oracle stored procedure

Hi I know this was asked a while ago but I've just figured this out and it might help someone else. Not sure if this is exactly what you're looking for but this is how I call a stored proc and view the output using SQL Developer.
In SQL Developer when viewing the proc, right click and choose 'Run' or select Ctrl+F11 to bring up the Run PL/SQL window. This creates a template with the input and output params which you need to modify. My proc returns a sys_refcursor. The tricky part for me was declaring a row type that is exactly equivalent to the select stmt / sys_refcursor being returned by the proc:

DECLARE
  P_CAE_SEC_ID_N NUMBER;
  P_FM_SEC_CODE_C VARCHAR2(200);
  P_PAGE_INDEX NUMBER;
  P_PAGE_SIZE NUMBER;
  v_Return sys_refcursor;
  type t_row is record (CAE_SEC_ID NUMBER,FM_SEC_CODE VARCHAR2(7),rownum number, v_total_count number);
  v_rec t_row;

BEGIN
  P_CAE_SEC_ID_N := NULL;
  P_FM_SEC_CODE_C := NULL;
  P_PAGE_INDEX := 0;
  P_PAGE_SIZE := 25;

  CAE_FOF_SECURITY_PKG.GET_LIST_FOF_SECURITY(
    P_CAE_SEC_ID_N => P_CAE_SEC_ID_N,
    P_FM_SEC_CODE_C => P_FM_SEC_CODE_C,
    P_PAGE_INDEX => P_PAGE_INDEX,
    P_PAGE_SIZE => P_PAGE_SIZE,
    P_FOF_SEC_REFCUR => v_Return
  );
  -- Modify the code to output the variable
  -- DBMS_OUTPUT.PUT_LINE('P_FOF_SEC_REFCUR = ');
  loop
    fetch v_Return into v_rec;
    exit when v_Return%notfound;
    DBMS_OUTPUT.PUT_LINE('sec_id = ' || v_rec.CAE_SEC_ID || 'sec code = ' ||v_rec.FM_SEC_CODE);
  end loop;

END;

PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

Just an additional note - if the server runs on a port other than 80 (as might be common on a development/intranet machine) then HTTP_HOST contains the port, while SERVER_NAME does not.

$_SERVER['HTTP_HOST'] == 'localhost:8080'
$_SERVER['SERVER_NAME'] == 'localhost'

(At least that's what I've noticed in Apache port-based virtualhosts)

As Mike has noted below, HTTP_HOST does not contain :443 when running on HTTPS (unless you're running on a non-standard port, which I haven't tested).

What's the difference between "2*2" and "2**2" in Python?

Power has more precedence than multiply, so:

2**2*3 = (2^2)*3
2*2*3 = 2*2*3

Show a number to two decimal places

That's the same question I came across today and want to round a number and return float value up to a given decimal place and it must not be string (as returned from number_format) the answer is

echo sprintf('%.' . $decimalPlaces . 'f', round($number, $decimalPlaces));

How to create JSON string in JavaScript?

This can be pretty easy and simple

var obj = new Object();
obj.name = "Raj";
obj.age = 32;
obj.married = false;

//convert object to json string
var string = JSON.stringify(obj);

//convert string to Json Object
console.log(JSON.parse(string)); // this is your requirement.

How do you see recent SVN log entries?

Besides what Bert F said, many commands, including log has the -r (or --revision) option. The following are some practical examples using this option to show ranges of revisions:

To list everything in ascending order:

svn log -r 1:HEAD

To list everything in descending order:

svn log -r HEAD:1

To list everything from the thirteenth to the base of the currently checked-out revision in ascending order:

svn log -r 13:BASE

To get everything between the given dates:

svn log -r {2011-02-02}:{2011-02-03}

You can combine all the above expressions with the --limit option, so that can you have a quite granular control over what is printed. For more info about these -r expressions refer to svn help log or the relevant chapter in the book Version Control with Subversion

.includes() not working in Internet Explorer

includes() is not supported by most browsers. Your options are either to use

-polyfill from MDN https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes

or to use

-indexof()

var str = "abcde";
var n = str.indexOf("cd");

Which gives you n=2

This is widely supported.

What's the best CRLF (carriage return, line feed) handling strategy with Git?

Using core.autocrlf=false stopped all the files from being marked updated as soon as I checked them out in my Visual Studio 2010 project. The other two members of the development team are also using Windows systems so a mixed environment didn't come into play, yet the default settings that came with the repository always marked all files as updated immediately after cloning.

I guess the bottom line is to find what CRLF setting works for your environment. Especially since in many other repositories on our Linux boxes setting autocrlf = true produces better results.

20+ years later and we're still dealing with line ending disparities between OSes... sad.

Disable output buffering

It is possible to override only write method of sys.stdout with one that calls flush. Suggested method implementation is below.

def write_flush(args, w=stdout.write):
    w(args)
    stdout.flush()

Default value of w argument will keep original write method reference. After write_flush is defined, the original write might be overridden.

stdout.write = write_flush

The code assumes that stdout is imported this way from sys import stdout.

What does the 'standalone' directive mean in XML?

The intent of the standalone=yes declaration is to guarantee that the information inside the document can be faithfully retrieved based only on the internal DTD, i.e. the document can "stand alone" with no external references. Validating a standalone document ensures that non-validating processors will have all of the information available to correctly parse the document.

The standalone declaration serves no purpose if a document has no external DTD, and the internal DTD has no parameter entity references, as these documents are already implicitly standalone.

The following are the actual effects of using standalone=yes.

  • Forces processors to throw an error when parsing documents with an external DTD or parameter entity references, if the document contains references to entities not declared in the internal DTD (with the exception of replacement text of parameter entities as non-validating processors are not required to parse this); amp, lt, gt, apos, and quot are the only exceptions

  • When parsing a document not declared as standalone, a non-validating processor is free to stop parsing the internal DTD as soon as it encounters a parameter entity reference. Declaring a document as standalone forces non-validating processors to parse markup declarations in the internal DTD even after they ignore one or more parameter entity references.

  • Forces validating processors to throw an error if any of the following are found in the document, and their respective declarations are in the external DTD or in parameter entity replacement text:

    • attributes with default values, if they do not have their value explicitly provided
    • entity references (other than amp, lt, gt, apos, and quot)
    • attributes with tokenized types, if the value of the attribute would be modified by normalization
    • elements with element content, if any white space occurs in their content

A non-validating processor might consider retrieving the external DTD and expanding all parameter entity references for documents that are not standalone, even though it is under no obligation to do so, i.e. setting standalone=yes could theoretically improve performance for non-validating processors (spoiler alert: it probably won't make a difference).


The other answers here are either incomplete or incorrect, the main misconception is that

The standalone declaration is a way of telling the parser to ignore any markup declarations in the DTD. The DTD is thereafter used for validation only.

standalone="yes" means that the XML processor must use the DTD for validation only.

Quite the opposite, declaring a document as standalone will actually force a non-validating processor to parse internal declarations it must normally ignore (i.e. those after an ignored parameter entity reference). Non-validating processors must still use the info in the internal DTD to provide default attribute values and normalize tokenized attributes, as this is independent of validation.

How to get full width in body element

You should set body and html to position:fixed;, and then set right:, left:, top:, and bottom: to 0;. That way, even if content overflows it will not extend past the limits of the viewport.

For example:

<html>
<body>
    <div id="wrapper"></div>
</body>
</html>

CSS:

html, body, {
    position:fixed;
    top:0;
    bottom:0;
    left:0;
    right:0;
}

JS Fiddle Example

Caveat: Using this method, if the user makes their window smaller, content will be cut off.

Angular 2 'component' is not a known element

I have the same issue width php storm version 2017.3. This fix it for me: intellij support forum

It was an error width @angular language service: https://www.npmjs.com/package/@angular/language-service

How to remove specific object from ArrayList in Java?

List<Object> list = new ArrayList();
for (Iterator<Object> iterator = list.iterator(); iterator.hasNext();) {
  Object obj= iterator.next();
    if (obj.getId().equals("1")) {
       // Remove the current element from the iterator and the list.
       iterator.remove();
    }
}

File Permissions and CHMOD: How to set 777 in PHP upon file creation?

PHP has a built in function called bool chmod(string $filename, int $mode )

http://php.net/function.chmod

private function writeFileContent($file, $content){
    $fp = fopen($file, 'w');
    fwrite($fp, $content);
    fclose($fp);
    chmod($file, 0777);  //changed to add the zero
    return true;
}

How to make unicode string with python3

This how I solved my problem to convert chars like \uFE0F, \u000A, etc. And also emojis that encoded with 16 bytes.

example = 'raw vegan chocolate cocoa pie w chocolate &amp; vanilla cream\\uD83D\\uDE0D\\uD83D\\uDE0D\\u2764\\uFE0F Present Moment Caf\\u00E8 in St.Augustine\\u2764\\uFE0F\\u2764\\uFE0F '
import codecs
new_str = codecs.unicode_escape_decode(example)[0]
print(new_str)
>>> 'raw vegan chocolate cocoa pie w chocolate &amp; vanilla cream\ud83d\ude0d\ud83d\ude0d?? Present Moment Cafè in St.Augustine???? '
new_new_str = new_str.encode('utf-16', 'surrogatepass').decode('utf-16')
print(new_new_str)
>>> 'raw vegan chocolate cocoa pie w chocolate &amp; vanilla cream?? Present Moment Cafè in St.Augustine???? '

How to check whether a int is not null or empty?

An integer can't be null but there is a really simple way of doing what you want to do. Use an if-then statement in which you check the integer's value against all possible values.

Example:

int x;

// Some Code...

if (x <= 0 || x > 0){
    // What you want the code to do if x has a value
} else {
    // What you want the code to do if x has no value 
}

Disclaimer: I am assuming that Java does not automatically set values of numbers to 0 if it doesn't see a value.

Example using Hyperlink in WPF

IMHO the simplest way is to use new control inherited from Hyperlink:

/// <summary>
/// Opens <see cref="Hyperlink.NavigateUri"/> in a default system browser
/// </summary>
public class ExternalBrowserHyperlink : Hyperlink
{
    public ExternalBrowserHyperlink()
    {
        RequestNavigate += OnRequestNavigate;
    }

    private void OnRequestNavigate(object sender, RequestNavigateEventArgs e)
    {
        Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
        e.Handled = true;
    }
}

Angularjs $q.all

The issue seems to be that you are adding the deffered.promise when deffered is itself the promise you should be adding:

Try changing to promises.push(deffered); so you don't add the unwrapped promise to the array.

 UploadService.uploadQuestion = function(questions){

            var promises = [];

            for(var i = 0 ; i < questions.length ; i++){

                var deffered  = $q.defer();
                var question  = questions[i]; 

                $http({

                    url   : 'upload/question',
                    method: 'POST',
                    data  : question
                }).
                success(function(data){
                    deffered.resolve(data);
                }).
                error(function(error){
                    deffered.reject();
                });

                promises.push(deffered);
            }

            return $q.all(promises);
        }

Declaring functions in JSP?

You need to enclose that in <%! %> as follows:

<%!

public String getQuarter(int i){
String quarter;
switch(i){
        case 1: quarter = "Winter";
        break;

        case 2: quarter = "Spring";
        break;

        case 3: quarter = "Summer I";
        break;

        case 4: quarter = "Summer II";
        break;

        case 5: quarter = "Fall";
        break;

        default: quarter = "ERROR";
}

return quarter;
}

%>

You can then invoke the function within scriptlets or expressions:

<%
     out.print(getQuarter(4));
%>

or

<%= getQuarter(17) %>

How to discard uncommitted changes in SourceTree?

Do as follow,

  • Click on commit
  • Select all by pressing CMD+A that you want to delete or discard
  • Right click on the selected uncommitted files that you want to delete
  • Select Remove from the drop-down list

Sort an ArrayList based on an object field

You can use the Bean Comparator to sort on any property in your custom class.

How to fetch FetchType.LAZY associations with JPA and Hibernate in a Spring Controller

Though this is an old post, please consider using @NamedEntityGraph (Javax Persistence) and @EntityGraph (Spring Data JPA). The combination works.

Example

@Entity
@Table(name = "Employee", schema = "dbo", catalog = "ARCHO")
@NamedEntityGraph(name = "employeeAuthorities",
            attributeNodes = @NamedAttributeNode("employeeGroups"))
public class EmployeeEntity implements Serializable, UserDetails {
// your props
}

and then the spring repo as below

@RepositoryRestResource(collectionResourceRel = "Employee", path = "Employee")
public interface IEmployeeRepository extends PagingAndSortingRepository<EmployeeEntity, String>           {

    @EntityGraph(value = "employeeAuthorities", type = EntityGraphType.LOAD)
    EmployeeEntity getByUsername(String userName);

}

How to calculate rolling / moving average using NumPy / SciPy?

Here is a fast implementation using numba (mind the types). Note it does contain nans where shifted.

import numpy as np
import numba as nb

@nb.jit(nb.float64[:](nb.float64[:],nb.int64),
        fastmath=True,nopython=True)
def moving_average( array, window ):    
    ret = np.cumsum(array)
    ret[window:] = ret[window:] - ret[:-window]
    ma = ret[window - 1:] / window
    n = np.empty(window-1); n.fill(np.nan)
    return np.concatenate((n.ravel(), ma.ravel())) 

jQuery: more than one handler for same event

Made it work successfully using the 2 methods: Stephan202's encapsulation and multiple event listeners. I have 3 search tabs, let's define their input text id's in an Array:

var ids = new Array("searchtab1", "searchtab2", "searchtab3");

When the content of searchtab1 changes, I want to update searchtab2 and searchtab3. Did it this way for encapsulation:

for (var i in ids) {
    $("#" + ids[i]).change(function() {
        for (var j in ids) {
            if (this != ids[j]) {
                $("#" + ids[j]).val($(this).val());
            }
        }
    });
}

Multiple event listeners:

for (var i in ids) {
    for (var j in ids) {
        if (ids[i] != ids[j]) {
            $("#" + ids[i]).change(function() {
                $("#" + ids[j]).val($(this).val());
            });
        }
    }
}

I like both methods, but the programmer chose encapsulation, however multiple event listeners worked also. We used Chrome to test it.

Error :The remote server returned an error: (401) Unauthorized

The answers did help, but I think a full implementation of this will help a lot of people.

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace Dom
{
    class Dom
    {
        public static string make_Sting_From_Dom(string reportname)
        {
            try
            {
                WebClient client = new WebClient();
                client.Credentials = CredentialCache.DefaultCredentials;
                // Retrieve resource as a stream               
                Stream data = client.OpenRead(new Uri(reportname.Trim()));
                // Retrieve the text
                StreamReader reader = new StreamReader(data);
                string htmlContent = reader.ReadToEnd();
                string mtch = "TILDE";
                bool b = htmlContent.Contains(mtch);

                if (b)
                {
                    int index = htmlContent.IndexOf(mtch);
                    if (index >= 0)
                        Console.WriteLine("'{0} begins at character position {1}",
                        mtch, index + 1);
                }
                // Cleanup
                data.Close();
                reader.Close();
                return htmlContent;
            }
            catch (Exception)
            {
                throw;
            }
        }

        static void Main(string[] args)
        {
            make_Sting_From_Dom("https://www.w3.org/TR/PNG/iso_8859-1.txt");
        }
    }
}