Programs & Examples On #Servlet listeners

The servlet listener interfaces that define the methods to be invoked in response to a desired event.

How do I install Java on Mac OSX allowing version switching?

Note: These solutions work for various versions of Java including Java 8, Java 11, and the new Java 15, and for any other previous Java version covered by the listed version managers. This includes alternative JDK's from OpenJDK, Oracle, IBM, Azul, Amazon Correto, Graal and more. Easily work with Java 7, Java 8, Java 9, Java 10, Java 11, Java 12, Java 13, Java 14, and Java 15!

You have a few options for how to do the installation as well as manage JDK switching. Installation can be done by Homebrew, SDKMAN, Jabba, or a manual install. Switching can be done by JEnv, SDKMAN, Jabba, or manually by setting JAVA_HOME. All of these are described below.


Installation

First, install Java using whatever method you prefer including Homebrew, SDKMAN or a manual install of the tar.gz file. The advantage of a manual install is that the location of the JDK can be placed in a standardized location for Mac OSX. Otherwise, there are easier options such as SDKMAN that also will install other important and common tools for the JVM.

Installing and Switching versions with SDKMAN

SDKMAN is a bit different and handles both the install and the switching. SDKMAN also places the installed JDK's into its own directory tree, which is typically ~/.sdkman/candidates/java. SDKMAN allows setting a global default version, and a version specific to the current shell.

  1. Install SDKMAN from https://sdkman.io/install

  2. List the Java versions available to make sure you know the version ID

    sdk list java
    
  3. Install one of those versions, for example, Java 15:

    sdk install java 15-open 
    
  4. Make 15 the default version:

    sdk default java 15-open
    

    Or switch to 15 for the session:

    sdk use java 15-open
    

When you list available versions for installation using the list command, you will see a wide variety of distributions of Java:

sdk list java

And install additional versions, such as JDK 8:

sdk install java 8.0.181-oracle

SDKMAN can work with previously installed existing versions. Just do a local install giving your own version label and the location of the JDK:

sdk install java my-local-13 /Library/Java/JavaVirtualMachines/jdk-13.jdk/Contents/Home

And use it freely:

sdk use java my-local-13

More information is available in the SDKMAN Usage Guide along with other SDK's it can install and manage.

SDKMAN will automatically manage your PATH and JAVA_HOME for you as you change versions.


Install manually from OpenJDK download page:

  1. Download OpenJDK for Mac OSX from http://jdk.java.net/ (for example Java 15)

  2. Unarchive the OpenJDK tar, and place the resulting folder (i.e. jdk-15.jdk) into your /Library/Java/JavaVirtualMachines/ folder since this is the standard and expected location of JDK installs. You can also install anywhere you want in reality.

Install with Homebrew

The version of Java available in Homebrew Cask previous to October 3, 2018 was indeed the Oracle JVM. Now, however, it has now been updated to OpenJDK. Be sure to update Homebrew and then you will see the lastest version available for install.

  1. install Homebrew if you haven't already. Make sure it is updated:

     brew update
    
  2. Add the casks tap, if you want to use the AdoptOpenJDK versions (which tend to be more current):

     brew tap adoptopenjdk/openjdk
    

    These casks change their Java versions often, and there might be other taps out there with additional Java versions.

  3. Look for installable versions:

     brew search java   
    

    or for AdoptOpenJDK versions:

     brew search jdk     
    
  4. Check the details on the version that will be installed:

     brew info java
    

    or for the AdoptOpenJDK version:

     brew info adoptopenjdk
    
  5. Install a specific version of the JDK such as java11, adoptopenjdk8, or adoptopenjdk13, or just java or adoptopenjdk for the most current of that distribution. For example:

     brew install java
    
     brew cask install adoptopenjdk13
    

And these will be installed into /Library/Java/JavaVirtualMachines/ which is the traditional location expected on Mac OSX.

Other installation options:

Some other flavours of OpenJDK are:

Azul Systems Java Zulu certified builds of OpenJDK can be installed by following the instructions on their site.

Zulu® is a certified build of OpenJDK that is fully compliant with the Java SE standard. Zulu is 100% open source and freely downloadable. Now Java developers, system administrators, and end-users can enjoy the full benefits of open source Java with deployment flexibility and control over upgrade timing.

Amazon Correto OpenJDK builds have an easy to use an installation package for Java 8 or Java 11, and installs to the standard /Library/Java/JavaVirtualMachines/ directory on Mac OSX.

Amazon Corretto is a no-cost, multiplatform, production-ready distribution of the Open Java Development Kit (OpenJDK). Corretto comes with long-term support that will include performance enhancements and security fixes. Amazon runs Corretto internally on thousands of production services and Corretto is certified as compatible with the Java SE standard. With Corretto, you can develop and run Java applications on popular operating systems, including Linux, Windows, and macOS.


Where is my JDK?!?!

To find locations of previously installed Java JDK's installed at the default system locations, use:

/usr/libexec/java_home -V

Matching Java Virtual Machines (8):
15, x86_64: "OpenJDK 15" /Library/Java/JavaVirtualMachines/jdk-15.jdk/Contents/Home 14, x86_64: "OpenJDK 14" /Library/Java/JavaVirtualMachines/jdk-14.jdk/Contents/Home 13, x86_64: "OpenJDK 13" /Library/Java/JavaVirtualMachines/openjdk-13.jdk/Contents/Home 12, x86_64: "OpenJDK 12" /Library/Java/JavaVirtualMachines/jdk-12.jdk/Contents/Home
11, x86_64: "Java SE 11" /Library/Java/JavaVirtualMachines/jdk-11.jdk/Contents/Home
10.0.2, x86_64: "Java SE 10.0.2" /Library/Java/JavaVirtualMachines/jdk-10.0.2.jdk/Contents/Home
9, x86_64: "Java SE 9" /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home
1.8.0_144, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home

You can also report just the location of a specific Java version using -v. For example for Java 15:

/usr/libexec/java_home -v 15

/Library/Java/JavaVirtualMachines/jdk-15.jdk/Contents/Home

Knowing the location of the installed JDK's is also useful when using tools like JEnv, or adding a local install to SDKMAN, or linking a system JDK in Jabba -- and you need to know where to find them.

If you need to find JDK's installed by other tools, check these locations:

  • SDKMAN installs to ~/.sdkman/candidates/java/
  • Jabba installs to ~/.jabba/jdk

Switching versions manually

The Java executable is a wrapper that will use whatever JDK is configured in JAVA_HOME, so you can change that to also change which JDK is in use.

For example, if you installed or untar'd JDK 15 to /Library/Java/JavaVirtualMachines/jdk-15.jdk if it is the highest version number it should already be the default, if not you could simply set:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-15.jdk/Contents/Home

And now whatever Java executable is in the path will see this and use the correct JDK.

Using the /usr/libexec/java_home utility as previously described helps you to create aliases or to run commands to change Java versions by identifying the locations of different JDK installations. For example, creating shell aliases in your .profile or .bash_profile to change JAVA_HOME for you:

export JAVA_8_HOME=$(/usr/libexec/java_home -v1.8)
export JAVA_9_HOME=$(/usr/libexec/java_home -v9)
export JAVA_10_HOME=$(/usr/libexec/java_home -v10)
export JAVA_11_HOME=$(/usr/libexec/java_home -v11)
export JAVA_12_HOME=$(/usr/libexec/java_home -v12)
export JAVA_13_HOME=$(/usr/libexec/java_home -v13)
export JAVA_14_HOME=$(/usr/libexec/java_home -v14)
export JAVA_15_HOME=$(/usr/libexec/java_home -v15)

alias java8='export JAVA_HOME=$JAVA_8_HOME'
alias java9='export JAVA_HOME=$JAVA_9_HOME'
alias java10='export JAVA_HOME=$JAVA_10_HOME'
alias java11='export JAVA_HOME=$JAVA_11_HOME'
alias java12='export JAVA_HOME=$JAVA_12_HOME'
alias java13='export JAVA_HOME=$JAVA_13_HOME'
alias java14='export JAVA_HOME=$JAVA_14_HOME'
alias java15='export JAVA_HOME=$JAVA_15_HOME'

# default to Java 15
java15

Then to change versions, just use the alias.

java8
java -version

java version "1.8.0_144"

Of course, setting JAVA_HOME manually works too!


Switching versions with JEnv

JEnv expects the Java JDK's to already exist on the machine and can be in any location. Typically you will find installed Java JDK's in /Library/Java/JavaVirtualMachines/. JEnv allows setting the global version of Java, one for the current shell, and a per-directory local version which is handy when some projects require different versions than others.

  1. Install JEnv if you haven't already, instructions on the site http://www.jenv.be/ for manual install or using Homebrew.

  2. Add any Java version to JEnv (adjust the directory if you placed this elsewhere):

    jenv add /Library/Java/JavaVirtualMachines/jdk-15.jdk/Contents/Home
    
  3. Set your global version using this command:

    jenv global 15
    

You can also add other existing versions using jenv add in a similar manner, and list those that are available. For example Java 8:

jenv add /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home 
jenv versions

See the JEnv docs for more commands. You may now switch between any Java versions (Oracle, OpenJDK, other) at any time either for the whole system, for shells, or per local directory.

To help manage JAVA_HOME while using JEnv you can add the export plugin to do this for you.

$ jenv enable-plugin export
  You may restart your session to activate jenv export plugin echo export plugin activated

The export plugin may not adjust JAVA_HOME if it is already set, so you may need to clear this variable in your profile so that it can be managed by JEnv.

You can also use jenv exec <command> <parms...> to run single commands with JAVA_HOME and PATH set correctly for that one command, which could include opening another shell.


Installing and Switching versions with Jabba

Jabba also handles both the install and the switching. Jabba also places the installed JDK's into its own directory tree, which is typically ~/.jabba/jdk.

  1. Install Jabba by following the instructions on the home page.

  2. List available JDK's

    jabba ls-remote

  3. Install Java JDK 12

    jabba install [email protected]

  4. Use it:

    jabba use [email protected]

You can also alias version names, link to existing JDK's already installed, and find a mix of interesting JDK's such as GraalVM, Adopt JDK, IBM JDK, and more. The complete usage guide is available on the home page as well.

Jabba will automatically manage your PATH and JAVA_HOME for you as you change versions.

Importing xsd into wsdl

import vs. include

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

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

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

WSDL:

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

XSD:

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

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

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

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

WPF: simple TextBox data binding

Your Window is not implementing the necessary data binding notifications that the grid requires to use it as a data source, namely the INotifyPropertyChanged interface.

Your "Name2" string needs also to be a property and not a public variable, as data binding is for use with properties.

Implementing the necessary interfaces for using an object as a data source can be found here.

Could not load NIB in bundle

Your XIB file is probably outside your project folder. This leads to not showing up the Target Inspector. However, moving the XIB file into your project folder should fix it.

How to loop through each and every row, column and cells in a GridView and get its value

As it's said by "Tim Schmelter" this is the best way : just change in it's code the seconde loop ( GridView2.Columns[i].Count by row.Cells.Count ) so it looks seem's that:

foreach(GridViewRow row in GridView2.Rows)
{
    for(int i = 0; i < GridView2.Columns.Count; i++)
    {
        String header = GridView2.Columns[i].HeaderText;
        String cellText = row.Cells[i].Text;
    }
}

thank you.

Excel compare two columns and highlight duplicates

NOTE: You may want to remove duplicate items (eg duplicate entries in the same column) before doing these steps to prevent false positives.

  1. Select both columns
  2. click Conditional Formatting
  3. click Highlight Cells Rules
  4. click Duplicate Values (the defaults should be OK)
  5. Duplicates are now highlighted in red:

enter image description here

enter image description here

How do you get the file size in C#?

The FileInfo class' Length property returns the size of the file (not the size on disk). If you want a formatted file size (i.e. 15 KB) rather than a long byte value you can use CSharpLib, a package I've made that adds more functionality to the FileInfo class. Here's an example:

using CSharpLib;
FileInfo info = new FileInfo("sample.txt");
Console.WriteLine(info.FormatBytes());  // Output: 15 MB

Clearing UIWebview cache

My educated guess is that the memory use you are seeing is not from the page content, but rather from loading UIWebView and all of it's supporting WebKit libraries. I love the UIWebView control, but it is a 'heavy' control that pulls in a very large block of code.

This code is a large sub-set of the iOS Safari browser, and likely initializes a large body of static structures.

Cross Domain Form POSTing

It is possible to build an arbitrary GET or POST request and send it to any server accessible to a victims browser. This includes devices on your local network, such as Printers and Routers.

There are many ways of building a CSRF exploit. A simple POST based CSRF attack can be sent using .submit() method. More complex attacks, such as cross-site file upload CSRF attacks will exploit CORS use of the xhr.withCredentals behavior.

CSRF does not violate the Same-Origin Policy For JavaScript because the SOP is concerned with JavaScript reading the server's response to a clients request. CSRF attacks don't care about the response, they care about a side-effect, or state change produced by the request, such as adding an administrative user or executing arbitrary code on the server.

Make sure your requests are protected using one of the methods described in the OWASP CSRF Prevention Cheat Sheet. For more information about CSRF consult the OWASP page on CSRF.

How to send a JSON object using html form data

I found a way to pass a JSON message using only a HTML form.

This example is for GraphQL but it will work for any endpoint that is expecting a JSON message.

GrapqhQL by default expects a parameter called operations where you can add your query or mutation in JSON format. In this specific case I am invoking this query which is requesting to get allUsers and return the userId of each user.

{ 
 allUsers 
  { 
  userId 
  }
}

I am using a text input to demonstrate how to use it, but you can change it for a hidden input to hide the query from the user.

<html>
<body>
    <form method="post" action="http://localhost:8080/graphql">
        <input type="text" name="operations" value="{&quot;query&quot;: &quot;{ allUsers { userId } }&quot;, "variables":  {}}"/>
        <input type="submit" />
    </form>
</body>
</html>

In order to make this dynamic you will need JS to transport the values of the text fields to the query string before submitting your form. Anyway I found this approach very interesting. Hope it helps.

Undefined symbols for architecture i386

A bit late to the party but might be valuable to someone with this error..

I just straight copied a bunch of files into an Xcode project, if you forget to add them to your projects Build Phases you will get the error "Undefined symbols for architecture i386". So add your implementation files to Compile Sources, and Xib files to Copy Bundle Resources.

The error was telling me that there was no link to my classes simply because they weren't included in the Compile Sources, quite obvious really but may save someone a headache.

Bootstrap 3 - 100% height of custom div inside column

You need to set the height of every parent element of the one you want the height defined.

<html style="height: 100%;">
  <body style="height: 100%;">
    <div style="height: 100%;">
      <p>
        Make this division 100% height.
      </p>
    </div>
  </body>
</html>

Article.

JsFiddle example

How to change permissions for a folder and its subfolders/files in one step?

If you want to set permissions on all files to a+r, and all directories to a+x, and do that recursively through the complete subdirectory tree, use:

chmod -R a+rX *

The X (that is capital X, not small x!) is ignored for files (unless they are executable for someone already) but is used for directories.

jQuery.ajax returns 400 Bad Request

I was getting the 400 Bad Request error, even after setting:

contentType: "application/json",
dataType: "json"

The issue was with the type of a property passed in the json object, for the data property in the ajax request object.
To figure out the issue, I added an error handler and then logged the error to the console. Console log will clearly show validation errors for the properties if any.

This was my initial code:

var data = {
    "TestId": testId,
    "PlayerId": parseInt(playerId),
    "Result": result
};

var url = document.location.protocol + "//" + document.location.host + "/api/tests"
$.ajax({
    url: url,
    method: "POST",
    contentType: "application/json",
    data: JSON.stringify(data), // issue with a property type in the data object
    dataType: "json",
    error: function (e) {
        console.log(e); // logging the error object to console
    },
    success: function () {
        console.log('Success saving test result');
    }
});

Now after making the request, I checked the console tab in the browser development tool.
It looked like this: enter image description here

responseJSON.errors[0] clearly shows a validation error: The JSON value could not be converted to System.String. Path: $.TestId, which means I have to convert TestId to a string in the data object, before making the request.

Changing the data object creation like below fixed the issue for me:

var data = {
        "TestId": String(testId), //converting testId to a string
        "PlayerId": parseInt(playerId),
        "Result": result
};

I assume other possible errors could also be identified by logging and inspecting the error object.

How to stop default link click behavior with jQuery

I've just wasted an hour on this. I tried everything - it turned out (and I can hardly believe this) that giving my cancel button and element id of cancel meant that any attempt to prevent event propagation would fail! I guess an HTML page must treat this as someone pressing ESC?

.htaccess rewrite subdomain to directory

Try putting this in your .htaccess file:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^sub.domain.com
RewriteRule ^(.*)$ /subdomains/sub/$1 [L,NC,QSA]

For a more general rule (that works with any subdomain, not just sub) replace the last two lines with this:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(.*)\.domain\.com
RewriteRule ^(.*)$ subdomains/%1/$1 [L,NC,QSA]

Manually install Gradle and use it in Android Studio

in first step you should go to http://www.gradle.org/downloads and then choose your Gradle version and follow download link in GitHub and then download Gradle from GitHub. after your download is completed, you should extract the downloaded file in a directory (every directory that you want). finally open extracted folder and just run gradlew.bat and wait several minutes for completing download. and after completing download files, Gradle install itself automaticly. Gradle will work correctly for next times. i resolve this problem with this way and i tested it and every things are ok, so every one can test this way, it should working well. Good Luck.

Value of type 'T' cannot be converted to

Even though it's inside of an if block, the compiler doesn't know that T is string.
Therefore, it doesn't let you cast. (For the same reason that you cannot cast DateTime to string)

You need to cast to object, (which any T can cast to), and from there to string (since object can be cast to string).
For example:

T newT1 = (T)(object)"some text";
string newT2 = (string)(object)t;

Dynamically Fill Jenkins Choice Parameter With Git Branches In a Specified Repo

The following groovy script would be useful, if your job does not use "Source Code Management" directly (likewise "Git Parameter Plugin"), but still have access to a local (cloned) git repository:

import jenkins.model.Jenkins

def envVars = Jenkins.instance.getNodeProperties()[0].getEnvVars() 
def GIT_PROJECT_PATH = envVars.get('GIT_PROJECT_PATH') 
def gettags = "git ls-remote -t --heads origin".execute(null, new File(GIT_PROJECT_PATH))

return gettags.text.readLines()
         .collect { it.split()[1].replaceAll('\\^\\{\\}', '').replaceAll('refs/\\w+/', '')  }
         .unique()

See full explanation here: https://stackoverflow.com/a/37810768/658497

Javascript switch vs. if...else if...else

Answering in generalities:

  1. Yes, usually.
  2. See More Info Here
  3. Yes, because each has a different JS processing engine, however, in running a test on the site below, the switch always out performed the if, elseif on a large number of iterations.

Test site

How does ifstream's eof() work?

-1 is get's way of saying you've reached the end of file. Compare it using the std::char_traits<char>::eof() (or std::istream::traits_type::eof()) - avoid -1, it's a magic number. (Although the other one is a bit verbose - you can always just call istream::eof)

The EOF flag is only set once a read tries to read past the end of the file. If I have a 3 byte file, and I only read 3 bytes, EOF is false, because I've not tried to read past the end of the file yet. While this seems confusing for files, which typically know their size, EOF is not known until a read is attempted on some devices, such as pipes and network sockets.

The second example works as inf >> foo will always return inf, with the side effect of attempt to read something and store it in foo. inf, in an if or while, will evaluate to true if the file is "good": no errors, no EOF. Thus, when a read fails, inf evaulates to false, and your loop properly aborts. However, take this common error:

while(!inf.eof())  // EOF is false here
{
    inf >> x;      // read fails, EOF becomes true, x is not set
    // use x       // we use x, despite our read failing.
}

However, this:

while(inf >> x)  // Attempt read into x, return false if it fails
{
    // will only be entered if read succeeded.
}

Which is what we want.

Run Command Prompt Commands

You can do this using CliWrap in one line:

var stdout = new Cli("cmd")
         .Execute("copy /b Image1.jpg + Archive.rar Image2.jpg")
         .StandardOutput;

How does functools partial do what it does?

Also worth to mention, that when partial function passed another function where we want to "hard code" some parameters, that should be rightmost parameter

def func(a,b):
    return a*b
prt = partial(func, b=7)
    print(prt(4))
#return 28

but if we do the same, but changing a parameter instead

def func(a,b):
    return a*b
 prt = partial(func, a=7)
    print(prt(4))

it will throw error, "TypeError: func() got multiple values for argument 'a'"

Google server putty connect 'Disconnected: No supported authentication methods available (server sent: publickey)

If the private key has been generated with ssh-keygen in Linux it needs to be converted with puttygen because Putty does not support openssh keys.

Start puttygen, and click on Conversions - Import key, then click Browse and select the private key generated with openssh, then click on Save private key.

Use your new key to connect.

Electron: jQuery is not defined

im building and Angular App with electron, my solution was the following:

index.html

<script>
    if ( typeof module === "object" && typeof module.exports === "object" ) {
      window.$ = window.jQuery = require('jquery');
    }
</script>

angular.json

"scripts": [
              "node_modules/jquery/dist/jquery.min.js",
              "node_modules/popper.js/dist/umd/popper.min.js",
              "node_modules/bootstrap/dist/js/bootstrap.min.js"
            ]

So Jquery gets loaded from angular.json if on browser, else if it is an electron builded app it will require module instead.

If you want to import jquery in index.html instead of importing from angular.json use the following solution:

<script src="path/to/jquery"></script>
<script>
    if ( typeof module === "object" && typeof module.exports === "object" ) {
      window.$ = window.jQuery = require('jquery');
    }
</script>

how to convert a string date to date format in oracle10g

You can convert a string to a DATE using the TO_DATE function, then reformat the date as another string using TO_CHAR, i.e.:

SELECT TO_CHAR(
         TO_DATE('15/August/2009,4:30 PM'
                ,'DD/Month/YYYY,HH:MI AM')
       ,'DD-MM-YYYY')
FROM DUAL;

15-08-2009

For example, if your table name is MYTABLE and the varchar2 column is MYDATESTRING:

SELECT TO_CHAR(
         TO_DATE(MYDATESTRING
                ,'DD/Month/YYYY,HH:MI AM')
       ,'DD-MM-YYYY')
FROM MYTABLE;

Add some word to all or some rows in Excel?

  • Select All cells that want to change.
  • right click and select Format cell.
  • In category select Custom.
  • In Type select General and insert this formol ----> "k"@

Android draw a Horizontal line between views

_x000D_
_x000D_
 <view
        android:id="@+id/blackLine"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#000000"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>
_x000D_
_x000D_
_x000D_

app:layout_constraintStart_toStartOf="parent"/>

Changing file permission in Python

You can use, pathlib also

from pathlib import Path

fl = Path("file_name")

fl.chmod(0o444)

Java Wait for thread to finish

Thread has a method that does that for you join which will block until the thread has finished executing.

Change keystore password from no password to a non blank password

If you're trying to do stuff with the Java default system keystore (cacerts), then the default password is changeit.

You can list keys without needing the password (even if it prompts you) so don't take that as an indication that it is blank.

(Incidentally who in the history of Java ever has changed the default keystore password? They should have left it blank.)

How to detect simple geometric shapes using OpenCV

The answer depends on the presence of other shapes, level of noise if any and invariance you want to provide for (e.g. rotation, scaling, etc). These requirements will define not only the algorithm but also required pre-procesing stages to extract features.

Template matching that was suggested above works well when shapes aren't rotated or scaled and when there are no similar shapes around; in other words, it finds a best translation in the image where template is located:

double minVal, maxVal;
Point minLoc, maxLoc;
Mat image, template, result; // template is your shape
matchTemplate(image, template, result, CV_TM_CCOEFF_NORMED);
minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc); // maxLoc is answer

Geometric hashing is a good method to get invariance in terms of rotation and scaling; this method would require extraction of some contour points.

Generalized Hough transform can take care of invariance, noise and would have minimal pre-processing but it is a bit harder to implement than other methods. OpenCV has such transforms for lines and circles.

In the case when number of shapes is limited calculating moments or counting convex hull vertices may be the easiest solution: openCV structural analysis

"implements Runnable" vs "extends Thread" in Java

Runnable because:

  • Leaves more flexibility for the Runnable implementation to extend another class
  • Separates the code from execution
  • Allows you to run your runnable from a Thread Pool, the event thread, or in any other way in the future.

Even if you don't need any of this now, you may in the future. Since there is no benefit to overriding Thread, Runnable is a better solution.

Cloning a private Github repo

This worked for me:

git clone https://[email protected]/username/repo_name

Why GDB jumps unpredictably between lines and prints variables as "<value optimized out>"?

Im using QtCreator with gdb.

Adding

QMAKE_CXXFLAGS += -O0
QMAKE_CXXFLAGS -= -O1
QMAKE_CXXFLAGS -= -O2
QMAKE_CXXFLAGS -= -O3

Works well for me

Change image size with JavaScript

If you want to resize an image after it is loaded, you can attach to the onload event of the <img> tag. Note that it may not be supported in all browsers (Microsoft's reference claims it is part of the HTML 4.0 spec, but the HTML 4.0 spec doesn't list the onload event for <img>).

The code below is tested and working in: IE 6, 7 & 8, Firefox 2, 3 & 3.5, Opera 9 & 10, Safari 3 & 4 and Google Chrome:

<img src="yourImage.jpg" border="0" height="real_height" width="real_width"
    onload="resizeImg(this, 200, 100);">

<script type="text/javascript">
function resizeImg(img, height, width) {
    img.height = height;
    img.width = width;
}
</script>

Random element from string array

Just store the index generated in a variable, and then access the array using this varaible:

int idx = new Random().nextInt(fruits.length);
String random = (fruits[idx]);

P.S. I usually don't like generating new Random object per randoization - I prefer using a single Random in the program - and re-use it. It allows me to easily reproduce a problematic sequence if I later find any bug in the program.

According to this approach, I will have some variable Random r somewhere, and I will just use:

int idx = r.nextInt(fruits.length)

However, your approach is OK as well, but you might have hard time reproducing a specific sequence if you need to later on.

How to execute a raw update sql with dynamic binding in rails

Here's a trick I recently worked out for executing raw sql with binds:

binds = SomeRecord.bind(a_string_field: value1, a_date_field: value2) +
        SomeOtherRecord.bind(a_numeric_field: value3)
SomeRecord.connection.exec_query <<~SQL, nil, binds
  SELECT *
  FROM some_records
  JOIN some_other_records ON some_other_records.record_id = some_records.id
  WHERE some_records.a_string_field = $1
    AND some_records.a_date_field < $2
    AND some_other_records.a_numeric_field > $3
SQL

where ApplicationRecord defines this:

# Convenient way of building custom sql binds
def self.bind(column_values)
  column_values.map do |column_name, value|
    [column_for_attribute(column_name), value]
  end
end

and that is similar to how AR binds its own queries.

Pipe to/from the clipboard in Bash script

If you're like me and run on a Linux server without root privileges and there isn't any xclip or GPM you could workaround this issue by just using a temporary file. For example:

$ echo "Hello, World!" > ~/clip
$ echo `cat ~/clip`
Hello, World!

What is "overhead"?

Wikipedia has us covered:

In computer science, overhead is generally considered any combination of excess or indirect computation time, memory, bandwidth, or other resources that are required to attain a particular goal. It is a special case of engineering overhead.

How to connect to SQL Server database from JavaScript in the browser?

You shouldn´t use client javascript to access databases for several reasons (bad practice, security issues, etc) but if you really want to do this, here is an example:

var connection = new ActiveXObject("ADODB.Connection") ;

var connectionstring="Data Source=<server>;Initial Catalog=<catalog>;User ID=<user>;Password=<password>;Provider=SQLOLEDB";

connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");

rs.Open("SELECT * FROM table", connection);
rs.MoveFirst
while(!rs.eof)
{
   document.write(rs.fields(1));
   rs.movenext;
}

rs.close;
connection.close; 

A better way to connect to a sql server would be to use some server side language like PHP, Java, .NET, among others. Client javascript should be used only for the interfaces.

And there are rumors of an ancient legend about the existence of server javascript, but this is another story. ;)

submit the form using ajax

Here is a universal solution that iterates through every field in form and creates the request string automatically. It is using new fetch API. Automatically reads form attributes: method and action and grabs all fields inside the form. Support single-dimension array fields, like emails[]. Could serve as universal solution to manage easily many (perhaps dynamic) forms with single source of truth - html.

document.querySelector('.ajax-form').addEventListener('submit', function(e) {
    e.preventDefault();
    let formData = new FormData(this);
    let parsedData = {};
    for(let name of formData) {
      if (typeof(parsedData[name[0]]) == "undefined") {
        let tempdata = formData.getAll(name[0]);
        if (tempdata.length > 1) {
          parsedData[name[0]] = tempdata;
        } else {
          parsedData[name[0]] = tempdata[0];
        }
      }
    }

    let options = {};
    switch (this.method.toLowerCase()) {
      case 'post':
        options.body = JSON.stringify(parsedData);
      case 'get':
        options.method = this.method;
        options.headers = {'Content-Type': 'application/json'};
      break;
    }

    fetch(this.action, options).then(r => r.json()).then(data => {
      console.log(data);
    });
});

<form method="POST" action="some/url">
    <input name="emails[]">
    <input name="emails[]">
    <input name="emails[]">
    <input name="name">
    <input name="phone">
</form>

Python 3 Float Decimal Points/Precision

The comments state the objective is to print to 2 decimal places.

There's a simple answer for Python 3:

>>> num=3.65
>>> "The number is {:.2f}".format(num)
'The number is 3.65'

or equivalently with f-strings (Python 3.6+):

>>> num = 3.65
>>> f"The number is {num:.2f}"
'The number is 3.65'

As always, the float value is an approximation:

>>> "{}".format(num)
'3.65'
>>> "{:.10f}".format(num)
'3.6500000000'
>>> "{:.20f}".format(num)
'3.64999999999999991118'

I think most use cases will want to work with floats and then only print to a specific precision.

Those that want the numbers themselves to be stored to exactly 2 decimal digits of precision, I suggest use the decimal type. More reading on floating point precision for those that are interested.

Generate Json schema from XML schema (XSD)

Disclaimer: I'm the author of jgeXml.

jgexml has Node.js based utility xsd2json which does a transformation between an XML schema (XSD) and a JSON schema file.

As with other options, it's not a 1:1 conversion, and you may need to hand-edit the output to improve the JSON schema validation, but it has been used to represent a complex XML schema inside an OpenAPI (swagger) definition.

A sample of the purchaseorder.xsd given in another answer is rendered as:

"PurchaseOrderType": {
  "type": "object",
  "properties": {
    "shipTo": {
      "$ref": "#/definitions/USAddress"
    },
    "billTo": {
      "$ref": "#/definitions/USAddress"
    },
    "comment": {
      "$ref": "#/definitions/comment"
    },
    "items": {
      "$ref": "#/definitions/Items"
    },
    "orderDate": {
      "type": "string",
      "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}.*$"
    }
  },

Need a row count after SELECT statement: what's the optimal SQL approach?

Approach 2 will always return a count that matches your result set.

I suggest you link the sub-query to your outer query though, to guarantee that the condition on your count matches the condition on the dataset.

SELECT 
  mt.my_row,
 (SELECT COUNT(mt2.my_row) FROM my_table mt2 WHERE mt2.foo = mt.foo) as cnt
FROM my_table mt
WHERE mt.foo = 'bar';

How can I create a dynamic button click event on a dynamic button?

It is much easier to do:

Button button = new Button();
button.Click += delegate
{
   // Your code
};

Formatting floats in a numpy array

In order to make numpy display float arrays in an arbitrary format, you can define a custom function that takes a float value as its input and returns a formatted string:

In [1]: float_formatter = "{:.2f}".format

The f here means fixed-point format (not 'scientific'), and the .2 means two decimal places (you can read more about string formatting here).

Let's test it out with a float value:

In [2]: float_formatter(1.234567E3)
Out[2]: '1234.57'

To make numpy print all float arrays this way, you can pass the formatter= argument to np.set_printoptions:

In [3]: np.set_printoptions(formatter={'float_kind':float_formatter})

Now numpy will print all float arrays this way:

In [4]: np.random.randn(5) * 10
Out[4]: array([5.25, 3.91, 0.04, -1.53, 6.68]

Note that this only affects numpy arrays, not scalars:

In [5]: np.pi
Out[5]: 3.141592653589793

It also won't affect non-floats, complex floats etc - you will need to define separate formatters for other scalar types.

You should also be aware that this only affects how numpy displays float values - the actual values that will be used in computations will retain their original precision.

For example:

In [6]: a = np.array([1E-9])

In [7]: a
Out[7]: array([0.00])

In [8]: a == 0
Out[8]: array([False], dtype=bool)

numpy prints a as if it were equal to 0, but it is not - it still equals 1E-9.

If you actually want to round the values in your array in a way that affects how they will be used in calculations, you should use np.round, as others have already pointed out.

Difference between SRC and HREF

They don't have similar meanings. 'src' indicates a resource the browser should fetch as part of the current page. HREF indicatea a resource to be fetched if the user requests it.

How can I use external JARs in an Android project?

Goto Current Project

RightClick->Properties->Java Build Path->Add Jar Files into Libraries -> Click OK

Then it is added into the Referenced Libraries File in your Current Project .

How do I get a PHP class constructor to call its parent's parent's constructor?

You must use Grandpa::__construct(), there's no other shortcut for it. Also, this ruins the encapsulation of the Papa class - when reading or working on Papa, it should be safe to assume that the __construct() method will be called during construction, but the Kiddo class does not do this.

Logarithmic returns in pandas dataframe

Here is one way to calculate log return using .shift(). And the result is similar to but not the same as the gross return calculated by pct_change(). Can you upload a copy of your sample data (dropbox share link) to reproduce the inconsistency you saw?

import pandas as pd
import numpy as np

np.random.seed(0)
df = pd.DataFrame(100 + np.random.randn(100).cumsum(), columns=['price'])
df['pct_change'] = df.price.pct_change()
df['log_ret'] = np.log(df.price) - np.log(df.price.shift(1))

Out[56]: 
       price  pct_change  log_ret
0   101.7641         NaN      NaN
1   102.1642      0.0039   0.0039
2   103.1429      0.0096   0.0095
3   105.3838      0.0217   0.0215
4   107.2514      0.0177   0.0176
5   106.2741     -0.0091  -0.0092
6   107.2242      0.0089   0.0089
7   107.0729     -0.0014  -0.0014
..       ...         ...      ...
92  101.6160      0.0021   0.0021
93  102.5926      0.0096   0.0096
94  102.9490      0.0035   0.0035
95  103.6555      0.0069   0.0068
96  103.6660      0.0001   0.0001
97  105.4519      0.0172   0.0171
98  105.5788      0.0012   0.0012
99  105.9808      0.0038   0.0038

[100 rows x 3 columns]

JFrame Exit on close Java

The following code works for me:

System.exit(home.EXIT_ON_CLOSE);

Python int to binary string?

Along a similar line to Yusuf Yazici's answer

def intToBin(n):
    if(n < 0):
        print "Sorry, invalid input."
    elif(n == 0):
        print n
    else:
        result = ""
        while(n != 0):
            result += str(n%2)
            n /= 2
        print result[::-1]

I adjusted it so that the only variable being mutated is result (and n of course).

If you need to use this function elsewhere (i.e., have the result used by another module), consider the following adjustment:

def intToBin(n):
    if(n < 0):
        return -1
    elif(n == 0):
        return str(n)
    else:
        result = ""
        while(n != 0):
            result += str(n%2)
            n //= 2            #added integer division
        return result[::-1]

So -1 will be your sentinel value indicating the conversion failed. (This is assuming you are converting ONLY positive numbers, whether they be integers or longs).

Go to Matching Brace in Visual Studio?

On a Mac use command+shift+\.

Source: a comment on this answer: https://stackoverflow.com/a/37877082/3345085. Tested in Visual Studio Code version 1.10.2.

View JSON file in Browser

Right click on JSON file, select open, navigate to program you want open with(notepad). Consecutive opens automatically use notepad.

Do checkbox inputs only post data if they're checked?

None of the above answers satisfied me. I found the best solution is to include a hidden input before each checkbox input with the same name.

<input type="hidden" name="foo[]" value="off"/>

<input type="checkbox" name="foo[]"/>

Then on the server side, using a little algorithm you can get something more like HTML should provide.

function checkboxHack(array $checkbox_input): array
{
    $foo = [];
    foreach($checkbox_input as $value) {
        if($value === 'on') {
            array_pop($foo);
        }
        $foo[] = $value;
    }
    return $foo;
}

This will be the raw input

array (
    0 => 'off',
    1 => 'on',
    2 => 'off',
    3 => 'off',
    4 => 'on',
    5 => 'off',
    6 => 'on',
),

And the function will return

array (
    0 => 'on',
    1 => 'off',
    2 => 'on',
    3 => 'on',
)  

AndroidStudio SDK directory does not exists

I finally find this file on the disk.The 'local.properties' file in The Android studio is not which you modify.see the picture,so you can modify this line 'sdk.dir' to your dir of sdk.Remember not in the android studio. enter image description here

White space showing up on right side of page when background image should extend full length of page

This question has been hanging around for a while, but none of the fixes I could find worked for me (having the same issue with ipad), but I managed my own solution which should work for most people I imagine.

Here's my code:

html {
   background: url("../images/blahblah.jpg") repeat-y;
   min-width: 100%;
   background-size: contain;
}

Enjoy!

How to list all the files in a commit?

$ git log 88ee8^..88ee8 --name-only --pretty="format:"

PHP CURL & HTTPS

I was trying to use CURL to do some https API calls with php and ran into this problem. I noticed a recommendation on the php site which got me up and running: http://php.net/manual/en/function.curl-setopt.php#110457

Please everyone, stop setting CURLOPT_SSL_VERIFYPEER to false or 0. If your PHP installation doesn't have an up-to-date CA root certificate bundle, download the one at the curl website and save it on your server:

http://curl.haxx.se/docs/caextract.html

Then set a path to it in your php.ini file, e.g. on Windows:

curl.cainfo=c:\php\cacert.pem

Turning off CURLOPT_SSL_VERIFYPEER allows man in the middle (MITM) attacks, which you don't want!

Maven: How to rename the war file for the project?

Lookup pom.xml > project tag > build tag.

I would like solution below.

<artifactId>bird</artifactId>
<name>bird</name>

<build>
    ...
    <finalName>${project.artifactId}</finalName>
  OR
    <finalName>${project.name}</finalName>
    ...
</build>

Worked for me. ^^

Use sed to replace all backslashes with forward slashes

If your text is in a Bash variable, then Parameter Substitution ${var//\\//} can replace substrings:

$ p='C:\foo\bar.xml'
$ printf '%s\n' "$p"
C:\foo\bar.xml
$ printf '%s\n' "${p//\\//}"
C:/foo/bar.xml

This may be leaner and clearer that filtering through a command such as tr or sed.

How to check if a stored procedure exists before creating it

I had the same error. I know this thread is pretty much dead already but I want to set another option besides "anonymous procedure".

I solved it like this:

  1. Check if the stored procedure exist:

    IF NOT EXISTS (SELECT * FROM sysobjects WHERE name='my_procedure') BEGIN
        print 'exists'  -- or watever you want
    END ELSE BEGIN
        print 'doesn''texists'   -- or watever you want
    END
    
  2. However the "CREATE/ALTER PROCEDURE' must be the first statement in a query batch" is still there. I solved it like this:

    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    
    CREATE -- view procedure function or anything you want ...
    
  3. I end up with this code:

    IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID('my_procedure'))
    BEGIN
        DROP PROCEDURE my_procedure
    END
    
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    
    CREATE PROCEDURE [dbo].my_procedure ...
    

MySQLi count(*) always returns 1

I find this way more readable:

$result = $mysqli->query('select count(*) as `c` from `table`');
$count = $result->fetch_object()->c;
echo "there are {$count} rows in the table";

Not that I have anything against arrays...

How to find which version of TensorFlow is installed in my system?

This depends on how you installed TensorFlow. I am going to use the same headings used by TensorFlow's installation instructions to structure this answer.


Pip installation

Run:

python -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 2
python3 -c 'import tensorflow as tf; print(tf.__version__)'  # for Python 3

Note that python is symlinked to /usr/bin/python3 in some Linux distributions, so use python instead of python3 in these cases.

pip list | grep tensorflow for Python 2 or pip3 list | grep tensorflow for Python 3 will also show the version of Tensorflow installed.


Virtualenv installation

Run:

python -c 'import tensorflow as tf; print(tf.__version__)'  # for both Python 2 and Python 3

pip list | grep tensorflow will also show the version of Tensorflow installed.

For example, I have installed TensorFlow 0.9.0 in a virtualenv for Python 3. So, I get:

$ python -c 'import tensorflow as tf; print(tf.__version__)'
0.9.0

$ pip list | grep tensorflow
tensorflow (0.9.0)

Equivalent of Clean & build in Android Studio?

Also you can edit your Run/Debug configuration and add clean task.

Click on the Edit configuration

Click on the Edit configuration

In the left list of available configurations choose your current configuration and then on the right side of the dialog window in the section Before launch press on plus sign and choose Run Gradle task

choose <code>Run Gradle task</code>

In the new window choose your gradle project and in the field Tasks type clean.

type <code>clean</code>

Then move your gradle clean on top of Gradle-Aware make

CASE IN statement with multiple values

Yes. You need to use the "Searched" form rather than the "Simple" form of the CASE expression

SELECT CASE
         WHEN c.Number IN ( '1121231', '31242323' ) THEN 1
         WHEN c.Number IN ( '234523', '2342423' ) THEN 2
       END AS Test
FROM   tblClient c  

Can Linux apps be run in Android?

Yes they can if they're compiled under an arm linux first or using a cross compiler. Debian arm versatile works, there's also arm-eabi for compiling under x86 linux to arm linux.

bool to int conversion

Section 6.5.8.6 of the C standard says:

Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false.) The result has type int.

Gulp error: The following tasks did not complete: Did you forget to signal async completion?

This worked!

gulp.task('script', done => {
    // ... code gulp.src( ... )
    done();
});

gulp.task('css', done => {
    // ... code gulp.src( ... )
    done();
});

gulp.task('default', gulp.parallel(
        'script',
        'css'
  )
);

Format date as dd/MM/yyyy using pipes

I think that it's because the locale is hardcoded into the DatePipe. See this link:

And there is no way to update this locale by configuration right now.

functional way to iterate over range (ES6/7)

One can create an empty array, fill it (otherwise map will skip it) and then map indexes to values:

Array(8).fill().map((_, i) => i * i);

How to set time to 24 hour format in Calendar

Here you will get all kinds of time related problems. I hope this will solve your problem.

public class MyClass {

    public static void main(String[] args) {


        Calendar cal = Calendar.getInstance();

        // To get the current hour
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        System.out.println("hour: " + hour);

        // To get the current time in 12 hours format
        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a",Locale.US);
        String a = sdf.format(cal.getTime());
        System.out.println("Time: " + a);

        // To get the desired time in 12 hours format from 23 hours format
        cal.set(Calendar.HOUR_OF_DAY, 24);
        SimpleDateFormat sdf1 = new SimpleDateFormat("hh:mm a",Locale.ENGLISH);
        String a1 = sdf1.format(cal.getTime());
        System.out.println("Time: " + a1);

        /*  H Hour in day (0-23) 
            k Hour in day (1-24) 
        */

        //To get the desired time in 24 hours format as 0-23 or 1-24
        cal.set(Calendar.HOUR_OF_DAY, 24);
        SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm",Locale.ENGLISH);
        SimpleDateFormat sdf3 = new SimpleDateFormat("kk:mm",Locale.ENGLISH);
        String a2 = sdf2.format(cal.getTime());
        String a3 = sdf3.format(cal.getTime());
        System.out.println("Time: " + a2);
        System.out.println("Time: " + a3);

        //For example, time like 12:30 PM. How can i convert to 24 hours time in java?

        SimpleDateFormat bigFormat = new SimpleDateFormat("kk:mm");
        SimpleDateFormat smallFormat = new SimpleDateFormat("hh:mm a");

        Date date = null;
        try {
            date = smallFormat.parse("12:30 AM");
        } catch (ParseException e) {
            e.printStackTrace();
        }        
        System.out.println(smallFormat.format(date) + " = " + bigFormat.format(date));

    }

}

Android - java.lang.SecurityException: Permission Denial: starting Intent

This is only for android studio

So I ran into this problem recently. The issue was in the build/run configuration. Apparently android studio had chosen an activity in my project as the launch activity thus disregarding my choice in the manifest file.

Click on the module name just to the left of the run button and click on "Edit configurations..." Now make sure "Launch default Activity" is selected.

The funny thing when I got this error was that I could still launch the app with from the device and it starts with the preferred Activity. But launching from the IDE seemed impossible.

What is C# equivalent of <map> in C++?

.NET Framework provides many collection classes too. You can use Dictionary in C#. Please find the below msdn link for details and samples http://msdn.microsoft.com/en-us/library/xfhwa508.aspx

OVER_QUERY_LIMIT in Google Maps API v3: How do I pause/delay in Javascript to slow it down?

You are using setTimeout wrong way. The (one of) function signature is setTimeout(callback, delay). So you can easily specify what code should be run after what delay.

var codeAddress = (function() {
    var index = 0;
    var delay = 100;

    function GeocodeCallback(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            new google.maps.Marker({ map: map, position: results[0].geometry.location, animation: google.maps.Animation.DROP });
            console.log(results);
        }
        else alert("Geocode was not successful for the following reason: " + status);
    };

    return function(vPostCode) {
        if (geocoder) setTimeout(geocoder.geocode.bind(geocoder, { 'address': "'" + vPostCode + "'"}, GeocodeCallback), index*delay);
        index++;
    };
})();

This way, every codeAddress() call will result in geocoder.geocode() being called 100ms later after previous call.

I also added animation to marker so you will have a nice animation effect with markers being added to map one after another. I'm not sure what is the current google limit, so you may need to increase the value of delay variable.

Also, if you are each time geocoding the same addresses, you should instead save the results of geocode to your db and next time just use those (so you will save some traffic and your application will be a little bit quicker)

how to return index of a sorted list?

How about

l1 = [2,3,1,4,5]
l2 = [l1.index(x) for x in sorted(l1)]

How to clone an InputStream?

This might not work in all situations, but here is what I did: I extended the FilterInputStream class and do the required processing of the bytes as the external lib reads the data.

public class StreamBytesWithExtraProcessingInputStream extends FilterInputStream {

    protected StreamBytesWithExtraProcessingInputStream(InputStream in) {
        super(in);
    }

    @Override
    public int read() throws IOException {
        int readByte = super.read();
        processByte(readByte);
        return readByte;
    }

    @Override
    public int read(byte[] buffer, int offset, int count) throws IOException {
        int readBytes = super.read(buffer, offset, count);
        processBytes(buffer, offset, readBytes);
        return readBytes;
    }

    private void processBytes(byte[] buffer, int offset, int readBytes) {
       for (int i = 0; i < readBytes; i++) {
           processByte(buffer[i + offset]);
       }
    }

    private void processByte(int readByte) {
       // TODO do processing here
    }

}

Then you simply pass an instance of StreamBytesWithExtraProcessingInputStream where you would have passed in the input stream. With the original input stream as constructor parameter.

It should be noted that this works byte for byte, so don't use this if high performance is a requirement.

Using Switch Statement to Handle Button Clicks

I use Butterknife with switch-case to handle this kind of cases:

    @OnClick({R.id.button_bireysel, R.id.button_kurumsal})
        public void onViewClicked(View view) {
            switch (view.getId()) {


                case R.id.button_bireysel:
 //Do something

                    break;
                case R.id.button_kurumsal:

     //Do something

                    break;

            }
        }

But the thing is there is no default case and switch statement falls through

Getting Class type from String

You can use the forName method of Class:

Class cls = Class.forName(clsName);
Object obj = cls.newInstance();

Execute php file from another php

It's trying to run it as a shell script, which interprets your <?php token as bash, which is a syntax error. Just use include() or one of its friends:

For example, in a.php put:

<?php
print "one";
include 'b.php';
print "three";
?>

In b.php put:

<?php
print "two";
?>

Prints:

eric@dev ~ $ php a.php
onetwothree

Whitespace Matching Regex - Java

Pattern whitespace = Pattern.compile("\\s\\s");
matcher = whitespace.matcher(modLine);

boolean flag = true;
while(flag)
{
 //Update your original search text with the result of the replace
 modLine = matcher.replaceAll(" ");
 //reset matcher to look at this "new" text
 matcher = whitespace.matcher(modLine);
 //search again ... and if no match , set flag to false to exit, else run again
 if(!matcher.find())
 {
 flag = false;
 }
}

How do I run Google Chrome as root?

  1. Go to /opt/google/chrome.

  2. Open google-chrome.

  3. Append current home for data directory. Replace this:

exec -a "$0" "$HERE/chrome" "$@"

With this:

exec -a "$0" "$HERE/chrome" "$@" --user-data-dir $HOME

For reference visit site this site, “How to run chrome as root user in Ubuntu.”

How to find time complexity of an algorithm

When you're analyzing code, you have to analyse it line by line, counting every operation/recognizing time complexity, in the end, you have to sum it to get whole picture.

For example, you can have one simple loop with linear complexity, but later in that same program you can have a triple loop that has cubic complexity, so your program will have cubic complexity. Function order of growth comes into play right here.

Let's look at what are possibilities for time complexity of an algorithm, you can see order of growth I mentioned above:

  • Constant time has an order of growth 1, for example: a = b + c.

  • Logarithmic time has an order of growth LogN, it usually occurs when you're dividing something in half (binary search, trees, even loops), or multiplying something in same way.

  • Linear, order of growth is N, for example

    int p = 0;
    for (int i = 1; i < N; i++)
      p = p + 2;
    
  • Linearithmic, order of growth is n*logN, usually occurs in divide and conquer algorithms.

  • Cubic, order of growth N^3, classic example is a triple loop where you check all triplets:

    int x = 0;
    for (int i = 0; i < N; i++)
       for (int j = 0; j < N; j++)
          for (int k = 0; k < N; k++)
              x = x + 2
    
  • Exponential, order of growth 2^N, usually occurs when you do exhaustive search, for example check subsets of some set.

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

How to retrieve Request Payload

If I understand the situation correctly, you are just passing json data through the http body, instead of application/x-www-form-urlencoded data.

You can fetch this data with this snippet:

$request_body = file_get_contents('php://input');

If you are passing json, then you can do:

$data = json_decode($request_body);

$data then contains the json data is php array.

php://input is a so called wrapper.

php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".

Allow only pdf, doc, docx format for file upload?

You can simply make it by REGEX:

Form:

<form method="post" action="" enctype="multipart/form-data">
    <div class="uploadExtensionError" style="display: none">Only PDF allowed!</div>
    <input type="file" name="item_file" />
    <input type="submit" id='submit' value="submit"/>
</form>

And java script validation:

<script>
    $('#submit').click(function(event) {
        var val = $('input[type=file]').val().toLowerCase();
        var regex = new RegExp("(.*?)\.(pdf|docx|doc)$");
        if(!(regex.test(val))) {
            $('.uploadExtensionError').show();
            event.preventDefault();
        }
    });
</script>

Cheers!

Initialize empty vector in structure - c++

The default vector constructor will create an empty vector. As such, you should be able to write:

struct user r = { string(), vector<unsigned char>() };

Note, I've also used the default string constructor instead of "".

You might want to consider making user a class and adding a default constructor that does this for you:

class User {
  User() {}
  string username;
  vector<unsigned char> password;
};

Then just writing:

User r;

Will result in a correctly initialized user.

Implementing a simple file download servlet

And to send a largFile

byte[] pdfData = getPDFData();

String fileType = "";

res.setContentType("application/pdf");

httpRes.setContentType("application/.pdf");
httpRes.addHeader("Content-Disposition", "attachment; filename=IDCards.pdf");
httpRes.setStatus(HttpServletResponse.SC_OK);
OutputStream out = res.getOutputStream();
System.out.println(pdfData.length);
         
out.write(pdfData);
System.out.println("sendDone");
out.flush();

How do SETLOCAL and ENABLEDELAYEDEXPANSION work?

ENABLEDELAYEDEXPANSION is a parameter passed to the SETLOCAL command (look at setlocal /?)

Its effect lives for the duration of the script, or an ENDLOCAL:

When the end of a batch script is reached, an implied ENDLOCAL is executed for any outstanding SETLOCAL commands issued by that batch script.

In particular, this means that if you use SETLOCAL ENABLEDELAYEDEXPANSION in a script, any environment variable changes are lost at the end of it unless you take special measures.

Receiving "Attempted import error:" in react app

import { combineReducers } from '../../store/reducers';

should be

import combineReducers from '../../store/reducers';

since it's a default export, and not a named export.

There's a good breakdown of the differences between the two here.

Is Safari on iOS 6 caching $.ajax results?

That's the work around for GWT-RPC

class AuthenticatingRequestBuilder extends RpcRequestBuilder 
{
       @Override
       protected RequestBuilder doCreate(String serviceEntryPoint) 
       {
               RequestBuilder requestBuilder = super.doCreate(serviceEntryPoint);           
               requestBuilder.setHeader("Cache-Control", "no-cache");

               return requestBuilder;
       }
}

AuthenticatingRequestBuilder builder = new AuthenticatingRequestBuilder();
((ServiceDefTarget)myService).setRpcRequestBuilder(builder);    

Spring Boot REST service exception handling

Solution with dispatcherServlet.setThrowExceptionIfNoHandlerFound(true); and @EnableWebMvc @ControllerAdvice worked for me with Spring Boot 1.3.1, while was not working on 1.2.7

Difference between null and empty ("") Java String

There is a pretty significant difference between the two. The empty string "" is "the string that has no characters in it." It's an actual string that has a well-defined length. All of the standard string operations are well-defined on the empty string - you can convert it to lower case, look up the index of some character in it, etc. The null string null is "no string at all." It doesn't have a length because it's not a string at all. Trying to apply any standard string operation to the null string will cause a NullPointerException at runtime.

how to fix Cannot call sendRedirect() after the response has been committed?

you can't call sendRedirect(), after you have already used forward(). So, you get that exception.

How to create a new object instance from a Type

Its pretty simple. Assume that your classname is Car and the namespace is Vehicles, then pass the parameter as Vehicles.Car which returns object of type Car. Like this you can create any instance of any class dynamically.

public object GetInstance(string strNamesapace)
{         
     Type t = Type.GetType(strNamesapace); 
     return  Activator.CreateInstance(t);         
}

If your Fully Qualified Name(ie, Vehicles.Car in this case) is in another assembly, the Type.GetType will be null. In such cases, you have loop through all assemblies and find the Type. For that you can use the below code

public object GetInstance(string strFullyQualifiedName)
{
     Type type = Type.GetType(strFullyQualifiedName);
     if (type != null)
         return Activator.CreateInstance(type);
     foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
     {
         type = asm.GetType(strFullyQualifiedName);
         if (type != null)
             return Activator.CreateInstance(type);
     }
     return null;
 }

And you can get the instance by calling the above method.

object objClassInstance = GetInstance("Vehicles.Car");

How to put more than 1000 values into an Oracle IN clause

Use ...from table(... :

create or replace type numbertype
as object
(nr number(20,10) )
/ 

create or replace type number_table
as table of numbertype
/ 

create or replace procedure tableselect
( p_numbers in number_table
, p_ref_result out sys_refcursor)
is
begin
  open p_ref_result for
    select *
    from employees , (select /*+ cardinality(tab 10) */ tab.nr from table(p_numbers) tab) tbnrs 
    where id = tbnrs.nr; 
end; 
/ 

This is one of the rare cases where you need a hint, else Oracle will not use the index on column id. One of the advantages of this approach is that Oracle doesn't need to hard parse the query again and again. Using a temporary table is most of the times slower.

edit 1 simplified the procedure (thanks to jimmyorr) + example

create or replace procedure tableselect
( p_numbers in number_table
, p_ref_result out sys_refcursor)
is
begin
  open p_ref_result for
    select /*+ cardinality(tab 10) */ emp.*
    from  employees emp
    ,     table(p_numbers) tab
    where tab.nr = id;
end;
/

Example:

set serveroutput on 

create table employees ( id number(10),name varchar2(100));
insert into employees values (3,'Raymond');
insert into employees values (4,'Hans');
commit;

declare
  l_number number_table := number_table();
  l_sys_refcursor sys_refcursor;
  l_employee employees%rowtype;
begin
  l_number.extend;
  l_number(1) := numbertype(3);
  l_number.extend;
  l_number(2) := numbertype(4);
  tableselect(l_number, l_sys_refcursor);
  loop
    fetch l_sys_refcursor into l_employee;
    exit when l_sys_refcursor%notfound;
    dbms_output.put_line(l_employee.name);
  end loop;
  close l_sys_refcursor;
end;
/

This will output:

Raymond
Hans

AngularJS $http-post - convert binary to excel file and download

You could as well take an alternative approach -- you don't have to use $http, you don't need any extra libraries, and it ought to work in any browser.

Just place an invisible form on your page.

<form name="downloadForm" action="/MyApp/MyFiles/Download" method="post" target="_self">
    <input type="hidden" name="value1" value="{{ctrl.value1}}" />
    <input type="hidden" name="value2" value="{{ctrl.value2}}" />
</form>

And place this code in your angular controller.

ctrl.value1 = 'some value 1';  
ctrl.value2 = 'some value 2';  
$timeout(function () {
    $window.document.forms['downloadForm'].submit();
});

This code will post your data to /MyApp/MyFiles/Download and you'll receive a file in your Downloads folder.
It works with Internet Explorer 10.

If a conventional HTML form doesn't let you post your complex object, then you have two options:

1. Stringify your object and put it into one of the form fields as a string.

<input type="hidden" name="myObjJson" value="{{ctrl.myObj | json:0}}" />


2. Consider HTML JSON forms: https://www.w3.org/TR/html-json-forms/

Max or Default?

Since DefaultIfEmpty isn't implemented in LINQ to SQL, I did a search on the error it returned and found a fascinating article that deals with null sets in aggregate functions. To summarize what I found, you can get around this limitation by casting to a nullable within your select. My VB is a little rusty, but I think it'd go something like this:

Dim x = (From y In context.MyTable _
         Where y.MyField = value _
         Select CType(y.MyCounter, Integer?)).Max

Or in C#:

var x = (from y in context.MyTable
         where y.MyField == value
         select (int?)y.MyCounter).Max();

Compare if BigDecimal is greater than zero

Possible better way:

if (value.signum() > 0)

signum returns -1, 0, or 1 as the value of this BigDecimal is negative, zero, or positive.

Deep copy an array in Angular 2 + TypeScript

This is working for me:

this.listCopy = Object.assign([], this.list);

Selecting specific rows and columns from NumPy array

Using np.ix_ is the most convenient way to do it (as answered by others), but here is another interesting way to do it:

>>> rows = [0, 1, 3]
>>> cols = [0, 2]

>>> a[rows].T[cols].T

array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

How can I extract embedded fonts from a PDF as valid font files?

PDF2SVG version 6.0 from PDFTron does a reasonable job. It produces OpenType (.otf) fonts by default. Use --preserve_fontnames to preserve "the font/font-family naming scheme as obtained from the source file."

PDF2SVG is a commercial product, but you can download a free demo executable (which includes watermarks on the SVG output but doesn't otherwise restrict usage). There may be other PDFTron products that also extract fonts, but I only recently discovered PDF2SVG myself.

How can I pretty-print JSON using node.js?

If you don't want to store this anywhere, but just view the object for debugging purposes.

console.log(JSON.stringify(object, null, "  "));

You can change the third parameter to adjust the indentation.

Scrolling to an Anchor using Transition/CSS3

You can find the answer to your question on the following page:

https://stackoverflow.com/a/17633941/2359161

Here is the JSFiddle that was given:

http://jsfiddle.net/YYPKM/3/

Note the scrolling section at the end of the CSS, specifically:

_x000D_
_x000D_
/*_x000D_
 *Styling_x000D_
 */_x000D_
_x000D_
html,body {_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    position: relative; _x000D_
}_x000D_
body {_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
header {_x000D_
background: #fff; _x000D_
position: fixed; _x000D_
left: 0; top: 0; _x000D_
width:100%;_x000D_
height: 3.5rem;_x000D_
z-index: 10; _x000D_
}_x000D_
_x000D_
nav {_x000D_
width: 100%;_x000D_
padding-top: 0.5rem;_x000D_
}_x000D_
_x000D_
nav ul {_x000D_
list-style: none;_x000D_
width: inherit; _x000D_
margin: 0; _x000D_
}_x000D_
_x000D_
_x000D_
ul li:nth-child( 3n + 1), #main .panel:nth-child( 3n + 1) {_x000D_
background: rgb( 0, 180, 255 );_x000D_
}_x000D_
_x000D_
ul li:nth-child( 3n + 2), #main .panel:nth-child( 3n + 2) {_x000D_
background: rgb( 255, 65, 180 );_x000D_
}_x000D_
_x000D_
ul li:nth-child( 3n + 3), #main .panel:nth-child( 3n + 3) {_x000D_
background: rgb( 0, 255, 180 );_x000D_
}_x000D_
_x000D_
ul li {_x000D_
display: inline-block; _x000D_
margin: 0 8px;_x000D_
margin: 0 0.5rem;_x000D_
padding: 5px 8px;_x000D_
padding: 0.3rem 0.5rem;_x000D_
border-radius: 2px; _x000D_
line-height: 1.5;_x000D_
}_x000D_
_x000D_
ul li a {_x000D_
color: #fff;_x000D_
text-decoration: none;_x000D_
}_x000D_
_x000D_
.panel {_x000D_
width: 100%;_x000D_
height: 500px;_x000D_
z-index:0; _x000D_
-webkit-transform: translateZ( 0 );_x000D_
transform: translateZ( 0 );_x000D_
-webkit-transition: -webkit-transform 0.6s ease-in-out;_x000D_
transition: transform 0.6s ease-in-out;_x000D_
-webkit-backface-visibility: hidden;_x000D_
backface-visibility: hidden;_x000D_
_x000D_
}_x000D_
_x000D_
.panel h1 {_x000D_
font-family: sans-serif;_x000D_
font-size: 64px;_x000D_
font-size: 4rem;_x000D_
color: #fff;_x000D_
position:relative;_x000D_
line-height: 200px;_x000D_
top: 33%;_x000D_
text-align: center;_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
/*_x000D_
 *Scrolling_x000D_
 */_x000D_
_x000D_
a[ id= "servicios" ]:target ~ #main article.panel {_x000D_
-webkit-transform: translateY( 0px);_x000D_
transform: translateY( 0px );_x000D_
}_x000D_
_x000D_
a[ id= "galeria" ]:target ~ #main article.panel {_x000D_
-webkit-transform: translateY( -500px );_x000D_
transform: translateY( -500px );_x000D_
}_x000D_
a[ id= "contacto" ]:target ~ #main article.panel {_x000D_
-webkit-transform: translateY( -1000px );_x000D_
transform: translateY( -1000px );_x000D_
}
_x000D_
<a id="servicios"></a>_x000D_
<a id="galeria"></a>_x000D_
<a id="contacto"></a>_x000D_
<header class="nav">_x000D_
<nav>_x000D_
    <ul>_x000D_
        <li><a href="#servicios"> Servicios </a> </li>_x000D_
        <li><a href="#galeria"> Galeria </a> </li>_x000D_
        <li><a href="#contacto">Contacta  nos </a> </li>_x000D_
    </ul>_x000D_
</nav>_x000D_
</header>_x000D_
_x000D_
<section id="main">_x000D_
<article class="panel" id="servicios">_x000D_
    <h1> Nuestros Servicios</h1>_x000D_
</article>_x000D_
_x000D_
<article class="panel" id="galeria">_x000D_
    <h1> Mustra de nuestro trabajos</h1>_x000D_
</article>_x000D_
_x000D_
<article class="panel" id="contacto">_x000D_
    <h1> Pongamonos en contacto</h1>_x000D_
</article>_x000D_
</section>
_x000D_
_x000D_
_x000D_

Change the content of a div based on selection from dropdown menu

Meh too slow. Here's my example anyway :)
http://jsfiddle.net/cqDES/

$(function() {
    $('select').change(function() {
        var val = $(this).val();
        if (val) {
            $('div:not(#div' + val + ')').slideUp();
            $('#div' + val).slideDown();
        } else {
            $('div').slideDown();
        }
    });
});

Unsupported Media Type in postman

Http 415 Media Unsupported is responded back only when the content type header you are providing is not supported by the application.

With POSTMAN, the Content-type header you are sending is Content type 'multipart/form-data not application/json. While in the ajax code you are setting it correctly to application/json. Pass the correct Content-type header in POSTMAN and it will work.

EXEC sp_executesql with multiple parameters

maybe this help :

declare 
@statement AS NVARCHAR(MAX)
,@text1 varchar(50)='hello'
,@text2 varchar(50)='world'

set @statement = '
select '''+@text1+''' + '' beautifull '' + ''' + @text2 + ''' 
'
exec sp_executesql @statement;

this is same as below :

select @text1 + ' beautifull ' + @text2

Why am I getting AttributeError: Object has no attribute

You can't access outside private fields of a class. private fields are starting with __ . for example -

class car:
    def __init__(self):
        self.__updatesoftware()

    def drive(self):
        print("driving")

    def __updatesoftware(self):
        print("updating software:")

obj = car()
obj.drive()  
obj.__updatesoftware()  ## here it will throw an error because 

__updatesoftware is an private method.

How do I stop a program when an exception is raised in Python?

import sys

try:
  print("stuff")
except:
  sys.exit(1) # exiing with a non zero value is better for returning from an error

What are the differences between C, C# and C++ in terms of real-world applications?

Bear in mind that I speak ASFAC++B. :) I've put the most important differentiating factor first.

Garbage Collection

Garbage Collection (GC) is the single most important factor in differentiating between these languages.

While C and C++ can be used with GC, it is a bolted-on afterthought and cannot be made to work as well (the best known is here) - it has to be "conservative" which means that it cannot collect all unused memory.

C# is designed from the ground up to work on a GC platform, with standard libraries also designed that way. It makes an absolutely fundamental difference to developer productivity that has to be experienced to be believed.

There is a belief widespread among C/C++ users that GC equates with "bad performance". But this is out-of-date folklore (even the Boehm collector on C/C++ performs much better than most people expect it to). The typical fear is of "long pauses" where the program stops so the GC can do some work. But in reality these long pauses happen with non-GC programs, because they run on top of a virtual memory system, which occasionally interrupts to move data between physical memory and disk.

There is also widespread belief that GC can be replaced with shared_ptr, but it can't; the irony is that in a multi-threaded program, shared_ptr is slower than a GC-based system.

There are environments that are so frugal that GC isn't practical - but these are increasingly rare. Cell phones typically have GC. The CLR's GC that C# typically runs on appears to be state-of-the-art.

Since adopting C# about 18 months ago I've gone through several phases of pure performance tuning with a profiler, and the GC is so efficient that it is practically invisible during the operation of the program.

GC is not a panacea, it doesn't solve all programming problems, it only really cleans up memory allocation, if you're allocating very large memory blocks then you will still need to take some care, and it is still possible to have what amounts to a memory leak in a sufficiently complex program - and yet, the effect of GC on productivity makes it a pretty close approximation to a panacea!

Undefined Behaviour

C++ is founded on the notion of undefined behaviour. That is, the language specification defines the outcome of certain narrowly defined usages of language features, and describes all other usages as causing undefined behaviour, meaning in principle that the operation could have any outcome at all (in practice this means hard-to-diagnose bugs involving apparently non-deterministic corruption of data).

Almost everything about C++ touches on undefined behaviour. Even very nice forthcoming features like lambda expressions can easily be used as convenient way to corrupt the stack (capture a local by reference, allow the lambda instance to outlive the local).

C# is founded on the principle that all possible operations should have defined behaviour. The worst that can happen is an exception is thrown. This completely changes the experience of software construction.

(There's unsafe mode, which has pointers and therefore undefined behaviour, but that is strongly discouraged for general use - think of it as analogous to embedded assembly language.)

Complexity

In terms of complexity, C++ has to be singled out, especially if we consider the very-soon-to-be standardized new version. C++ does absolutely everything it can to make itself effective, short of assuming GC, and as a result it has an awesome learning curve. The language designers excuse much of this by saying "Those features are only for library authors, not ordinary users" - but to be truly effective in any language, you need to build your code as reusable libraries. So you can't escape.

On the positive side, C++ is so complex, it's like a playground for nerds! I can assure you that you would have a lot of fun learning how it all fits together. But I can't seriously recommend it as a basis for productive new work (oh, the wasted years...) on mainstream platforms.

C keeps the language simple (simple in the sense of "the compiler is easy to write"), but this makes the coding techniques more arcane.

Note that not all new language features equate with added complexity. Some language features are described as "syntactic sugar", because they are shorthand that the compiler expands for you. This is a good way to think of a great deal of the enhancements to C# over recent years. The language standard even specifies some features by giving the translation to longhand, e.g. using statement expands into try/finally.

At one point, it was possible to think of C++ templates in the same way. But they've since become so powerful that they are now form the basis of a whole separate dimension of the language, with its own enthusiastic user communities and idioms.

Libraries

The strangest thing about C and C++ is that they don't have a standard interchangeable form of pre-compiled library. Integrating someone else's code into your project is always a little fiddly, with obscure decisions to be made about how you'll be linking to it.

Also, the standard library is extremely basic - C++ has a complete set of data structures and a way of representing strings (std::string), but that's still minimal. Is there a standard way of finding a list of files in a directory? Amazingly, no! Is there standard library support for parsing or generating XML? No. What about accessing databases? Be serious! Writing a web site back-end? Are you crazy? etc.

So you have to go hunting further afield. For XML, try Xerces. But does it use std::string to represent strings? Of course not!

And do all these third-party libraries have their own bizarre customs for naming classes and functions? You betcha!

The situation in C# couldn't be more different; the fundamentals were in place from the start, so everything inter-operates beautifully (and because the fundamentals are supplied by the CLR, there is cross-language support).

It's not all perfect; generics should have been in place from the start but wasn't, which does leave a visible scar on some older libraries; but it is usually trivial to fix this externally. Also a number of popular libraries are ported from Java, which isn't as good a fit as it first appears.

Closures (Anonymous Methods with Local Variable Capture)

Java and C are practically the last remaining mainstream languages to lack closures, and libraries can be designed and used much more neatly with them than without (this is one reason why ported Java libraries sometimes seem clunky to a C# user).

The amusing thing about C++ is that its standard library was designed as if closures were available in the language (container types, <algorithm>, <functional>). Then ten years went by, and now they're finally being added! They will have a huge impact (although, as noted above, they leak underfined behaviour).

C# and JavaScript are the most widely used languages in which closures are "idiomatically established". (The major difference between those languages being that C# is statically typed while JavaScript is dynamically typed).

Platform Support

I've put this last only because it doesn't appear to differentiate these languages as much as you might think. All these languages can run on multiple OSes and machine architectures. C is the most widely-supported, then C++, and finally C# (although C# can be used on most major platforms thanks to an open source implementation called Mono).

My experience of porting C++ programs between Windows and various Unix flavours was unpleasant. I've never tried porting anything very complex in C# to Mono, so I can't comment on that.

How do you use MySQL's source command to import large files in windows

On windows: Use explorer to navigate to the folder with the .sql file. Type cmd in the top address bar. Cmd will open. Type:

"C:\path\to\mysql.exe" -u "your_username" -p "your password" < "name_of_your_sql_file.sql"

Wait a bit and the sql file will have been executed on your database. Confirmed to work with MariaDB in feb 2018.

cordova run with ios error .. Error code 65 for command: xcodebuild with args:

You need a development provisioning profile on your build machine. Apps can run on the simulator without a profile, but they are required to run on an actual device.

If you open the project in Xcode, it may automatically set up provisioning for you. Otherwise you will have to create go to the iOS Dev Center and create a profile.

How to set HTTP header to UTF-8 using PHP which is valid in W3C validator?

Use header to modify the HTTP header:

header('Content-Type: text/html; charset=utf-8');

Note to call this function before any output has been sent to the client. Otherwise the header has been sent too and you obviously can’t change it any more. You can check that with headers_sent. See the manual page of header for more information.

Pylint "unresolved import" error in Visual Studio Code

I have a different solution: my Visual Studio Code instance had picked up the virtualenv stored in .venv, but it was using the wrong Python binary. It was using .venv/bin/python3.7; using the switcher in the blue status bar.

I changed it to use .venv/bin/python and all of my imports were resolved correctly.

I don't know what Visual Studio Code is doing behind the scenes when I do this, nor do I understand why this was causing my problem, but for me this was a slightly simpler solution than editing my workspace settings.

access key and value of object using *ngFor

From Angular 6.1 you can use the keyvalue pipe:

<div *ngFor="let item of testObject | keyvalue">
    Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>
</div>

But it has the inconvenient that sorts the resulting list by the key value. If you need something neutral:

@Pipe({ name: 'keyValueUnsorted', pure: false  })
export class KeyValuePipe implements PipeTransform {
  transform(input: any): any {
    let keys = [];
    for (let key in input) {
      if (input.hasOwnProperty(key)) {
        keys.push({ key: key, value: input[key]});
      }
    }
    return keys;
  }
}

Don't forget to specify the pure:false pipe attribute. In this case, the pipe is invoked on each change-detection cycle, even if the input reference has not changed (so is the case when you add properties to an object).

How to get an ASP.NET MVC Ajax response to redirect to new page instead of inserting view into UpdateTargetId?

I needed to do this because I have an ajax login form. When users login successfully I redirect to a new page and end the previous request because the other page handles redirecting back to the relying party (because it's a STS SSO System).

However, I also wanted it to work with javascript disabled, being the central login hop and all, so I came up with this,

    public static string EnsureUrlEndsWithSlash(string url)
    {
        if (string.IsNullOrEmpty(url))
            throw new ArgumentNullException("url");
        if (!url.EndsWith("/"))
            return string.Concat(url, "/");
        return url;
    }

    public static string GetQueryStringFromArray(KeyValuePair<string, string>[] values)
    {
        Dictionary<string, string> dValues = new Dictionary<string,string>();
        foreach(var pair in values)            
            dValues.Add(pair.Key, pair.Value);            
        var array = (from key in dValues.Keys select string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(dValues[key]))).ToArray();
        return "?" + string.Join("&", array);
    }

    public static void RedirectTo(this HttpRequestBase request, string url, params KeyValuePair<string, string>[] queryParameters)
    {            
        string redirectUrl = string.Concat(EnsureUrlEndsWithSlash(url), GetQueryStringFromArray(queryParameters));
        if (request.IsAjaxRequest())
            HttpContext.Current.Response.Write(string.Format("<script type=\"text/javascript\">window.location='{0}';</script>", redirectUrl));
        else
            HttpContext.Current.Response.Redirect(redirectUrl, true);

    }

How can I make a clickable link in an NSAttributedString?

Swift Version :

    // Attributed String for Label
    let plainText = "Apkia"
    let styledText = NSMutableAttributedString(string: plainText)
    // Set Attribuets for Color, HyperLink and Font Size
    let attributes = [NSFontAttributeName: UIFont.systemFontOfSize(14.0), NSLinkAttributeName:NSURL(string: "http://apkia.com/")!, NSForegroundColorAttributeName: UIColor.blueColor()]
    styledText.setAttributes(attributes, range: NSMakeRange(0, plainText.characters.count))
    registerLabel.attributedText = styledText

Understanding CUDA grid dimensions, block dimensions and threads organization (simple explanation)

Suppose a 9800GT GPU:

  • it has 14 multiprocessors (SM)
  • each SM has 8 thread-processors (AKA stream-processors, SP or cores)
  • allows up to 512 threads per block
  • warpsize is 32 (which means each of the 14x8=112 thread-processors can schedule up to 32 threads)

https://www.tutorialspoint.com/cuda/cuda_threads.htm

A block cannot have more active threads than 512 therefore __syncthreads can only synchronize limited number of threads. i.e. If you execute the following with 600 threads:

func1();
__syncthreads();
func2();
__syncthreads();

then the kernel must run twice and the order of execution will be:

  1. func1 is executed for the first 512 threads
  2. func2 is executed for the first 512 threads
  3. func1 is executed for the remaining threads
  4. func2 is executed for the remaining threads

Note:

The main point is __syncthreads is a block-wide operation and it does not synchronize all threads.


I'm not sure about the exact number of threads that __syncthreads can synchronize, since you can create a block with more than 512 threads and let the warp handle the scheduling. To my understanding it's more accurate to say: func1 is executed at least for the first 512 threads.

Before I edited this answer (back in 2010) I measured 14x8x32 threads were synchronized using __syncthreads.

I would greatly appreciate if someone test this again for a more accurate piece of information.

Number of days between past date and current date in Google spreadsheet

Since this is the top Google answer for this, and it was way easier than I expected, here is the simple answer. Just subtract date1 from date2.

If this is your spreadsheet dates

     A            B
1 10/11/2017  12/1/2017

=(B1)-(A1)

results in 51, which is the number of days between a past date and a current date in Google spreadsheet

As long as it is a date format Google Sheets recognizes, you can directly subtract them and it will be correct.

To do it for a current date, just use the =TODAY() function.

=TODAY()-A1

While today works great, you can't use a date directly in the formula, you should referencing a cell that contains a date.

=(12/1/2017)-(10/1/2017) results in 0.0009915716411, not 61.

Secondary axis with twinx(): how to add to legend?

You can easily get what you want by adding the line in ax:

ax.plot([], [], '-r', label = 'temp')

or

ax.plot(np.nan, '-r', label = 'temp')

This would plot nothing but add a label to legend of ax.

I think this is a much easier way. It's not necessary to track lines automatically when you have only a few lines in the second axes, as fixing by hand like above would be quite easy. Anyway, it depends on what you need.

The whole code is as below:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')

time = np.arange(22.)
temp = 20*np.random.rand(22)
Swdown = 10*np.random.randn(22)+40
Rn = 40*np.random.rand(22)

fig = plt.figure()
ax = fig.add_subplot(111)
ax2 = ax.twinx()

#---------- look at below -----------

ax.plot(time, Swdown, '-', label = 'Swdown')
ax.plot(time, Rn, '-', label = 'Rn')

ax2.plot(time, temp, '-r')  # The true line in ax2
ax.plot(np.nan, '-r', label = 'temp')  # Make an agent in ax

ax.legend(loc=0)

#---------------done-----------------

ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()

The plot is as below:

enter image description here


Update: add a better version:

ax.plot(np.nan, '-r', label = 'temp')

This will do nothing while plot(0, 0) may change the axis range.


One extra example for scatter

ax.scatter([], [], s=100, label = 'temp')  # Make an agent in ax
ax2.scatter(time, temp, s=10)  # The true scatter in ax2

ax.legend(loc=1, framealpha=1)

Integer value comparison

Integers are autounboxed, so you can just do

if (count > 0) {
    .... 
}

How to prompt for user input and read command-line arguments

var = raw_input("Please enter something: ")
print "you entered", var

Or for Python 3:

var = input("Please enter something: ")
print("You entered: " + var)

How to create an empty DataFrame with a specified schema?

import scala.reflect.runtime.{universe => ru}
def createEmptyDataFrame[T: ru.TypeTag] =
    hiveContext.createDataFrame(sc.emptyRDD[Row],
      ScalaReflection.schemaFor(ru.typeTag[T].tpe).dataType.asInstanceOf[StructType]
    )
  case class RawData(id: String, firstname: String, lastname: String, age: Int)
  val sourceDF = createEmptyDataFrame[RawData]

What's the difference between ASCII and Unicode?

ASCII has 128 code positions, allocated to graphic characters and control characters (control codes).

Unicode has 1,114,112 code positions. About 100,000 of them have currently been allocated to characters, and many code points have been made permanently noncharacters (i.e. not used to encode any character ever), and most code points are not yet assigned.

The only things that ASCII and Unicode have in common are: 1) They are character codes. 2) The 128 first code positions of Unicode have been defined to have the same meanings as in ASCII, except that the code positions of ASCII control characters are just defined as denoting control characters, with names corresponding to their ASCII names, but their meanings are not defined in Unicode.

Sometimes, however, Unicode is characterized (even in the Unicode standard!) as “wide ASCII”. This is a slogan that mainly tries to convey the idea that Unicode is meant to be a universal character code the same way as ASCII once was (though the character repertoire of ASCII was hopelessly insufficient for universal use), as opposite to using different codes in different systems and applications and for different languages.

Unicode as such defines only the “logical size” of characters: Each character has a code number in a specific range. These code numbers can be presented using different transfer encodings, and internally, in memory, Unicode characters are usually represented using one or two 16-bit quantities per character, depending on character range, sometimes using one 32-bit quantity per character.

VBA, if a string contains a certain letter

Try using the InStr function which returns the index in the string at which the character was found. If InStr returns 0, the string was not found.

If InStr(myString, "A") > 0 Then

InStr MSDN Website

For the error on the line assigning to newStr, convert oldStr.IndexOf to that InStr function also.

Left(oldStr, InStr(oldStr, "A"))

Differences between "java -cp" and "java -jar"?

There won't be any difference in terms of performance. Using java - cp we can specify the required classes and jar's in the classpath for running a java class file.

If it is a executable jar file . When java -jar command is used, jvm finds the class that it needs to run from /META-INF/MANIFEST.MF file inside the jar file.

How to sort a file in-place

The sort command prints the result of the sorting operation to standard output by default. In order to achieve an "in-place" sort, you can do this:

sort -o file file

This overwrites the input file with the sorted output. The -o switch, used to specify an output, is defined by POSIX, so should be available on all version of sort:

-o Specify the name of an output file to be used instead of the standard output. This file can be the same as one of the input files.

If you are unfortunate enough to have a version of sort without the -o switch (Luis assures me that they exist), you can achieve an "in-place" edit in the standard way:

sort file > tmp && mv tmp file

What is the difference between DBMS and RDBMS?

A DBMS is used for storage of data in files. In DBMS relationships can be established between two files. Data is stored in flat files with metadata whereas RDBMS stores the data in tabular form with additional condition of data that enforces relationships among the tables. Unlike RDBMS, DBMS does not support client server architecture. RDBMS imposes integrity constraints and also follows normalization which is not supported in DBMS.

How to extract hours and minutes from a datetime.datetime object?

It's easier to use the timestamp for this things since Tweepy gets both

import datetime
print(datetime.datetime.fromtimestamp(int(t1)).strftime('%H:%M'))

Run text file as commands in Bash

Execute

. example.txt

That does exactly what you ask for, without setting an executable flag on the file or running an extra bash instance.

For a detailed explanation see e.g. https://unix.stackexchange.com/questions/43882/what-is-the-difference-between-sourcing-or-source-and-executing-a-file-i

How to use HTTP_X_FORWARDED_FOR properly?

You can use this function to get proper client IP:

public function getClientIP(){       
     if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)){
            return  $_SERVER["HTTP_X_FORWARDED_FOR"];  
     }else if (array_key_exists('REMOTE_ADDR', $_SERVER)) { 
            return $_SERVER["REMOTE_ADDR"]; 
     }else if (array_key_exists('HTTP_CLIENT_IP', $_SERVER)) {
            return $_SERVER["HTTP_CLIENT_IP"]; 
     } 

     return '';
}

'xmlParseEntityRef: no name' warnings while loading xml into a php file

The XML is most probably invalid.

The problem could be the "&"

$text=preg_replace('/&(?!#?[a-z0-9]+;)/', '&amp;', $text);

will get rid of the "&" and replace it with it's HTML code version...give it a try.

Pull request vs Merge request

In my point of view, they mean the same activity but from different perspectives:

Think about that, Alice makes some commits on repository A, which was forked from Bob's repository B.

When Alice wants to "merge" her changes into B, she actually wants Bob to "pull" these changes from A.

Therefore, from Alice's point of view, it is a "merge request", while Bob views it as a "pull request".

Placing border inside of div and not on its edge

A more modern solution might be to use css variables and calc. calc is widely supported but variables is not yet in IE11 (polyfills available).

:root {
  box-width: 100px;
  border-width: 1px;
}

#box {
  width: calc(var(--box-width) - var(--border-width));
}

Although this does use some calculations, which the original questions was looking to avoid. I think this is an ok time to use calculations as they are controlled by the css itself. It also has no need for additional markup or misappropriating other css properties that may be needed later on.

This solution is only really useful if a fixed height isn't needed.

Python xml ElementTree from a string source?

io.StringIO is another option for getting XML into xml.etree.ElementTree:

import io
f = io.StringIO(xmlstring)
tree = ET.parse(f)
root = tree.getroot()

Hovever, it does not affect the XML declaration one would assume to be in tree (although that's needed for ElementTree.write()). See How to write XML declaration using xml.etree.ElementTree.

Can I convert a C# string value to an escaped string literal

Interesting question.

If you can't find a better method, you can always replace.
In case you're opting for it, you could use this C# Escape Sequence List:

  • \' - single quote, needed for character literals
  • \" - double quote, needed for string literals
  • \ - backslash
  • \0 - Unicode character 0
  • \a - Alert (character 7)
  • \b - Backspace (character 8)
  • \f - Form feed (character 12)
  • \n - New line (character 10)
  • \r - Carriage return (character 13)
  • \t - Horizontal tab (character 9)
  • \v - Vertical quote (character 11)
  • \uxxxx - Unicode escape sequence for character with hex value xxxx
  • \xn[n][n][n] - Unicode escape sequence for character with hex value nnnn (variable length version of \uxxxx)
  • \Uxxxxxxxx - Unicode escape sequence for character with hex value xxxxxxxx (for generating surrogates)

This list can be found in the C# Frequently Asked Questions What character escape sequences are available?

Convert a file path to Uri in Android

Below code works fine before 18 API :-

public String getRealPathFromURI(Uri contentUri) {

        // can post image
        String [] proj={MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery( contentUri,
                        proj, // Which columns to return
                        null,       // WHERE clause; which rows to return (all rows)
                        null,       // WHERE clause selection arguments (none)
                        null); // Order-by clause (ascending by name)
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();

        return cursor.getString(column_index);
}

below code use on kitkat :-

public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] {
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @param selection (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 */
public static String getDataColumn(Context context, Uri uri, String selection,
        String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}


/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

see below link for more info:-

https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java

How do I make a branch point at a specific commit?

You can make master point at 1258f0d0aae this way:

git checkout master
git reset --hard 1258f0d0aae

But you have to be careful about doing this. It may well rewrite the history of that branch. That would create problems if you have published it and other people are working on the branch.

Also, the git reset --hard command will throw away any uncommitted changes (i.e. those just in your working tree or the index).

You can also force an update to a branch with:

git branch -f master 1258f0d0aae

... but git won't let you do that if you're on master at the time.

How do I create a timeline chart which shows multiple events? Eg. Metallica Band members timeline on wiki

A Stacked bar chart should suffice:

Setup data as follows

Name    Start       End         Duration (End - Start)
Fred    1/01/1981   1/06/1985    1612   
Bill    1/07/1985   1/11/2000    5602  
Joe     1/01/1980   1/12/2001    8005  
Jim     1/03/1999   1/01/2000    306  
  1. Plot Start and Duration as a stacked bar chart
  2. Set the X-Axis minimum to the desired start date
  3. Set the Fill Colour of thestart range to no fill
  4. Set the Fill of individual bars to suit

(example prepared in Excel 2010)

enter image description here

Moment JS - check if a date is today or in the future

function isTodayOrFuture(date){
  date = stripTime(date);
  return date.diff(stripTime(moment.now())) >= 0;
}

function stripTime(date){
  date = moment(date);
  date.hours(0);
  date.minutes(0);
  date.seconds(0);
  date.milliseconds(0);
  return date;
}

And then just use it line this :

isTodayOrFuture(YOUR_TEST_DATE_HERE)

Android textview outline text

You can put a shadow behind the text, which can often help readability. Try experimenting with 50% translucent black shadows on your green text. Details on how to do this are over here: Android - shadow on text?

To really add a stroke around the text, you need to do something a bit more involved, like this: How do you draw text with a border on a MapView in Android?

Facebook database design?

Have a look at the following database schema, reverse engineered by Anatoly Lubarsky:

Facebook Schema

The ResourceConfig instance does not contain any root resource classes

Ok... For me work fine just only assigning the "servlet-class" to com.sum.jersey.spi.container.servlet.ServletContainer, I am using IDE (Eclipse Mars)

<servlet>
        <servlet-name>Jersey Web Application</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Jersey Web Application</servlet-name>
        <url-pattern>/frontend/*</url-pattern>
    </servlet-mapping>

but for some reason I had to reboot my computer in order to work in my localhost. If still not work? You have to add in your web.xml this code in between "servlet" tag.

<init-param>
  <param-name>com.sun.jersey.config.property.packages</param-name>
  <param-value>the.package.name</param-value>
</init-param>

"the.package.name" is the package name where you have your classes. If you are using IDE, refresh the project and run again in Tomcat. still not work? reboot your computer and will work.

How to generate the JPA entity Metamodel?

Let's assume our application uses the following Post, PostComment, PostDetails, and Tag entities, which form a one-to-many, one-to-one, and many-to-many table relationships:

JPA Criteria Metamodel

How to generate the JPA Criteria Metamodel

The hibernate-jpamodelgen tool provided by Hibernate ORM can be used to scan the project entities and generate the JPA Criteria Metamodel. All you need to do is add the following annotationProcessorPath to the maven-compiler-plugin in the Maven pom.xml configuration file:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>${maven-compiler-plugin.version}</version>
    <configuration>
        <annotationProcessorPaths>
            <annotationProcessorPath>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-jpamodelgen</artifactId>
                <version>${hibernate.version}</version>
            </annotationProcessorPath>
        </annotationProcessorPaths>
    </configuration>
</plugin>

Now, when the project is compiled, you can see that in the target folder, the following Java classes are generated:

> tree target/generated-sources/
target/generated-sources/
+-- annotations
    +-- com
        +-- vladmihalcea
            +-- book
                +-- hpjp
                    +-- hibernate
                        +-- forum
                        ¦   +-- PostComment_.java
                        ¦   +-- PostDetails_.java
                        ¦   +-- Post_.java
                        ¦   +-- Tag_.java

Tag entity Metamodel

If the Tag entity is mapped as follows:

@Entity
@Table(name = "tag")
public class Tag {

    @Id
    private Long id;

    private String name;

    //Getters and setters omitted for brevity
}

The Tag_ Metamodel class is generated like this:

@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(Tag.class)
public abstract class Tag_ {

    public static volatile SingularAttribute<Tag, String> name;
    public static volatile SingularAttribute<Tag, Long> id;

    public static final String NAME = "name";
    public static final String ID = "id";
}

The SingularAttribute is used for the basic id and name Tag JPA entity attributes.

Post entity Metamodel

The Post entity is mapped like this:

@Entity
@Table(name = "post")
public class Post {

    @Id
    private Long id;

    private String title;

    @OneToMany(
        mappedBy = "post",
        cascade = CascadeType.ALL,
        orphanRemoval = true
    )
    private List<PostComment> comments = new ArrayList<>();

    @OneToOne(
        mappedBy = "post",
        cascade = CascadeType.ALL,
        fetch = FetchType.LAZY
    )
    @LazyToOne(LazyToOneOption.NO_PROXY)
    private PostDetails details;

    @ManyToMany
    @JoinTable(
        name = "post_tag",
        joinColumns = @JoinColumn(name = "post_id"),
        inverseJoinColumns = @JoinColumn(name = "tag_id")
    )
    private List<Tag> tags = new ArrayList<>();
    
    //Getters and setters omitted for brevity
}

The Post entity has two basic attributes, id and title, a one-to-many comments collection, a one-to-one details association, and a many-to-many tags collection.

The Post_ Metamodel class is generated as follows:

@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(Post.class)
public abstract class Post_ {

    public static volatile ListAttribute<Post, PostComment> comments;
    public static volatile SingularAttribute<Post, PostDetails> details;
    public static volatile SingularAttribute<Post, Long> id;
    public static volatile SingularAttribute<Post, String> title;
    public static volatile ListAttribute<Post, Tag> tags;

    public static final String COMMENTS = "comments";
    public static final String DETAILS = "details";
    public static final String ID = "id";
    public static final String TITLE = "title";
    public static final String TAGS = "tags";
}

The basic id and title attributes, as well as the one-to-one details association, are represented by a SingularAttribute while the comments and tags collections are represented by the JPA ListAttribute.

PostDetails entity Metamodel

The PostDetails entity is mapped like this:

@Entity
@Table(name = "post_details")
public class PostDetails {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "created_on")
    private Date createdOn;

    @Column(name = "created_by")
    private String createdBy;

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    @JoinColumn(name = "id")
    private Post post;
    
    //Getters and setters omitted for brevity
}

All entity attributes are going to be represented by the JPA SingularAttribute in the associated PostDetails_ Metamodel class:

@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(PostDetails.class)
public abstract class PostDetails_ {

    public static volatile SingularAttribute<PostDetails, Post> post;
    public static volatile SingularAttribute<PostDetails, String> createdBy;
    public static volatile SingularAttribute<PostDetails, Long> id;
    public static volatile SingularAttribute<PostDetails, Date> createdOn;

    public static final String POST = "post";
    public static final String CREATED_BY = "createdBy";
    public static final String ID = "id";
    public static final String CREATED_ON = "createdOn";
}

PostComment entity Metamodel

The PostComment is mapped as follows:

@Entity
@Table(name = "post_comment")
public class PostComment {

    @Id
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    private Post post;

    private String review;
    
    //Getters and setters omitted for brevity
}

And, all entity attributes are represented by the JPA SingularAttribute in the associated PostComments_ Metamodel class:

@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(PostComment.class)
public abstract class PostComment_ {

    public static volatile SingularAttribute<PostComment, Post> post;
    public static volatile SingularAttribute<PostComment, String> review;
    public static volatile SingularAttribute<PostComment, Long> id;

    public static final String POST = "post";
    public static final String REVIEW = "review";
    public static final String ID = "id";
}

Using the JPA Criteria Metamodel

Without the JPA Metamodel, a Criteria API query that needs to fetch the PostComment entities filtered by their associated Post title would look like this:

CriteriaBuilder builder = entityManager.getCriteriaBuilder();

CriteriaQuery<PostComment> query = builder.createQuery(PostComment.class);
Root<PostComment> postComment = query.from(PostComment.class);

Join<PostComment, Post> post = postComment.join("post");

query.where(
    builder.equal(
        post.get("title"),
        "High-Performance Java Persistence"
    )
);

List<PostComment> comments = entityManager
    .createQuery(query)
    .getResultList();

Notice that we used the post String literal when creating the Join instance, and we used the title String literal when referencing the Post title.

The JPA Metamodel allows us to avoid hard-coding entity attributes, as illustrated by the following example:

CriteriaBuilder builder = entityManager.getCriteriaBuilder();

CriteriaQuery<PostComment> query = builder.createQuery(PostComment.class);
Root<PostComment> postComment = query.from(PostComment.class);

Join<PostComment, Post> post = postComment.join(PostComment_.post);

query.where(
    builder.equal(
        post.get(Post_.title),
        "High-Performance Java Persistence"
    )
);

List<PostComment> comments = entityManager
    .createQuery(query)
    .getResultList();

Or, let's say we want to fetch a DTO projection while filtering the Post title and the PostDetails createdOn attributes.

We can use the Metamodel when creating the join attributes, as well as when building the DTO projection column aliases or when referencing the entity attributes we need to filter:

CriteriaBuilder builder = entityManager.getCriteriaBuilder();

CriteriaQuery<Object[]> query = builder.createQuery(Object[].class);

Root<PostComment> postComment = query.from(PostComment.class);
Join<PostComment, Post> post = postComment.join(PostComment_.post);

query.multiselect(
    postComment.get(PostComment_.id).alias(PostComment_.ID),
    postComment.get(PostComment_.review).alias(PostComment_.REVIEW),
    post.get(Post_.title).alias(Post_.TITLE)
);

query.where(
    builder.and(
        builder.like(
            post.get(Post_.title),
            "%Java Persistence%"
        ),
        builder.equal(
            post.get(Post_.details).get(PostDetails_.CREATED_BY),
            "Vlad Mihalcea"
        )
    )
);

List<PostCommentSummary> comments = entityManager
    .createQuery(query)
    .unwrap(Query.class)
    .setResultTransformer(Transformers.aliasToBean(PostCommentSummary.class))
    .getResultList();

Cool, right?

Bootstrap4 adding scrollbar to div

Use the overflow-y: scroll property on the element that contains the elements.

The overflow-y property specifies whether to clip the content, add a scroll bar, or display overflow content of a block-level element, when it overflows at the top and bottom edges.

Sometimes it is interesting to place a height for the element next to the overflow-y property, as in the example below:

<ul class="nav nav-pills nav-stacked" style="height: 250px; overflow-y: scroll;">
  <li class="nav-item">
    <a class="nav-link active" href="#">Active</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#">Link</a>
  </li>
  <li class="nav-item">
    <a class="nav-link" href="#">Link</a>
  </li>
  <li class="nav-item">
    <a class="nav-link disabled" href="#">Disabled</a>
  </li>
</ul>

Distinct pair of values SQL

What you mean is either

SELECT DISTINCT a, b FROM pairs;

or

SELECT a, b FROM pairs GROUP BY a, b;

How can I generate an apk that can run without server with react-native?

The GUI way in Android Studio

  • Have the Android app part of the React Native app open in Android Studio (this just means opening the android folder of your react-native project with Android Studio)
  • Go to the "Build" tab at the top
  • Go down to "Build Bundle(s) / APK(s)"
  • Then select "Build APK(s)"
  • This will walk you through a process of locating your keys to sign the APK or creating your keys if you don't have them already which is all very straightforward. If you're just practicing, you can generate these keys and save them to your desktop.
  • Once that process is complete and if the build was successful, there will be a popup down below in Android Studio. Click the link within it that says "locate" (the APK)
  • That will take you to the apk file, move that over to your android device. Then navigate to that file on the Android device and install it.

Sorting a Data Table

After setting the sort expression on the DefaultView (table.DefaultView.Sort = "Town ASC, Cutomer ASC" ) you should loop over the table using the DefaultView not the DataTable instance itself

foreach(DataRowView r in table.DefaultView)
{
    //... here you get the rows in sorted order
    Console.WriteLine(r["Town"].ToString());
}

Using the Select method of the DataTable instead, produces an array of DataRow. This array is sorted as from your request, not the DataTable

DataRow[] rowList = table.Select("", "Town ASC, Cutomer ASC");
foreach(DataRow r in rowList)
{
    Console.WriteLine(r["Town"].ToString());
}

How to download a file from my server using SSH (using PuTTY on Windows)

There's no way to initiate a file transfer back to/from local Windows from a SSH session opened in PuTTY window.

Though PuTTY supports connection-sharing.

While you still need to run a compatible file transfer client (pscp or psftp), no new login is required, it automatically (if enabled) makes use of an existing PuTTY session.

To enable the sharing see:
Sharing an SSH connection between PuTTY tools.


Even without connection-sharing, you can still use the psftp or pscp from Windows command line.

See How to use PSCP to copy file from Unix machine to Windows machine ...?

Note that the scp is OpenSSH program. It's primarily *nix program, but you can run it via Windows Subsystem for Linux or get a Windows build from Win32-OpenSSH (it is already built-in in the latest versions of Windows 10).


If you really want to download the files to a local desktop, you have to specify a target path as %USERPROFILE%\Desktop (what typically resolves to a path like C:\Users\username\Desktop).


Alternative way is to use WinSCP, a GUI SFTP/SCP client. While you browse the remote site, you can anytime open SSH terminal to the same site using Open in PuTTY command.
See Opening Session in PuTTY.

With an additional setup, you can even make PuTTY automatically navigate to the same directory you are browsing with WinSCP.
See Opening PuTTY in the same directory.

(I'm the author of WinSCP)

"Connection for controluser as defined in your configuration failed" with phpMyAdmin in XAMPP

On Ubunbtu.

Ben's message is close but it's not the root password that is the problem, the problem I found was I had created a password for the phpmyadmin database when I installed it. This password is not carried into the installation on ubuntu so the variable $dbpass=''; in the database settings file is empty and not the password you set.

  1. To check you have the right password at the command line login to mysql using the following command: mysql -u phpmyadmin -p try a blank password I found I got access denied, enter the command again using the password you set during installation. If it logs in you now know what the password is.
  2. Edit /etc/phpadmin/config-db.php and change $dbpass=''; to $dbpass='Your Password'; and save the file.
  3. Edit /etc/dbconfig-common/phpmyadmin.conf change dbc_dbpass=''; to dbc_dbpass='Your Password'; and save the file. Close your browser and reload you will now find the message has gone way.

How do I change the font color in an html table?

table td{
  color:#0000ff;
}

<table>
  <tbody>
    <tr>
    <td>
      <select name="test">
        <option value="Basic">Basic : $30.00 USD - yearly</option>
        <option value="Sustaining">Sustaining : $60.00 USD - yearly</option>
        <option value="Supporting">Supporting : $120.00 USD - yearly</option>
      </select>
    </td>
    </tr>
  </tbody>
</table>

How do I set Java's min and max heap size through environment variables?

You can't do it using environment variables directly. You need to use the set of "non standard" options that are passed to the java command. Run: java -X for details. The options you're looking for are -Xmx and -Xms (this is "initial" heap size, so probably what you're looking for.)

Some products like Ant or Tomcat might come with a batch script that looks for the JAVA_OPTS environment variable, but it's not part of the Java runtime. If you are using one of those products, you may be able to set the variable like:

set JAVA_OPTS="-Xms128m -Xmx256m"  

You can also take this approach with your own command line like:

set JAVA_OPTS="-Xms128m -Xmx256m"  
java ${JAVA_OPTS} MyClass

How to create an 2D ArrayList in java?

1st of all, when you declare a variable in java, you should declare it using Interfaces even if you specify the implementation when instantiating it

ArrayList<ArrayList<String>> listOfLists = new ArrayList<ArrayList<String>>();

should be written

List<List<String>> listOfLists = new ArrayList<List<String>>(size); 

Then you will have to instantiate all columns of your 2d array

    for(int i = 0; i < size; i++)  {
        listOfLists.add(new ArrayList<String>());
    }

And you will use it like this :

listOfLists.get(0).add("foobar");

But if you really want to "create a 2D array that each cell is an ArrayList!"

Then you must go the dijkstra way.

Why does checking a variable against multiple values with `OR` only check the first value?

("Jesse" or "jesse")

The above expression tests whether or not "Jesse" evaluates to True. If it does, then the expression will return it; otherwise, it will return "jesse". The expression is equivalent to writing:

"Jesse" if "Jesse" else "jesse"

Because "Jesse" is a non-empty string though, it will always evaluate to True and thus be returned:

>>> bool("Jesse")  # Non-empty strings evaluate to True in Python
True
>>> bool("")  # Empty strings evaluate to False
False
>>>
>>> ("Jesse" or "jesse")
'Jesse'
>>> ("" or "jesse")
'jesse'
>>>

This means that the expression:

name == ("Jesse" or "jesse")

is basically equivalent to writing this:

name == "Jesse"

In order to fix your problem, you can use the in operator:

# Test whether the value of name can be found in the tuple ("Jesse", "jesse")
if name in ("Jesse", "jesse"):

Or, you can lowercase the value of name with str.lower and then compare it to "jesse" directly:

# This will also handle inputs such as "JeSSe", "jESSE", "JESSE", etc.
if name.lower() == "jesse":

What is the Regular Expression For "Not Whitespace and Not a hyphen"

Which programming language are you using? May be you just need to escape the backslash like "[^\\s-]"

What is the difference between Visual Studio Express 2013 for Windows and Visual Studio Express 2013 for Windows Desktop?

More importantly, the 2013 versions of Visual Studio Express have all the languages that comes with the commercial versions. You can use the Windows desktop versions not only to program using Windows Forms, it is possible to write those windowed applications with any language that comes with the software, may it be C++ using the windows.h header if you want to actually learn how to create windows applications from scratch, or use Windows form to create windows in C# or visual Basic.

In the past, you had to download one version for each language or type of content. Or just download an all-in-one that still installed separate versions of the software for different languages. Now with 2013 you get all the languages needed in each content oriented version of the 2013 express.

You pick what matters the most to you.

Besides, it might be a good way to learn using notepad and the command line to write and compile, but I find that a bit tedious to use. While using an IDE might be overwhelming at first, you start small, learning how to create a project, write code, compile your code. They have gone way over their heads to ease up your day when you take it for the first time.

Case insensitive 'Contains(string)'

Just like this:

string s="AbcdEf";
if(s.ToLower().Contains("def"))
{
    Console.WriteLine("yes");
}

How to remove all subviews of a view in Swift?

did you try something like

for o : AnyObject in self.subviews {
     if let v = o as? NSView {
         v.removeFromSuperview()
     }
}

Get all Attributes from a HTML element with Javascript/jQuery

Very simple. You just need to loop over the attributes element and push their nodeValues into an array:

let att = document.getElementById('id');

let arr = Array();

for (let i = 0; i < att.attributes.length; i++) {
    arr.push(att.attributes[i].nodeValue);
}

If want the name of the attribute you can replace 'nodeValue' for 'nodeName'.

let att = document.getElementById('id');

let arr = Array();

for (let i = 0; i < att.attributes.length; i++) {
    arr.push(att.attributes[i].nodeName);
}

Python convert tuple to string

This works:

''.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))

It will produce:

'abcdgxre'

You can also use a delimiter like a comma to produce:

'a,b,c,d,g,x,r,e'

By using:

','.join(('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e'))

Live-stream video from one android phone to another over WiFi

You can check the android VLC it can stream and play video, if you want to indagate more, you can check their GIT to analyze what their do. Good luck!

How to split a string by spaces in a Windows batch file?

@echo off

:: read a file line by line
for /F  %%i in ('type data.csv') do (
    echo %%i
    :: and we extract four tokens, ; is the delimiter.
    for /f "tokens=1,2,3,4 delims=;" %%a in ("%%i") do (
        set first=%%a&set second=%%b&set third=%%c&set fourth=%%d
        echo %first% and %second% and %third% and %fourth% 
    )
)

Extract the maximum value within each group in a dataframe

There are many possibilities to do this in R. Here are some of them:

df <- read.table(header = TRUE, text = 'Gene   Value
A      12
A      10
B      3
B      5
B      6
C      1
D      3
D      4')

# aggregate
aggregate(df$Value, by = list(df$Gene), max)
aggregate(Value ~ Gene, data = df, max)

# tapply
tapply(df$Value, df$Gene, max)

# split + lapply
lapply(split(df, df$Gene), function(y) max(y$Value))

# plyr
require(plyr)
ddply(df, .(Gene), summarise, Value = max(Value))

# dplyr
require(dplyr)
df %>% group_by(Gene) %>% summarise(Value = max(Value))

# data.table
require(data.table)
dt <- data.table(df)
dt[ , max(Value), by = Gene]

# doBy
require(doBy)
summaryBy(Value~Gene, data = df, FUN = max)

# sqldf
require(sqldf)
sqldf("select Gene, max(Value) as Value from df group by Gene", drv = 'SQLite')

# ave
df[as.logical(ave(df$Value, df$Gene, FUN = function(x) x == max(x))),]

S3 - Access-Control-Allow-Origin Header

This configuration solved the issue for me:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <ExposeHeader>ETag</ExposeHeader>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

Regex to match string containing two names in any order

You can do checks using lookarounds:

^(?=.*\bjack\b)(?=.*\bjames\b).*$

Test it.

This approach has the advantage that you can easily specify multiple conditions.

^(?=.*\bjack\b)(?=.*\bjames\b)(?=.*\bjason\b)(?=.*\bjules\b).*$

sort json object in javascript

In some ways, your question seems very legitimate, but I still might label it an XY problem. I'm guessing the end result is that you want to display the sorted values in some way? As Bergi said in the comments, you can never quite rely on Javascript objects ( {i_am: "an_object"} ) to show their properties in any particular order.

For the displaying order, I might suggest you take each key of the object (ie, i_am) and sort them into an ordered array. Then, use that array when retrieving elements of your object to display. Pseudocode:

var keys = [...]
var sortedKeys = [...]
for (var i = 0; i < sortedKeys.length; i++) {
  var key = sortedKeys[i];
  addObjectToTable(json[key]);
}

What are the uses of "using" in C#?

Not that it is ultra important, but using can also be used to change resources on the fly. Yes disposable as mentioned earlier, but perhaps specifically you don't want the resources they mismatch with other resources during the rest of your execution. So you want to dispose of it so it doesn't interfere elsewhere.

Split string into string array of single characters

Simple!!
one line:

 var res = test.Select(x => new string(x, 1)).ToArray();

How to get the size of a string in Python?

The most Pythonic way is to use the len(). Keep in mind that the '\' character in escape sequences is not counted and can be dangerous if not used correctly.

>>> len('foo')
3
>>> len('\foo')
3
>>> len('\xoo')
  File "<stdin>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \xXX escape

How to: Install Plugin in Android Studio

1) Launch Android Studio application

2) Choose File -> Settings (For Mac Preference )

3) Search for Plugins

enter image description here

In Android Studio 3.4.2

enter image description here

Twitter Bootstrap inline input with dropdown

Daniel Farrell's Bootstrap Combobox does the job perfectly. Here's an example from his GitHub repository.

_x000D_
_x000D_
$(document).ready(function(){_x000D_
  $('.combobox').combobox();_x000D_
  _x000D_
  // bonus: add a placeholder_x000D_
  $('.combobox').attr('placeholder', 'For example, start typing "Pennsylvania"');_x000D_
});
_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-combobox/1.1.8/css/bootstrap-combobox.min.css">_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-combobox/1.1.8/js/bootstrap-combobox.min.js"></script>_x000D_
_x000D_
<select class="combobox form-control">_x000D_
  <option></option>_x000D_
  <option value="PA">Pennsylvania</option>_x000D_
  <option value="CT">Connecticut</option>_x000D_
  <option value="NY">New York</option>_x000D_
  <option value="MD">Maryland</option>_x000D_
  <option value="VA">Virginia</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

As an added bonus, I've included a placeholder in script since applying it to the markup does not hold.

Git: Create a branch from unstaged/uncommitted changes on master

If you are using the GitHub Windows client (as I am) and you are in the situation of having made uncommitted changes that you wish to move to a new branch, you can simply "Crate a new branch" via the GitHub client. It will switch to the newly created branch and preserve your changes.

enter image description here

gradlew command not found?

If the answer marked as correct does not work, it is because you need to identify yourself as a super user.

sudo gradle wrapper --gradle-version 2.13

It worked for me.

How do I assign ls to an array in Linux Bash?

Whenever possible, you should avoid parsing the output of ls (see Greg's wiki on the subject). Basically, the output of ls will be ambiguous if there are funny characters in any of the filenames. It's also usually a waste of time. In this case, when you execute ls -d */, what happens is that the shell expands */ to a list of subdirectories (which is already exactly what you want), passes that list as arguments to ls -d, which looks at each one, says "yep, that's a directory all right" and prints it (in an inconsistent and sometimes ambiguous format). The ls command isn't doing anything useful!

Well, ok, it is doing one thing that's useful: if there are no subdirectories, */ will get left as is, ls will look for a subdirectory named "*", not find it, print an error message that it doesn't exist (to stderr), and not print the "*/" (to stdout).

The cleaner way to make an array of subdirectory names is to use the glob (*/) without passing it to ls. But in order to avoid putting "*/" in the array if there are no actual subdirectories, you should set nullglob first (again, see Greg's wiki):

shopt -s nullglob
array=(*/)
shopt -u nullglob # Turn off nullglob to make sure it doesn't interfere with anything later
echo "${array[@]}"  # Note double-quotes to avoid extra parsing of funny characters in filenames

If you want to print an error message if there are no subdirectories, you're better off doing it yourself:

if (( ${#array[@]} == 0 )); then
    echo "No subdirectories found" >&2
fi

AngularJS: Insert HTML from a string

you can also use $sce.trustAsHtml('"<h1>" + str + "</h1>"'),if you want to know more detail, please refer to $sce

Sharing url link does not show thumbnail image on facebook

The issue is with the facebook cache and solution is to refresh the facebook cache by going to the link. https://developers.facebook.com/tools/debug/og/object/

and pressing the button "Fetch New Scrape information".

Hope it helps

Ifelse statement in R with multiple conditions

Very simple use of any

df <- <your structure>

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

PreparedStatement setNull(..)

Finally I did a small test and while I was programming it it came to my mind, that without the setNull(..) method there would be no way to set null values for the Java primitives. For Objects both ways

setNull(..)

and

set<ClassName>(.., null)) 

behave the same way.

GROUP_CONCAT ORDER BY

The group_concat supports its own order by clause

http://mahmudahsan.wordpress.com/2008/08/27/mysql-the-group_concat-function/

So you should be able to write:

SELECT li.clientid, group_concat(li.views order by views) AS views,
group_concat(li.percentage order by percentage) 
FROM table_views GROUP BY client_id

How to append a newline to StringBuilder

It should be

r.append("\n");

But I recommend you to do as below,

r.append(System.getProperty("line.separator"));

System.getProperty("line.separator") gives you system-dependent newline in java. Also from Java 7 there's a method that returns the value directly: System.lineSeparator()

How to validate IP address in Python?

The IPy module (a module designed for dealing with IP addresses) will throw a ValueError exception for invalid addresses.

>>> from IPy import IP
>>> IP('127.0.0.1')
IP('127.0.0.1')
>>> IP('277.0.0.1')
Traceback (most recent call last):
 ...
ValueError: '277.0.0.1': single byte must be 0 <= byte < 256
>>> IP('foobar')
Traceback (most recent call last):
 ...
ValueError: invalid literal for long() with base 10: 'foobar'

However, like Dustin's answer, it will accept things like "4" and "192.168" since, as mentioned, these are valid representations of IP addresses.

If you're using Python 3.3 or later, it now includes the ipaddress module:

>>> import ipaddress
>>> ipaddress.ip_address('127.0.0.1')
IPv4Address('127.0.0.1')
>>> ipaddress.ip_address('277.0.0.1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.3/ipaddress.py", line 54, in ip_address
    address)
ValueError: '277.0.0.1' does not appear to be an IPv4 or IPv6 address
>>> ipaddress.ip_address('foobar')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.3/ipaddress.py", line 54, in ip_address
    address)
ValueError: 'foobar' does not appear to be an IPv4 or IPv6 address

For Python 2, you can get the same functionality using ipaddress if you install python-ipaddress:

pip install ipaddress

This module is compatible with Python 2 and provides a very similar API to that of the ipaddress module included in the Python Standard Library since Python 3.3. More details here. In Python 2 you will need to explicitly convert the IP address string to unicode: ipaddress.ip_address(u'127.0.0.1').

How to install latest version of openssl Mac OS X El Capitan

Try creating a symlink, make sure you have openssl installed in /usr/local/include first.

ln -s /usr/local/Cellar/openssl/{version}/include/openssl /usr/local/include/openssl

More info at Openssl with El Capitan.

When should I write the keyword 'inline' for a function/method?

When developing and debugging code, leave inline out. It complicates debugging.

The major reason for adding them is to help optimize the generated code. Typically this trades increased code space for speed, but sometimes inline saves both code space and execution time.

Expending this kind of thought about performance optimization before algorithm completion is premature optimization.

TortoiseSVN icons overlay not showing after updating to Windows 10

Registry editor shot

As in current recommended answer mentioned, you need to sort the entries of the overlay identifiers in the registry. I haven't deleted those OneDrive or GoogleDrive entries but renamed all Tortoise Folders by adding 3 spaces to bring them on top. Just restart and even with Tortoise SVN client 1.7.9 you'll see your SVN overlay icons under Windows 10 again.

How to pass variable as a parameter in Execute SQL Task SSIS?

The EXCEL and OLED DB connection managers use the parameter names 0 and 1.

I was using a oledb connection and wasted couple of hours trying to figure out the reason why the query was not working or taking the parameters. the above explanation helped a lot Thanks a lot.

How to rename a single column in a data.frame?

library(dplyr)
rename(data, de=de.y)

Finding first and last index of some value in a list in Python

This method can be more optimized than above

def rindex(iterable, value):
    try:
        return len(iterable) - next(i for i, val in enumerate(reversed(iterable)) if val == value) - 1
    except StopIteration:
        raise ValueError

How to add additional libraries to Visual Studio project?

This description is very vague. What did you try, and how did it fail.

To include a library with your project, you have to include it in the modules passed to the linker. The exact steps to do this depend on the tools you are using. That part has nothing to do with the OS.

Now, if you are successfully compiling the library into your app and it doesn't run, that COULD be related to the OS.

How can I stop .gitignore from appearing in the list of untracked files?

You could actually put a line .gitignore into your .gitignore file. This would cause the .gitignore file to be ignored by git. I do not actually think this is a good idea. I think the ignore file should be version controlled and tracked. I'm just putting this out there for completeness.

Total size of the contents of all the files in a directory

Just an alternative:

ls -lAR | grep -v '^d' | awk '{total += $5} END {print "Total:", total}'

grep -v '^d' will exclude the directories.

Combine or merge JSON on node.js without jQuery

A better approach from the correct solution here in order to not alter target:

function extend(){
  let sources = [].slice.call(arguments, 0), result = {};
  sources.forEach(function (source) {
    for (let prop in source) {
      result[prop] = source[prop];
    }
  });
  return result;
}

How to export datagridview to excel using vb.net?

In design mode: Set DataGridView1 ClipboardCopyMode properties to EnableAlwaysIncludeHeaderText

or on the program code

DataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText

In the run time select all cells content (Ctrl+A) and copy (Ctrl+C) and paste to the Excel Program. Let the Excel do the rest

Sorry for the inconvenient, I have been searching the method to print data directly from the datagridvew (create report from vb.net VB2012) and have not found the satisfaction result. Above code just my though, wondering if my applications user can rely on above simple step it will be nice and I could go ahead to next step on my program progress.

Python - How do you run a .py file?

Your command should include the url parameter as stated in the script usage comments. The main function has 2 parameters, url and out (which is set to a default value) C:\python23\python "C:\PathToYourScript\SCRIPT.py" http://yoururl.com "C:\OptionalOutput\"

List directory tree structure in python?

@dhobbs's answer is great!

but simply change to easy get the level info

def print_list_dir(dir):
    print("=" * 64)
    print("[PRINT LIST DIR] %s" % dir)
    print("=" * 64)
    for root, dirs, files in os.walk(dir):
        level = root.replace(dir, '').count(os.sep)
        indent = '| ' * level
        print('{}{} \\'.format(indent, os.path.basename(root)))
        subindent = '| ' * (level + 1)
        for f in files:
            print('{}{}'.format(subindent, f))
    print("=" * 64)

and the output like

================================================================
[PRINT LIST DIR] ./
================================================================
 \
| os_name.py
| json_loads.py
| linspace_python.py
| list_file.py
| to_gson_format.py
| type_convert_test.py
| in_and_replace_test.py
| online_log.py
| padding_and_clipping.py
| str_tuple.py
| set_test.py
| script_name.py
| word_count.py
| get14.py
| np_test2.py
================================================================

you can get the level by | count!

How do I simulate placeholder functionality on input date field?

The input[type="date"] DOMElement only takes the following value: YYYY-MM-DD, any other format or text with be skipped.

Live Demo

HTML

<input type="text" placeholder="bingo" />
<input type="date" placeholder="2013-01-25" />

Pure JavaScript

window.onload = function () {
    /* Grab all elements with a placeholder attribute */
    var element = document.querySelectorAll('[placeholder]');

    /* Loop through each found elements */
    for (var i in element) {
        /* If the element is a DOMElement and has the nodeName "INPUT" */
        if (element[i].nodeType == 1 && element[i].nodeName == "INPUT") {

            /* We change the value of the element to its placeholder attr value */
            element[i].value = element[i].getAttribute('placeholder');
            /* We change its color to a light gray */
            element[i].style.color = "#777";

            /* When the input is selected/clicked on */
            element[i].onfocus = function (event) {
                /* If the value within it is the placeholder, we clear it */
                if (this.value == this.getAttribute('placeholder')) {
                    this.value = "";
                    /* Setting default text color */
                    this.style.color = "#000";
                };
            };

            /* We the input is left */
            element[i].onblur = function (event) {
                /* If the field is empty, we set its value to the placeholder */
                if (this.value == "") {
                    this.value = this.getAttribute('placeholder');
                    this.style.color = "#777";
                }
            };
        }
    }
}

Performance review

In this exact case, with 2 input elements, Pure JavaScript is ~40% ± 10% faster.

With 32 input elements, the difference remains the same (~43% ± 10% faster for Pure JS).

Static Classes In Java

Well, Java has "static nested classes", but they're not at all the same as C#'s static classes, if that's where you were coming from. A static nested class is just one which doesn't implicitly have a reference to an instance of the outer class.

Static nested classes can have instance methods and static methods.

There's no such thing as a top-level static class in Java.