Programs & Examples On #Jsr286

JSR 286 is the Java Portlet 2 specification.

How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?

One way I found after some struggling is creating a function which gets data_plot matrix, file name and order as parameter to create boxplots from the given data in the ordered figure (different orders = different figures) and save it under the given file_name.

def plotFigure(data_plot,file_name,order):
    fig = plt.figure(order, figsize=(9, 6))
    ax = fig.add_subplot(111)
    bp = ax.boxplot(data_plot)
    fig.savefig(file_name, bbox_inches='tight')
    plt.close()

Do Facebook Oauth 2.0 Access Tokens Expire?

After digging around a bit, i found this. It seems to be the answer:

Updated (11/April/2018)

  • The token will expire after about 60 days.
  • The token will be refreshed once per day, for up to 90 days, when the person using your app makes a request to Facebook's servers.
  • All access tokens need to be renewed every 90 days with the consent of the person using your app.

Facebook change announce (10/04/2018)

Facebook updated token expiration page (10/04/2018)

offline_access: Enables your application to perform authorized requests on behalf of the user at any time. By default, most access tokens expire after a short time period to ensure applications only make requests on behalf of the user when the are actively using the application. This permission makes the access token returned by our OAuth endpoint long-lived.

Its a permission value requested.

http://developers.facebook.com/docs/authentication/permissions

UPDATE

offline_access permission has been removed a while ago.

https://developers.facebook.com/docs/roadmap/completed-changes/offline-access-removal/

What is the difference between the operating system and the kernel?

The kernel is part of the operating system and closer to the hardware it provides low level services like:

  • device driver
  • process management
  • memory management
  • system calls

An operating system also includes applications like the user interface (shell, gui, tools, and services).

Can CSS detect the number of children an element has?

Clarification:

Because of a previous phrasing in the original question, a few SO citizens have raised concerns that this answer could be misleading. Note that, in CSS3, styles cannot be applied to a parent node based on the number of children it has. However, styles can be applied to the children nodes based on the number of siblings they have.


Original answer:

Incredibly, this is now possible purely in CSS3.

/* one item */
li:first-child:nth-last-child(1) {
/* -or- li:only-child { */
    width: 100%;
}

/* two items */
li:first-child:nth-last-child(2),
li:first-child:nth-last-child(2) ~ li {
    width: 50%;
}

/* three items */
li:first-child:nth-last-child(3),
li:first-child:nth-last-child(3) ~ li {
    width: 33.3333%;
}

/* four items */
li:first-child:nth-last-child(4),
li:first-child:nth-last-child(4) ~ li {
    width: 25%;
}

The trick is to select the first child when it's also the nth-from-the-last child. This effectively selects based on the number of siblings.

Credit for this technique goes to André Luís (discovered) & Lea Verou (refined).

Don't you just love CSS3?

CodePen Example:

Sources:

shell script to remove a file if it already exist

if [ $( ls <file> ) ]; then rm <file>; fi

Also, if you redirect your output with > instead of >> it will overwrite the previous file

How to get the selected item of a combo box to a string variable in c#

Test this

  var selected = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
  MessageBox.Show(selected);

Change URL parameters

2020 Solution: sets the variable or removes iti if you pass null or undefined to the value.

var setSearchParam = function(key, value) {
    if (!window.history.pushState) {
        return;
    }

    if (!key) {
        return;
    }

    var url = new URL(window.location.href);
    var params = new window.URLSearchParams(window.location.search);
    if (value === undefined || value === null) {
        params.delete(key);
    } else {
        params.set(key, value);
    }

    url.search = params;
    url = url.toString();
    window.history.replaceState({url: url}, null, url);
}

Why does "npm install" rewrite package-lock.json?

I've found that there will be a new version of npm 5.7.1 with the new command npm ci, that will install from package-lock.json only

The new npm ci command installs from your lock-file ONLY. If your package.json and your lock-file are out of sync then it will report an error.

It works by throwing away your node_modules and recreating it from scratch.

Beyond guaranteeing you that you'll only get what is in your lock-file it's also much faster (2x-10x!) than npm install when you don't start with a node_modules.

As you may take from the name, we expect it to be a big boon to continuous integration environments. We also expect that folks who do production deploys from git tags will see major gains.

How to generate classes from wsdl using Maven and wsimport?

Here is an example of how to generate classes from wsdl with jaxws maven plugin from a url or from a file location (from wsdl file location is commented).

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<build>  
    <plugins>           
        <!-- usage of jax-ws maven plugin-->
        <plugin> 
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>jaxws-maven-plugin</artifactId>
            <version>1.12</version>
            <executions> 
                <execution> 
                    <id>wsimport-from-jdk</id>
                    <goals>
                        <goal>wsimport</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <!-- using wsdl from an url -->
                <wsdlUrls>
                    <wsdlUrl>
                        http://myWSDLurl?wsdl
                    </wsdlUrl>
                </wsdlUrls>
                <!-- or using wsdls file directory -->
                    <!-- <wsdlDirectory>src/wsdl</wsdlDirectory> -->
                <!-- which wsdl file -->
                <!-- <wsdlFiles> -->
                    <!-- <wsdlFile>myWSDL.wsdl</wsdlFile> -->
                <!--</wsdlFiles> -->
                <!-- Keep generated files -->
                <keep>true</keep> 
                <!-- Package name --> 
                <packageName>com.organization.name</packageName> 
                <!-- generated source files destination-->
                <sourceDestDir>target/generatedclasses</sourceDestDir>
            </configuration>
        </plugin>
    </plugins>  
</build>  

sql: check if entry in table A exists in table B

This also works

SELECT *
FROM tableB
WHERE ID NOT IN (
  SELECT ID FROM tableA
);

Authentication plugin 'caching_sha2_password' cannot be loaded

Ok, wasted a lot of time on this so here is a summary as of 19 March 2019

If you are specifically trying to use a Docker image with MySql 8+, and then use SequelPro to access your database(s) running on that docker container, you are out of luck.

See the sequelpro issue 2699

My setup is sequelpro 1.1.2 using docker desktop 2.0.3.0 (mac - mojave), and tried using mysql:latest (v8.0.15).

As others have reported, using mysql 5.7 works with nothing required:

docker run -p 3306:3306 --name mysql1 -e MYSQL_ROOT_PASSWORD=secret -d mysql:5.7

Of course, it is possible to use MySql 8+ on docker, and in that situation (if needed), other answers provided here for caching_sha2_password type issues do work. But sequelpro is a NO GO with MySql 8+

Finally, I abandoned sequelpro (a trusted friend from back in 2013-2014) and instead installed DBeaver. Everything worked out of the box. For docker, I used:

docker run -p 3306:3306 --name mysql1 -e MYSQL_ROOT_PASSWORD=secret -d mysql:latest --default-authentication-plugin=mysql_native_password

You can quickly peek at the mysql databases using:

docker exec -it mysql1 bash

mysql -u root -p

show databases;

Replacing column values in a pandas DataFrame

I think that in answer should be pointed which type of object do you get in all methods suggested above: is it Series or DataFrame.

When you get column by w.female. or w[[2]] (where, suppose, 2 is number of your column) you'll get back DataFrame. So in this case you can use DataFrame methods like .replace.

When you use .loc or iloc you get back Series, and Series don't have .replace method, so you should use methods like apply, map and so on.

How do I release memory used by a pandas dataframe?

It seems there is an issue with glibc that affects the memory allocation in Pandas: https://github.com/pandas-dev/pandas/issues/2659

The monkey patch detailed on this issue has resolved the problem for me:

# monkeypatches.py

# Solving memory leak problem in pandas
# https://github.com/pandas-dev/pandas/issues/2659#issuecomment-12021083
import pandas as pd
from ctypes import cdll, CDLL
try:
    cdll.LoadLibrary("libc.so.6")
    libc = CDLL("libc.so.6")
    libc.malloc_trim(0)
except (OSError, AttributeError):
    libc = None

__old_del = getattr(pd.DataFrame, '__del__', None)

def __new_del(self):
    if __old_del:
        __old_del(self)
    libc.malloc_trim(0)

if libc:
    print('Applying monkeypatch for pd.DataFrame.__del__', file=sys.stderr)
    pd.DataFrame.__del__ = __new_del
else:
    print('Skipping monkeypatch for pd.DataFrame.__del__: libc or malloc_trim() not found', file=sys.stderr)

How can I force users to access my page over HTTPS instead of HTTP?

maybe this one can help, you, that's how I did for my website, it works like a charm :

$protocol = $_SERVER["HTTP_CF_VISITOR"];

if (!strstr($protocol, 'https')){
    header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
    exit();
}

Postgres FOR LOOP

I find it more convenient to make a connection using a procedural programming language (like Python) and do these types of queries.

import psycopg2
connection_psql = psycopg2.connect( user="admin_user"
                                  , password="***"
                                  , port="5432"
                                  , database="myDB"
                                  , host="[ENDPOINT]")
cursor_psql = connection_psql.cursor()

myList = [...]
for item in myList:
  cursor_psql.execute('''
    -- The query goes here
  ''')

connection_psql.commit()
cursor_psql.close()

SQL Server Profiler - How to filter trace to only display events from one database?

By experiment I was able to observe this:

When SQL Profiler 2005 or SQL Profiler 2000 is used with database residing in SQLServer 2000 - problem mentioned problem persists, but when SQL Profiler 2005 is used with SQLServer 2005 database, it works perfect!

In Summary, the issue seems to be prevalent in SQLServer 2000 & rectified in SQLServer 2005.

The solution for the issue when dealing with SQLServer 2000 is (as explained by wearejimbo)

  1. Identify the DatabaseID of the database you want to filter by querying the sysdatabases table as below

    SELECT * 
    FROM master..sysdatabases 
    WHERE name like '%your_db_name%'   -- Remove this line to see all databases
    ORDER BY dbid
    
  2. Use the DatabaseID Filter (instead of DatabaseName) in the New Trace window of SQL Profiler 2000

iframe to Only Show a Certain Part of the Page

I got this work good for me.

<div style="border: 3px solid rgb(201, 0, 1); overflow: hidden; margin: 15px auto; max-width: 736px;">
<iframe scrolling="no" src="http://www.w3schools.com/css/default.asp" style="border: 0px none; margin-left: -185px; height: 859px; margin-top: -533px; width: 926px;">
</iframe>
</div>

Is this working for you or not let us know.

Source: http://www.dimpost.com/2012/12/iframe-how-to-display-specific-part-of.html

How do I concatenate text in a query in sql server?

You might want to consider NULL values as well. In your example, if the column notes has a null value, then the resulting value will be NULL. If you want the null values to behave as empty strings (so that the answer comes out 'SomeText'), then use the IsNull function:

Select IsNull(Cast(notes as nvarchar(4000)),'') + 'SomeText' From NotesTable a

Encrypt and decrypt a string in C#?

To support mattmanser answer. Here's an example using MachineKey class to encrypt/decrypt URL safe values.

Something to bear in mind, as mentioned before, this will use Machine config settings (https://msdn.microsoft.com/en-us/library/ff649308.aspx). You can set encryption and decryption key/algorithm manually (you might need this specially if your site is running on multiple servers) in web.config file. You can generate keys from IIS (see here: https://blogs.msdn.microsoft.com/vijaysk/2009/05/13/iis-7-tip-10-you-can-generate-machine-keys-from-the-iis-manager/) or can use an online machine key generator like: http://www.developerfusion.com/tools/generatemachinekey/

    private static readonly UTF8Encoding Encoder = new UTF8Encoding();

    public static string Encrypt(string unencrypted)
    {
        if (string.IsNullOrEmpty(unencrypted)) 
            return string.Empty;

        try
        {
            var encryptedBytes = MachineKey.Protect(Encoder.GetBytes(unencrypted));

            if (encryptedBytes != null && encryptedBytes.Length > 0)
                return HttpServerUtility.UrlTokenEncode(encryptedBytes);    
        }
        catch (Exception)
        {
            return string.Empty;
        }

        return string.Empty;
    }

    public static string Decrypt(string encrypted)
    {
        if (string.IsNullOrEmpty(encrypted)) 
            return string.Empty;

        try
        {
            var bytes = HttpServerUtility.UrlTokenDecode(encrypted);
            if (bytes != null && bytes.Length > 0)
            {
                var decryptedBytes = MachineKey.Unprotect(bytes);
                if(decryptedBytes != null && decryptedBytes.Length > 0)
                    return Encoder.GetString(decryptedBytes);
            }

        }
        catch (Exception)
        {
            return string.Empty;
        }

        return string.Empty;
    }

Get Mouse Position

import java.awt.MouseInfo;
import java.awt.GridLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;

import javax.swing.*;

public class MyClass {
  public static void main(String[] args) throws InterruptedException{
    while(true){
      //Thread.sleep(100);
      System.out.println("(" + MouseInfo.getPointerInfo().getLocation().x + 
              ", " + 
              MouseInfo.getPointerInfo().getLocation().y + ")");
    }
  }
}

How do I empty an array in JavaScript?

If you need to keep the original array because you have other references to it that should be updated too, you can clear it without creating a new array by setting its length to zero:

A.length = 0;

Extracting an attribute value with beautifulsoup

For me:

<input id="color" value="Blue"/>

This can be fetched by below snippet.

page = requests.get("https://www.abcd.com")
soup = BeautifulSoup(page.content, 'html.parser')
colorName = soup.find(id='color')
print(color['value'])

What is the purpose and use of **kwargs?

In Java, you use constructors to overload classes and allow for multiple input parameters. In python, you can use kwargs to provide similar behavior.

java example: https://beginnersbook.com/2013/05/constructor-overloading/

python example:

class Robot():
    # name is an arg and color is a kwarg
    def __init__(self,name, color='red'):
        self.name = name
        self.color = color

red_robot = Robot('Bob')
blue_robot = Robot('Bob', color='blue')

print("I am a {color} robot named {name}.".format(color=red_robot.color, name=red_robot.name))
print("I am a {color} robot named {name}.".format(color=blue_robot.color, name=blue_robot.name))

>>> I am a red robot named Bob.
>>> I am a blue robot named Bob.

just another way to think about it.

Best Way to Refresh Adapter/ListView on Android

just write in your Custom ArrayAdaper this code:

public void swapItems(ArrayList<Item> arrayList) {
    this.clear();
    this.addAll(arrayList);
}

How can I include all JavaScript files in a directory via JavaScript file?

You can't do that in JavaScript, since JS is executed in the browser, not in the server, so it didn't know anything about directories or other server resources.

The best option is using a server side script like the one posted by jellyfishtree.

Calculating average of an array list?

If using Java8 you can get the average of the values from a List as follows:

    List<Integer> intList = Arrays.asList(1,2,2,3,1,5);

    Double average = intList.stream().mapToInt(val -> val).average().orElse(0.0);

This has the advantage of having no moving parts. It can be easily adapted to work with a List of other types of object by changing the map method call.

For example with Doubles:

    List<Double> dblList = Arrays.asList(1.1,2.1,2.2,3.1,1.5,5.3);
    Double average = dblList.stream().mapToDouble(val -> val).average().orElse(0.0);

NB. mapToDouble is required because it returns a DoubleStream which has an average method, while using map does not.

or BigDecimals:

@Test
public void bigDecimalListAveragedCorrectly() {
    List<BigDecimal> bdList = Arrays.asList(valueOf(1.1),valueOf(2.1),valueOf(2.2),valueOf(3.1),valueOf(1.5),valueOf(5.3));
    Double average = bdList.stream().mapToDouble(BigDecimal::doubleValue).average().orElse(0.0);
    assertEquals(2.55, average, 0.000001);
}

using orElse(0.0) removes problems with the Optional object returned from the average being 'not present'.

MySQL Workbench not opening on Windows

it might be due to running of xampp or wampp server stop all services running and try to open mysql command line

Install apps silently, with granted INSTALL_PACKAGES permission

I made a test app for silent installs, using PackageManager.installPackage method.

I get installPackage method through reflection, and made android.content.pm.IPackageInstallObserver interface in my src folder (because it's hidden in android.content.pm package).

When i run installPackage, i got SecurityException with string indication, that my app has no android.permission.INSTALL_PACKAGES, but it defined in AndroidManifest.xml.

So, i think, it's not possible to use this method.

PS. I tested in on Android SDK 2.3 and 4.0. Maybe it will work with earlier versions.

Java foreach loop: for (Integer i : list) { ... }

Another way, you can use a pass-through object to capture the last value and then do something with it:

List<Integer> list = new ArrayList<Integer>();
Integer lastValue = null;
for (Integer i : list) {
    // do stuff
    lastValue = i;
}
// do stuff with last value

How to properly validate input values with React.JS?

You can use npm install --save redux-form

Im writing a simple email and submit button form, which validates email and submits form. with redux-form, form by default runs event.preventDefault() on html onSubmit action.

import React, {Component} from 'react';
import {reduxForm} from 'redux-form';

class LoginForm extends Component {
  onSubmit(props) {
    //do your submit stuff
  }


  render() {
    const {fields: {email}, handleSubmit} = this.props;

    return (
      <form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
        <input type="text" placeholder="Email"
               className={`form-control ${email.touched && email.invalid ? 'has-error' : '' }`}
          {...email}
        />
          <span className="text-help">
            {email.touched ? email.error : ''}
          </span>
        <input type="submit"/>
      </form>
    );
  }
}

function validation(values) {
  const errors = {};
  const emailPattern = /(.+)@(.+){2,}\.(.+){2,}/;
  if (!emailPattern.test(values.email)) {
    errors.email = 'Enter a valid email';
  }

  return errors;
}

LoginForm = reduxForm({
  form: 'LoginForm',
  fields: ['email'],
  validate: validation
}, null, null)(LoginForm);

export default LoginForm;

Syntax for a single-line Bash infinite while loop

If you want the while loop to stop after some condition, and your foo command returns non-zero when this condition is met then you can get the loop to break like this:

while foo; do echo 'sleeping...'; sleep 5; done;

For example, if the foo command is deleting things in batches, and it returns 1 when there is nothing left to delete.

This works well if you have a custom script that needs to run a command many times until some condition. You write the script to exit with 1 when the condition is met and exit with 0 when it should be run again.

For example, say you have a python script batch_update.py which updates 100 rows in a database and returns 0 if there are more to update and 1 if there are no more. The the following command will allow you to update rows 100 at a time with sleeping for 5 seconds between updates:

while batch_update.py; do echo 'sleeping...'; sleep 5; done;

Commenting out code blocks in Atom

On an belgium keyboard asserted on the mac command + shift + / is the keystroke for commenting out a block.

How do I fix the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"?

You are debugging two or more times. so the application may run more at a time. Then only this issue will occur. You should close all debugging applications using task-manager, Then debug again.

How do I add 24 hours to a unix timestamp in php?

A Unix timestamp is simply the number of seconds since January the first 1970, so to add 24 hours to a Unix timestamp we just add the number of seconds in 24 hours. (24 * 60 *60)

time() + 24*60*60;

What is the cause for "angular is not defined"

I had the same problem as deke. I forgot to include the most important script: angular.js :)

<script type="text/javascript" src="bower_components/angular/angular.min.js"></script>

Error in Swift class: Property not initialized at super.init call

From the docs

Safety check 1

A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass initializer.


Why do we need a safety check like this?

To answer this lets go though the initialization process in swift.

Two-Phase Initialization

Class initialization in Swift is a two-phase process. In the first phase, each stored property is assigned an initial value by the class that introduced it. Once the initial state for every stored property has been determined, the second phase begins, and each class is given the opportunity to customize its stored properties further before the new instance is considered ready for use.

The use of a two-phase initialization process makes initialization safe, while still giving complete flexibility to each class in a class hierarchy. Two-phase initialization prevents property values from being accessed before they are initialized, and prevents property values from being set to a different value by another initializer unexpectedly.

So, to make sure the two step initialization process is done as defined above, there are four safety checks, one of them is,

Safety check 1

A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass initializer.

Now, the two phase initialization never talks about order, but this safety check, introduces super.init to be ordered, after the initialization of all the properties.

Safety check 1 might seem irrelevant as, Two-phase initialization prevents property values from being accessed before they are initialized can be satisfied, without this safety check 1.

Like in this sample

class Shape {
    var name: String
    var sides : Int
    init(sides:Int, named: String) {
        self.sides = sides
        self.name = named
    }
}

class Triangle: Shape {
    var hypotenuse: Int
    init(hypotenuse:Int) {
        super.init(sides: 3, named: "Triangle") 
        self.hypotenuse = hypotenuse
    }
}

Triangle.init has initialized, every property before being used. So Safety check 1 seems irrelevant,

But then there could be another scenario, a little bit complex,

class Shape {
    var name: String
    var sides : Int
    init(sides:Int, named: String) {
        self.sides = sides
        self.name = named
        printShapeDescription()
    }
    func printShapeDescription() {
        print("Shape Name :\(self.name)")
        print("Sides :\(self.sides)")
    }
}

class Triangle: Shape {
    var hypotenuse: Int
    init(hypotenuse:Int) {
        self.hypotenuse = hypotenuse
        super.init(sides: 3, named: "Triangle")
    }

    override func printShapeDescription() {
        super.printShapeDescription()
        print("Hypotenuse :\(self.hypotenuse)")
    }
}

let triangle = Triangle(hypotenuse: 12)

Output :

Shape Name :Triangle
Sides :3
Hypotenuse :12

Here if we had called the super.init before setting the hypotenuse, the super.init call would then have called the printShapeDescription() and since that has been overridden it would first fallback to Triangle class implementation of printShapeDescription(). The printShapeDescription() of Triangle class access the hypotenuse a non optional property that still has not been initialised. And this is not allowed as Two-phase initialization prevents property values from being accessed before they are initialized

So make sure the Two phase initialization is done as defined, there needs to be a specific order of calling super.init, and that is, after initializing all the properties introduced by self class, thus we need a Safety check 1

The way to check a HDFS directory's size?

hdfs dfs -count <dir>

info from man page:

-count [-q] [-h] [-v] [-t [<storage type>]] [-u] <path> ... :
  Count the number of directories, files and bytes under the paths
  that match the specified file pattern.  The output columns are:
  DIR_COUNT FILE_COUNT CONTENT_SIZE PATHNAME
  or, with the -q option:
  QUOTA REM_QUOTA SPACE_QUOTA REM_SPACE_QUOTA
        DIR_COUNT FILE_COUNT CONTENT_SIZE PATHNAME

How to map calculated properties with JPA and Hibernate

JPA doesn't offer any support for derived property so you'll have to use a provider specific extension. As you mentioned, @Formula is perfect for this when using Hibernate. You can use an SQL fragment:

@Formula("PRICE*1.155")
private float finalPrice;

Or even complex queries on other tables:

@Formula("(select min(o.creation_date) from Orders o where o.customer_id = id)")
private Date firstOrderDate;

Where id is the id of the current entity.

The following blog post is worth the read: Hibernate Derived Properties - Performance and Portability.

Without more details, I can't give a more precise answer but the above link should be helpful.

See also:

How do I create a new user in a SQL Azure database?

I found this link very helpful:
https://azure.microsoft.com/en-gb/documentation/articles/sql-database-manage-logins/

It details things like:
- Azure SQL Database subscriber account
- Using Azure Active Directory users to access the database
- Server-level principal accounts (unrestricted access)
- Adding users to the dbmanager database role

I used this and Stuart's answer to do the following:
On the master database (see link as to who has permissions on this):

CREATE LOGIN [MyAdmin] with password='ReallySecurePassword'

And then on the database in question:

CREATE USER [MyAdmin] FROM LOGIN [MyAdmin]
ALTER ROLE db_owner ADD MEMBER [MyAdmin]

You can also create users like this, according to the link:

CREATE USER [[email protected]] FROM EXTERNAL PROVIDER;

JPanel Padding in Java

Set an EmptyBorder around your JPanel.
Example:

JPanel p =new JPanel();
p.setBorder(new EmptyBorder(10, 10, 10, 10));

What's the difference between size_t and int in C++?

size_t is the type used to represent sizes (as its names implies). Its platform (and even potentially implementation) dependent, and should be used only for this purpose. Obviously, representing a size, size_t is unsigned. Many stdlib functions, including malloc, sizeof and various string operation functions use size_t as a datatype.

An int is signed by default, and even though its size is also platform dependant, it will be a fixed 32bits on most modern machine (and though size_t is 64 bits on 64-bits architecture, int remain 32bits long on those architectures).

To summarize : use size_t to represent the size of an object and int (or long) in other cases.

disable all form elements inside div

For jquery 1.6+, use .prop() instead of .attr(),

$("#parent-selector :input").prop("disabled", true);

or

$("#parent-selector :input").attr("disabled", "disabled");

How to get/generate the create statement for an existing hive table?

Steps to generate Create table DDLs for all the tables in the Hive database and export into text file to run later:

step 1)
create a .sh file with the below content, say hive_table_ddl.sh

#!/bin/bash
rm -f tableNames.txt
rm -f HiveTableDDL.txt
hive -e "use $1; show tables;" > tableNames.txt  
wait
cat tableNames.txt |while read LINE
   do
   hive -e "use $1;show create table $LINE;" >>HiveTableDDL.txt
   echo  -e "\n" >> HiveTableDDL.txt
   done
rm -f tableNames.txt
echo "Table DDL generated"

step 2)

Run the above shell script by passing 'db name' as paramanter

>bash hive_table_dd.sh <<databasename>>

output :

All the create table statements of your DB will be written into the HiveTableDDL.txt

How to specify test directory for mocha?

I had this problem just now and solved it by removing the --recursive option (which I had set) and using the same structure suggested above:

mochify "test/unit/**/*.js"

This ran all tests in all directories under /test/unit/ for me while ignoring the other directories within /test/

Excel - find cell with same value in another worksheet and enter the value to the left of it

The easiest way is probably with VLOOKUP(). This will require the 2nd worksheet to have the employee number column sorted though. In newer versions of Excel, apparently sorting is no longer required.

For example, if you had a "Sheet2" with two columns - A = the employee number, B = the employee's name, and your current worksheet had employee numbers in column D and you want to fill in column E, in cell E2, you would have:

=VLOOKUP($D2, Sheet2!$A$2:$B$65535, 2, FALSE)

Then simply fill this formula down the rest of column D.

Explanation:

  • The first argument $D2 specifies the value to search for.
  • The second argument Sheet2!$A$2:$B$65535 specifies the range of cells to search in. Excel will search for the value in the first column of this range (in this case Sheet2!A2:A65535). Note I am assuming you have a header cell in row 1.
  • The third argument 2 specifies a 1-based index of the column to return from within the searched range. The value of 2 will return the second column in the range Sheet2!$A$2:$B$65535, namely the value of the B column.
  • The fourth argument FALSE says to only return exact matches.

Sorting a list using Lambda/Linq to objects

Sort uses the IComparable interface, if the type implements it. And you can avoid the ifs by implementing a custom IComparer:

class EmpComp : IComparer<Employee>
{
    string fieldName;
    public EmpComp(string fieldName)
    {
        this.fieldName = fieldName;
    }

    public int Compare(Employee x, Employee y)
    {
        // compare x.fieldName and y.fieldName
    }
}

and then

list.Sort(new EmpComp(sortBy));

how to hide <li> bullets in navigation menu and footer links BUT show them for listing items

when bullet have to hide then use:

li { list-style: none;}

when bullet have to list show, then use:

li { list-style: initial;}

How to top, left justify text in a <td> cell that spans multiple rows

 <td rowspan="2" style="text-align:left;vertical-align:top;padding:0">Save a lot</td>

That should do it.

Not Able To Debug App In Android Studio

Check, if you're app-project is selected in the drop-down menu next to the debug-button. Sometimes Android Studio just resets this selection...

enter image description here

Overflow:hidden dots at the end

In bootstrap 4, you can add a .text-truncate class to truncate the text with an ellipsis.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>_x000D_
_x000D_
<!-- Inline level -->_x000D_
<span class="d-inline-block text-truncate" style="max-width: 190px;">_x000D_
  I like big butts and I cannot lie_x000D_
</span>
_x000D_
_x000D_
_x000D_

Maven error :Perhaps you are running on a JRE rather than a JDK?

For solving my issue on Linux don't have a JDK, I just download the JDK and upload to the Linux server, and type: tar xvf jdk-8u45-linux-x64.tar.gz

Split list into smaller lists (split in half)

This is similar to other solutions, but a little faster.

# Usage: split_half([1,2,3,4,5]) Result: ([1, 2], [3, 4, 5])

def split_half(a):
    half = len(a) >> 1
    return a[:half], a[half:]

How can you have SharePoint Link Lists default to opening in a new window?

You can edit the page in SharePoint designer, convert the List View web part to an XSLT Data View. (by right click + "Convert to XSLT Data View").
Then you can edit the XSLT - find the A tag and add an attribute target="_blank"

Counting unique values in a column in pandas dataframe like in Qlik?

If I assume data is the name of your dataframe, you can do :

data['race'].value_counts()

this will show you the distinct element and their number of occurence.

Styling an anchor tag to look like a submit button

The best you can get with simple styles would be something like:

.likeabutton {
    text-decoration: none; font: menu;
    display: inline-block; padding: 2px 8px;
    background: ButtonFace; color: ButtonText;
    border-style: solid; border-width: 2px;
    border-color: ButtonHighlight ButtonShadow ButtonShadow ButtonHighlight;
}
.likeabutton:active {
    border-color: ButtonShadow ButtonHighlight ButtonHighlight ButtonShadow;
}

(Possibly with some kind of fix to stop IE6-IE7 treating focused buttons as being ‘active’.)

This won't necessarily look exactly like the buttons on the native desktop, though; indeed, for many desktop themes it won't be possible to reproduce the look of a button in simple CSS.

However, you can ask the browser to use native rendering, which is best of all:

.likeabutton {
    appearance: button;
    -moz-appearance: button;
    -webkit-appearance: button;
    text-decoration: none; font: menu; color: ButtonText;
    display: inline-block; padding: 2px 8px;
}

Unfortunately, as you may have guessed from the browser-specific prefixes, this is a CSS3 feature that isn't suppoorted everywhere yet. In particular IE and Opera will ignore it. But if you include the other styles as backup, the browsers that do support appearance drop that property, preferring the explicit backgrounds and borders!

What you might do is use the appearance styles as above by default, and do JavaScript fixups as necessary, eg.:

<script type="text/javascript">
    var r= document.documentElement;
    if (!('appearance' in r || 'MozAppearance' in r || 'WebkitAppearance' in r)) {
        // add styles for background and border colours
        if (/* IE6 or IE7 */)
            // add mousedown, mouseup handlers to push the button in, if you can be bothered
        else
            // add styles for 'active' button
    }
</script>

Define preprocessor macro through CMake?

To do this for a specific target, you can do the following:

target_compile_definitions(my_target PRIVATE FOO=1 BAR=1)

You should do this if you have more than one target that you're building and you don't want them all to use the same flags. Also see the official documentation on target_compile_definitions.

How to find numbers from a string?

Based on @brettdj's answer using a VBScript regex ojbect with two modifications:

  • The function handles variants and returns a variant. That is, to take care of a null case; and
  • Uses explicit object creation, with a reference to the "Microsoft VBScript Regular Expressions 5.5" library
Function GetDigitsInVariant(inputVariant As Variant) As Variant
  ' Returns:
  '     Only the digits found in a varaint.
  ' Examples:
  '     GetDigitsInVariant(Null) => Null
  '     GetDigitsInVariant("") => ""
  '     GetDigitsInVariant(2021-/05-May/-18, Tue) => 20210518
  '     GetDigitsInVariant(2021-05-18) => 20210518
  ' Notes:
  '     If the inputVariant is null, null will be returned.
  '     If the inputVariant is "", "" will be returned.
  ' Usage:
  '     VBA IDE Menu > Tools > References ...
  '       > "Microsoft VBScript Regular Expressions 5.5" > [OK]

  ' With an explicit object reference to RegExp we can get intellisense
  ' and review the object heirarchy with the object browser
  ' (VBA IDE Menu > View > Object Browser).
  Dim regex As VBScript_RegExp_55.RegExp
  Set regex = New VBScript_RegExp_55.RegExp
  
  Dim result As Variant
  result = Null
  
  If IsNull(inputVariant) Then
    result = Null
    
  Else
    With regex
      .Global = True
      .Pattern = "[^\d]+"
      result = .Replace(inputVariant, vbNullString)
    End With
  End If
  
  GetDigitsInVariant = result
End Function

Testing:

Private Sub TestGetDigitsInVariant()
  Dim dateVariants As Variant
  dateVariants = Array(Null, "", "2021-/05-May/-18, Tue", _
          "2021-05-18", "18/05/2021", "3434 ..,sdf,sfd 444")
  
  Dim dateVariant As Variant
  For Each dateVariant In dateVariants
    Debug.Print dateVariant & ": ", , GetDigitsInVariant(dateVariant)
  Next dateVariant
  Debug.Print
End Sub

What are the -Xms and -Xmx parameters when starting JVM?

The question itself has already been addressed above. Just adding part of the default values.

As per http://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/jrdocs/refman/optionX.html

The default value of Xmx will depend on platform and amount of memory available in the system.

What's a "static method" in C#?

When you add a "static" keyword to a method, it means that underlying implementation gives the same result for any instance of the class. Needless to say, result varies with change in the value of parameters

How to add url parameter to the current url?

Maybe you can write a function as follows:

var addParams = function(key, val, url) {
  var arr = url.split('?');
  if(arr.length == 1) {
    return url + '?' + key + '=' + val;
  }
  else if(arr.length == 2) {
    var params = arr[1].split('&');
    var p = {};
    var a = [];
    var strarr = [];
    $.each(params, function(index, element) {
      a = element.split('=');
      p[a[0]] = a[1];
      })
    p[key] = val;
    for(var o in p) {
      strarr.push(o + '=' + p[o]);
    }
    var str = strarr.join('&');
    return(arr[0] + '?' + str);
  }
}

Error:attempt to apply non-function

I got the error because of a clumsy typo:

This errors:

knitr::opts_chunk$seet(echo = FALSE)

Error: attempt to apply non-function

After correcting the typo, it works:

knitr::opts_chunk$set(echo = FALSE)

IIS sc-win32-status codes

Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx

You can also use command line utility net to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code

How to view file diff in git before commit

git diff HEAD file

will show you changes you added to your worktree from the last commit. All the changes (staged or not staged) will be shown.

Does C have a string type?

There is no string type in C. You have to use char arrays.

By the way your code will not work ,because the size of the array should allow for the whole array to fit in plus one additional zero terminating character.

Python functions call by reference

class demoClass:
    x = 4
    y = 3
foo1 = demoClass()
foo1.x = 2
foo2 = demoClass()
foo2.y = 5
def mySquare(myObj):
    myObj.x = myObj.x**2
    myObj.y = myObj.y**2
print('foo1.x =', foo1.x)
print('foo1.y =', foo1.y)
print('foo2.x =', foo2.x)
print('foo2.y =', foo2.y)
mySquare(foo1)
mySquare(foo2)
print('After square:')
print('foo1.x =', foo1.x)
print('foo1.y =', foo1.y)
print('foo2.x =', foo2.x)
print('foo2.y =', foo2.y)

maximum value of int

I know it's an old question but maybe someone can use this solution:

int size = 0; // Fill all bits with zero (0)
size = ~size; // Negate all bits, thus all bits are set to one (1)

So far we have -1 as result 'till size is a signed int.

size = (unsigned int)size >> 1; // Shift the bits of size one position to the right.

As Standard says, bits that are shifted in are 1 if variable is signed and negative and 0 if variable would be unsigned or signed and positive.

As size is signed and negative we would shift in sign bit which is 1, which is not helping much, so we cast to unsigned int, forcing to shift in 0 instead, setting the sign bit to 0 while letting all other bits remain 1.

cout << size << endl; // Prints out size which is now set to maximum positive value.

We could also use a mask and xor but then we had to know the exact bitsize of the variable. With shifting in bits front, we don't have to know at any time how many bits the int has on machine or compiler nor need we include extra libraries.

What are queues in jQuery?

To understand queue method, you have to understand how jQuery does animation. If you write multiple animate method calls one after the other, jQuery creates an 'internal' queue and adds these method calls to it. Then it runs those animate calls one by one.

Consider following code.

function nonStopAnimation()
{
    //These multiple animate calls are queued to run one after
    //the other by jQuery.
    //This is the reason that nonStopAnimation method will return immeidately
    //after queuing these calls. 
    $('#box').animate({ left: '+=500'}, 4000);
    $('#box').animate({ top: '+=500'}, 4000);
    $('#box').animate({ left: '-=500'}, 4000);

    //By calling the same function at the end of last animation, we can
    //create non stop animation. 
    $('#box').animate({ top: '-=500'}, 4000 , nonStopAnimation);
}

The 'queue'/'dequeue' method gives you control over this 'animation queue'.

By default the animation queue is named 'fx'. I have created a sample page here which has various examples which will illustrate how the queue method could be used.

http://jsbin.com/zoluge/1/edit?html,output

Code for above sample page:

$(document).ready(function() {
    $('#nonStopAnimation').click(nonStopAnimation);

    $('#stopAnimationQueue').click(function() {
        //By default all animation for particular 'selector'
        //are queued in queue named 'fx'.
        //By clearning that queue, you can stop the animation.
        $('#box').queue('fx', []);
    });

    $('#addAnimation').click(function() {
        $('#box').queue(function() {
            $(this).animate({ height : '-=25'}, 2000);
            //De-queue our newly queued function so that queues
            //can keep running.
            $(this).dequeue();
        });
    });

    $('#stopAnimation').click(function() {
        $('#box').stop();
    });

    setInterval(function() {
        $('#currentQueueLength').html(
         'Current Animation Queue Length for #box ' + 
          $('#box').queue('fx').length
        );
    }, 2000);
});

function nonStopAnimation()
{
    //These multiple animate calls are queued to run one after
    //the other by jQuery.
    $('#box').animate({ left: '+=500'}, 4000);
    $('#box').animate({ top: '+=500'}, 4000);
    $('#box').animate({ left: '-=500'}, 4000);
    $('#box').animate({ top: '-=500'}, 4000, nonStopAnimation);
}

Now you may ask, why should I bother with this queue? Normally, you wont. But if you have a complicated animation sequence which you want to control, then queue/dequeue methods are your friend.

Also see this interesting conversation on jQuery group about creating a complicated animation sequence.

http://groups.google.com/group/jquery-en/browse_thread/thread/b398ad505a9b0512/f4f3e841eab5f5a2?lnk=gst

Demo of the animation:

http://www.exfer.net/test/jquery/tabslide/

Let me know if you still have questions.

How to declare and initialize a static const array as a class member?

You are mixing pointers and arrays. If what you want is an array, then use an array:

struct test {
   static int data[10];        // array, not pointer!
};
int test::data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

If on the other hand you want a pointer, the simplest solution is to write a helper function in the translation unit that defines the member:

struct test {
   static int *data;
};
// cpp
static int* generate_data() {            // static here is "internal linkage"
   int * p = new int[10];
   for ( int i = 0; i < 10; ++i ) p[i] = 10*i;
   return p;
}
int *test::data = generate_data();

Create Excel files from C# without office

There are a handful of options:

  • NPOI - Which is free and open source.
  • Aspose - Is definitely not free but robust.
  • Spreadsheet ML - Basically XML for creating spreadsheets.

Using the Interop will require that the Excel be installed on the machine from which it is running. In a server side solution, this will be awful. Instead, you should use a tool like the ones above that lets you build an Excel file without Excel being installed.

If the user does not have Excel but has a tool that will read Excel (like Open Office), then obviously they will be able to open it. Microsoft has a free Excel viewer available for those users that do not have Excel.

Adding a custom header to HTTP request using angular.js

And what's the answer from the server? It should reply a 204 and then really send the GET you are requesting.

In the OPTIONS the client is checking if the server allows CORS requests. If it gives you something different than a 204 then you should configure your server to send the correct Allow-Origin headers.

The way you are adding headers is the right way to do it.

How to crop an image using PIL?

You need to import PIL (Pillow) for this. Suppose you have an image of size 1200, 1600. We will crop image from 400, 400 to 800, 800

from PIL import Image
img = Image.open("ImageName.jpg")
area = (400, 400, 800, 800)
cropped_img = img.crop(area)
cropped_img.show()

How to skip a iteration/loop in while-loop

while(rs.next())
  {
    if(f.exists() && !f.isDirectory())
      continue;  //then skip the iteration

     else
     {
     //proceed
     }
  }

R memory management / cannot allocate vector of size n Mb

If you are running your script at linux environment you can use this command:

bsub -q server_name -R "rusage[mem=requested_memory]" "Rscript script_name.R"

and the server will allocate the requested memory for you (according to the server limits, but with good server - hugefiles can be used)

Create a sample login page using servlet and JSP?

You aren't really using the doGet() method. When you're opening the page, it issues a GET request, not POST.

Try changing doPost() to service() instead... then you're using the same method to handle GET and POST requests.

...

Best way to get application folder path

For a web application, to get the current web application root directory, generally call by web page for the current incoming request:

HttpContext.Current.Server.MapPath();

System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;

Above code description

Controlling mouse with Python

Quick and dirty function that'll left click wherever clicks times on Windows 7 using the ctypes library. No downloads required.

import ctypes

SetCursorPos = ctypes.windll.user32.SetCursorPos
mouse_event = ctypes.windll.user32.mouse_event

def left_click(x, y, clicks=1):
  SetCursorPos(x, y)
  for i in xrange(clicks):
   mouse_event(2, 0, 0, 0, 0)
   mouse_event(4, 0, 0, 0, 0)

left_click(200, 200) #left clicks at 200, 200 on your screen. Was able to send 10k clicks instantly.

Nested jQuery.each() - continue/break

Unfortunately no. The problem here is that the iteration happens inside functions, so they aren't like normal loops. The only way you can "break" out of a function is by returning or by throwing an exception. So yes, using a boolean flag seems to be the only reasonable way to "break" out of the outer "loop".

Maven plugins can not be found in IntelliJ

I had the same error and was able to get rid of it by deleting my old Maven settings file. Then I updated the Maven plugins manually using the mvn command:

mv ~/.m2/settings.xml ~/.m2/settings.xml.old
mvn -up

Finally I ran the "Reimport All Maven Projects" button in the Maven Project tab in IntelliJ. The errors vanished in my case.

Converting bool to text in C++

Use boolalpha to print bool to string.

std::cout << std::boolalpha << b << endl;
std::cout << std::noboolalpha << b << endl;

C++ Reference

Dynamic Web Module 3.0 -- 3.1

I had similar troubles in eclipse and the only way to fix it for me was to

  • Remove the web module
  • Apply
  • Change the module version
  • Add the module
  • Configure (Further configuration available link at the bottom of the dialog)
  • Apply

Just make sure you configure the web module before applying it as by default it will look for your web files in /WebContent/ and this is not what Maven project structure should be.

EDIT:

Here is a second way in case nothing else helps

  • Exit eclipse, go to your project in the file system, then to .settings folder.
  • Open the org.eclipse.wst.common.project.facet.core.xml , make backup, and remove the web module entry.
  • You can also modify the web module version there, but again, no guarantees.

#ifdef replacement in the Swift language

My two cents for Xcode 8:

a) A custom flag using the -D prefix works fine, but...

b) Simpler use:

In Xcode 8 there is a new section: "Active Compilation Conditions", already with two rows, for debug and release.

Simply add your define WITHOUT -D.

Default property value in React component using TypeScript

You can use the spread operator to re-assign props with a standard functional component. The thing I like about this approach is that you can mix required props with optional ones that have a default value.

interface MyProps {
   text: string;
   optionalText?: string;
}

const defaultProps = {
   optionalText = "foo";
}

const MyComponent = (props: MyProps) => {
   props = { ...defaultProps, ...props }
}

Why do we use __init__ in Python classes?

By what you wrote, you are missing a critical piece of understanding: the difference between a class and an object. __init__ doesn't initialize a class, it initializes an instance of a class or an object. Each dog has colour, but dogs as a class don't. Each dog has four or fewer feet, but the class of dogs doesn't. The class is a concept of an object. When you see Fido and Spot, you recognise their similarity, their doghood. That's the class.

When you say

class Dog:
    def __init__(self, legs, colour):
        self.legs = legs
        self.colour = colour

fido = Dog(4, "brown")
spot = Dog(3, "mostly yellow")

You're saying, Fido is a brown dog with 4 legs while Spot is a bit of a cripple and is mostly yellow. The __init__ function is called a constructor, or initializer, and is automatically called when you create a new instance of a class. Within that function, the newly created object is assigned to the parameter self. The notation self.legs is an attribute called legs of the object in the variable self. Attributes are kind of like variables, but they describe the state of an object, or particular actions (functions) available to the object.

However, notice that you don't set colour for the doghood itself - it's an abstract concept. There are attributes that make sense on classes. For instance, population_size is one such - it doesn't make sense to count the Fido because Fido is always one. It does make sense to count dogs. Let us say there're 200 million dogs in the world. It's the property of the Dog class. Fido has nothing to do with the number 200 million, nor does Spot. It's called a "class attribute", as opposed to "instance attributes" that are colour or legs above.

Now, to something less canine and more programming-related. As I write below, class to add things is not sensible - what is it a class of? Classes in Python make up of collections of different data, that behave similarly. Class of dogs consists of Fido and Spot and 199999999998 other animals similar to them, all of them peeing on lampposts. What does the class for adding things consist of? By what data inherent to them do they differ? And what actions do they share?

However, numbers... those are more interesting subjects. Say, Integers. There's a lot of them, a lot more than dogs. I know that Python already has integers, but let's play dumb and "implement" them again (by cheating and using Python's integers).

So, Integers are a class. They have some data (value), and some behaviours ("add me to this other number"). Let's show this:

class MyInteger:
    def __init__(self, newvalue)
        # imagine self as an index card.
        # under the heading of "value", we will write
        # the contents of the variable newvalue.
        self.value = newvalue
    def add(self, other):
        # when an integer wants to add itself to another integer,
        # we'll take their values and add them together,
        # then make a new integer with the result value.
        return MyInteger(self.value + other.value)

three = MyInteger(3)
# three now contains an object of class MyInteger
# three.value is now 3
five = MyInteger(5)
# five now contains an object of class MyInteger
# five.value is now 5
eight = three.add(five)
# here, we invoked the three's behaviour of adding another integer
# now, eight.value is three.value + five.value = 3 + 5 = 8
print eight.value
# ==> 8

This is a bit fragile (we're assuming other will be a MyInteger), but we'll ignore now. In real code, we wouldn't; we'd test it to make sure, and maybe even coerce it ("you're not an integer? by golly, you have 10 nanoseconds to become one! 9... 8....")

We could even define fractions. Fractions also know how to add themselves.

class MyFraction:
    def __init__(self, newnumerator, newdenominator)
        self.numerator = newnumerator
        self.denominator = newdenominator
        # because every fraction is described by these two things
    def add(self, other):
        newdenominator = self.denominator * other.denominator
        newnumerator = self.numerator * other.denominator + self.denominator * other.numerator
        return MyFraction(newnumerator, newdenominator)

There's even more fractions than integers (not really, but computers don't know that). Let's make two:

half = MyFraction(1, 2)
third = MyFraction(1, 3)
five_sixths = half.add(third)
print five_sixths.numerator
# ==> 5
print five_sixths.denominator
# ==> 6

You're not actually declaring anything here. Attributes are like a new kind of variable. Normal variables only have one value. Let us say you write colour = "grey". You can't have another variable named colour that is "fuchsia" - not in the same place in the code.

Arrays solve that to a degree. If you say colour = ["grey", "fuchsia"], you have stacked two colours into the variable, but you distinguish them by their position (0, or 1, in this case).

Attributes are variables that are bound to an object. Like with arrays, we can have plenty colour variables, on different dogs. So, fido.colour is one variable, but spot.colour is another. The first one is bound to the object within the variable fido; the second, spot. Now, when you call Dog(4, "brown"), or three.add(five), there will always be an invisible parameter, which will be assigned to the dangling extra one at the front of the parameter list. It is conventionally called self, and will get the value of the object in front of the dot. Thus, within the Dog's __init__ (constructor), self will be whatever the new Dog will turn out to be; within MyInteger's add, self will be bound to the object in the variable three. Thus, three.value will be the same variable outside the add, as self.value within the add.

If I say the_mangy_one = fido, I will start referring to the object known as fido with yet another name. From now on, fido.colour is exactly the same variable as the_mangy_one.colour.

So, the things inside the __init__. You can think of them as noting things into the Dog's birth certificate. colour by itself is a random variable, could contain anything. fido.colour or self.colour is like a form field on the Dog's identity sheet; and __init__ is the clerk filling it out for the first time.

Any clearer?

EDIT: Expanding on the comment below:

You mean a list of objects, don't you?

First of all, fido is actually not an object. It is a variable, which is currently containing an object, just like when you say x = 5, x is a variable currently containing the number five. If you later change your mind, you can do fido = Cat(4, "pleasing") (as long as you've created a class Cat), and fido would from then on "contain" a cat object. If you do fido = x, it will then contain the number five, and not an animal object at all.

A class by itself doesn't know its instances unless you specifically write code to keep track of them. For instance:

class Cat:
    census = [] #define census array

    def __init__(self, legs, colour):
        self.colour = colour
        self.legs = legs
        Cat.census.append(self)

Here, census is a class-level attribute of Cat class.

fluffy = Cat(4, "white")
spark = Cat(4, "fiery")
Cat.census
# ==> [<__main__.Cat instance at 0x108982cb0>, <__main__.Cat instance at 0x108982e18>]
# or something like that

Note that you won't get [fluffy, sparky]. Those are just variable names. If you want cats themselves to have names, you have to make a separate attribute for the name, and then override the __str__ method to return this name. This method's (i.e. class-bound function, just like add or __init__) purpose is to describe how to convert the object to a string, like when you print it out.

How do I get the width and height of a HTML5 canvas?

The answers mentioning canvas.width return the internal dimensions of the canvas, i.e. those specified when creating the element:

<canvas width="500" height="200">

If you size the canvas with CSS, its DOM dimensions are accessible via .scrollWidth and .scrollHeight:

_x000D_
_x000D_
var canvasElem = document.querySelector('canvas');_x000D_
document.querySelector('#dom-dims').innerHTML = 'Canvas DOM element width x height: ' +_x000D_
      canvasElem.scrollWidth +_x000D_
      ' x ' +_x000D_
      canvasElem.scrollHeight_x000D_
_x000D_
var canvasContext = canvasElem.getContext('2d');_x000D_
document.querySelector('#internal-dims').innerHTML = 'Canvas internal width x height: ' +_x000D_
      canvasContext.canvas.width +_x000D_
      ' x ' +_x000D_
      canvasContext.canvas.height;_x000D_
_x000D_
canvasContext.fillStyle = "#00A";_x000D_
canvasContext.fillText("Distorted", 0, 10);
_x000D_
<p id="dom-dims"></p>_x000D_
<p id="internal-dims"></p>_x000D_
<canvas style="width: 100%; height: 123px; border: 1px dashed black">
_x000D_
_x000D_
_x000D_

unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.9

The Mike R's solution works for me. This is the full set of commands:

Xvfb :99 -ac -screen 0 1280x1024x24 &
export DISPLAY=:99
nice -n 10 x11vnc 2>&1 &

Later you can run google-chrome:

google-chrome --no-sandbox &

Or start google chrome via selenium driver (for example):

ng e2e --serve true --port 4200 --watch true

Protractor.conf file:

capabilities: {
    'browserName': 'chrome',
    'chromeOptions': {
        'args': ['no-sandbox']
    }
},

What is the garbage collector in Java?

Garbage Collector is part of JRE that makes sure that object that are not referenced will be freed from memory.
It usually runs when you app runs out of memory. AFAIK it holds a graph that represents the links between the objects and isolated objects can be freed.
To save performance the current objects grouped into generations, each time GC scans an object and finds that it is still referenced its generation count incremented by 1 (to some max maximum value, 3 or 4 i think) , and the new generation are scanned first (the shortest the object in memory the more probably it is no longer needed) so not all objects being scanned every time GC run.
read this for more information.

Removing leading zeroes from a field in a SQL statement

select replace(replace(rtrim(replace(replace(replace(replace(ltrim(replace(replace([COLUMN],' ','[Ltrim]'),[Ltrim],' ')),' ',[Ltrim]),'[Ltrim]',' '),' ','[Rtrim]'),[Rtrim],' ')),' ',[Rtrim]),'[Rtrim]',' ') As Result

This is a Sql script that emulates the functionality of the TRIM command in tsql prior to 2017, its basically the same as the other recomendateions,but the others replace with a single uncommon character which still can occur, '[Rtrim]' or '[Ltrim]' could still occur in text, but replacing hat with a unique text, for example a Guid would solve that problem.

i havent tested it regarding speed

restrict edittext to single line

Using android:singleLine="true" is deprecated.

Just add your input type and set maxline to 1 and everything will work fine

android:inputType="text"
android:maxLines="1"

Add CSS to iFrame

Based on solution You've already found How to apply CSS to iframe?:

var cssLink = document.createElement("link") 
cssLink.href = "file://path/to/style.css"; 
cssLink .rel = "stylesheet"; 
cssLink .type = "text/css"; 
frames['iframe'].document.body.appendChild(cssLink);

or more jqueryish (from Append a stylesheet to an iframe with jQuery):

var $head = $("iframe").contents().find("head");                
$head.append($("<link/>", 
    { rel: "stylesheet", href: "file://path/to/style.css", type: "text/css" }));

as for security issues: Disabling same-origin policy in Safari

Where do I find the current C or C++ standard documents?

The ISO C and C++ standards are bloody expensive. On the other hand, the INCITS republishes them for a lot less. http://www.techstreet.com/ seems to have the PDF for $30 (search for INCITS/ISO/IEC 14882:2003).

Hardcopy versions are available, too. Look for the British Standards Institute versions, published by Wiley.

Programmatically change the src of an img tag

if you use the JQuery library use this instruction:

$("#imageID").attr('src', 'srcImage.jpg');

Is it possible to assign numeric value to an enum in Java?

Assuming that EXIT_CODE is referring to System . exit ( exit_code ) then you could do

enum ExitCode
{
      NORMAL_SHUTDOWN ( 0 ) , EMERGENCY_SHUTDOWN ( 10 ) , OUT_OF_MEMORY ( 20 ) , WHATEVER ( 30 ) ;

      private int value ;

      ExitCode ( int value )
      {
           this . value = value ;
      }

      public void exit ( )
      {
            System . exit ( value ) ;
      }
}

Then you can put the following at appropriate spots in your code

ExitCode . NORMAL_SHUTDOWN . exit ( ) '

Truncating long strings with CSS: feasible yet?

2014 March: Truncating long strings with CSS: a new answer with focus on browser support

Demo on http://jsbin.com/leyukama/1/ (I use jsbin because it supports old version of IE).

<style type="text/css">
    span {
        display: inline-block;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;     /** IE6+, Firefox 7+, Opera 11+, Chrome, Safari **/
        -o-text-overflow: ellipsis;  /** Opera 9 & 10 **/
        width: 370px; /* note that this width will have to be smaller to see the effect */
    }
</style>

<span>Some very long text that should be cut off at some point coz it's a bit too long and the text overflow ellipsis feature is used</span>

The -ms-text-overflow CSS property is not necessary: it is a synonym of the text-overflow CSS property, but versions of IE from 6 to 11 already support the text-overflow CSS property.

Successfully tested (on Browserstack.com) on Windows OS, for web browsers:

  • IE6 to IE11
  • Opera 10.6, Opera 11.1, Opera 15.0, Opera 20.0
  • Chrome 14, Chrome 20, Chrome 25
  • Safari 4.0, Safari 5.0, Safari 5.1
  • Firefox 7.0, Firefox 15

Firefox: as pointed out by Simon Lieschke (in another answer), Firefox only support the text-overflow CSS property from Firefox 7 onwards (released September 27th 2011).

I double checked this behavior on Firefox 3.0 & Firefox 6.0 (text-overflow is not supported).

Some further testing on a Mac OS web browsers would be needed.

Note: you may want to show a tooltip on mouse hover when an ellipsis is applied, this can be done via javascript, see this questions: HTML text-overflow ellipsis detection and HTML - how can I show tooltip ONLY when ellipsis is activated

Resources:

What are the default access modifiers in C#?

Class is Internal by default.

  • Class members are private by default.

Interface is Internal by default.

  • Interface members are public by default. (Interfaces won't allow us to specify any kind of accessibility to it's members.)

    Note: If you try to specify any access specifier to interface's members then, it shows compile error.

Struct is Internal by default.

  • Struct members are private by default.

How to add manifest permission to an application?

If you are using the Eclipse ADT plugin for your development, open AndroidManifest.xml in the Android Manifest Editor (should be the default action for opening AndroidManifest.xml from the project files list).

Afterwards, select the Permissions tab along the bottom of the editor (Manifest - Application - Permissions - Instrumentation - AndroidManifest.xml), then click Add... a Uses Permission and select the desired permission from the dropdown on the right, or just copy-paste in the necessary one (such as the android.permission.INTERNET permission you required).

How to show grep result with complete path or file name

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

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

Or on Linux:

cd /
grep -r somethingtosearch ~/temp

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

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

Is It Possible to NSLog C Structs (Like CGRect or CGPoint)?

NSLog(@"%@", CGRectCreateDictionaryRepresentation(rect));

Is it wrong to place the <script> tag after the </body> tag?

IE doesn't allow this anymore (since Version 10, I believe) and will ignore such scripts. FF and Chrome still tolerate them, but there are chances that some day they will drop this as non-standard.

filter items in a python dictionary where keys contain a specific string

How about a dict comprehension:

filtered_dict = {k:v for k,v in d.iteritems() if filter_string in k}

One you see it, it should be self-explanatory, as it reads like English pretty well.

This syntax requires Python 2.7 or greater.

In Python 3, there is only dict.items(), not iteritems() so you would use:

filtered_dict = {k:v for (k,v) in d.items() if filter_string in k}

Reset identity seed after deleting records in SQL Server

Reset identity column with new id...

DECLARE @MAX INT
SELECT @MAX=ISNULL(MAX(Id),0) FROM [TestTable]

DBCC CHECKIDENT ('[TestTable]', RESEED,@MAX)

How to troubleshoot an "AttributeError: __exit__" in multiproccesing in Python?

The reason behind this error is : Flask app is already running, hasn't shut down and in middle of that we try to start another instance by: with app.app_context(): #Code Before we use this with statement we need to make sure that scope of the previous running app is closed.

How to import multiple csv files in a single load?

Using Spark 2.0+, we can load multiple CSV files from different directories using df = spark.read.csv(['directory_1','directory_2','directory_3'.....], header=True). For more information, refer the documentation here

Check whether a string is not null and not empty

Just adding Android in here:

import android.text.TextUtils;

if (!TextUtils.isEmpty(str)) {
...
}

IntelliJ: Working on multiple projects

I am new to maven and did not understand how I could work with local maven project added through Viktor Nordling's answer and still have a proper dependency in pom.xml file. The answer is simple: intellij first looks at your locally added module and if it doesn't find one it goes to get the project remotely. You can check this by looking at "external libraries" under your project browser when you add or remove maven module.

Hope this helps anyone.

Bold & Non-Bold Text In A Single UILabel?

Update

In Swift we don't have to deal with iOS5 old stuff besides syntax is shorter so everything becomes really simple:

Swift 5

func attributedString(from string: String, nonBoldRange: NSRange?) -> NSAttributedString {
    let fontSize = UIFont.systemFontSize
    let attrs = [
        NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: fontSize),
        NSAttributedString.Key.foregroundColor: UIColor.black
    ]
    let nonBoldAttribute = [
        NSAttributedString.Key.font: UIFont.systemFont(ofSize: fontSize),
    ]
    let attrStr = NSMutableAttributedString(string: string, attributes: attrs)
    if let range = nonBoldRange {
        attrStr.setAttributes(nonBoldAttribute, range: range)
    }
    return attrStr
}

Swift 3

func attributedString(from string: String, nonBoldRange: NSRange?) -> NSAttributedString {
    let fontSize = UIFont.systemFontSize
    let attrs = [
        NSFontAttributeName: UIFont.boldSystemFont(ofSize: fontSize),
        NSForegroundColorAttributeName: UIColor.black
    ]
    let nonBoldAttribute = [
        NSFontAttributeName: UIFont.systemFont(ofSize: fontSize),
    ]
    let attrStr = NSMutableAttributedString(string: string, attributes: attrs)
    if let range = nonBoldRange {
        attrStr.setAttributes(nonBoldAttribute, range: range)
    }
    return attrStr
}

Usage:

let targetString = "Updated 2012/10/14 21:59 PM"
let range = NSMakeRange(7, 12)

let label = UILabel(frame: CGRect(x:0, y:0, width:350, height:44))
label.backgroundColor = UIColor.white
label.attributedText = attributedString(from: targetString, nonBoldRange: range)
label.sizeToFit()

Bonus: Internationalisation

Some people commented about internationalisation. I personally think this is out of scope of this question but for instructional purposes this is how I would do it

// Date we want to show
let date = Date()

// Create the string.
// I don't set the locale because the default locale of the formatter is `NSLocale.current` so it's good for internationalisation :p
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .short
let targetString = String(format: NSLocalizedString("Update %@", comment: "Updated string format"),
                          formatter.string(from: date))

// Find the range of the non-bold part
formatter.timeStyle = .none
let nonBoldRange = targetString.range(of: formatter.string(from: date))

// Convert Range<Int> into NSRange
let nonBoldNSRange: NSRange? = nonBoldRange == nil ?
    nil :
    NSMakeRange(targetString.distance(from: targetString.startIndex, to: nonBoldRange!.lowerBound),
                targetString.distance(from: nonBoldRange!.lowerBound, to: nonBoldRange!.upperBound))

// Now just build the attributed string as before :)
label.attributedText = attributedString(from: targetString,
                                        nonBoldRange: nonBoldNSRange)

Result (Assuming English and Japanese Localizable.strings are available)

enter image description here

enter image description here


Previous answer for iOS6 and later (Objective-C still works):

In iOS6 UILabel, UIButton, UITextView, UITextField, support attributed strings which means we don't need to create CATextLayers as our recipient for attributed strings. Furthermore to make the attributed string we don't need to play with CoreText anymore :) We have new classes in obj-c Foundation.framework like NSParagraphStyle and other constants that will make our life easier. Yay!

So, if we have this string:

NSString *text = @"Updated: 2012/10/14 21:59"

We only need to create the attributed string:

if ([_label respondsToSelector:@selector(setAttributedText:)])
{
    // iOS6 and above : Use NSAttributedStrings

    // Create the attributes
    const CGFloat fontSize = 13;
    NSDictionary *attrs = @{
        NSFontAttributeName:[UIFont boldSystemFontOfSize:fontSize],
        NSForegroundColorAttributeName:[UIColor whiteColor]
    };
    NSDictionary *subAttrs = @{
        NSFontAttributeName:[UIFont systemFontOfSize:fontSize]
    };

    // Range of " 2012/10/14 " is (8,12). Ideally it shouldn't be hardcoded
    // This example is about attributed strings in one label
    // not about internationalisation, so we keep it simple :)
    // For internationalisation example see above code in swift
    const NSRange range = NSMakeRange(8,12);

    // Create the attributed string (text + attributes)
    NSMutableAttributedString *attributedText =
      [[NSMutableAttributedString alloc] initWithString:text
                                             attributes:attrs];
    [attributedText setAttributes:subAttrs range:range];

    // Set it in our UILabel and we are done!
    [_label setAttributedText:attributedText];
} else {
    // iOS5 and below
    // Here we have some options too. The first one is to do something
    // less fancy and show it just as plain text without attributes.
    // The second is to use CoreText and get similar results with a bit
    // more of code. Interested people please look down the old answer.

    // Now I am just being lazy so :p
    [_label setText:text];
}

There is a couple of good introductory blog posts here from guys at invasivecode that explain with more examples uses of NSAttributedString, look for "Introduction to NSAttributedString for iOS 6" and "Attributed strings for iOS using Interface Builder" :)

PS: Above code it should work but it was brain-compiled. I hope it is enough :)


Old Answer for iOS5 and below

Use a CATextLayer with an NSAttributedString ! much lighter and simpler than 2 UILabels. (iOS 3.2 and above)

Example.

Don't forget to add QuartzCore framework (needed for CALayers), and CoreText (needed for the attributed string.)

#import <QuartzCore/QuartzCore.h>
#import <CoreText/CoreText.h>

Below example will add a sublayer to the toolbar of the navigation controller. à la Mail.app in the iPhone. :)

- (void)setRefreshDate:(NSDate *)aDate
{
    [aDate retain];
    [refreshDate release];
    refreshDate = aDate;

    if (refreshDate) {

        /* Create the text for the text layer*/    
        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        [df setDateFormat:@"MM/dd/yyyy hh:mm"];

        NSString *dateString = [df stringFromDate:refreshDate];
        NSString *prefix = NSLocalizedString(@"Updated", nil);
        NSString *text = [NSString stringWithFormat:@"%@: %@",prefix, dateString];
        [df release];

        /* Create the text layer on demand */
        if (!_textLayer) {
            _textLayer = [[CATextLayer alloc] init];
            //_textLayer.font = [UIFont boldSystemFontOfSize:13].fontName; // not needed since `string` property will be an NSAttributedString
            _textLayer.backgroundColor = [UIColor clearColor].CGColor;
            _textLayer.wrapped = NO;
            CALayer *layer = self.navigationController.toolbar.layer; //self is a view controller contained by a navigation controller
            _textLayer.frame = CGRectMake((layer.bounds.size.width-180)/2 + 10, (layer.bounds.size.height-30)/2 + 10, 180, 30);
            _textLayer.contentsScale = [[UIScreen mainScreen] scale]; // looks nice in retina displays too :)
            _textLayer.alignmentMode = kCAAlignmentCenter;
            [layer addSublayer:_textLayer];
        }

        /* Create the attributes (for the attributed string) */
        CGFloat fontSize = 13;
        UIFont *boldFont = [UIFont boldSystemFontOfSize:fontSize];
        CTFontRef ctBoldFont = CTFontCreateWithName((CFStringRef)boldFont.fontName, boldFont.pointSize, NULL);
        UIFont *font = [UIFont systemFontOfSize:13];
        CTFontRef ctFont = CTFontCreateWithName((CFStringRef)font.fontName, font.pointSize, NULL);
        CGColorRef cgColor = [UIColor whiteColor].CGColor;
        NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                    (id)ctBoldFont, (id)kCTFontAttributeName,
                                    cgColor, (id)kCTForegroundColorAttributeName, nil];
        CFRelease(ctBoldFont);
        NSDictionary *subAttributes = [NSDictionary dictionaryWithObjectsAndKeys:(id)ctFont, (id)kCTFontAttributeName, nil];
        CFRelease(ctFont);

        /* Create the attributed string (text + attributes) */
        NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:text attributes:attributes];
        [attrStr addAttributes:subAttributes range:NSMakeRange(prefix.length, 12)]; //12 is the length of " MM/dd/yyyy/ "

        /* Set the attributes string in the text layer :) */
        _textLayer.string = attrStr;
        [attrStr release];

        _textLayer.opacity = 1.0;
    } else {
        _textLayer.opacity = 0.0;
        _textLayer.string = nil;
    }
}

In this example I only have two different types of font (bold and normal) but you could also have different font size, different color, italics, underlined, etc. Take a look at NSAttributedString / NSMutableAttributedString and CoreText attributes string keys.

Hope it helps

Excel VBA Code: Compile Error in x64 Version ('PtrSafe' attribute required)

I'm quite sure you won't get this 32Bit DLL working in Office 64Bit. The DLL needs to be updated by the author to be compatible with 64Bit versions of Office.

The code changes you have found and supplied in the question are used to convert calls to APIs that have already been rewritten for Office 64Bit. (Most Windows APIs have been updated.)

From: http://technet.microsoft.com/en-us/library/ee681792.aspx:

"ActiveX controls and add-in (COM) DLLs (dynamic link libraries) that were written for 32-bit Office will not work in a 64-bit process."

Edit: Further to your comment, I've tried the 64Bit DLL version on Win 8 64Bit with Office 2010 64Bit. Since you are using User Defined Functions called from the Excel worksheet you are not able to see the error thrown by Excel and just end up with the #VALUE returned.

If we create a custom procedure within VBA and try one of the DLL functions we see the exact error thrown. I tried a simple function of swe_day_of_week which just has a time as an input and I get the error Run-time error '48' File not found: swedll32.dll.

Now I have the 64Bit DLL you supplied in the correct locations so it should be found which suggests it has dependencies which cannot be located as per https://stackoverflow.com/a/8607250/1733206

I've got all the .NET frameworks installed which would be my first guess, so without further information from the author it might be difficult to find the problem.

Edit2: And after a bit more investigating it appears the 64Bit version you have supplied is actually a 32Bit version. Hence the error message on the 64Bit Office. You can check this by trying to access the '64Bit' version in Office 32Bit.

Python regex to match dates

I use something like this

>>> import datetime
>>> regex = datetime.datetime.strptime
>>>
>>> # TEST
>>> assert regex('2020-08-03', '%Y-%m-%d')
>>>

>>> assert regex('2020-08', '%Y-%m-%d')
ValueError: time data '2020-08' does not match format '%Y-%m-%d'

>>> assert regex('08/03/20', '%m/%d/%y')
>>>

>>> assert regex('08-03-2020', '%m/%d/%y')
ValueError: time data '08-03-2020' does not match format '%m/%d/%y'

Pass a reference to DOM object with ng-click

The angular way is shown in the angular docs :)

https://docs.angularjs.org/api/ng/directive/ngReadonly

Here is the example they use:

<body>
    Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
    <input type="text" ng-readonly="checked" value="I'm Angular"/>
</body>

Basically the angular way is to create a model object that will hold whether or not the input should be readonly and then set that model object accordingly. The beauty of angular is that most of the time you don't need to do any dom manipulation. You just have angular render the view they way your model is set (let angular do the dom manipulation for you and keep your code clean).

So basically in your case you would want to do something like below or check out this working example.

<button ng-click="isInput1ReadOnly = !isInput1ReadOnly">Click Me</button>
<input type="text" ng-readonly="isInput1ReadOnly" value="Angular Rules!"/>

Add a prefix string to beginning of each line

Using & (the whole part of the input that was matched by the pattern”):

cat in.txt | sed -e "s/.*/prefix&/" > out.txt

OR using back references:

cat in.txt | sed -e "s/\(.*\)/prefix\1/" > out.txt

Any free WPF themes?

You might want to try www.reuxables.com - we have both commercial and free themes, and it is the largest and most diverse theme library for WPF.

Get git branch name in Jenkins Pipeline/Jenkinsfile

For me this worked: (using Jenkins 2.150, using simple Pipeline type - not multibranch, my branch specifier: '**')

echo 'Pulling... ' + env.GIT_BRANCH

Output:

Pulling... origin/myBranch

where myBranch is the name of the feature branch

Setting up Gradle for api 26 (Android)

Appears to be resolved by Android Studio 3.0 Canary 4 and Gradle 3.0.0-alpha4.

How to extract the substring between two markers?

Surprised that nobody has mentioned this which is my quick version for one-off scripts:

>>> x = 'gfgfdAAA1234ZZZuijjk'
>>> x.split('AAA')[1].split('ZZZ')[0]
'1234'

UIScrollView not scrolling

If your scrollView is a subview of a containerView of some type, then make sure that your scrollView is within the frame or bounds of the containerView. I had containerView.clipsToBounds = NO which still allowed me see the scrollView, but because scrollView wasn't within the bounds of containerView it wouldn't detect touch events.

For example:

containerView.frame = CGRectMake(0, 0, 200, 200);
scrollView.frame = CGRectMake(0, 200, 200, 200);
[containerView addSubview:scrollView];
scrollView.userInteractionEnabled = YES;

You will be able to see the scrollView but it won't receive user interactions.

How do we control web page caching, across all browsers?

The headers in the answer provided by BalusC does not prevent Safari 5 (and possibly older versions as well) from displaying content from the browser cache when using the browser's back button. A way to prevent this is to add an empty onunload event handler attribute to the body tag:

<body onunload=""> 

This hack apparently breaks the back-forward cache in Safari: Is there a cross-browser onload event when clicking the back button?

java doesn't run if structure inside of onclick listener

both your conditions are the same:

if(s < f) {     calc = f - s;     n = s; }else if(f > s){     calc =  s - f;     n = f;  } 

so

if(s < f)   

and

}else if(f > s){ 

are the same

change to

}else if(f < s){ 

Laravel - Session store not set on request

In my case (using Laravel 5.3) adding only the following 2 middleware allowed me to access session data in my API routes:

  • \App\Http\Middleware\EncryptCookies::class
  • \Illuminate\Session\Middleware\StartSession::class

Whole declaration ($middlewareGroups in Kernel.php):

'api' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Session\Middleware\StartSession::class,
            'throttle:60,1',
            'bindings',
        ],

How to set shadows in React Native for android?

for an android screen you can use this property elevation.

for example :

 HeaderView:{
    backgroundColor:'#F8F8F8',
    justifyContent:'center',
    alignItems:'center',
    height:60,
    paddingTop:15,

    //Its for IOS
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.2,

    // its for android 
    elevation: 5,
    position:'relative',

},

How to find schema name in Oracle ? when you are connected in sql session using read only user

How about the following 3 statements?

-- change to your schema

ALTER SESSION SET CURRENT_SCHEMA=yourSchemaName;

-- check current schema

SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL;

-- generate drop table statements

SELECT 'drop table ', table_name, 'cascade constraints;' FROM ALL_TABLES WHERE OWNER = 'yourSchemaName';

COPY the RESULT and PASTE and RUN.

Can you use a trailing comma in a JSON object?

According to the Class JSONArray specification:

  • An extra , (comma) may appear just before the closing bracket.
  • The null value will be inserted when there is , (comma) elision.

So, as I understand it, it should be allowed to write:

[0,1,2,3,4,5,]

But it could happen that some parsers will return the 7 as item count (like IE8 as Daniel Earwicker pointed out) instead of the expected 6.


Edited:

I found this JSON Validator that validates a JSON string against RFC 4627 (The application/json media type for JavaScript Object Notation) and against the JavaScript language specification. Actually here an array with a trailing comma is considered valid just for JavaScript and not for the RFC 4627 specification.

However, in the RFC 4627 specification is stated that:

2.3. Arrays

An array structure is represented as square brackets surrounding zero or more values (or elements). Elements are separated by commas.

array = begin-array [ value *( value-separator value ) ] end-array

To me this is again an interpretation problem. If you write that Elements are separated by commas (without stating something about special cases, like the last element), it could be understood in both ways.

P.S. RFC 4627 isn't a standard (as explicitly stated), and is already obsolited by RFC 7159 (which is a proposed standard) RFC 7159

str_replace with array

Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements.

    // Outputs F because A is replaced with B, then B is replaced with C, and so on...
    // Finally E is replaced with F, because of left to right replacements.
    $search  = array('A', 'B', 'C', 'D', 'E');
    $replace = array('B', 'C', 'D', 'E', 'F');
    $subject = 'A';
    echo str_replace($search, $replace, $subject);

Python Progress Bar

I like Gabriel answer, but i changed it to be flexible. You can send bar-length to the function and get your progress bar with any length that you want. And you can't have a progress bar with zero or negative length. Also, you can use this function like Gabriel answer (Look at the Example #2).

import sys
import time

def ProgressBar(Total, Progress, BarLength=20, ProgressIcon="#", BarIcon="-"):
    try:
        # You can't have a progress bar with zero or negative length.
        if BarLength <1:
            BarLength = 20
        # Use status variable for going to the next line after progress completion.
        Status = ""
        # Calcuting progress between 0 and 1 for percentage.
        Progress = float(Progress) / float(Total)
        # Doing this conditions at final progressing.
        if Progress >= 1.:
            Progress = 1
            Status = "\r\n"    # Going to the next line
        # Calculating how many places should be filled
        Block = int(round(BarLength * Progress))
        # Show this
        Bar = "[{}] {:.0f}% {}".format(ProgressIcon * Block + BarIcon * (BarLength - Block), round(Progress * 100, 0), Status)
        return Bar
    except:
        return "ERROR"

def ShowBar(Bar):
    sys.stdout.write(Bar)
    sys.stdout.flush()

if __name__ == '__main__':
    print("This is a simple progress bar.\n")

    # Example #1:
    print('Example #1')
    Runs = 10
    for i in range(Runs + 1):
        progressBar = "\rProgress: " + ProgressBar(10, i, Runs)
        ShowBar(progressBar)
        time.sleep(1)

    # Example #2:
    print('\nExample #2')
    Runs = 10
    for i in range(Runs + 1):
        progressBar = "\rProgress: " + ProgressBar(10, i, 20, '|', '.')
        ShowBar(progressBar)
        time.sleep(1)

    print('\nDone.')

# Example #2:
Runs = 10
for i in range(Runs + 1):
    ProgressBar(10, i)
    time.sleep(1)

Result:

This is a simple progress bar.

Example #1

Progress: [###-------] 30%

Example #2

Progress: [||||||||||||........] 60%

Done.

Why can't I set text to an Android TextView?

Or you can do this way :

((TextView)findViewById(R.id.this_is_the_id_of_textview)).setText("Test");

Async/Await Class Constructor

You can definitely do this. Basically:

class AsyncConstructor {
    constructor() {
        return (async () => {

            // All async code here
            this.value = await asyncFunction();

            return this; // when done
        })();
    }
}

to create the class use:

let instance = await new AsyncConstructor();

This solution has a few short falls though:

super note: If you need to use super, you cannot call it within the async callback.

TypeScript note: this causes issues with TypeScript because the constructor returns type Promise<MyClass> instead of MyClass. There is no definitive way to resolve this that I know of. One potential way suggested by @blitter is to put /** @type {any} */ at the beginning of the constructor body— I do not know if this works in all situations however.

How to implement a Keyword Search in MySQL?

For a single keyword on VARCHAR fields you can use LIKE:

SELECT id, category, location
FROM table
WHERE
(
    category LIKE '%keyword%'
    OR location LIKE '%keyword%'
)

For a description you're usually better adding a full text index and doing a Full-Text Search (MyISAM only):

SELECT id, description
FROM table
WHERE MATCH (description) AGAINST('keyword1 keyword2')

Event listener for when element becomes visible?

my solution:

; (function ($) {
$.each([ "toggle", "show", "hide" ], function( i, name ) {
    var cssFn = $.fn[ name ];
    $.fn[ name ] = function( speed, easing, callback ) {
        if(speed == null || typeof speed === "boolean"){
            var ret=cssFn.apply( this, arguments )
            $.fn.triggerVisibleEvent.apply(this,arguments)
            return ret
        }else{
            var that=this
            var new_callback=function(){
                callback.call(this)
                $.fn.triggerVisibleEvent.apply(that,arguments)
            }
            var ret=this.animate( genFx( name, true ), speed, easing, new_callback )
            return ret
        }
    };
});

$.fn.triggerVisibleEvent=function(){
    this.each(function(){
        if($(this).is(':visible')){
            $(this).trigger('visible')
            $(this).find('[data-trigger-visible-event]').triggerVisibleEvent()
        }
    })
}
})(jQuery);

for example:

if(!$info_center.is(':visible')){
    $info_center.attr('data-trigger-visible-event','true').one('visible',processMoreLessButton)
}else{
    processMoreLessButton()
}

function processMoreLessButton(){
//some logic
}

Foreign Key to non-primary key

As others have pointed out, ideally, the foreign key would be created as a reference to a primary key (usually an IDENTITY column). However, we don't live in an ideal world, and sometimes even a "small" change to a schema can have significant ripple effects to the application logic.

Consider the case of a Customer table with a SSN column (and a dumb primary key), and a Claim table that also contains a SSN column (populated by business logic from the Customer data, but no FK exists). The design is flawed, but has been in use for several years, and three different applications have been built on the schema. It should be obvious that ripping out Claim.SSN and putting in a real PK-FK relationship would be ideal, but would also be a significant overhaul. On the other hand, putting a UNIQUE constraint on Customer.SSN, and adding a FK on Claim.SSN, could provide referential integrity, with little or no impact on the applications.

Don't get me wrong, I'm all for normalization, but sometimes pragmatism wins over idealism. If a mediocre design can be helped with a band-aid, surgery might be avoided.

How to properly -filter multiple strings in a PowerShell copy script

Get-ChildItem $originalPath\* -Include @("*.gif", "*.jpg", "*.xls*", "*.doc*", "*.pdf*", "*.wav*", "*.ppt")

Using :: in C++

look at it is informative [Qualified identifiers

A qualified id-expression is an unqualified id-expression prepended by a scope resolution operator ::, and optionally, a sequence of enumeration, (since C++11)class or namespace names or decltype expressions (since C++11) separated by scope resolution operators. For example, the expression std::string::npos is an expression that names the static member npos in the class string in namespace std. The expression ::tolower names the function tolower in the global namespace. The expression ::std::cout names the global variable cout in namespace std, which is a top-level namespace. The expression boost::signals2::connection names the type connection declared in namespace signals2, which is declared in namespace boost.

The keyword template may appear in qualified identifiers as necessary to disambiguate dependent template names]1

open existing java project in eclipse

  1. File -> Import -> Existing Project into Workspace
  2. Browse for that directory.

Alternative: Check out the code in SVN to some folder

  1. Create a new folder in windows
  2. In eclipse File -> switchWorkspace -> newFolderName
  3. close the welcome window in eclipse
  4. In eclipse File -> Import -> Existing project into workspce-> select root dir -> browse and show the svn checkout folder

What is “the inverse side of the association” in a bidirectional JPA OneToMany/ManyToOne association?

For two Entity Classes Customer and Order , hibernate will create two tables.

Possible Cases:

  1. mappedBy is not used in Customer.java and Order.java Class then->

    At customer side a new table will be created[name = CUSTOMER_ORDER] which will keep mapping of CUSTOMER_ID and ORDER_ID. These are primary keys of Customer and Order Tables. At Order side an additional column is required to save the corresponding Customer_ID record mapping.

  2. mappedBy is used in Customer.java [As given in problem statement] Now additional table[CUSTOMER_ORDER] is not created. Only one column in Order Table

  3. mappedby is used in Order.java Now additional table will be created by hibernate.[name = CUSTOMER_ORDER] Order Table will not have additional column [Customer_ID ] for mapping.

Any Side can be made Owner of the relationship. But its better to choose xxxToOne side.

Coding effect - > Only Owning side of entity can change relationship status. In below example BoyFriend class is owner of the relationship. even if Girlfriend wants to break-up , she can't.

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Entity
@Table(name = "BoyFriend21")
public class BoyFriend21 {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "Boy_ID")
    @SequenceGenerator(name = "Boy_ID", sequenceName = "Boy_ID_SEQUENCER", initialValue = 10,allocationSize = 1)
    private Integer id;

    @Column(name = "BOY_NAME")
    private String name;

    @OneToOne(cascade = { CascadeType.ALL })
    private GirlFriend21 girlFriend;

    public BoyFriend21(String name) {
        this.name = name;
    }

    public BoyFriend21() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public BoyFriend21(String name, GirlFriend21 girlFriend) {
        this.name = name;
        this.girlFriend = girlFriend;
    }

    public GirlFriend21 getGirlFriend() {
        return girlFriend;
    }

    public void setGirlFriend(GirlFriend21 girlFriend) {
        this.girlFriend = girlFriend;
    }
}

import org.hibernate.annotations.*;
import javax.persistence.*;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.util.ArrayList;
import java.util.List;

@Entity 
@Table(name = "GirlFriend21")
public class GirlFriend21 {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "Girl_ID")
    @SequenceGenerator(name = "Girl_ID", sequenceName = "Girl_ID_SEQUENCER", initialValue = 10,allocationSize = 1)
    private Integer id;

    @Column(name = "GIRL_NAME")
    private String name;

    @OneToOne(cascade = {CascadeType.ALL},mappedBy = "girlFriend")
    private BoyFriend21 boyFriends = new BoyFriend21();

    public GirlFriend21() {
    }

    public GirlFriend21(String name) {
        this.name = name;
    }


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public GirlFriend21(String name, BoyFriend21 boyFriends) {
        this.name = name;
        this.boyFriends = boyFriends;
    }

    public BoyFriend21 getBoyFriends() {
        return boyFriends;
    }

    public void setBoyFriends(BoyFriend21 boyFriends) {
        this.boyFriends = boyFriends;
    }
}


import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import java.util.Arrays;

public class Main578_DS {

    public static void main(String[] args) {
        final Configuration configuration = new Configuration();
         try {
             configuration.configure("hibernate.cfg.xml");
         } catch (HibernateException e) {
             throw new RuntimeException(e);
         }
        final SessionFactory sessionFactory = configuration.buildSessionFactory();
        final Session session = sessionFactory.openSession();
        session.beginTransaction();

        final BoyFriend21 clinton = new BoyFriend21("Bill Clinton");
        final GirlFriend21 monica = new GirlFriend21("monica lewinsky");

        clinton.setGirlFriend(monica);
        session.save(clinton);

        session.getTransaction().commit();
        session.close();
    }
}

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import java.util.List;

public class Main578_Modify {

    public static void main(String[] args) {
        final Configuration configuration = new Configuration();
        try {
            configuration.configure("hibernate.cfg.xml");
        } catch (HibernateException e) {
            throw new RuntimeException(e);
        }
        final SessionFactory sessionFactory = configuration.buildSessionFactory();
        final Session session1 = sessionFactory.openSession();
        session1.beginTransaction();

        GirlFriend21 monica = (GirlFriend21)session1.load(GirlFriend21.class,10);  // Monica lewinsky record has id  10.
        BoyFriend21 boyfriend = monica.getBoyFriends();
        System.out.println(boyfriend.getName()); // It will print  Clinton Name
        monica.setBoyFriends(null); // It will not impact relationship

        session1.getTransaction().commit();
        session1.close();

        final Session session2 = sessionFactory.openSession();
        session2.beginTransaction();

        BoyFriend21 clinton = (BoyFriend21)session2.load(BoyFriend21.class,10);  // Bill clinton record

        GirlFriend21 girlfriend = clinton.getGirlFriend();
        System.out.println(girlfriend.getName()); // It will print Monica name.
        //But if Clinton[Who owns the relationship as per "mappedby" rule can break this]
        clinton.setGirlFriend(null);
        // Now if Monica tries to check BoyFriend Details, she will find Clinton is no more her boyFriend
        session2.getTransaction().commit();
        session2.close();

        final Session session3 = sessionFactory.openSession();
        session1.beginTransaction();

        monica = (GirlFriend21)session3.load(GirlFriend21.class,10);  // Monica lewinsky record has id  10.
        boyfriend = monica.getBoyFriends();

        System.out.println(boyfriend.getName()); // Does not print Clinton Name

        session3.getTransaction().commit();
        session3.close();
    }
}

How to make the Facebook Like Box responsive?

I was trying to do this on Drupal 7 with the " fb_likebox" module (https://drupal.org/project/fb_likebox). To get it to be responsive. Turns out I had to write my own Contrib module Variation and stripe out the width setting option. (the default height option didn't matter for me). Once I removed the width, I added the <div id="likebox-wrapper"> in the fb_likebox.tpl.php.

Here's my CSS to style it:

 `#likebox-wrapper * {
  width: 100% !important;
  background: url('../images/block.png') repeat 0 0;
  color: #fbfbfb;
 -webkit-border-radius: 7px;
  -moz-border-radius: 7px;
   -o-border-radius: 7px;
  border-radius: 7px;
   border: 1px solid #DDD;}`

How to use ScrollView in Android?

How to use ScrollView

Using ScrollView is not very difficult. You can just add one to your layout and put whatever you want to scroll inside. ScrollView only takes one child so if you want to put a few things inside then you should make the first thing be something like a LinearLayout.

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <!-- things to scroll -->

    </LinearLayout>
</ScrollView>

If you want to scroll things horizontally, then use a HorizontalScrollView.

Making the content fill the screen

As is talked about in this post, sometimes you want the ScrollView content to fill the screen. For example, if you had some buttons at the end of a readme. You want the buttons to always be at the end of the text and at bottom of the screen, even if the text doesn't scroll.

If the content scrolls, everything is fine. However, if the content is smaller than the size of the screen, the buttons are not at the bottom.

enter image description here

This can be solved with a combination of using fillViewPort on the ScrollView and using a layout weight on the content. Using fillViewPort makes the ScrollView fill the parent area. Setting the layout_weight on one of the views in the LinearLayout makes that view expand to fill any extra space.

enter image description here

Here is the XML

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">                        <--- fillViewport

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textview"
            android:layout_height="0dp"                <--- 
            android:layout_weight="1"                  <--- set layout_weight
            android:layout_width="match_parent"
            android:padding="6dp"
            android:text="hello"/>

        <LinearLayout
            android:layout_height="wrap_content"       <--- wrap_content
            android:layout_width="match_parent"
            android:background="@android:drawable/bottom_bar"
            android:gravity="center_vertical">

            <Button
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:text="Accept" />

            <Button
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="wrap_content"
                android:text="Refuse" />

        </LinearLayout>
    </LinearLayout>
</ScrollView>

The idea for this answer came from a previous answer that is now deleted (link for 10K users). The content of this answer is an update and adaptation of this post.

OR is not supported with CASE Statement in SQL Server

UPDATE table_name 
  SET column_name=CASE 
WHEN column_name in ('value1', 'value2',.....) 
  THEN 'update_value' 
WHEN column_name in ('value1', 'value2',.....) 
  THEN 'update_value' 
END

table_name = The name of table on which you want to perform operation.

column_name = The name of Column/Field of which value you want to set.

update_value = The value you want to set of column_name

How to call stopservice() method of Service class from the calling activity class

I actually used pretty much the same code as you above. My service registration in the manifest is the following

<service android:name=".service.MyService" android:enabled="true">
            <intent-filter android:label="@string/menuItemStartService" >
                <action android:name="it.unibz.bluedroid.bluetooth.service.MY_SERVICE"/>
            </intent-filter>
        </service>

In the service class I created an according constant string identifying the service name like:

public class MyService extends ForeGroundService {
    public static final String MY_SERVICE = "it.unibz.bluedroid.bluetooth.service.MY_SERVICE";
   ...
}

and from the according Activity I call it with

startService(new Intent(MyService.MY_SERVICE));

and stop it with

stopService(new Intent(MyService.MY_SERVICE));

It works perfectly. Try to check your configuration and if you don't find anything strange try to debug whether your stopService get's called properly.

oracle varchar to number

You have to use the TO_NUMBER function:

select * from exception where exception_value = to_number('105')

Extract number from string with Oracle function

You'd use REGEXP_REPLACE in order to remove all non-digit characters from a string:

select regexp_replace(column_name, '[^0-9]', '')
from mytable;

or

select regexp_replace(column_name, '[^[:digit:]]', '')
from mytable;

Of course you can write a function extract_number. It seems a bit like overkill though, to write a funtion that consists of only one function call itself.

create function extract_number(in_number varchar2) return varchar2 is
begin
  return regexp_replace(in_number, '[^[:digit:]]', '');
end; 

How to print pandas DataFrame without index

To answer the "How to print dataframe without an index" question, you can set the index to be an array of empty strings (one for each row in the dataframe), like this:

blankIndex=[''] * len(df)
df.index=blankIndex

If we use the data from your post:

row1 = (123, '2014-07-08 00:09:00', 1411)
row2 = (123, '2014-07-08 00:49:00', 1041)
row3 = (123, '2014-07-08 00:09:00', 1411)
data = [row1, row2, row3]
#set up dataframe
df = pd.DataFrame(data, columns=('User ID', 'Enter Time', 'Activity Number'))
print(df)

which would normally print out as:

   User ID           Enter Time  Activity Number
0      123  2014-07-08 00:09:00             1411
1      123  2014-07-08 00:49:00             1041
2      123  2014-07-08 00:09:00             1411

By creating an array with as many empty strings as there are rows in the data frame:

blankIndex=[''] * len(df)
df.index=blankIndex
print(df)

It will remove the index from the output:

  User ID           Enter Time  Activity Number
      123  2014-07-08 00:09:00             1411
      123  2014-07-08 00:49:00             1041
      123  2014-07-08 00:09:00             1411

And in Jupyter Notebooks would render as per this screenshot: Juptyer Notebooks dataframe with no index column

Bootstrap - Removing padding or margin when screen size is smaller

This thread was helpful in finding the solution in my particular case (bootstrap 3)

@media (max-width: 767px) {
  .container-fluid, .row {
    padding:0px;
  }
  .navbar-header {
    margin:0px;
  }
}

Python print statement “Syntax Error: invalid syntax”

Use print("use this bracket -sample text")

In Python 3 print "Hello world" gives invalid syntax error.

To display string content in Python3 have to use this ("Hello world") brackets.

How to download and save an image in Android

Edit as of 30.12.2015 - The Ultimate Guide to image downloading


last major update: Mar 31 2016


TL;DR a.k.a. stop talking, just give me the code!!

Skip to the bottom of this post, copy the BasicImageDownloader (javadoc version here) into your project, implement the OnImageLoaderListener interface and you're done.

Note: though the BasicImageDownloader handles possible errors and will prevent your app from crashing in case anything goes wrong, it will not perform any post-processing (e.g. downsizing) on the downloaded Bitmaps.


Since this post has received quite a lot of attention, I have decided to completely rework it to prevent the folks from using deprecated technologies, bad programming practices or just doing silly things - like looking for "hacks" to run network on the main thread or accept all SSL certs.

I've created a demo project named "Image Downloader" that demonstrates how to download (and save) an image using my own downloader implementation, the Android's built-in DownloadManager as well as some popular open-source libraries. You can view the complete source code or download the project on GitHub.

Note: I have not adjusted the permission management for SDK 23+ (Marshmallow) yet, thus the project is targeting SDK 22 (Lollipop).

In my conclusion at the end of this post I will share my humble opinion about the proper use-case for each particular way of image downloading I've mentioned.

Let's start with an own implementation (you can find the code at the end of the post). First of all, this is a BasicImageDownloader and that's it. All it does is connecting to the given url, reading the data and trying to decode it as a Bitmap, triggering the OnImageLoaderListener interface callbacks when appropriate. The advantage of this approach - it is simple and you have a clear overview of what's going on. A good way to go if all you need is downloading/displaying and saving some images, whilst you don't care about maintaining a memory/disk cache.

Note: in case of large images, you might need to scale them down.

--

Android DownloadManager is a way to let the system handle the download for you. It's actually capable of downloading any kind of files, not just images. You may let your download happen silently and invisible to the user, or you can enable the user to see the download in the notification area. You can also register a BroadcastReceiver to get notified after you download is complete. The setup is pretty much straightforward, refer to the linked project for sample code.

Using the DownloadManager is generally not a good idea if you also want to display the image, since you'd need to read and decode the saved file instead of just setting the downloaded Bitmap into an ImageView. The DownloadManager also does not provide any API for you app to track the download progress.

--

Now the introduction of the great stuff - the libraries. They can do much more than just downloading and displaying images, including: creating and managing the memory/disk cache, resizing images, transforming them and more.

I will start with Volley, a powerful library created by Google and covered by the official documentation. While being a general-purpose networking library not specializing on images, Volley features quite a powerful API for managing images.

You will need to implement a Singleton class for managing Volley requests and you are good to go.

You might want to replace your ImageView with Volley's NetworkImageView, so the download basically becomes a one-liner:

((NetworkImageView) findViewById(R.id.myNIV)).setImageUrl(url, MySingleton.getInstance(this).getImageLoader());

If you need more control, this is what it looks like to create an ImageRequest with Volley:

     ImageRequest imgRequest = new ImageRequest(url, new Response.Listener<Bitmap>() {
             @Override
             public void onResponse(Bitmap response) {
                    //do stuff
                }
            }, 0, 0, ImageView.ScaleType.CENTER_CROP, Bitmap.Config.ARGB_8888, 
             new Response.ErrorListener() {
             @Override
             public void onErrorResponse(VolleyError error) {
                   //do stuff
                }
            });

It is worth mentioning that Volley features an excellent error handling mechanism by providing the VolleyError class that helps you to determine the exact cause of an error. If your app does a lot of networking and managing images isn't its main purpose, then Volley it a perfect fit for you.

--

Square's Picasso is a well-known library which will do all of the image loading stuff for you. Just displaying an image using Picasso is as simple as:

 Picasso.with(myContext)
       .load(url)
       .into(myImageView); 

By default, Picasso manages the disk/memory cache so you don't need to worry about that. For more control you can implement the Target interface and use it to load your image into - this will provide callbacks similar to the Volley example. Check the demo project for examples.

Picasso also lets you apply transformations to the downloaded image and there are even other libraries around that extend those API. Also works very well in a RecyclerView/ListView/GridView.

--

Universal Image Loader is an another very popular library serving the purpose of image management. It uses its own ImageLoader that (once initialized) has a global instance which can be used to download images in a single line of code:

  ImageLoader.getInstance().displayImage(url, myImageView);

If you want to track the download progress or access the downloaded Bitmap:

 ImageLoader.getInstance().displayImage(url, myImageView, opts, 
 new ImageLoadingListener() {
     @Override
     public void onLoadingStarted(String imageUri, View view) {
                     //do stuff
                }

      @Override
      public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                   //do stuff
                }

      @Override
      public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                   //do stuff
                }

      @Override
      public void onLoadingCancelled(String imageUri, View view) {
                   //do stuff
                }
            }, new ImageLoadingProgressListener() {
      @Override
      public void onProgressUpdate(String imageUri, View view, int current, int total) {
                   //do stuff
                }
            });

The opts argument in this example is a DisplayImageOptions object. Refer to the demo project to learn more.

Similar to Volley, UIL provides the FailReason class that enables you to check what went wrong on download failure. By default, UIL maintains a memory/disk cache if you don't explicitly tell it not to do so.

Note: the author has mentioned that he is no longer maintaining the project as of Nov 27th, 2015. But since there are many contributors, we can hope that the Universal Image Loader will live on.

--

Facebook's Fresco is the newest and (IMO) the most advanced library that takes image management to a new level: from keeping Bitmaps off the java heap (prior to Lollipop) to supporting animated formats and progressive JPEG streaming.

To learn more about ideas and techniques behind Fresco, refer to this post.

The basic usage is quite simple. Note that you'll need to call Fresco.initialize(Context); only once, preferable in the Application class. Initializing Fresco more than once may lead to unpredictable behavior and OOM errors.

Fresco uses Drawees to display images, you can think of them as of ImageViews:

    <com.facebook.drawee.view.SimpleDraweeView
    android:id="@+id/drawee"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    fresco:fadeDuration="500"
    fresco:actualImageScaleType="centerCrop"
    fresco:placeholderImage="@drawable/placeholder_grey"
    fresco:failureImage="@drawable/error_orange"
    fresco:placeholderImageScaleType="fitCenter"
    fresco:failureImageScaleType="centerInside"
    fresco:retryImageScaleType="centerCrop"
    fresco:progressBarImageScaleType="centerInside"
    fresco:progressBarAutoRotateInterval="1000"
    fresco:roundAsCircle="false" />

As you can see, a lot of stuff (including transformation options) gets already defined in XML, so all you need to do to display an image is a one-liner:

 mDrawee.setImageURI(Uri.parse(url));

Fresco provides an extended customization API, which, under circumstances, can be quite complex and requires the user to read the docs carefully (yes, sometimes you need to RTFM).

I have included examples for progressive JPEG's and animated images into the sample project.


Conclusion - "I have learned about the great stuff, what should I use now?"

Note that the following text reflects my personal opinion and should not be taken as a postulate.

  • If you only need to download/save/display some images, don't plan to use them in a Recycler-/Grid-/ListView and don't need a whole bunch of images to be display-ready, the BasicImageDownloader should fit your needs.
  • If your app saves images (or other files) as a result of a user or an automated action and you don't need the images to be displayed often, use the Android DownloadManager.
  • In case your app does a lot of networking, transmits/receives JSON data, works with images, but those are not the main purpose of the app, go with Volley.
  • Your app is image/media-focused, you'd like to apply some transformations to images and don't want to bother with complex API: use Picasso (Note: does not provide any API to track the intermediate download status) or Universal Image Loader
  • If your app is all about images, you need advanced features like displaying animated formats and you are ready to read the docs, go with Fresco.

In case you missed that, the Github link for the demo project.


And here's the BasicImageDownloader.java

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashSet;
import java.util.Set;

public class BasicImageDownloader {

    private OnImageLoaderListener mImageLoaderListener;
    private Set<String> mUrlsInProgress = new HashSet<>();
    private final String TAG = this.getClass().getSimpleName();

    public BasicImageDownloader(@NonNull OnImageLoaderListener listener) {
        this.mImageLoaderListener = listener;
    }

    public interface OnImageLoaderListener {
        void onError(ImageError error);      
        void onProgressChange(int percent);
        void onComplete(Bitmap result);
    }


    public void download(@NonNull final String imageUrl, final boolean displayProgress) {
        if (mUrlsInProgress.contains(imageUrl)) {
            Log.w(TAG, "a download for this url is already running, " +
                    "no further download will be started");
            return;
        }

        new AsyncTask<Void, Integer, Bitmap>() {

            private ImageError error;

            @Override
            protected void onPreExecute() {
                mUrlsInProgress.add(imageUrl);
                Log.d(TAG, "starting download");
            }

            @Override
            protected void onCancelled() {
                mUrlsInProgress.remove(imageUrl);
                mImageLoaderListener.onError(error);
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                mImageLoaderListener.onProgressChange(values[0]);
            }

        @Override
        protected Bitmap doInBackground(Void... params) {
            Bitmap bitmap = null;
            HttpURLConnection connection = null;
            InputStream is = null;
            ByteArrayOutputStream out = null;
            try {
                connection = (HttpURLConnection) new URL(imageUrl).openConnection();
                if (displayProgress) {
                    connection.connect();
                    final int length = connection.getContentLength();
                    if (length <= 0) {
                        error = new ImageError("Invalid content length. The URL is probably not pointing to a file")
                                .setErrorCode(ImageError.ERROR_INVALID_FILE);
                        this.cancel(true);
                    }
                    is = new BufferedInputStream(connection.getInputStream(), 8192);
                    out = new ByteArrayOutputStream();
                    byte bytes[] = new byte[8192];
                    int count;
                    long read = 0;
                    while ((count = is.read(bytes)) != -1) {
                        read += count;
                        out.write(bytes, 0, count);
                        publishProgress((int) ((read * 100) / length));
                    }
                    bitmap = BitmapFactory.decodeByteArray(out.toByteArray(), 0, out.size());
                } else {
                    is = connection.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);
                }
            } catch (Throwable e) {
                if (!this.isCancelled()) {
                    error = new ImageError(e).setErrorCode(ImageError.ERROR_GENERAL_EXCEPTION);
                    this.cancel(true);
                }
            } finally {
                try {
                    if (connection != null)
                        connection.disconnect();
                    if (out != null) {
                        out.flush();
                        out.close();
                    }
                    if (is != null)
                        is.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return bitmap;
        }

            @Override
            protected void onPostExecute(Bitmap result) {
                if (result == null) {
                    Log.e(TAG, "factory returned a null result");
                    mImageLoaderListener.onError(new ImageError("downloaded file could not be decoded as bitmap")
                            .setErrorCode(ImageError.ERROR_DECODE_FAILED));
                } else {
                    Log.d(TAG, "download complete, " + result.getByteCount() +
                            " bytes transferred");
                    mImageLoaderListener.onComplete(result);
                }
                mUrlsInProgress.remove(imageUrl);
                System.gc();
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    public interface OnBitmapSaveListener {
        void onBitmapSaved();
        void onBitmapSaveError(ImageError error);
    }


    public static void writeToDisk(@NonNull final File imageFile, @NonNull final Bitmap image,
                               @NonNull final OnBitmapSaveListener listener,
                               @NonNull final Bitmap.CompressFormat format, boolean shouldOverwrite) {

    if (imageFile.isDirectory()) {
        listener.onBitmapSaveError(new ImageError("the specified path points to a directory, " +
                "should be a file").setErrorCode(ImageError.ERROR_IS_DIRECTORY));
        return;
    }

    if (imageFile.exists()) {
        if (!shouldOverwrite) {
            listener.onBitmapSaveError(new ImageError("file already exists, " +
                    "write operation cancelled").setErrorCode(ImageError.ERROR_FILE_EXISTS));
            return;
        } else if (!imageFile.delete()) {
            listener.onBitmapSaveError(new ImageError("could not delete existing file, " +
                    "most likely the write permission was denied")
                    .setErrorCode(ImageError.ERROR_PERMISSION_DENIED));
            return;
        }
    }

    File parent = imageFile.getParentFile();
    if (!parent.exists() && !parent.mkdirs()) {
        listener.onBitmapSaveError(new ImageError("could not create parent directory")
                .setErrorCode(ImageError.ERROR_PERMISSION_DENIED));
        return;
    }

    try {
        if (!imageFile.createNewFile()) {
            listener.onBitmapSaveError(new ImageError("could not create file")
                    .setErrorCode(ImageError.ERROR_PERMISSION_DENIED));
            return;
        }
    } catch (IOException e) {
        listener.onBitmapSaveError(new ImageError(e).setErrorCode(ImageError.ERROR_GENERAL_EXCEPTION));
        return;
    }

    new AsyncTask<Void, Void, Void>() {

        private ImageError error;

        @Override
        protected Void doInBackground(Void... params) {
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(imageFile);
                image.compress(format, 100, fos);
            } catch (IOException e) {
                error = new ImageError(e).setErrorCode(ImageError.ERROR_GENERAL_EXCEPTION);
                this.cancel(true);
            } finally {
                if (fos != null) {
                    try {
                        fos.flush();
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }

        @Override
        protected void onCancelled() {
            listener.onBitmapSaveError(error);
        }

        @Override
        protected void onPostExecute(Void result) {
            listener.onBitmapSaved();
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
  }

public static Bitmap readFromDisk(@NonNull File imageFile) {
    if (!imageFile.exists() || imageFile.isDirectory()) return null;
    return BitmapFactory.decodeFile(imageFile.getAbsolutePath());
}

public interface OnImageReadListener {
    void onImageRead(Bitmap bitmap);
    void onReadFailed();
}

public static void readFromDiskAsync(@NonNull File imageFile, @NonNull final OnImageReadListener listener) {
    new AsyncTask<String, Void, Bitmap>() {
        @Override
        protected Bitmap doInBackground(String... params) {
            return BitmapFactory.decodeFile(params[0]);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null)
                listener.onImageRead(bitmap);
            else
                listener.onReadFailed();
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, imageFile.getAbsolutePath());
}

    public static final class ImageError extends Throwable {

        private int errorCode;
        public static final int ERROR_GENERAL_EXCEPTION = -1;
        public static final int ERROR_INVALID_FILE = 0;
        public static final int ERROR_DECODE_FAILED = 1;
        public static final int ERROR_FILE_EXISTS = 2;
        public static final int ERROR_PERMISSION_DENIED = 3;
        public static final int ERROR_IS_DIRECTORY = 4;


        public ImageError(@NonNull String message) {
            super(message);
        }

        public ImageError(@NonNull Throwable error) {
            super(error.getMessage(), error.getCause());
            this.setStackTrace(error.getStackTrace());
        }

        public ImageError setErrorCode(int code) {
            this.errorCode = code;
            return this;
        }

        public int getErrorCode() {
            return errorCode;
        }
      }
   }

How to declare and use 1D and 2D byte arrays in Verilog?

In addition to Marty's excellent Answer, the SystemVerilog specification offers the byte data type. The following declares a 4x8-bit variable (4 bytes), assigns each byte a value, then displays all values:

module tb;

byte b [4];

initial begin
    foreach (b[i]) b[i] = 1 << i;
    foreach (b[i]) $display("Address = %0d, Data = %b", i, b[i]);
    $finish;
end

endmodule

This prints out:

Address = 0, Data = 00000001
Address = 1, Data = 00000010
Address = 2, Data = 00000100
Address = 3, Data = 00001000

This is similar in concept to Marty's reg [7:0] a [0:3];. However, byte is a 2-state data type (0 and 1), but reg is 4-state (01xz). Using byte also requires your tool chain (simulator, synthesizer, etc.) to support this SystemVerilog syntax. Note also the more compact foreach (b[i]) loop syntax.

The SystemVerilog specification supports a wide variety of multi-dimensional array types. The LRM can explain them better than I can; refer to IEEE Std 1800-2005, chapter 5.

Restrict varchar() column to specific values?

You want a check constraint.

CHECK constraints determine the valid values from a logical expression that is not based on data in another column. For example, the range of values for a salary column can be limited by creating a CHECK constraint that allows for only data that ranges from $15,000 through $100,000. This prevents salaries from being entered beyond the regular salary range.

You want something like:

ALTER TABLE dbo.Table ADD CONSTRAINT CK_Table_Frequency
    CHECK (Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly'))

You can also implement check constraints with scalar functions, as described in the link above, which is how I prefer to do it.

python selenium click on button

Remove space between classes in css selector:

driver.find_element_by_css_selector('.button .c_button .s_button').click()
#                                           ^         ^

=>

driver.find_element_by_css_selector('.button.c_button.s_button').click()

AngularJS - Does $destroy remove event listeners?

Event listeners

First off it's important to understand that there are two kinds of "event listeners":

  1. Scope event listeners registered via $on:

    $scope.$on('anEvent', function (event, data) {
      ...
    });
    
  2. Event handlers attached to elements via for example on or bind:

    element.on('click', function (event) {
      ...
    });
    

$scope.$destroy()

When $scope.$destroy() is executed it will remove all listeners registered via $on on that $scope.

It will not remove DOM elements or any attached event handlers of the second kind.

This means that calling $scope.$destroy() manually from example within a directive's link function will not remove a handler attached via for example element.on, nor the DOM element itself.


element.remove()

Note that remove is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.

When element.remove() is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on.

It will not destroy the $scope associated with the element.

To make it more confusing there is also a jQuery event called $destroy. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:

element.on('$destroy', function () {
  scope.$destroy();
});

What to do when a directive is "destroyed"

This depends on how the directive is "destroyed".

A normal case is that a directive is destroyed because ng-view changes the current view. When this happens the ng-view directive will destroy the associated $scope, sever all the references to its parent scope and call remove() on the element.

This means that if that view contains a directive with this in its link function when it's destroyed by ng-view:

scope.$on('anEvent', function () {
 ...
});

element.on('click', function () {
 ...
});

Both event listeners will be removed automatically.

However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references.

Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.

For example if you have registered a listener on $rootScope:

var unregisterFn = $rootScope.$on('anEvent', function () {});

scope.$on('$destroy', unregisterFn);

This is needed since $rootScope is never destroyed during the lifetime of the application.

The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.

Another situation would be to cancel $interval/$timeout:

var promise = $interval(function () {}, 1000);

scope.$on('$destroy', function () {
  $interval.cancel(promise);
});

If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:

var windowClick = function () {
   ...
};

angular.element(window).on('click', windowClick);

scope.$on('$destroy', function () {
  angular.element(window).off('click', windowClick);
});

These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view or ng-if.

If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.

How to update cursor limit for ORA-01000: maximum open cursors exceed

you can update the setting under init.ora in oraclexe\app\oracle\product\11.2.0\server\config\scripts

The entitlements specified...profile. (0xE8008016). Error iOS 4.2

Happened to me on Xcode 8, it was partially caused by the new Provisioning Profile build setting, as in this Xcode version there are two entries for provisioning profile:

  • Provisioning Profile
  • Provisioning Profile (Deprecated)

My fault was that I updated only the first one, and the deprecated entry was still pointing to an invalid provisioning profile. Changing both to the same value solved the issue (clearing the deprecated entry should also have the same effect).

Edit a text file on the console using Powershell

I had to do some debugging on a Windows Nano docker image and needed to edit the content of a file, who would have guessed it was so difficult.

I used a combination of Get-Content and Set-Content and base 64 encoding/decoding to update files. For instance

Editing foo.txt

PS C:\app> Set-Content foo.txt "Hello World"                                                                                                                                                                                        
PS C:\app> Get-Content foo.txt                                                                                                                                                                                                      
Hello World                                                                                                                                                                                                                         
PS C:\app> [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("TXkgbmV3IG11bHRpDQpsaW5lIGRvY3VtZW50DQp3aXRoIGFsbCBraW5kcyBvZiBmdW4gc3R1ZmYNCiFAIyVeJSQmXiYoJiopIUAjIw0KLi4ud29ybGQ=")) | Set-Content foo.txt 
PS C:\app> Get-Content foo.txt                                                                                                                                                                                                      
My new multi                                                                                                                                                                                                                        
line document                                                                                                                                                                                                                       
with all kinds of fun stuff                                                                                                                                                                                                         
!@#%^%$&^&(&*)!@##                                                                                                                                                                                                                  
...world                                                                                                                                                                                                                            
PS C:\app>       

The trick is piping the base 64 decoded string to Set-Content

[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String("...")) | Set-Content foo.txt 

Its no vim but I can update files, for what its worth.

Convert one date format into another in PHP

$old_date = date('y-m-d-h-i-s');       // works

you are doing wrong here, this should be

$old_date = date('y-m-d h:i:s');       // works

separator of time is ':'


I think this will help...

$old_date = date('y-m-d-h-i-s');              // works

preg_match_all('/(\d+)-(\d+)-(\d+)-(\d+)-(\d+)-(\d+)/', $old_date, $out, PREG_SET_ORDER);
$out = $out[0];
$time = mktime($out[4], $out[5], $out[6], $out[2], $out[3], $out[1]);

$new_date = date('Y-m-d H:i:s', $time); 

OR


$old_date = date('y-m-d-h-i-s');              // works

$out = explode('-', $old_date);
$time = mktime($out[3], $out[4], $out[5], $out[1], $out[2], $out[0]);

$new_date = date('Y-m-d H:i:s', $time); 

How to select the row with the maximum value in each group

Using dplyr 1.0.2 there are now two ways to do this, one is long hand and the other is using the verb across():

      # create data
      ID    <- c(1,1,1,2,2,2,2,3,3)
      Value <- c(2,3,5,2,5,8,17,3,5)
      Event <- c(1,1,2,1,2,1,2,2,2)
      
      group <- data.frame(Subject=ID, pt=Value, Event=Event)

Long hand the verb is max() but note the na.rm = TRUE which is useful for examples where there are NAs as in the closed question: Merge rows in a dataframe where the rows are disjoint and contain NAs:

       group %>% 
        group_by(Subject) %>% 
        summarise(pt = max(pt, na.rm = TRUE),
                  Event = max(Event, na.rm = TRUE))

This is ok if there are only a few columns but if the table has many columns across() is useful. The examples for this verb are often with summarise(across(start_with... but in this example the columns don't start with the same characters. Either they could be changed or the positions listed:

    group %>% 
        group_by(Subject) %>% 
        summarise(across(1:ncol(group)-1, max, na.rm = TRUE, .names = "{.col}"))

Note for the verb across() 1 refers to the first column after the first actual column so using ncol(group) won't work as that is too many columns (makes it position 4 rather than 3).

JSP tricks to make templating easier?

As skaffman suggested, JSP 2.0 Tag Files are the bee's knees.

Let's take your simple example.

Put the following in WEB-INF/tags/wrapper.tag

<%@tag description="Simple Wrapper Tag" pageEncoding="UTF-8"%>
<html><body>
  <jsp:doBody/>
</body></html>

Now in your example.jsp page:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>

<t:wrapper>
    <h1>Welcome</h1>
</t:wrapper>

That does exactly what you think it does.


So, lets expand upon that to something a bit more general. WEB-INF/tags/genericpage.tag

<%@tag description="Overall Page template" pageEncoding="UTF-8"%>
<%@attribute name="header" fragment="true" %>
<%@attribute name="footer" fragment="true" %>
<html>
  <body>
    <div id="pageheader">
      <jsp:invoke fragment="header"/>
    </div>
    <div id="body">
      <jsp:doBody/>
    </div>
    <div id="pagefooter">
      <jsp:invoke fragment="footer"/>
    </div>
  </body>
</html>

To use this:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>

<t:genericpage>
    <jsp:attribute name="header">
      <h1>Welcome</h1>
    </jsp:attribute>
    <jsp:attribute name="footer">
      <p id="copyright">Copyright 1927, Future Bits When There Be Bits Inc.</p>
    </jsp:attribute>
    <jsp:body>
        <p>Hi I'm the heart of the message</p>
    </jsp:body>
</t:genericpage>

What does that buy you? A lot really, but it gets even better...


WEB-INF/tags/userpage.tag

<%@tag description="User Page template" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>
<%@attribute name="userName" required="true"%>

<t:genericpage>
    <jsp:attribute name="header">
      <h1>Welcome ${userName}</h1>
    </jsp:attribute>
    <jsp:attribute name="footer">
      <p id="copyright">Copyright 1927, Future Bits When There Be Bits Inc.</p>
    </jsp:attribute>
    <jsp:body>
        <jsp:doBody/>
    </jsp:body>
</t:genericpage>

To use this: (assume we have a user variable in the request)

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>

<t:userpage userName="${user.fullName}">
  <p>
    First Name: ${user.firstName} <br/>
    Last Name: ${user.lastName} <br/>
    Phone: ${user.phone}<br/>
  </p>
</t:userpage>

But it turns you like to use that user detail block in other places. So, we'll refactor it. WEB-INF/tags/userdetail.tag

<%@tag description="User Page template" pageEncoding="UTF-8"%>
<%@tag import="com.example.User" %>
<%@attribute name="user" required="true" type="com.example.User"%>

First Name: ${user.firstName} <br/>
Last Name: ${user.lastName} <br/>
Phone: ${user.phone}<br/>

Now the previous example becomes:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="t" tagdir="/WEB-INF/tags" %>

<t:userpage userName="${user.fullName}">
  <p>
    <t:userdetail user="${user}"/>
  </p>
</t:userpage>

The beauty of JSP Tag files is that it lets you basically tag generic markup and then refactor it to your heart's content.

JSP Tag Files have pretty much usurped things like Tiles etc., at least for me. I find them much easier to use as the only structure is what you give it, nothing preconceived. Plus you can use JSP tag files for other things (like the user detail fragment above).

Here's an example that is similar to DisplayTag that I've done, but this is all done with Tag Files (and the Stripes framework, that's the s: tags..). This results in a table of rows, alternating colors, page navigation, etc:

<t:table items="${actionBean.customerList}" var="obj" css_class="display">
  <t:col css_class="checkboxcol">
    <s:checkbox name="customerIds" value="${obj.customerId}"
                onclick="handleCheckboxRangeSelection(this, event);"/>
  </t:col>
  <t:col name="customerId" title="ID"/>
  <t:col name="firstName" title="First Name"/>
  <t:col name="lastName" title="Last Name"/>
  <t:col>
    <s:link href="/Customer.action" event="preEdit">
      Edit
      <s:param name="customer.customerId" value="${obj.customerId}"/>
      <s:param name="page" value="${actionBean.page}"/>
    </s:link>
  </t:col>
</t:table>

Of course the tags work with the JSTL tags (like c:if, etc.). The only thing you can't do within the body of a tag file tag is add Java scriptlet code, but this isn't as much of a limitation as you might think. If I need scriptlet stuff, I just put the logic in to a tag and drop the tag in. Easy.

So, tag files can be pretty much whatever you want them to be. At the most basic level, it's simple cut and paste refactoring. Grab a chunk of layout, cut it out, do some simple parameterization, and replace it with a tag invocation.

At a higher level, you can do sophisticated things like this table tag I have here.

unable to install pg gem

I had this problem, this worked for me:

Install the postgresql-devel package, this will solve the issue of pg_config missing.

sudo apt-get install libpq-dev

CASE WHEN statement for ORDER BY clause

declare @OrderByCmd  nvarchar(2000)
declare @OrderByName nvarchar(100)
declare @OrderByCity nvarchar(100)
set @OrderByName='Name'    
set @OrderByCity='city'
set @OrderByCmd= 'select * from customer Order By '+@OrderByName+','+@OrderByCity+''
EXECUTE sp_executesql @OrderByCmd 

Unit tests vs Functional tests

very simply we can say:

  • black box: user interface test like functional test
  • white box: code test like unit test

read more here.

Why are primes important in cryptography?

One more resource for you. Security Now! episode 30(~30 minute podcast, link is to the transcript) talks about cryptography issues, and explains why primes are important.

What does 'low in coupling and high in cohesion' mean

Cohesion in software engineering, as in real life, is how much the elements consisting a whole(in our case let's say a class) can be said that they actually belong together. Thus, it is a measure of how strongly related each piece of functionality expressed by the source code of a software module is.

One way of looking at cohesion in terms of OO is if the methods in the class are using any of the private attributes.

Now the discussion is bigger than this but High Cohesion (or the cohesion's best type - the functional cohesion) is when parts of a module are grouped because they all contribute to a single well-defined task of the module.

Coupling in simple words, is how much one component (again, imagine a class, although not necessarily) knows about the inner workings or inner elements of another one, i.e. how much knowledge it has of the other component.

Loose coupling is a method of interconnecting the components in a system or network so that those components, depend on each other to the least extent practically possible…

I wrote a blog post about this. It discusses all this in much detail, with examples etc. It also explains the benefits of why you should follow these principles.

WPF Data Binding and Validation Rules Best Practices

From MS's Patterns & Practices documentation:

Data Validation and Error Reporting

Your view model or model will often be required to perform data validation and to signal any data validation errors to the view so that the user can act to correct them.

Silverlight and WPF provide support for managing data validation errors that occur when changing individual properties that are bound to controls in the view. For single properties that are data-bound to a control, the view model or model can signal a data validation error within the property setter by rejecting an incoming bad value and throwing an exception. If the ValidatesOnExceptions property on the data binding is true, the data binding engine in WPF and Silverlight will handle the exception and display a visual cue to the user that there is a data validation error.

However, throwing exceptions with properties in this way should be avoided where possible. An alternative approach is to implement the IDataErrorInfo or INotifyDataErrorInfo interfaces on your view model or model classes. These interfaces allow your view model or model to perform data validation for one or more property values and to return an error message to the view so that the user can be notified of the error.

The documentation goes on to explain how to implement IDataErrorInfo and INotifyDataErrorInfo.

How to read a text file into a string variable and strip newlines?

you can compress this into one into two lines of code!!!

content = open('filepath','r').read().replace('\n',' ')
print(content)

if your file reads:

hello how are you?
who are you?
blank blank

python output

hello how are you? who are you? blank blank

Check if at least two out of three booleans are true

Here's a test-driven, general approach. Not as "efficient" as most of the solutions so far offered, but clear, tested, working, and generalized.

public class CountBooleansTest extends TestCase {
    public void testThreeFalse() throws Exception {
        assertFalse(atLeastTwoOutOfThree(false, false, false));
    }

    public void testThreeTrue() throws Exception {
        assertTrue(atLeastTwoOutOfThree(true, true, true));
    }

    public void testOnes() throws Exception {
        assertFalse(atLeastTwoOutOfThree(true, false, false));
        assertFalse(atLeastTwoOutOfThree(false, true, false));
        assertFalse(atLeastTwoOutOfThree(false, false, true));
    }

    public void testTwos() throws Exception {
        assertTrue(atLeastTwoOutOfThree(false, true, true));
        assertTrue(atLeastTwoOutOfThree(true, false, true));
        assertTrue(atLeastTwoOutOfThree(true, true, false));
    }

    private static boolean atLeastTwoOutOfThree(boolean b, boolean c, boolean d) {
        return countBooleans(b, c, d) >= 2;
    }

    private static int countBooleans(boolean... bs) {
        int count = 0;
        for (boolean b : bs)
            if (b)
                count++;
        return count;
    }
}

How to break out of a loop from inside a switch?

AFAIK there is no "double break" or similar construct in C++. The closest would be a goto - which, while it has a bad connotation to its name, exists in the language for a reason - as long as it's used carefully and sparingly, it's a viable option.

MVC controller : get JSON object from HTTP body?

use Request.Form to get the Data

Controller:

    [HttpPost]
    public ActionResult Index(int? id)
    {
        string jsonData= Request.Form[0]; // The data from the POST
    }

I write this to try

View:

<input type="button" value="post" id="btnPost" />

<script type="text/javascript">
    $(function () {
        var test = {
            number: 456,
            name: "Ryu"
        }
        $("#btnPost").click(function () {
            $.post('@Url.Action("Index", "Home")', JSON.stringify(test));
        });
    });
</script>

and write Request.Form[0] or Request.Params[0] in controller can get the data.

I don't write <form> tag in view.

Declare and assign multiple string variables at the same time

string Camnr , Klantnr , Ordernr , Bonnr , Volgnr , Omschrijving , Startdatum , Bonprioriteit , Matsoort , Dikte , Draaibaarheid , Draaiomschrijving , Orderleverdatum , Regeltaakkode , Gebruiksvoorkeur , Regelcamprog , Regeltijd , Orderrelease;
Camnr = Klantnr = Ordernr = Bonnr = Volgnr = Omschrijving = Startdatum = Bonprioriteit = Matsoort = Dikte = Draaibaarheid = Draaiomschrijving = Orderleverdatum = Regeltaakkode = Gebruiksvoorkeur = Regelcamprog = Regeltijd = Orderrelease = string.Empty;

Firebase Storage How to store and Retrieve images

Update (20160519): Firebase just released a new feature called Firebase Storage. This allows you to upload images and other non-JSON data to a dedicated storage service. We highly recommend that you use this for storing images, instead of storing them as base64 encoded data in the JSON database.

You certainly can! Depending on how big your images are, you have a couple options:

1. For smaller images (under 10mb)

We have an example project that does that here: https://github.com/firebase/firepano

The general approach is to load the file locally (using FileReader) so you can then store it in Firebase just as you would any other data. Since images are binary files, you'll want to get the base64-encoded contents so you can store it as a string. Or even more convenient, you can store it as a data: url which is then ready to plop in as the src of an img tag (this is what the example does)!

2. For larger images

Firebase does have a 10mb (of utf8-encoded string data) limit. If your image is bigger, you'll have to break it into 10mb chunks. You're right though that Firebase is more optimized for small strings that change frequently rather than multi-megabyte strings. If you have lots of large static data, I'd definitely recommend S3 or a CDN instead.

Py_Initialize fails - unable to load the file system codec

Check the PYTHONPATH and PYTHONHOME environment variables and make sure they don't point to Python 2.x.

http://bugs.python.org/issue11288

PHP: How do you determine every Nth iteration of a loop?

every 3 posts?

if($counter % 3 == 0){
    echo IMAGE;
}

Ruby: How to post a file via HTTP as multipart/form-data?

I can't say enough good things about Nick Sieger's multipart-post library.

It adds support for multipart posting directly to Net::HTTP, removing your need to manually worry about boundaries or big libraries that may have different goals than your own.

Here is a little example on how to use it from the README:

require 'net/http/post/multipart'

url = URI.parse('http://www.example.com/upload')
File.open("./image.jpg") do |jpg|
  req = Net::HTTP::Post::Multipart.new url.path,
    "file" => UploadIO.new(jpg, "image/jpeg", "image.jpg")
  res = Net::HTTP.start(url.host, url.port) do |http|
    http.request(req)
  end
end

You can check out the library here: http://github.com/nicksieger/multipart-post

or install it with:

$ sudo gem install multipart-post

If you're connecting via SSL you need to start the connection like this:

n = Net::HTTP.new(url.host, url.port) 
n.use_ssl = true
# for debugging dev server
#n.verify_mode = OpenSSL::SSL::VERIFY_NONE
res = n.start do |http|

How can I find out what version of git I'm running?

In a command prompt:

$ git --version

Button inside of anchor link works in Firefox but not in Internet Explorer?

Since this is only an issue in IE, to resolve this, I'm first detecting if the browser is IE and if so, use a jquery click event. I put this code into a global file so it's fixed throughout the site.

if (navigator.appName === 'Microsoft Internet Explorer')
{
    $('a input.button').click(function()
    {
        window.location = $(this).closest('a').attr('href');
    });
}

This way we only have the overhead of assigning click events to linked input buttons for IE. note: The above code is inside a document ready function to make sure the page is completely loaded before assigning click events.

I also assigned class names to my input buttons to save some overhead when using IE so I can search for

$('a input.button')

instead of

$('a input[type=button]')

.

<a href="some_link"><input type="button" class="button" value="some value" /></a>

On top of all that, I'm also utilizing CSS to make the buttons look clickable when your mouse hovers over it:

input.button {cursor: pointer}

ModelState.IsValid == false, why?

If you remove the check for the ModelsState.IsValid and let it error, if you copy this line ((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors and paste it in the watch section in Visual Studio it will give you exactly what the error is. Saves a lot of time checking where the error is.

Function to calculate distance between two coordinates

I implemeneted this algorithm in typescript and ES6

export type Coordinate = {
  lat: number;
  lon: number;
};

get the distance between two points:

function getDistanceBetweenTwoPoints(cord1: Coordinate, cord2: Coordinate) {
  if (cord1.lat == cord2.lat && cord1.lon == cord2.lon) {
    return 0;
  }

  const radlat1 = (Math.PI * cord1.lat) / 180;
  const radlat2 = (Math.PI * cord2.lat) / 180;

  const theta = cord1.lon - cord2.lon;
  const radtheta = (Math.PI * theta) / 180;

  let dist =
    Math.sin(radlat1) * Math.sin(radlat2) +
    Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);

  if (dist > 1) {
    dist = 1;
  }

  dist = Math.acos(dist);
  dist = (dist * 180) / Math.PI;
  dist = dist * 60 * 1.1515;
  dist = dist * 1.609344; //convert miles to km
  
  return dist;
}

get the distance between an array of coordinates

export function getTotalDistance(coordinates: Coordinate[]) {
  coordinates = coordinates.filter((cord) => {
    if (cord.lat && cord.lon) {
      return true;
    }
  });
  
  let totalDistance = 0;

  if (!coordinates) {
    return 0;
  }

  if (coordinates.length < 2) {
    return 0;
  }

  for (let i = 0; i < coordinates.length - 2; i++) {
    if (
      !coordinates[i].lon ||
      !coordinates[i].lat ||
      !coordinates[i + 1].lon ||
      !coordinates[i + 1].lat
    ) {
      totalDistance = totalDistance;
    }
    totalDistance =
      totalDistance +
      getDistanceBetweenTwoPoints(coordinates[i], coordinates[i + 1]);
  }

  return totalDistance.toFixed(2);
}

How should I resolve java.lang.IllegalArgumentException: protocol = https host = null Exception?

URLs use forward slashes (/), not backward ones (as windows). Try:

serverURLS = "https://abc.my.domain.com:55555/update";

The reason why you get the error is that the URL class can't parse the host part of the string and therefore, host is null.

Why are my CSS3 media queries not working on mobile devices?

The OP's code snippet clearly uses the correct comment markup but CSS can break in a progressive way — so, if there's a syntax error, everything after that is likely to fail. A couple times I've relied on trustworthy sources that supplied incorrect comment markup that broke my style sheet. Since the OP provided just a small section of their code, I'd suggest the following:

Make sure all of your CSS comments use this markup /* ... */ -- which is the correct comment markup for css according to MDN

Validate your css with a linter or a secure online validator. Here's one by W3

More info: I went to check the latest recommended media query breakpoints from bootstrap 4 and ended up copying the boiler plate straight from their docs. Almost every code block was labeled with javascript-style comments //, which broke my code — and gave me only cryptic compile errors with which to troubleshoot, which went over my head at the time and caused me sadness.

IntelliJ text editor allowed me to comment out specific lines of css in a LESS file using the ctrl+/ hotkey which was great except it inserts // by default on unrecognized file types. It isn't freeware and less is fairly mainstream so I trusted it and went with it. That broke my code. There's a preference menu for teaching it the correct comment markup for each filetype.

Vim clear last search highlighting

You can alternatively add mapping on your .vimrc file as,

nmap <C-N> :nohlsearch

and then you can press

Ctrl+N

to anytime to clear the highlighted text

Remove spaces from a string in VB.NET

To trim a string down so it does not contain two or more spaces in a row. Every instance of 2 or more space will be trimmed down to 1 space. A simple solution:

While ImageText1.Contains("  ")                     '2 spaces.
    ImageText1 = ImageText1.Replace("  ", " ")      'Replace with 1 space.
End While

GROUP BY with MAX(DATE)

Another solution:

select * from traintable
where (train, time) in (select train, max(time) from traintable group by train);

How to import a Python class that is in a directory above?

import sys
sys.path.append("..") # Adds higher directory to python modules path.

Disable Drag and Drop on HTML elements?

This JQuery Worked for me :-

$(document).ready(function() {
  $('#con_image').on('mousedown', function(e) {
      e.preventDefault();
  });
});

MySQL: determine which database is selected?

In the comments of http://www.php.net/manual/de/function.mysql-db-name.php I found this one from ericpp % bigfoot.com:

If you just need the current database name, you can use MySQL's SELECT DATABASE() command:

<?php
function mysql_current_db() {
    $r = mysql_query("SELECT DATABASE()") or die(mysql_error());
    return mysql_result($r,0);
}
?>

"Uncaught TypeError: undefined is not a function" - Beginner Backbone.js Application

Uncaught TypeError: undefined is not a function example_app.js:7

This error message tells the whole story. On this line, you are trying to execute a function. However, whatever is being executed is not a function! Instead, it's undefined.

So what's on example_app.js line 7? Looks like this:

var tasks = new ExampleApp.Collections.Tasks(data.tasks);

There is only one function being run on that line. We found the problem! ExampleApp.Collections.Tasks is undefined.

So lets look at where that is declared:

var Tasks = Backbone.Collection.extend({
    model: Task,
    url: '/tasks'
});

If that's all the code for this collection, then the root cause is right here. You assign the constructor to global variable, called Tasks. But you never add it to the ExampleApp.Collections object, a place you later expect it to be.

Change that to this, and I bet you'd be good.

ExampleApp.Collections.Tasks = Backbone.Collection.extend({
    model: Task,
    url: '/tasks'
});

See how important the proper names and line numbers are in figuring this out? Never ever regard errors as binary (it works or it doesn't). Instead read the error, in most cases the error message itself gives you the critical clues you need to trace through to find the real issue.


In Javascript, when you execute a function, it's evaluated like:

expression.that('returns').aFunctionObject(); // js
execute -> expression.that('returns').aFunctionObject // what the JS engine does

That expression can be complex. So when you see undefined is not a function it means that expression did not return a function object. So you have to figure out why what you are trying to execute isn't a function.

And in this case, it was because you didn't put something where you thought you did.

Using '<%# Eval("item") %>'; Handling Null Value and showing 0 against

I have tried this code and it works well for both null and empty situations :

'<%# (Eval("item")=="" || Eval("item")==null) ? "0" : Eval("item")%>'

Select row and element in awk

To print the columns with a specific string, you use the // search pattern. For example, if you are looking for second columns that contains abc:

awk '$2 ~ /abc/'

... and if you want to print only a particular column:

awk '$2 ~ /abc/ { print $3 }'

... and for a particular line number:

awk '$2 ~ /abc/ && FNR == 5 { print $3 }'

How to round a numpy array?

Numpy provides two identical methods to do this. Either use

np.round(data, 2)

or

np.around(data, 2)

as they are equivalent.

See the documentation for more information.


Examples:

>>> import numpy as np
>>> a = np.array([0.015, 0.235, 0.112])
>>> np.round(a, 2)
array([0.02, 0.24, 0.11])
>>> np.around(a, 2)
array([0.02, 0.24, 0.11])
>>> np.round(a, 1)
array([0. , 0.2, 0.1])

How does the @property decorator work in Python?

Below is another example on how @property can help when one has to refactor code which is taken from here (I only summarize it below):

Imagine you created a class Money like this:

class Money:
    def __init__(self, dollars, cents):
        self.dollars = dollars
        self.cents = cents

and an user creates a library depending on this class where he/she uses e.g.

money = Money(27, 12)

print("I have {} dollar and {} cents.".format(money.dollars, money.cents))
# prints I have 27 dollar and 12 cents.

Now let's suppose you decide to change your Money class and get rid of the dollars and cents attributes but instead decide to only track the total amount of cents:

class Money:
    def __init__(self, dollars, cents):
        self.total_cents = dollars * 100 + cents

If the above mentioned user now tries to run his/her library as before

money = Money(27, 12)

print("I have {} dollar and {} cents.".format(money.dollars, money.cents))

it will result in an error

AttributeError: 'Money' object has no attribute 'dollars'

That means that now everyone who relies on your original Money class would have to change all lines of code where dollars and cents are used which can be very painful... So, how could this be avoided? By using @property!

That is how:

class Money:
    def __init__(self, dollars, cents):
        self.total_cents = dollars * 100 + cents

    # Getter and setter for dollars...
    @property
    def dollars(self):
        return self.total_cents // 100

    @dollars.setter
    def dollars(self, new_dollars):
        self.total_cents = 100 * new_dollars + self.cents

    # And the getter and setter for cents.
    @property
    def cents(self):
        return self.total_cents % 100

    @cents.setter
    def cents(self, new_cents):
        self.total_cents = 100 * self.dollars + new_cents

when we now call from our library

money = Money(27, 12)

print("I have {} dollar and {} cents.".format(money.dollars, money.cents))
# prints I have 27 dollar and 12 cents.

it will work as expected and we did not have to change a single line of code in our library! In fact, we would not even have to know that the library we depend on changed.

Also the setter works fine:

money.dollars += 2
print("I have {} dollar and {} cents.".format(money.dollars, money.cents))
# prints I have 29 dollar and 12 cents.

money.cents += 10
print("I have {} dollar and {} cents.".format(money.dollars, money.cents))
# prints I have 29 dollar and 22 cents.

You can use @property also in abstract classes; I give a minimal example here.

How can I reuse a navigation bar on multiple pages?

I know this is a quite old question, but when you have JavaScript available you could use jQuery and its AJAX methods.

First, create a page with all the navigation bar's HTML content.

Next, use jQuery's $.get method to fetch the content of the page. For example, let's say you've put all the navigation bar's HTML into a file called navigation.html and added a placeholder tag (Like <div id="nav-placeholder">) in your index.html, then you would use the following code:

<script src="//code.jquery.com/jquery.min.js"></script>
<script>
$.get("navigation.html", function(data){
    $("#nav-placeholder").replaceWith(data);
});
</script>

Get the directory from a file path in java (android)

I have got solution on this after 4 days, Please note following points while giving path to File class in Android(Java):

  1. Use path for internal storage String path="/storage/sdcard0/myfile.txt";
  2. path="/storage/sdcard1/myfile.txt";
  3. mention permissions in Manifest file.

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

  4. First check file length for confirmation.
  5. Check paths in ES File Explorer regarding sdcard0 & sdcard1 is this same or else......

e.g.

File file=new File(path);
long=file.length();//in Bytes

What is the use of the @Temporal annotation in Hibernate?

This annotation must be specified for persistent fields or properties of type java.util.Date and java.util.Calendar. It may only be specified for fields or properties of these types.

The Temporal annotation may be used in conjunction with the Basic annotation, the Id annotation, or the ElementCollection annotation (when the element collection value is of such a temporal type.

In plain Java APIs, the temporal precision of time is not defined. When dealing with temporal data, you might want to describe the expected precision in database. Temporal data can have DATE, TIME, or TIMESTAMP precision (i.e., the actual date, only the time, or both). Use the @Temporal annotation to fine tune that.

The temporal data is the data related to time. For example, in a content management system, the creation-date and last-updated date of an article are temporal data. In some cases, temporal data needs precision and you want to store precise date/time or both (TIMESTAMP) in database table.

The temporal precision is not specified in core Java APIs. @Temporal is a JPA annotation that converts back and forth between timestamp and java.util.Date. It also converts time-stamp into time. For example, in the snippet below, @Temporal(TemporalType.DATE) drops the time value and only preserves the date.

@Temporal(TemporalType.DATE)
private java.util.Date creationDate;

As per javadocs,

Annotation to declare an appropriate {@code TemporalType} on query method parameters. Note that this annotation can only be used on parameters of type {@link Date} with default TemporalType.DATE

[Information above collected from various sources]

Can I run a 64-bit VMware image on a 32-bit machine?

If your hardware is 32-bit only, then no. If you have 64 bit hardware and a 32-bit operating system, then maybe. See Hardware and Firmware Requirements for 64-Bit Guest Operating Systems for details. It has nothing to do with one vs. multiple processors.

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer in java 1.6

Use:

((Long) userService.getAttendanceList(currentUser)).intValue();

instead.

The .intValue() method is defined in class Number, which Long extends.

What is the use of DesiredCapabilities in Selenium WebDriver?

I know I am very late to answer this question.
But would like to add for further references to the give answers.
DesiredCapabilities are used like setting your config with key-value pair.
Below is an example related to Appium used for Automating Mobile platforms like Android and IOS.
So we generally set DesiredCapabilities for conveying our WebDriver for specific things we will be needing to run our test to narrow down the performance and to increase the accuracy.

So we set our DesiredCapabilities as:

// Created object of DesiredCapabilities class.
DesiredCapabilities capabilities = new DesiredCapabilities();

// Set android deviceName desired capability. Set your device name.
capabilities.setCapability("deviceName", "your Device Name");

// Set BROWSER_NAME desired capability.
capabilities.setCapability(CapabilityType.BROWSER_NAME, "Chrome");

// Set android VERSION desired capability. Set your mobile device's OS version.
capabilities.setCapability(CapabilityType.VERSION, "5.1");

// Set android platformName desired capability. It's Android in our case here.
capabilities.setCapability("platformName", "Android");

// Set android appPackage desired capability.

//You need to check for your appPackage Name for your app, you can use this app for that APK INFO

// Set your application's appPackage if you are using any other app. 
capabilities.setCapability("appPackage", "com.android.appPackageName");

// Set android appActivity desired capability. You can use the same app for finding appActivity of your app
capabilities.setCapability("appActivity", "com.android.calculator2.Calculator");

This DesiredCapabilities are very specific to Appium on Android Platform. For more you can refer to the official site of Selenium desiredCapabilities class

linking jquery in html

Seeing the answers I have nothing else to add but one more thing:

in your test.html file you have written

link rel="stylesheet" type="css/text" href="test.css"/

see where you have written

type="css/text"

there you need to change into

type="text/css"

so it will look like that

link rel="stylesheet" type="text/css" href="test.css"/

and in this case the CSS file will be linked to HTML file

Access mysql remote database from command line

If you want to not use ssh tunnel, in my.cnf or mysqld.cnf you must change 127.0.0.1 with your local ip address (192.168.1.100) in order to have access over the Lan. example bellow:

sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

Search for bind-address in my.cnf or mysqld.cnf

bind-address            =  127.0.0.1

and change 127.0.0.1 to 192.168.1.100 ( local ip address )

bind-address            =  192.168.1.100

To apply the change you made, must restart mysql server using next command.

sudo /etc/init.d/mysql restart

Modify user root for lan acces ( run the query's bellow in remote server that you want to have access )

[email protected]:~$ mysql -u root -p

..

CREATE USER 'root'@'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;

If you want to have access only from specific ip address , change 'root'@'%' to 'root'@'( ip address or hostname)'

CREATE USER 'root'@'192.168.1.100' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.1.100' WITH GRANT OPTION;
FLUSH PRIVILEGES;

Then you can connect:

nobus@xray:~$ mysql -h 192.168.1.100 -u root -p

tested on ubuntu 18.04 server

Get all files and directories in specific path fast

Maybe it will be helpfull for you. You could use "DirectoryInfo.EnumerateFiles" method and handle UnauthorizedAccessException as you need.

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        DirectoryInfo diTop = new DirectoryInfo(@"d:\");
        try
        {
            foreach (var fi in diTop.EnumerateFiles())
            {
                try
                {
                    // Display each file over 10 MB; 
                    if (fi.Length > 10000000)
                    {
                        Console.WriteLine("{0}\t\t{1}", fi.FullName, fi.Length.ToString("N0"));
                    }
                }
                catch (UnauthorizedAccessException UnAuthTop)
                {
                    Console.WriteLine("{0}", UnAuthTop.Message);
                }
            }

            foreach (var di in diTop.EnumerateDirectories("*"))
            {
                try
                {
                    foreach (var fi in di.EnumerateFiles("*", SearchOption.AllDirectories))
                    {
                        try
                        {
                            // Display each file over 10 MB; 
                            if (fi.Length > 10000000)
                            {
                                Console.WriteLine("{0}\t\t{1}",  fi.FullName, fi.Length.ToString("N0"));
                            }
                        }
                        catch (UnauthorizedAccessException UnAuthFile)
                        {
                            Console.WriteLine("UnAuthFile: {0}", UnAuthFile.Message);
                        }
                    }
                }
                catch (UnauthorizedAccessException UnAuthSubDir)
                {
                    Console.WriteLine("UnAuthSubDir: {0}", UnAuthSubDir.Message);
                }
            }
        }
        catch (DirectoryNotFoundException DirNotFound)
        {
            Console.WriteLine("{0}", DirNotFound.Message);
        }
        catch (UnauthorizedAccessException UnAuthDir)
        {
            Console.WriteLine("UnAuthDir: {0}", UnAuthDir.Message);
        }
        catch (PathTooLongException LongPath)
        {
            Console.WriteLine("{0}", LongPath.Message);
        }
    }
}

How can I remove text within parentheses with a regex?

The pattern that matches substrings in parentheses having no other ( and ) characters in between (like (xyz 123) in Text (abc(xyz 123)) is

\([^()]*\)

Details:

  • \( - an opening round bracket (note that in POSIX BRE, ( should be used, see sed example below)
  • [^()]* - zero or more (due to the * Kleene star quantifier) characters other than those defined in the negated character class/POSIX bracket expression, that is, any chars other than ( and )
  • \) - a closing round bracket (no escaping in POSIX BRE allowed)

Removing code snippets:

  • JavaScript: string.replace(/\([^()]*\)/g, '')
  • PHP: preg_replace('~\([^()]*\)~', '', $string)
  • Perl: $s =~ s/\([^()]*\)//g
  • Python: re.sub(r'\([^()]*\)', '', s)
  • C#: Regex.Replace(str, @"\([^()]*\)", string.Empty)
  • VB.NET: Regex.Replace(str, "\([^()]*\)", "")
  • Java: s.replaceAll("\\([^()]*\\)", "")
  • Ruby: s.gsub(/\([^()]*\)/, '')
  • R: gsub("\\([^()]*\\)", "", x)
  • Lua: string.gsub(s, "%([^()]*%)", "")
  • Bash/sed: sed 's/([^()]*)//g'
  • Tcl: regsub -all {\([^()]*\)} $s "" result
  • C++ std::regex: std::regex_replace(s, std::regex(R"(\([^()]*\))"), "")
  • Objective-C:
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\([^()]*\\)" options:NSRegularExpressionCaseInsensitive error:&error]; NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""];
  • Swift: s.replacingOccurrences(of: "\\([^()]*\\)", with: "", options: [.regularExpression])

No log4j2 configuration file found. Using default configuration: logging only errors to the console

Tested with: log4j-ap 2.13.2, log4j-core 2.13.2.

  1. Keep XML file directly under below folder structure. src/main/java
  2. In the POM:
    <build>   
 <resources>       
             <resource>
                <filtering>false</filtering>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>             
            </resource>
 </resources>  
</build>
  1. Clean and build.

Nginx 403 error: directory index of [folder] is forbidden

You need execute permission on your static files directory. Also they need to be chown'ed by your nginx user and group.

Playing .mp3 and .wav in Java?

To give the readers another alternative, I am suggesting JACo MP3 Player library, a cross platform java mp3 player.

Features:

  • very low CPU usage (~2%)
  • incredible small library (~90KB)
  • doesn't need JMF (Java Media Framework)
  • easy to integrate in any application
  • easy to integrate in any web page (as applet).

For a complete list of its methods and attributes you can check its documentation here.

Sample code:

import jaco.mp3.player.MP3Player;
import java.io.File;

public class Example1 {
  public static void main(String[] args) {
    new MP3Player(new File("test.mp3")).play();
  }
}

For more details, I created a simple tutorial here that includes a downloadable sourcecode.