Programs & Examples On #Mixed

IntelliJ: Error:java: error: release version 5 not supported

The only working solution in my case was adding the following block to pom.xml:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.0</version> <configuration> <release>12</release>
        </configuration>
        </plugin>
    </plugins>
</build>

Error: Java: invalid target release: 11 - IntelliJ IDEA

In your pom.xml file inside that <java.version> write "8" instead write "11" ,and RECOMPILE your pom.xml file And tadaaaaaa it works !

Failed to run sdkmanager --list with Java 9

(WINDOWS)

If you have installed Android Studio already go to File >> Project Structure... >> SDK Location.

Go to that location + \cmdline-tools\latest\bin Copy the Path into Environment Variables

than it is OK to use the command line tool.

Failed to install android-sdk: "java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema"

In my case, I need both JDK 8 (trying to use the AVD and SDK manager in Qt under ubuntu) and 11 for different tools. Removing version 11 is not an option.

The 'JAVA_OPTS' solutions did not do anything. I don't really like the export JAVA_HOME, as it might force you do launch whatever tool calls these utils from the same shell (like Qt), or force you to make this permanent, which is not convenient.

So for me the solution is quite simple. Add something like this in the second line of ~/Android/tools/bin/sdkmanager and ~/Android/tools/bin/avdmanager:

JAVA_HOME="/usr/lib/jvm/java-8-openjdk-amd64"

(or whatever the path is to your rev 8 jdk).

With this, these command line tools work in a stand alone mode, they work also when called by other tools such as Qt, and jdk 11 is still the system default for others. No need to mix libs etc...

The only downside is that any update to these command line tools will erase these modifications, which you will have to put back in.

How to enable CORS in ASP.net Core WebAPI

Here is how I did this.

I see that in some answers they are setting app.UserCors("xxxPloicy") and putting [EnableCors("xxxPloicy")] in controllers. You do not need to do both.

Here are the steps.

In Startup.cs inside the ConfigureServices add the following code.

    services.AddCors(c=>c.AddPolicy("xxxPolicy",builder => {
        builder.AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader();
    }));

If you want to apply all over the project then add the following code in Configure method in Startup.cs

app.UseCors("xxxPolicy");

Or

If you want to add it to the specific controllers then add enable cors code as shown below.

[EnableCors("xxxPolicy")]
[Route("api/[controller]")]
[ApiController]
public class TutorialController : ControllerBase {}

For more info: see this

Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint

Try to add a s after http

Like this:

http://integration.jsite.com/data/vis => https://integration.jsite.com/data/vis

It works for me

Unsupported major.minor version 52.0 in my app

The Simplest solution is you have to update your JDK to latest, version . Because Cordova supports only latest JDK .

1. First of all you have to update your Android SDK. Then,

2. If you are not able to update through your terminal , Got to your Software center of Linux destro and search the Latest (which one you want to install) and install that one .

Then again run Cordova build .

It will solve the problem .

In ,my case it worked.

Why is JavaFX is not included in OpenJDK 8 on Ubuntu Wily (15.10)?

I use ubuntu 16.04 and because I already had openJDK installed, this command have solved the problem. Don't forget that JavaFX is part of OpenJDK.

sudo apt-get install openjfx

"Mixed content blocked" when running an HTTP AJAX operation in an HTTPS page

Instead of using Ajax Post method, you can use dynamic form along with element. It will works even page is loaded in SSL and submitted source is non SSL.

You need to set value value of element of form.

Actually new dynamic form will open as non SSL mode in separate tab of Browser when target attribute has set '_blank'

var f = document.createElement('form');
f.action='http://XX.XXX.XX.XX/vicidial/non_agent_api.php';
f.method='POST';
//f.target='_blank';
//f.enctype="multipart/form-data"

var k=document.createElement('input');
k.type='hidden';k.name='CustomerID';
k.value='7299';
f.appendChild(k);



//var z=document.getElementById("FileNameId")
//z.setAttribute("name", "IDProof");
//z.setAttribute("id", "IDProof");
//f.appendChild(z);

document.body.appendChild(f);
f.submit()

Java 6 Unsupported major.minor version 51.0

I ran into the same problem. I use jdk 1.8 and maven 3.3.9 Once I export JAVA_HOME, I did not see this error. export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/

Moving from JDK 1.7 to JDK 1.8 on Ubuntu

Most of the answers for this question can not helped me in 2020.

This notification from download site of Oracle may be the reason:

Important Oracle JDK License Update

The Oracle JDK License has changed for releases starting April 16, 2019.

I try to google a little bit and those tutorials below helped me a lot.

  1. Remove completely the previous version of JVM installed on your PC.

    sudo update-alternatives --remove-all java
    sudo update-alternatives --remove-all javac
    sudo update-alternatives --remove-all javaws
    
    # /usr/lib/jvm/jdk1.7.0 is the path you installed the previous version of JVM on your PC
    sudo rm -rf /usr/lib/jvm/jdk1.7.0 
    

    Check to see whether java is uninstalled or not

    java -version
    
  2. Install Java 8 JDK.

    • Download Java 8 from Oracle's website. The version being used is 1.8.0_251. Pay attention to this value, you may need it to edit commands in this answer when Java 8 is upgraded to another version.
    • Extract the compressed file to the place where you want to install.

    cd /usr/lib/jvm
    sudo tar xzf ~/Downloads/jdk-8u251-linux-x64.tar.gz
    
    • Edit environment file

    sudo gedit /etc/environment
    
    • Edit the PATH's value by appending the string below to the current value

    :/usr/lib/jvm/jdk1.8.0_251/bin:/usr/lib/jvm/jdk1.8.0_251/jre/bin
    
    • Append those strings to the environment file

    J2SDKDIR="/usr/lib/jvm/jdk1.8.0_251"
    J2REDIR="/usr/lib/jvm/jdk1.8.0_251/jre"
    JAVA_HOME="/usr/lib/jvm/jdk1.8.0_251"
    
    • Complete the installation by running commands below

    sudo update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk1.8.0_251/bin/java" 0
    sudo update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk1.8.0_251/bin/javac" 0
    sudo update-alternatives --set java /usr/lib/jvm/jdk1.8.0_251/bin/java
    sudo update-alternatives --set javac /usr/lib/jvm/jdk1.8.0_251/bin/javac
    
    update-alternatives --list java
    update-alternatives --list javac
    

Registry key Error: Java version has value '1.8', but '1.7' is required

I didn't delete any of the java.exe files, but changed the ordering of my System - "path" variable - so that it reflected %JAVA_HOME%\bin as the first entry. That did the trick.

Shuffle DataFrame rows

You can simply use sklearn for this

from sklearn.utils import shuffle
df = shuffle(df)

Maven Installation OSX Error Unsupported major.minor version 51.0

Please rather try:

$JAVA_HOME/bin/java -version

Maven uses $JAVA_HOME for classpath resolution of JRE libs. To be sure to use a certain JDK, set it explicitly before compiling, for example:

export JAVA_HOME=/usr/java/jdk1.7.0_51

Isn't there a version < 1.7 and you're using Maven 3.3.1? In this case the reason is a new prerequisite: https://issues.apache.org/jira/browse/MNG-5780

Force hide address bar in Chrome on Android

Check this has everything you need

http://www.html5rocks.com/en/mobile/fullscreen/

The Chrome team has recently implemented a feature that tells the browser to launch the page fullscreen when the user has added it to the home screen. It is similar to the iOS Safari model.

<meta name="mobile-web-app-capable" content="yes">

Why is my Button text forced to ALL CAPS on Lollipop?

Set android:textAllCaps="false". If you are using an appcompat style, make sure textAllCaps comes before the style. Otherwise the style will override it. For example:

android:textAllCaps="false"
style="@style/Base.TextAppearance.AppCompat"

Multiple scenarios @RequestMapping produces JSON/XML together with Accept or ResponseEntity

All your problems are that you are mixing content type negotiation with parameter passing. They are things at different levels. More specific, for your question 2, you constructed the response header with the media type your want to return. The actual content negotiation is based on the accept media type in your request header, not response header. At the point the execution reaches the implementation of the method getPersonFormat, I am not sure whether the content negotiation has been done or not. Depends on the implementation. If not and you want to make the thing work, you can overwrite the request header accept type with what you want to return.

return new ResponseEntity<>(PersonFactory.createPerson(), httpHeaders, HttpStatus.OK);

How to convert entire dataframe to numeric while preserving decimals?

> df2 <- data.frame(sapply(df1, function(x) as.numeric(as.character(x))))
> df2
     a b
1 0.01 2
2 0.02 4
3 0.03 5
4 0.04 7
> sapply(df2, class)
        a         b 
"numeric" "numeric" 

Importing CommonCrypto in a Swift framework

For anyone using swift 4.2 with Xcode 10:

CommonCrypto module is now provided by the system, so you can directly import it like any other system framework.

import CommonCrypto

pandas dataframe columns scaling with sklearn

df = pd.DataFrame(scale.fit_transform(df.values), columns=df.columns, index=df.index)

This should work without depreciation warnings.

How to set JAVA_HOME in Linux for all users

I use the line:

export JAVA_HOME=$(readlink -f $(dirname $(readlink -f $(which java) ))/../)

to my ~/.profile so it uses the base of the default java directory at login time. This is for bash.

Error launching Eclipse 4.4 "Version 1.6.0_65 of the JVM is not suitable for this product."

Your -vm argument seems ok BUT it's position is wrong. According to this Eclipse Wiki entry :

The -vm option must occur before the -vmargs option, since everything after -vmargs is passed directly to the JVM.

So your -vm argument is not taken into account and it fails over to your default java installation, which is probably 1.6.0_65.

The type java.lang.CharSequence cannot be resolved in package declaration

"Java 8 support for Eclipse Kepler SR2", and the new "JavaSE-1.8" execution environment showed up automatically.

Download this one:- Eclipse kepler SR2

and then follow this link:- Eclipse_Java_8_Support_For_Kepler

Pandas read_csv low_memory and dtype options

The deprecated low_memory option

The low_memory option is not properly deprecated, but it should be, since it does not actually do anything differently[source]

The reason you get this low_memory warning is because guessing dtypes for each column is very memory demanding. Pandas tries to determine what dtype to set by analyzing the data in each column.

Dtype Guessing (very bad)

Pandas can only determine what dtype a column should have once the whole file is read. This means nothing can really be parsed before the whole file is read unless you risk having to change the dtype of that column when you read the last value.

Consider the example of one file which has a column called user_id. It contains 10 million rows where the user_id is always numbers. Since pandas cannot know it is only numbers, it will probably keep it as the original strings until it has read the whole file.

Specifying dtypes (should always be done)

adding

dtype={'user_id': int}

to the pd.read_csv() call will make pandas know when it starts reading the file, that this is only integers.

Also worth noting is that if the last line in the file would have "foobar" written in the user_id column, the loading would crash if the above dtype was specified.

Example of broken data that breaks when dtypes are defined

import pandas as pd
try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO


csvdata = """user_id,username
1,Alice
3,Bob
foobar,Caesar"""
sio = StringIO(csvdata)
pd.read_csv(sio, dtype={"user_id": int, "username": "string"})

ValueError: invalid literal for long() with base 10: 'foobar'

dtypes are typically a numpy thing, read more about them here: http://docs.scipy.org/doc/numpy/reference/generated/numpy.dtype.html

What dtypes exists?

We have access to numpy dtypes: float, int, bool, timedelta64[ns] and datetime64[ns]. Note that the numpy date/time dtypes are not time zone aware.

Pandas extends this set of dtypes with its own:

'datetime64[ns, ]' Which is a time zone aware timestamp.

'category' which is essentially an enum (strings represented by integer keys to save

'period[]' Not to be confused with a timedelta, these objects are actually anchored to specific time periods

'Sparse', 'Sparse[int]', 'Sparse[float]' is for sparse data or 'Data that has a lot of holes in it' Instead of saving the NaN or None in the dataframe it omits the objects, saving space.

'Interval' is a topic of its own but its main use is for indexing. See more here

'Int8', 'Int16', 'Int32', 'Int64', 'UInt8', 'UInt16', 'UInt32', 'UInt64' are all pandas specific integers that are nullable, unlike the numpy variant.

'string' is a specific dtype for working with string data and gives access to the .str attribute on the series.

'boolean' is like the numpy 'bool' but it also supports missing data.

Read the complete reference here:

Pandas dtype reference

Gotchas, caveats, notes

Setting dtype=object will silence the above warning, but will not make it more memory efficient, only process efficient if anything.

Setting dtype=unicode will not do anything, since to numpy, a unicode is represented as object.

Usage of converters

@sparrow correctly points out the usage of converters to avoid pandas blowing up when encountering 'foobar' in a column specified as int. I would like to add that converters are really heavy and inefficient to use in pandas and should be used as a last resort. This is because the read_csv process is a single process.

CSV files can be processed line by line and thus can be processed by multiple converters in parallel more efficiently by simply cutting the file into segments and running multiple processes, something that pandas does not support. But this is a different story.

WebService Client Generation Error with JDK8

If you are using ant you can add a jvmarg to your java calls:

<jvmarg value="-Djavax.xml.accessExternalSchema=all" />

What's the location of the JavaFX runtime JAR file, jfxrt.jar, on Linux?

The location of jfxrt.jar in JDK 1.8 (Windows) is:

C:\Program Files\Java\jdk1.8.0_05\jre\lib\ext\jfxrt.jar

Gradle finds wrong JAVA_HOME even though it's correctly set

For me an explicit set on the arguments section of the external tools configuration in Eclipse was the problem.

enter image description here

Internet Explorer 11- issue with security certificate error prompt

This behavior is related to Zone that is set - Internet/Intranet/etc and corresponding Security Level

You can change this by setting less secure Security Level (not recommended) or by customizing Display Mixed Content property

You can do that by following steps:

  1. Click on Gear icon at the top of the browser window.
  2. Select Internet Options.
  3. Select the Security tab at the top.
  4. Click the Custom Level... button.
  5. Scroll about halfway down to the Miscellaneous heading (denoted by a "blank page" icon).
  6. Under this heading is the option Display Mixed Content; set this to Enable/Prompt.
  7. Click OK, then Yes when prompted to confirm the change, then OK to close the Options window.
  8. Close and restart the browser.

enter image description here

c++ "Incomplete type not allowed" error accessing class reference information (Circular dependency with forward declaration)

Player.cpp require the definition of Ball class. So simply add #include "Ball.h"

Player.cpp:

#include "Player.h"
#include "Ball.h"

void Player::doSomething(Ball& ball) {
    ball.ballPosX += 10;                   // incomplete type error occurs here.
}

Jquery Ajax beforeSend and success,error & complete

Maybe you can try the following :

var i = 0;
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
$.ajax({
    type: 'POST',
    url: url,
    data: data,
    beforeSend: function() {
        // setting a timeout
        $(placeholder).addClass('loading');
        i++;
    },
    success: function(data) {
        if (append) {
            $(placeholder).append(data);
        } else {
            $(placeholder).html(data);
        }
    },
    error: function(xhr) { // if error occured
        alert("Error occured.please try again");
        $(placeholder).append(xhr.statusText + xhr.responseText);
        $(placeholder).removeClass('loading');
    },
    complete: function() {
        i--;
        if (i <= 0) {
            $(placeholder).removeClass('loading');
        }
    },
    dataType: 'html'
});
}

This way, if the beforeSend statement is called before the complete statement i will be greater than 0 so it will not remove the class. Then only the last call will be able to remove it.

I cannot test it, let me know if it works or not.

Difference between CLOB and BLOB from DB2 and Oracle Perspective?

They can be considered as equivalent. The limits in size are the same:

  • Maximum length of CLOB (in bytes or OCTETS)) 2 147 483 647
  • Maximum length of BLOB (in bytes) 2 147 483 647

There is also the DBCLOBs, for double byte characters.

References:

Spring MVC Multipart Request with JSON

This must work!

client (angular):

$scope.saveForm = function () {
      var formData = new FormData();
      var file = $scope.myFile;
      var json = $scope.myJson;
      formData.append("file", file);
      formData.append("ad",JSON.stringify(json));//important: convert to JSON!
      var req = {
        url: '/upload',
        method: 'POST',
        headers: {'Content-Type': undefined},
        data: formData,
        transformRequest: function (data, headersGetterFunction) {
          return data;
        }
      };

Backend-Spring Boot:

@RequestMapping(value = "/upload", method = RequestMethod.POST)
    public @ResponseBody
    Advertisement storeAd(@RequestPart("ad") String adString, @RequestPart("file") MultipartFile file) throws IOException {

        Advertisement jsonAd = new ObjectMapper().readValue(adString, Advertisement.class);
//do whatever you want with your file and jsonAd

"application blocked by security settings" prevent applets running using oracle SE 7 update 51 on firefox on Linux mint

The application that you are running is blocked because the application does not comply with security guidelines implemented in Java 7 Update 51

Installing Android Studio, does not point to a valid JVM installation error

Don't include bin folder while coping the path for Java_home.

NoSuchMethodError in javax.persistence.Table.indexes()[Ljavax/persistence/Index

I've ran into the same problem. The question here is that play-java-jpa artifact (javaJpa key in the build.sbt file) depends on a different version of the spec (version 2.0 -> "org.hibernate.javax.persistence" % "hibernate-jpa-2.0-api" % "1.0.1.Final").

When you added hibernate-entitymanager 4.3 this brought the newer spec (2.1) and a different factory provider for the entitymanager. Basically you ended up having both jars in the classpath as transitive dependencies.

Edit your build.sbt file like this and it will temporarily fix you problem until play releases a new version of the jpa plugin for the newer api dependency.

libraryDependencies ++= Seq(
javaJdbc,
javaJpa.exclude("org.hibernate.javax.persistence", "hibernate-jpa-2.0-api"),
"org.hibernate" % "hibernate-entitymanager" % "4.3.0.Final"
)

This is for play 2.2.x. In previous versions there were some differences in the build files.

SQLSTATE[42S22]: Column not found: 1054 Unknown column - Laravel

Try to change where Member class

public function users() {
    return $this->hasOne('User');
} 

return $this->belongsTo('User');

Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine

This might also occur if you are running on 64-bit Machine with 32-bit JVM (JDK), switch it to 64-bit JVM. Check your (Right Click on My Computer --> Properties) Control Panel\System and Security\System --> Advanced System Settings -->Advanced Tab--> Environment Variables --> JAVA_HOME...

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

Applying a CORS restriction is a security feature defined by a server and implemented by a browser.

The browser looks at the CORS policy of the server and respects it.

However, the Postman tool does not bother about the CORS policy of the server.

That is why the CORS error appears in the browser, but not in Postman.

invalid target release: 1.7

Other than setting JAVA_HOME environment variable, you got to make sure you are using the correct JDK in your Maven run configuration. Go to Run -> Run Configuration, select your Maven Build configuration, go to JRE tab and set the correct Runtime JRE.

Maven run configuration

JDBC ODBC Driver Connection

As mentioned in the comments to the question, the JDBC-ODBC Bridge is - as the name indicates - only a mechanism for the JDBC layer to "talk to" the ODBC layer. Even if you had a JDBC-ODBC Bridge on your Mac you would also need to have

  • an implementation of ODBC itself, and
  • an appropriate ODBC driver for the target database (ACE/Jet, a.k.a. "Access")

So, for most people, using JDBC-ODBC Bridge technology to manipulate ACE/Jet ("Access") databases is really a practical option only under Windows. It is also important to note that the JDBC-ODBC Bridge will be has been removed in Java 8 (ref: here).

There are other ways of manipulating ACE/Jet databases from Java, such as UCanAccess and Jackcess. Both of these are pure Java implementations so they work on non-Windows platforms. For details on how to use UCanAccess see

Manipulating an Access database from Java without ODBC

How to define object in array in Mongoose schema correctly with 2d geo index

Thanks for the replies.

I tried the first approach, but nothing changed. Then, I tried to log the results. I just drilled down level by level, until I finally got to where the data was being displayed.

After a while I found the problem: When I was sending the response, I was converting it to a string via .toString().

I fixed that and now it works brilliantly. Sorry for the false alarm.

Why Maven uses JDK 1.6 but my java -version is 1.7

Get into

/System/Library/Frameworks/JavaVM.framework/Versions

and update the CurrentJDK symbolic link to point to

/Library/Java/JavaVirtualMachines/YOUR_JDK_VERSION/Contents/

E.g.

cd /System/Library/Frameworks/JavaVM.framework/Versions
sudo rm CurrentJDK
sudo ln -s /Library/Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/ CurrentJDK

Now it shall work immediately.

How to get Chrome to allow mixed content?

You could use cors anywhere for testing purposes. But its note recommend for production environments.

https://cors-anywhere.herokuapp.com/

something like: https://cors-anywhere.herokuapp.com/http://yourdomain.com/api

Why am I suddenly getting a "Blocked loading mixed active content" issue in Firefox?

Its given the error because of security. for this please use "https" not "http" in the website url.

For example :

   "https://code.jquery.com/ui/1.8.10/themes/smoothness/jquery-ui.css"
   "https://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/jquery-ui.min.js"

Converting a column within pandas dataframe from int to string

Just for an additional reference.

All of the above answers will work in case of a data frame. But if you are using lambda while creating / modify a column this won't work, Because there it is considered as a int attribute instead of pandas series. You have to use str( target_attribute ) to make it as a string. Please refer the below example.

def add_zero_in_prefix(df):
    if(df['Hour']<10):
        return '0' + str(df['Hour'])

data['str_hr'] = data.apply(add_zero_in_prefix, axis=1)

Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything

Here's the code that works for me everytime (for Outlook emails):

#to read Subjects and Body of email in a folder (or subfolder)

import win32com.client  
#import package

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")  
#create object

#get to the desired folder ([email protected] is my root folder)

root_folder = 
outlook.Folders['[email protected]'].Folders['Inbox'].Folders['SubFolderName']

#('Inbox' and 'SubFolderName' are the subfolders)

messages = root_folder.Items

for message in messages:
if message.Unread == True:    # gets only 'Unread' emails
    subject_content = message.subject
# to store subject lines of mails

    body_content = message.body
# to store Body of mails

    print(subject_content)
    print(body_content)

    message.Unread = True         # mark the mail as 'Read'
    message = messages.GetNext()  #iterate over mails

Using the grep and cut delimiter command (in bash shell scripting UNIX) - and kind of "reversing" it?

You don't need to change the delimiter to display the right part of the string with cut.

The -f switch of the cut command is the n-TH element separated by your delimiter : :, so you can just type :

 grep puddle2_1557936 | cut -d ":" -f2

Another solutions (adapt it a bit) if you want fun :

Using :

grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                        
/home/rogers.williams/folderz/puddle2

or still with look around

grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                    
/home/rogers.williams/folderz/puddle2

or with :

perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                      
/home/rogers.williams/folderz/puddle2

or using (thanks to glenn jackman)

ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

awk -F'puddle2_1557936:' '{print $2}'  <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or using only :

IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2

or using in a :

js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2

or using in a :

php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2' 
/home/rogers.williams/folderz/puddle2

Where is the Java SDK folder in my computer? Ubuntu 12.04

For me, on Ubuntu, the various versions of JDK were in /usr/lib/jvm.

Decoding JSON String in Java

Instead of downloading separate java files as suggested by Veer, you could just add this JAR file to your package.

To add the jar file to your project in Eclipse, do the following:

  1. Right click on your project, click Build Path > Configure Build Path
  2. Goto Libraries tab > Add External JARs
  3. Locate the JAR file and add

Convert from lowercase to uppercase all values in all character variables in dataframe

It simple with apply function in R

f <- apply(f,2,toupper)

No need to check if the column is character or any other type.

Installing Java 7 on Ubuntu

This answer used to describe how to install Oracle Java 7. This no longer works since Oracle end-of-lifed Java 7 and put the binary downloads for versions with security patches behind a paywall. Also, OpenJDK has grown up and is a more viable alternative nowadays.

In Ubuntu 16.04 and higher, Java 7 is no longer available. Usually you're best off installing Java 8 (or 9) instead.

sudo apt-get install openjdk-8-jre

or, f you also want the compiler, get the jdk:

sudo apt-get install openjdk-8-jdk

In Trusty, the easiest way to install Java 7 currently is to install OpenJDK package:

sudo apt-get install openjdk-7-jre

or, for the jdk:

sudo apt-get install openjdk-7-jdk

If you are specifically looking for Java 7 on a version of Ubuntu that no longer supports it, see https://askubuntu.com/questions/761127/how-do-i-install-openjdk-7-on-ubuntu-16-04-or-higher .

Use SQL Server Management Studio to connect remotely to an SQL Server Express instance hosted on an Azure Virtual Machine

The fact that you're getting an error from the Names Pipes Provider tells us that you're not using the TCP/IP protocol when you're trying to establish the connection. Try adding the "tcp" prefix and specifying the port number:

tcp:name.cloudapp.net,1433

How to install JRE 1.7 on Mac OS X and use it with Eclipse?

The download from java.com which installs in /Library/Internet Plug-Ins is only the JRE, for development you probably want to download the JDK from http://www.oracle.com/technetwork/java/javase/downloads/index.html and install that instead. This will install the JDK at /Library/Java/JavaVirtualMachines/jdk1.7.0_<something>.jdk/Contents/Home which you can then add to Eclipse via Preferences -> Java -> Installed JREs.

"Large data" workflows using pandas

It is worth mentioning here Ray as well,
it's a distributed computation framework, that has it's own implementation for pandas in a distributed way.

Just replace the pandas import, and the code should work as is:

# import pandas as pd
import ray.dataframe as pd

#use pd as usual

can read more details here:

https://rise.cs.berkeley.edu/blog/pandas-on-ray/

Using SSIS BIDS with Visual Studio 2012 / 2013

Welcome to Microsoft Marketing Speak hell. With the 2012 release of SQL Server, the BIDS, Business Intelligence Designer Studio, plugin for Visual Studio was renamed to SSDT, SQL Server Data Tools. SSDT is available for 2010 and 2012. The problem is, there are two different products called SSDT.

There is SSDT which replaces the database designer thing which was called Data Dude in VS 2008 and in 2010 became database projects. That a free install and if you snag the web installer, that's what you get when you install SSDT. It puts the correct project templates and such into Visual Studio.

There's also the SSDT which is the "BIDS" replacement for developing SSIS, SSRS and SSAS stuff. As of March 2013, it is now available for the 2012 release of Visual Studio. The download is labeled SSDTBI_VS2012_X86.msi Perhaps that's a signal on how the product is going to be referred to in marketing materials. Download links are

None the less, we have Business Intelligence projects available to us in Visual Studio 2012. And the people did rejoice and did feast upon the lambs and toads and tree-sloths and fruit-bats and orangutans and breakfast cereals

enter image description here

Compiling Java 7 code via Maven

right click on ur project in eclipse and open "Run Configurations"..check the jre version there. some times this will not change by default in eclipse,after even changing the version in the buildpath.

How to change maven java home

Even if you install the Oracle JDK, your $JAVA_HOME variable should refer to the path of the JRE that is inside the JDK root. You can refer to my other answer to a similar question for more details.

ISO C90 forbids mixed declarations and code in C

Make sure the variable is on the top part of the block, and in case you compile it with -ansi-pedantic, make sure it looks like this:

function() {
    int i;
    i = 0;

    someCode();
}

Installed Java 7 on Mac OS X but Terminal is still using version 6

I resolved this issue with sudo rm /usr/bin/java

And I downloaded and installed the last Java SE Runtime Environment: http://www.oracle.com/technetwork/java/javase/downloads/index.html

sudo ln -s /Library/Java/JavaVirtualMachines/jdk1.8.0_31.jdk/Contents/Home/jre/bin/java /usr/bin/java did not work for me because I got Operation not permitted. El Capitan now protects certain system directories in "rootless" mode (a.k.a. System Integrity Protection). It is applicable to macOS Sierra, and probably new macOS versions for the foreseeable future.

Bulk Insertion in Laravel using eloquent ORM

We can update GTF answer to update timestamps easily

$data = array(
    array(
        'name'=>'Coder 1', 'rep'=>'4096',
        'created_at'=>date('Y-m-d H:i:s'),
        'modified_at'=> date('Y-m-d H:i:s')
       ),
    array(
         'name'=>'Coder 2', 'rep'=>'2048',
         'created_at'=>date('Y-m-d H:i:s'),
         'modified_at'=> date('Y-m-d H:i:s')
       ),
    //...
);

Coder::insert($data);

Update: to simplify the date we can use carbon as @Pedro Moreira suggested

$now = Carbon::now('utc')->toDateTimeString();
$data = array(
    array(
        'name'=>'Coder 1', 'rep'=>'4096',
        'created_at'=> $now,
        'modified_at'=> $now
       ),
    array(
         'name'=>'Coder 2', 'rep'=>'2048',
         'created_at'=> $now,
         'modified_at'=> $now
       ),
    //...
);

Coder::insert($data);

UPDATE2: for laravel 5 , use updated_at instead of modified_at

$now = Carbon::now('utc')->toDateTimeString();
$data = array(
    array(
        'name'=>'Coder 1', 'rep'=>'4096',
        'created_at'=> $now,
        'updated_at'=> $now
       ),
    array(
         'name'=>'Coder 2', 'rep'=>'2048',
         'created_at'=> $now,
         'updated_at'=> $now
       ),
    //...
);

Coder::insert($data);

SQL query return data from multiple tables

Ok, I found this post very interesting and I would like to share some of my knowledge on creating a query. Thanks for this Fluffeh. Others who may read this and may feel that I'm wrong are 101% free to edit and criticise my answer. (Honestly, I feel very thankful for correcting my mistake(s).)

I'll be posting some of the frequently asked questions in MySQL tag.


Trick No. 1 (rows that matches to multiple conditions)

Given this schema

CREATE TABLE MovieList
(
    ID INT,
    MovieName VARCHAR(25),
    CONSTRAINT ml_pk PRIMARY KEY (ID),
    CONSTRAINT ml_uq UNIQUE (MovieName)
);

INSERT INTO MovieList VALUES (1, 'American Pie');
INSERT INTO MovieList VALUES (2, 'The Notebook');
INSERT INTO MovieList VALUES (3, 'Discovery Channel: Africa');
INSERT INTO MovieList VALUES (4, 'Mr. Bean');
INSERT INTO MovieList VALUES (5, 'Expendables 2');

CREATE TABLE CategoryList
(
    MovieID INT,
    CategoryName VARCHAR(25),
    CONSTRAINT cl_uq UNIQUE(MovieID, CategoryName),
    CONSTRAINT cl_fk FOREIGN KEY (MovieID) REFERENCES MovieList(ID)
);

INSERT INTO CategoryList VALUES (1, 'Comedy');
INSERT INTO CategoryList VALUES (1, 'Romance');
INSERT INTO CategoryList VALUES (2, 'Romance');
INSERT INTO CategoryList VALUES (2, 'Drama');
INSERT INTO CategoryList VALUES (3, 'Documentary');
INSERT INTO CategoryList VALUES (4, 'Comedy');
INSERT INTO CategoryList VALUES (5, 'Comedy');
INSERT INTO CategoryList VALUES (5, 'Action');

QUESTION

Find all movies that belong to at least both Comedy and Romance categories.

Solution

This question can be very tricky sometimes. It may seem that a query like this will be the answer:-

SELECT  DISTINCT a.MovieName
FROM    MovieList a
        INNER JOIN CategoryList b
            ON a.ID = b.MovieID
WHERE   b.CategoryName = 'Comedy' AND
        b.CategoryName = 'Romance'

SQLFiddle Demo

which is definitely very wrong because it produces no result. The explanation of this is that there is only one valid value of CategoryName on each row. For instance, the first condition returns true, the second condition is always false. Thus, by using AND operator, both condition should be true; otherwise, it will be false. Another query is like this,

SELECT  DISTINCT a.MovieName
FROM    MovieList a
        INNER JOIN CategoryList b
            ON a.ID = b.MovieID
WHERE   b.CategoryName IN ('Comedy','Romance')

SQLFiddle Demo

and the result is still incorrect because it matches to record that has at least one match on the categoryName. The real solution would be by counting the number of record instances per movie. The number of instance should match to the total number of the values supplied in the condition.

SELECT  a.MovieName
FROM    MovieList a
        INNER JOIN CategoryList b
            ON a.ID = b.MovieID
WHERE   b.CategoryName IN ('Comedy','Romance')
GROUP BY a.MovieName
HAVING COUNT(*) = 2

SQLFiddle Demo (the answer)


Trick No. 2 (maximum record for each entry)

Given schema,

CREATE TABLE Software
(
    ID INT,
    SoftwareName VARCHAR(25),
    Descriptions VARCHAR(150),
    CONSTRAINT sw_pk PRIMARY KEY (ID),
    CONSTRAINT sw_uq UNIQUE (SoftwareName)  
);

INSERT INTO Software VALUES (1,'PaintMe','used for photo editing');
INSERT INTO Software VALUES (2,'World Map','contains map of different places of the world');
INSERT INTO Software VALUES (3,'Dictionary','contains description, synonym, antonym of the words');

CREATE TABLE VersionList
(
    SoftwareID INT,
    VersionNo INT,
    DateReleased DATE,
    CONSTRAINT sw_uq UNIQUE (SoftwareID, VersionNo),
    CONSTRAINT sw_fk FOREIGN KEY (SOftwareID) REFERENCES Software(ID)
);

INSERT INTO VersionList VALUES (3, 2, '2009-12-01');
INSERT INTO VersionList VALUES (3, 1, '2009-11-01');
INSERT INTO VersionList VALUES (3, 3, '2010-01-01');
INSERT INTO VersionList VALUES (2, 2, '2010-12-01');
INSERT INTO VersionList VALUES (2, 1, '2009-12-01');
INSERT INTO VersionList VALUES (1, 3, '2011-12-01');
INSERT INTO VersionList VALUES (1, 2, '2010-12-01');
INSERT INTO VersionList VALUES (1, 1, '2009-12-01');
INSERT INTO VersionList VALUES (1, 4, '2012-12-01');

QUESTION

Find the latest version on each software. Display the following columns: SoftwareName,Descriptions,LatestVersion (from VersionNo column),DateReleased

Solution

Some SQL developers mistakenly use MAX() aggregate function. They tend to create like this,

SELECT  a.SoftwareName, a.Descriptions,
        MAX(b.VersionNo) AS LatestVersion, b.DateReleased
FROM    Software a
        INNER JOIN VersionList b
            ON a.ID = b.SoftwareID
GROUP BY a.ID
ORDER BY a.ID

SQLFiddle Demo

(most RDBMS generates a syntax error on this because of not specifying some of the non-aggregated columns on the group by clause) the result produces the correct LatestVersion on each software but obviously the DateReleased are incorrect. MySQL doesn't support Window Functions and Common Table Expression yet as some RDBMS do already. The workaround on this problem is to create a subquery which gets the individual maximum versionNo on each software and later on be joined on the other tables.

SELECT  a.SoftwareName, a.Descriptions,
        b.LatestVersion, c.DateReleased
FROM    Software a
        INNER JOIN
        (
            SELECT  SoftwareID, MAX(VersionNO) LatestVersion
            FROM    VersionList
            GROUP BY SoftwareID
        ) b ON a.ID = b.SoftwareID
        INNER JOIN VersionList c
            ON  c.SoftwareID = b.SoftwareID AND
                c.VersionNO = b.LatestVersion
GROUP BY a.ID
ORDER BY a.ID

SQLFiddle Demo (the answer)


So that was it. I'll be posting another soon as I recall any other FAQ on MySQL tag. Thank you for reading this little article. I hope that you have atleast get even a little knowledge from this.

UPDATE 1


Trick No. 3 (Finding the latest record between two IDs)

Given Schema

CREATE TABLE userList
(
    ID INT,
    NAME VARCHAR(20),
    CONSTRAINT us_pk PRIMARY KEY (ID),
    CONSTRAINT us_uq UNIQUE (NAME)  
);

INSERT INTO userList VALUES (1, 'Fluffeh');
INSERT INTO userList VALUES (2, 'John Woo');
INSERT INTO userList VALUES (3, 'hims056');

CREATE TABLE CONVERSATION
(
    ID INT,
    FROM_ID INT,
    TO_ID INT,
    MESSAGE VARCHAR(250),
    DeliveryDate DATE
);

INSERT INTO CONVERSATION VALUES (1, 1, 2, 'hi john', '2012-01-01');
INSERT INTO CONVERSATION VALUES (2, 2, 1, 'hello fluff', '2012-01-02');
INSERT INTO CONVERSATION VALUES (3, 1, 3, 'hey hims', '2012-01-03');
INSERT INTO CONVERSATION VALUES (4, 1, 3, 'please reply', '2012-01-04');
INSERT INTO CONVERSATION VALUES (5, 3, 1, 'how are you?', '2012-01-05');
INSERT INTO CONVERSATION VALUES (6, 3, 2, 'sample message!', '2012-01-05');

QUESTION

Find the latest conversation between two users.

Solution

SELECT    b.Name SenderName,
          c.Name RecipientName,
          a.Message,
          a.DeliveryDate
FROM      Conversation a
          INNER JOIN userList b
            ON a.From_ID = b.ID
          INNER JOIN userList c
            ON a.To_ID = c.ID
WHERE     (LEAST(a.FROM_ID, a.TO_ID), GREATEST(a.FROM_ID, a.TO_ID), DeliveryDate)
IN
(
    SELECT  LEAST(FROM_ID, TO_ID) minFROM,
            GREATEST(FROM_ID, TO_ID) maxTo,
            MAX(DeliveryDate) maxDate
    FROM    Conversation
    GROUP BY minFROM, maxTo
)

SQLFiddle Demo

The module was expected to contain an assembly manifest

I found that, I am using a different InstallUtil from my target .NET Framework. I am building a .NET Framework 4.5, meanwhile the error occured if I am using the .NET Framework 2.0 release. Having use the right InstallUtil for my target .NET Framework, solved this problem!

java.lang.UnsupportedClassVersionError Unsupported major.minor version 51.0

Make sure you're using the correct SDK when compiling/running and also, make sure you use source/target 1.7.

Maven error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

I had this problem when I used Maven 3.5.4 on OpenJDK 11 on Ubuntu. The OpenJDK 11 on Ubuntu is actually still a JDK10:

$ ls -al /etc/alternatives/java
lrwxrwxrwx 1 root root 43 Aug 24 04:54 /etc/alternatives/java -> /usr/lib/jvm/java-11-openjdk-amd64/bin/java
$ java --version
openjdk 10.0.2 2018-07-17
OpenJDK Runtime Environment (build 10.0.2+13-Ubuntu-1ubuntu0.18.04.3)
OpenJDK 64-Bit Server VM (build 10.0.2+13-Ubuntu-1ubuntu0.18.04.3, mixed mode)

I installed OpenJDK from Oracle into /opt/jdk-11.0.1 and run Maven like this:

JAVA_HOME=/opt/jdk-11.0.1 mvn

It now works like a charm.

org.xml.sax.SAXParseException: Premature end of file for *VALID* XML

Please make sure that you are not consuming your inputstream anywhere before parsing. Sample code is following: the respose below is httpresponse(i.e. response) and main content is contain inside StringEntity (i.e. getEntity())in form of inputStream(i.e. getContent()).

InputStream rescontent = response.getEntity().getContent();
tsResponse=(TsResponse) transformer.convertFromXMLToObject(rescontent );

How to specify 64 bit integers in c

How to specify 64 bit integers in c

Going against the usual good idea to appending LL.

Appending LL to a integer constant will insure the type is at least as wide as long long. If the integer constant is octal or hex, the constant will become unsigned long long if needed.

If ones does not care to specify too wide a type, then LL is OK. else, read on.

long long may be wider than 64-bit.

Today, it is rare that long long is not 64-bit, yet C specifies long long to be at least 64-bit. So by using LL, in the future, code may be specifying, say, a 128-bit number.

C has Macros for integer constants which in the below case will be type int_least64_t

#include <stdint.h>
#include <inttypes.h>

int main(void) {
  int64_t big = INT64_C(9223372036854775807);
  printf("%" PRId64 "\n", big);
  uint64_t jenny = INT64_C(0x08675309) << 32;  // shift was done on at least 64-bit type 
  printf("0x%" PRIX64 "\n", jenny);
}

output

9223372036854775807
0x867530900000000

Bootstrap: 'TypeError undefined is not a function'/'has no method 'tab'' when using bootstrap-tabs

This can also be caused if you include bootstrap.js before jquery.js.

Others might have the same problem I did.

Include jQuery before bootstrap.

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I tested below code with SQL Server 2008 R2 Express and I believe we should have solution for all 6 steps you outlined. Let's take on them one-by-one:

1 - Enable TCP/IP

We can enable TCP/IP protocol with WMI:

set wmiComputer = GetObject( _
    "winmgmts:" _
    & "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProtocols = wmiComputer.ExecQuery( _
    "select * from ServerNetworkProtocol " _
    & "where InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'")

if tcpProtocols.Count = 1 then
    ' set tcpProtocol = tcpProtocols(0)
    ' I wish this worked, but unfortunately 
    ' there's no int-indexed Item property in this type

    ' Doing this instead
    for each tcpProtocol in tcpProtocols
        dim setEnableResult
            setEnableResult = tcpProtocol.SetEnable()
            if setEnableResult <> 0 then 
                Wscript.Echo "Failed!"
            end if
    next
end if

2 - Open the right ports in the firewall

I believe your solution will work, just make sure you specify the right port. I suggest we pick a different port than 1433 and make it a static port SQL Server Express will be listening on. I will be using 3456 in this post, but please pick a different number in the real implementation (I feel that we will see a lot of applications using 3456 soon :-)

3 - Modify TCP/IP properties enable a IP address

We can use WMI again. Since we are using static port 3456, we just need to update two properties in IPAll section: disable dynamic ports and set the listening port to 3456:

set wmiComputer = GetObject( _
    "winmgmts:" _
    & "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProperties = wmiComputer.ExecQuery( _
    "select * from ServerNetworkProtocolProperty " _
    & "where InstanceName='SQLEXPRESS' and " _
    & "ProtocolName='Tcp' and IPAddressName='IPAll'")

for each tcpProperty in tcpProperties
    dim setValueResult, requestedValue

    if tcpProperty.PropertyName = "TcpPort" then
        requestedValue = "3456"
    elseif tcpProperty.PropertyName ="TcpDynamicPorts" then
        requestedValue = ""
    end if

    setValueResult = tcpProperty.SetStringValue(requestedValue)
    if setValueResult = 0 then 
        Wscript.Echo "" & tcpProperty.PropertyName & " set."
    else
        Wscript.Echo "" & tcpProperty.PropertyName & " failed!"
    end if
next

Note that I didn't have to enable any of the individual addresses to make it work, but if it is required in your case, you should be able to extend this script easily to do so.

Just a reminder that when working with WMI, WBEMTest.exe is your best friend!

4 - Enable mixed mode authentication in sql server

I wish we could use WMI again, but unfortunately this setting is not exposed through WMI. There are two other options:

  1. Use LoginMode property of Microsoft.SqlServer.Management.Smo.Server class, as described here.

  2. Use LoginMode value in SQL Server registry, as described in this post. Note that by default the SQL Server Express instance is named SQLEXPRESS, so for my SQL Server 2008 R2 Express instance the right registry key was HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQLServer.

5 - Change user (sa) default password

You got this one covered.

6 - Finally (connect to the instance)

Since we are using a static port assigned to our SQL Server Express instance, there's no need to use instance name in the server address anymore.

SQLCMD -U sa -P newPassword -S 192.168.0.120,3456

Please let me know if this works for you (fingers crossed!).

Creating virtual directories in IIS express

I had to make the entry in the [project].vs\config\applicationhost.config file.

Prior to this, it worked from deployment but not from code.

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

That method was added in Servlet 2.5.

So this problem can have at least 3 causes:

  1. The servlet container does not support Servlet 2.5.
  2. The web.xml is not declared conform Servlet 2.5 or newer.
  3. The webapp's runtime classpath is littered with servlet container specific JAR files of a different servlet container make/version which does not support Servlet 2.5.

To solve it,

  1. Make sure that your servlet container supports at least Servlet 2.5. That are at least Tomcat 6, Glassfish 2, JBoss AS 4.1, etcetera. Tomcat 5.5 for example supports at highest Servlet 2.4. If you can't upgrade Tomcat, then you'd need to downgrade Spring to a Servlet 2.4 compatible version.
  2. Make sure that the root declaration of web.xml complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.
  3. Make sure that you don't have any servlet container specific libraries like servlet-api.jar or j2ee.jar in /WEB-INF/lib or even worse, the JRE/lib or JRE/lib/ext. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.

How to get the current directory of the cmdlet being executed

To expand on @Cradle 's answer: you could also write a multi-purpose function that will get you the same result per the OP's question:

Function Get-AbsolutePath {

    [CmdletBinding()]
    Param(
        [parameter(
            Mandatory=$false,
            ValueFromPipeline=$true
        )]
        [String]$relativePath=".\"
    )

    if (Test-Path -Path $relativePath) {
        return (Get-Item -Path $relativePath).FullName -replace "\\$", ""
    } else {
        Write-Error -Message "'$relativePath' is not a valid path" -ErrorId 1 -ErrorAction Stop
    }

}

Check if string is upper, lower, or mixed case in Python

I want to give a shoutout for using re module for this. Specially in the case of case sensitivity.

We use the option re.IGNORECASE while compiling the regex for use of in production environments with large amounts of data.

>>> import re
>>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER']
>>>
>>>
>>> pattern = re.compile('is')
>>>
>>> [word for word in m if pattern.match(word)]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

However try to always use the in operator for string comparison as detailed in this post

faster-operation-re-match-or-str

Also detailed in the one of the best books to start learning python with

idiomatic-python

How to fetch Java version using single line command in Linux

Since (at least on my linux system) the version string looks like "1.8.0_45":

 #!/bin/bash
 function checkJavaVers {
    for token in $(java -version 2>&1)
    do
        if [[ $token =~ \"([[:digit:]])\.([[:digit:]])\.(.*)\" ]]
        then
            export JAVA_MAJOR=${BASH_REMATCH[1]}
            export JAVA_MINOR=${BASH_REMATCH[2]}
            export JAVA_BUILD=${BASH_REMATCH[3]}
            return 0
        fi
    done
    return 1
}

#test
checkJavaVers || { echo "check failed" ; exit; }
echo "$JAVA_MAJOR $JAVA_MINOR $JAVA_BUILD"
~

Finding import static statements for Mockito constructs

Here's what I've been doing to cope with the situation.

I use global imports on a new test class.

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*;

When you are finished writing your test and need to commit, you just CTRL+SHIFT+O to organize the packages. For example, you may just be left with:

import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.anyString;

This allows you to code away without getting 'stuck' trying to find the correct package to import.

Styling Password Fields in CSS

When I needed to create similar dots in input[password] I use a custom font in base64 (with 2 glyphs see above 25CF and 2022)

SCSS styles

@font-face {
  font-family: 'pass';
  font-style: normal;
  font-weight: 400;
  src: url(data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAAATsAA8AAAAAB2QAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABGRlRNAAABWAAAABwAAAAcg9+z70dERUYAAAF0AAAAHAAAAB4AJwANT1MvMgAAAZAAAAA/AAAAYH7AkBhjbWFwAAAB0AAAAFkAAAFqZowMx2N2dCAAAAIsAAAABAAAAAQAIgKIZ2FzcAAAAjAAAAAIAAAACAAAABBnbHlmAAACOAAAALkAAAE0MwNYJ2hlYWQAAAL0AAAAMAAAADYPA2KgaGhlYQAAAyQAAAAeAAAAJAU+ATJobXR4AAADRAAAABwAAAAcCPoA6mxvY2EAAANgAAAAEAAAABAA5gFMbWF4cAAAA3AAAAAaAAAAIAAKAE9uYW1lAAADjAAAARYAAAIgB4hZ03Bvc3QAAASkAAAAPgAAAE5Ojr8ld2ViZgAABOQAAAAGAAAABuK7WtIAAAABAAAAANXulPUAAAAA1viLwQAAAADW+JM4eNpjYGRgYOABYjEgZmJgBEI2IGYB8xgAA+AANXjaY2BifMg4gYGVgYVBAwOeYEAFjMgcp8yiFAYHBl7VP8wx/94wpDDHMIoo2DP8B8kx2TLHACkFBkYA8/IL3QB42mNgYGBmgGAZBkYGEEgB8hjBfBYGDyDNx8DBwMTABmTxMigoKKmeV/3z/z9YJTKf8f/X/4/vP7pldosLag4SYATqhgkyMgEJJnQFECcMOGChndEAfOwRuAAAAAAiAogAAQAB//8AD3jaY2BiUGJgYDRiWsXAzMDOoLeRkUHfZhM7C8Nbo41srHdsNjEzAZkMG5lBwqwg4U3sbIx/bDYxgsSNBRUF1Y0FlZUYBd6dOcO06m+YElMa0DiGJIZUxjuM9xjkGRhU2djZlJXU1UDQ1MTcDASNjcTFQFBUBGjYEkkVMJCU4gcCKRTeHCk+fn4+KSllsJiUJEhMUgrMUQbZk8bgz/iA8SRR9qzAY087FjEYD2QPDDAzMFgyAwC39TCRAAAAeNpjYGRgYADid/fqneL5bb4yyLMwgMC1H90HIfRkCxDN+IBpFZDiYGAC8QBbSwuceNpjYGRgYI7594aBgcmOAQgYHzAwMqACdgBbWQN0AAABdgAiAAAAAAAAAAABFAAAAj4AYgI+AGYB9AAAAAAAKgAqACoAKgBeAJIAmnjaY2BkYGBgZ1BgYGIAAUYGBNADEQAFQQBaAAB42o2PwUrDQBCGvzVV9GAQDx485exBY1CU3PQgVgIFI9prlVqDwcZNC/oSPoKP4HNUfQLfxYN/NytCe5GwO9/88+/MBAh5I8C0VoAtnYYNa8oaXpAn9RxIP/XcIqLreZENnjwvyfPieVVdXj2H7DHxPJH/2/M7sVn3/MGyOfb8SWjOGv4K2DRdctpkmtqhos+D6ISh4kiUUXDj1Fr3Bc/Oc0vPqec6A8aUyu1cdTaPZvyXyqz6Fm5axC7bxHOv/r/dnbSRXCk7+mpVrOqVtFqdp3NKxaHUgeod9cm40rtrzfrt2OyQa8fppCO9tk7d1x0rpiQcuDuRkjjtkHt16ctbuf/radZY52/PnEcphXpZOcofiEZNcQAAeNpjYGIAg///GBgZsAF2BgZGJkZmBmaGdkYWRla29JzKggxD9tK8TAMDAxc2D0MLU2NjENfI1M0ZACUXCrsAAAABWtLiugAA) format('woff');
}

input.password {
  font-family: 'pass', 'Roboto', Helvetica, Arial, sans-serif ;
  font-size: 18px;
  &::-webkit-input-placeholder {
    transform: scale(0.77);
    transform-origin: 0 50%;
  }
  &::-moz-placeholder {
    font-size: 14px;
    opacity: 1;
  }
  &:-ms-input-placeholder {
    font-size: 14px;
    font-family: 'Roboto', Helvetica, Arial, sans-serif;
  }

After that, I got identical display input[password]

Why Is Subtracting These Two Times (in 1927) Giving A Strange Result?

To avoid that issue, when incrementing time you should convert back to UTC and then add or subtract.

This way you will be able to walk through any periods where hours or minutes happen twice.

If you converted to UTC, add each second, and convert to local time for display. You would go through 11:54:08 p.m. LMT - 11:59:59 p.m. LMT and then 11:54:08 p.m. CST - 11:59:59 p.m. CST.

RESTful API methods; HEAD & OPTIONS

OPTIONS tells you things such as "What methods are allowed for this resource".

HEAD gets the HTTP header you would get if you made a GET request, but without the body. This lets the client determine caching information, what content-type would be returned, what status code would be returned. The availability is only a small part of it.

Could not reserve enough space for object heap to start JVM

It looks like the machine you're trying to run this on has only 256 MB memory.

Maybe the JVM tries to allocate a large, contiguous block of 64 MB memory. The 192 MB that you have free might be fragmented into smaller pieces, so that there is no contiguous block of 64 MB free to allocate.

Try starting your Java program with a smaller heap size, for example:

java -Xms16m ...

A fatal error has been detected by the Java Runtime Environment: SIGSEGV, libjvm

1.Set the following Environment Property on your active Shell. - open bash terminal and type in:

  $ export LD_BIND_NOW=1
  1. Re-Run the Jar or Java File

Note: for superuser in bash type su and press enter

Mixed mode assembly is built against version ‘v2.0.50727' of the runtime

I actually had this identical issue with the inverse solution. I had upgraded a .NET project to .NET 4.0 and then reverted back to .NET 3.5. The app.config in my project continued to have the following which was causing the above error in question:

<startup>
  <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>

The solution to solve the error for this was to revert it back to the proper 2.0 reference as follows:

<startup>
  <supportedRuntime version="v2.0.50727"/>
</startup>

So if a downgrade is producing the above error, you might need to back up the .NET Framework supported version.

How can I make SQL case sensitive string comparison on MySQL?

http://dev.mysql.com/doc/refman/5.0/en/case-sensitivity.html

The default character set and collation are latin1 and latin1_swedish_ci, so nonbinary string comparisons are case insensitive by default. This means that if you search with col_name LIKE 'a%', you get all column values that start with A or a. To make this search case sensitive, make sure that one of the operands has a case sensitive or binary collation. For example, if you are comparing a column and a string that both have the latin1 character set, you can use the COLLATE operator to cause either operand to have the latin1_general_cs or latin1_bin collation:

col_name COLLATE latin1_general_cs LIKE 'a%'
col_name LIKE 'a%' COLLATE latin1_general_cs
col_name COLLATE latin1_bin LIKE 'a%'
col_name LIKE 'a%' COLLATE latin1_bin

If you want a column always to be treated in case-sensitive fashion, declare it with a case sensitive or binary collation.

Tools for making latex tables in R

The stargazer package is another good option. It supports objects from many commonly used functions and packages (lm, glm, svyreg, survival, pscl, AER), as well as from zelig. In addition to regression tables, it can also output summary statistics for data frames, or directly output the content of data frames.

Unable to run Java GUI programs with Ubuntu

Check your X Window environment variables using the "env" command.

How do implement a breadth first traversal?

Breadth first is a queue, depth first is a stack.

For breadth first, add all children to the queue, then pull the head and do a breadth first search on it, using the same queue.

For depth first, add all children to the stack, then pop and do a depth first on that node, using the same stack.

How to make tesseract to recognize only numbers, when they are mixed with letters?

For tesseract 3, i try to create config file according FAQ.

BEFORE calling an Init function or put this in a text file called tessdata/configs/digits:

tessedit_char_whitelist 0123456789                 

then, it works by using the command: tesseract imagename outputbase digits

How to modify a CSS display property from JavaScript?

I found the solution.

As said in the EDIT of my answer, a <div> is misfunctioning in a <table>. So I wrote this code instead :

<tr id="hidden" style="display:none;">
    <td class="depot_table_left">
        <label for="sexe">Sexe</label>
    </td>
    <td>
        <select type="text" name="sexe">
            <option value="1">Sexe</option>
            <option value="2">Joueur</option>
            <option value="3">Joueuse</option>
        </select>
    </td>
</tr>

And this is working fine.

Thanks everybody ;)

Import CSV file with mixed data types

In R2013b or later you can use a table:

>> table = readtable('myfile.txt','Delimiter',';','ReadVariableNames',false)
>> table = 

    Var1    Var2     Var3     Var4     Var5        Var6          Var7         Var8      Var9    Var10
    ____    _____    _____    _____    _____    __________    __________    ________    ____    _____

      4     'abc'    'def'    'ghj'    'klm'    ''            ''            ''          NaN     NaN  
    NaN     ''       ''       ''       ''       'Test'        'text'        '0xFF'      NaN     NaN  
    NaN     ''       ''       ''       ''       'asdfhsdf'    'dsafdsag'    '0x0F0F'    NaN     NaN  

Here is more info.

How to check java bit version on Linux?

Works for every binary, not only java:

file - < $(which java) # heavyly bashic

cat `which java` | file - # universal

Why doesn't importing java.util.* include Arrays and Lists?

Case 1 should have worked. I don't see anything wrong. There may be some other problems. I would suggest a clean build.

Sending Multipart File as POST parameters with RestTemplate requests

One of our guys does something similar with the filesystemresource. try

mvm.add("file", new FileSystemResource(pUploadDTO.getFile())); 

assuming the output of your .getFile is a java File object, that should work the same as ours, which just has a File parameter.

JSON order mixed up

I agree with the other answers. You cannot rely on the ordering of JSON elements.

However if we need to have an ordered JSON, one solution might be to prepare a LinkedHashMap object with elements and convert it to JSONObject.

@Test
def void testOrdered() {
    Map obj = new LinkedHashMap()
    obj.put("a", "foo1")
    obj.put("b", new Integer(100))
    obj.put("c", new Double(1000.21))
    obj.put("d", new Boolean(true))
    obj.put("e", "foo2")
    obj.put("f", "foo3")
    obj.put("g", "foo4")
    obj.put("h", "foo5")
    obj.put("x", null)

    JSONObject json = (JSONObject) obj
    logger.info("Ordered Json : %s", json.toString())

    String expectedJsonString = """{"a":"foo1","b":100,"c":1000.21,"d":true,"e":"foo2","f":"foo3","g":"foo4","h":"foo5"}"""
    assertEquals(expectedJsonString, json.toString())
    JSONAssert.assertEquals(JSONSerializer.toJSON(expectedJsonString), json)
}

Normally the order is not preserved as below.

@Test
def void testUnordered() {
    Map obj = new HashMap()
    obj.put("a", "foo1")
    obj.put("b", new Integer(100))
    obj.put("c", new Double(1000.21))
    obj.put("d", new Boolean(true))
    obj.put("e", "foo2")
    obj.put("f", "foo3")
    obj.put("g", "foo4")
    obj.put("h", "foo5")
    obj.put("x", null)

    JSONObject json = (JSONObject) obj
    logger.info("Unordered Json : %s", json.toString(3, 3))

    String unexpectedJsonString = """{"a":"foo1","b":100,"c":1000.21,"d":true,"e":"foo2","f":"foo3","g":"foo4","h":"foo5"}"""

    // string representation of json objects are different
    assertFalse(unexpectedJsonString.equals(json.toString()))
    // json objects are equal
    JSONAssert.assertEquals(JSONSerializer.toJSON(unexpectedJsonString), json)
}

You may check my post too: http://www.flyingtomoon.com/2011/04/preserving-order-in-json.html

Mail multipart/alternative vs multipart/mixed

Mixed Subtype

The "mixed" subtype of "multipart" is intended for use when the body parts are independent and need to be bundled in a particular order. Any "multipart" subtypes that an implementation does not recognize must be treated as being of subtype "mixed".

Alternative Subtype

The "multipart/alternative" type is syntactically identical to "multipart/mixed", but the semantics are different. In particular, each of the body parts is an "alternative" version of the same information

Source

How to increase the Java stack size?

I did Anagram excersize, which is like Count Change problem but with 50 000 denominations (coins). I am not sure that it can be done iteratively, I do not care. I just know that the -xss option had no effect -- I always failed after 1024 stack frames (might be scala does bad job delivering to to java or printStackTrace limitation. I do not know). This is bad option, as explained anyway. You do not want all threads in to app to be monstrous. However, I did some experiments with new Thread (stack size). This works indeed,

  def measureStackDepth(ss: Long): Long = {
    var depth: Long = 0
      val thread: Thread = new Thread(null, new Runnable() {
        override def run() {
          try {
          def sum(n: Long): Long = {depth += 1; if (n== 0) 0 else sum(n-1) + 1}
          println("fact = " + sum(ss * 10))
          } catch {
            case e: StackOverflowError => // eat the exception, that is expected
          }
        }
      }, "deep stack for money exchange", ss)
      thread.start()
      thread.join()
    depth
  }                                               //> measureStackDepth: (ss: Long)Long


  for (ss <- (0 to 10)) println("ss = 10^" +  ss + " allows stack of size " -> measureStackDepth((scala.math.pow (10, ss)).toLong) )
                                                  //> fact = 10
                                                  //| (ss = 10^0 allows stack of size ,11)
                                                  //| fact = 100
                                                  //| (ss = 10^1 allows stack of size ,101)
                                                  //| fact = 1000
                                                  //| (ss = 10^2 allows stack of size ,1001)
                                                  //| fact = 10000
                                                  //| (ss = 10^3 allows stack of size ,10001)
                                                  //| (ss = 10^4 allows stack of size ,1336)
                                                  //| (ss = 10^5 allows stack of size ,5456)
                                                  //| (ss = 10^6 allows stack of size ,62736)
                                                  //| (ss = 10^7 allows stack of size ,623876)
                                                  //| (ss = 10^8 allows stack of size ,6247732)
                                                  //| (ss = 10^9 allows stack of size ,62498160)

You see that stack can grow exponentially deeper with exponentially more stack alloted to the thread.

Can regular JavaScript be mixed with jQuery?

Why is MichalBE getting downvoted? He's right - using jQuery (or any library) just to fire a function on page load is overkill, potentially costing people money on mobile connections and slowing down the user experience. If the original poster doesn't want to use onload in the body tag (and he's quite right not to), add this after the draw() function:

if (draw) window.onload = draw;

Or this, by Simon Willison, if you want more than one function to be executed:

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

What's the difference between git reset --mixed, --soft, and --hard?

You don't have to force yourself to remember differences between them. Think of how you actually made a commit.

  1. Make some changes.

  2. git add .

  3. git commit -m "I did Something"

Soft, Mixed and Hard is the way enabling you to give up the operations you did from 3 to 1.

  • Soft "pretended" to never see you have did git commit.
  • Mixed "pretended" to never see you have did git add .
  • Hard "pretended" to never see you have made file changes.

Why declare unicode by string in python?

The header definition is to define the encoding of the code itself, not the resulting strings at runtime.

putting a non-ascii character like ? in the python script without the utf-8 header definition will throw a warning

error

How can I tell jaxb / Maven to generate multiple schema packages?

There is another, a clear one (IMO) solution to this There is a parameter called "staleFile" that uses as a flag to not generate stuff again. Simply alter it in each execution.

Rails: update_attribute vs update_attributes

To answer your question, update_attribute skips pre save "validations" but it still runs any other callbacks like after_save etc. So if you really want to "just update the column and skip any AR cruft" then you need to use (apparently)

Model.update_all(...) see https://stackoverflow.com/a/7243777/32453

Visual Studio 2010 always thinks project is out of date, but nothing has changed

This happened to me today. I was able to track down the cause: The project included a header file which no longer existed on disk.

Removing the file from the project solved the problem.

How do I lowercase a string in C?

to convert to lower case is equivalent to rise bit 0x60 if you restrict yourself to ASCII:

for(char *p = pstr; *p; ++p)
    *p = *p > 0x40 && *p < 0x5b ? *p | 0x60 : *p;

java.lang.UnsupportedClassVersionError: Bad version number in .class file?

Also check any jar files in your project that have been compiled for a higher version of Java. If these are your own libraries, you can fix this by changing the target version attribute to javac

<javac destdir="${classes.dir}"
            debug="on" classpathref="project.classpath" target="1.6">

What 'additional configuration' is necessary to reference a .NET 2.0 mixed mode assembly in a .NET 4.0 project?

Using 2.0 and 4.0 assemblies together isn't quite straight forward.

The ORDER of the supported framework declarations in app.config actually have an effect on the exception of mixed mode being thrown. If you flip the declaration order you will get mixed mode error. This is the purpose of this answer.

So if you get the error in a Windows Forms app, , try this, mostly Windows Forms apps.

  <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0,Profile=Client"/>
    <supportedRuntime version="v2.0.50727"></supportedRuntime>
  </startup>

Or if the project is not Windows Form. In a Web project add this to web.config file.

  <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
    <supportedRuntime version="v2.0.50727"></supportedRuntime>
  </startup>

jQuery ajax upload file in asp.net mvc

Upload files using AJAX in ASP.Net MVC

Things have changed since HTML5

JavaScript

document.getElementById('uploader').onsubmit = function () {
    var formdata = new FormData(); //FormData object
    var fileInput = document.getElementById('fileInput');
    //Iterating through each files selected in fileInput
    for (i = 0; i < fileInput.files.length; i++) {
        //Appending each file to FormData object
        formdata.append(fileInput.files[i].name, fileInput.files[i]);
    }
    //Creating an XMLHttpRequest and sending
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/Home/Upload');
    xhr.send(formdata);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            alert(xhr.responseText);
        }
    }
    return false;
}   

Controller

public JsonResult Upload()
{
    for (int i = 0; i < Request.Files.Count; i++)
    {
        HttpPostedFileBase file = Request.Files[i]; //Uploaded file
        //Use the following properties to get file's name, size and MIMEType
        int fileSize = file.ContentLength;
        string fileName = file.FileName;
        string mimeType = file.ContentType;
        System.IO.Stream fileContent = file.InputStream;
        //To save file, use SaveAs method
        file.SaveAs(Server.MapPath("~/")+ fileName ); //File will be saved in application root
    }
    return Json("Uploaded " + Request.Files.Count + " files");
}

EDIT : The HTML

<form id="uploader">
    <input id="fileInput" type="file" multiple>
    <input type="submit" value="Upload file" />
</form>

php variable in html no other way than: <?php echo $var; ?>

Use the HEREDOC syntax. You can mix single and double quotes, variables and even function calls with unaltered / unescaped html markup.

echo <<<MYTAG
  <tr><td> <input type="hidden" name="type" value="$var1" ></td></tr>
  <tr><td> <input type="hidden" name="type" value="$var2" ></td></tr>
  <tr><td> <input type="hidden" name="type" value="$var3" ></td></tr>
  <tr><td> <input type="hidden" name="type" value="$var4" ></td></tr>
MYTAG;

Add IIS 7 AppPool Identities as SQL Server Logons

If you're going across machines, you either need to be using NETWORK SERVICE, LOCAL SYSTEM, a domain account, or a SQL 2008 R2 (if you have it) Managed Service Account (which is my preference if you had such an infrastructure). You can not use an account which is not visible to the Active Directory domain.

"Parameter" vs "Argument"

A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.

Consider the following code:

void Foo(int i, float f)
{
    // Do things
}

void Bar()
{
    int anInt = 1;
    Foo(anInt, 2.0);
}

Here i and f are the parameters, and anInt and 2.0 are the arguments.

Function names in C++: Capitalize or not?

The most common ones I see in production code are (in this order):

myFunctionName     // lower camel case

MyFunctionName     // upper camel case

my_function_name   // K & R ?

I find the naming convention a programmer uses in C++ code usually has something to do with their programming background.

E.g. ex-java programmers tend to use lower camel case for functions

How to Find the Default Charset/Encoding in Java?

Is this a bug or feature?

Looks like undefined behaviour. I know that, in practice, you can change the default encoding using a command-line property, but I don't think what happens when you do this is defined.

Bug ID: 4153515 on problems setting this property:

This is not a bug. The "file.encoding" property is not required by the J2SE platform specification; it's an internal detail of Sun's implementations and should not be examined or modified by user code. It's also intended to be read-only; it's technically impossible to support the setting of this property to arbitrary values on the command line or at any other time during program execution.

The preferred way to change the default encoding used by the VM and the runtime system is to change the locale of the underlying platform before starting your Java program.

I cringe when I see people setting the encoding on the command line - you don't know what code that is going to affect.

If you do not want to use the default encoding, set the encoding you do want explicitly via the appropriate method/constructor.

What does 'useLegacyV2RuntimeActivationPolicy' do in the .NET 4 config?

Here's an explanation I wrote recently to help with the void of information on this attribute. http://www.marklio.com/marklio/PermaLink,guid,ecc34c3c-be44-4422-86b7-900900e451f9.aspx (Internet Archive Wayback Machine link)

To quote the most relevant bits:

[Installing .NET] v4 is “non-impactful”. It should not change the behavior of existing components when installed.

The useLegacyV2RuntimeActivationPolicy attribute basically lets you say, “I have some dependencies on the legacy shim APIs. Please make them work the way they used to with respect to the chosen runtime.”

Why don’t we make this the default behavior? You might argue that this behavior is more compatible, and makes porting code from previous versions much easier. If you’ll recall, this can’t be the default behavior because it would make installation of v4 impactful, which can break existing apps installed on your machine.

The full post explains this in more detail. At RTM, the MSDN docs on this should be better.

How can I change from SQL Server Windows mode to mixed mode (SQL Server 2008)?

Open the registry and search for key LoginMode under:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server

Update the LoginMode value as 2.

Generating CSV file for Excel, how to have a newline inside a value

For File Open only, the syntax is

 ,"one\n
 two",...

The critical thing is that there is no space after the first ",". Normally spaces are fine, and trimmed if the string is not quoted. But otherwise nasty. Took me a while to figure that out.

It does not seem to matter if the line is ended \n or \c\n.

Make sure you expand the formula bar so you can actually see the text in the cell (got me after a long day...)

Now of course, File Open will not support UTF-8 Properly (unless one uses tricks).

Excel > Data > Get External Data > From Text

Can be set into UTF-8 mode (it is way down the list of fonts). However, in that case the new lines do not seem to work and I know no way to fix that.

(One might thing that after 30 years MS would get this stuff right.)

Unable to install Maven on Windows: "JAVA_HOME is set to an invalid directory"

you should set JAVA_HOME or MAVEN_HOME without bin directory for example: - JAVA_HOME=C:\Program Files (x86)\Java\jdk1.7.0_45 - MAVEN_HOME=C:\Program Files (x86)\apache-maven-3.1.1 now path=.....;%MAVEN_HOME%\bin;%JAVA_HOME%\bin it's work correctly

Attach the Java Source Code

You don't necessarily need to add the source, but you rather may need to remove a JRE that does not have the source attached.

On looking at the "installed JRE's" I saw that my JDK was setup properly with source, but the default JRE on the machine had no sources. Eclipse was defaulting to that when looking for source.

I just used the remove button to expel the JRE, leaving my JDK. I then hit F3 and the source was there. Yeah!

How to solve "java.io.IOException: error=12, Cannot allocate memory" calling Runtime#exec()?

You can use the Tanuki wrapper to spawn a process with POSIX spawn instead of fork. http://wrapper.tanukisoftware.com/doc/english/child-exec.html

The WrapperManager.exec() function is an alternative to the Java-Runtime.exec() which has the disadvantage to use the fork() method, which can become on some platforms very memory expensive to create a new process.

Detect when browser receives file download

If you don't want to generate and store the file on the server, are you willing to store the status, e.g. file-in-progress, file-complete? Your "waiting" page could poll the server to know when the file generation is complete. You wouldn't know for sure that the browser started the download but you'd have some confidence.

Initialization of all elements of an array to one default value in C++?

Should be a standard feature but for some reason it's not included in standard C nor C++...

#include <stdio.h>

 __asm__
 (
"    .global _arr;      "
"    .section .data;    "
"_arr: .fill 100, 1, 2; "
 );

extern char arr[];

int main() 
{
    int i;

    for(i = 0; i < 100; ++i) {
        printf("arr[%u] = %u.\n", i, arr[i]);
    }
}

In Fortran you could do:

program main
    implicit none

    byte a(100)
    data a /100*2/
    integer i

    do i = 0, 100
        print *, a(i)
    end do
end

but it does not have unsigned numbers...

Why can't C/C++ just implement it. Is it really so hard? It's so silly to have to write this manually to achieve the same result...

#include <stdio.h>
#include <stdint.h>

/* did I count it correctly? I'm not quite sure. */
uint8_t arr = {
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
    2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
};    

int main() 
{
    int i;

    for(i = 0; i < 100; ++i) {
        printf("arr[%u] = %u.\n", i, arr[i]);
    }
}

What if it was an array of 1,000,00 bytes? I'd need to write a script to write it for me, or resort to hacks with assembly/etc. This is nonsense.

It's perfectly portable, there's no reason for it not to be in the language.

Just hack it in like:

#include <stdio.h>
#include <stdint.h>

/* a byte array of 100 twos declared at compile time. */
uint8_t twos[] = {100:2};

int main()
{
    uint_fast32_t i;
    for (i = 0; i < 100; ++i) {
        printf("twos[%u] = %u.\n", i, twos[i]);
    }

    return 0;
}

One way to hack it in is via preprocessing... (Code below does not cover edge cases, but is written to quickly demonstrate what could be done.)

#!/usr/bin/perl
use warnings;
use strict;

open my $inf, "<main.c";
open my $ouf, ">out.c";

my @lines = <$inf>;

foreach my $line (@lines) {
    if ($line =~ m/({(\d+):(\d+)})/) {
        printf ("$1, $2, $3");        
        my $lnew = "{" . "$3, "x($2 - 1) . $3 . "}";
        $line =~ s/{(\d+:\d+)}/$lnew/;
        printf $ouf $line;
    } else {
        printf $ouf $line;
    }
}

close($ouf);
close($inf);

How to reverse apply a stash?

This is in addition to the above answers but adds search for the git stash based on the message as the stash number can change when new stashes are saved. I have written a couple of bash functions:

apply(){
  if [ "$1" ]; then
    git stash apply `git stash list | grep -oPm1 "(.*)(?=:.*:.*$1.*)"`
  fi
}
remove(){
  if [ "$1" ]; then
    git stash show -p `git stash list | grep -oPm1 "(.*)(?=:.*:.*$1.*)"` | git apply -R
    git status
  fi
}
  1. Create stash with name (message) $ git stash save "my stash"
  2. To appply named $ apply "my stash"
  3. To remove named stash $ remove "my stash"

Edit and Continue: "Changes are not allowed when..."

I had this happen in a linked class file. The rest of the project allowed E&C, but I got the same error editing the linked file. Solution was to break linked file into it's own project and reference the project.

Neatest way to remove linebreaks in Perl

Note from 2017: File::Slurp is not recommended due to design mistakes and unmaintained errors. Use File::Slurper or Path::Tiny instead.

extending on your answer

use File::Slurp ();
my $value = File::Slurp::slurp($filename);
$value =~ s/\R*//g;

File::Slurp abstracts away the File IO stuff and just returns a string for you.

NOTE

  1. Important to note the addition of /g , without it, given a multi-line string, it will only replace the first offending character.

  2. Also, the removal of $, which is redundant for this purpose, as we want to strip all line breaks, not just line-breaks before whatever is meant by $ on this OS.

  3. In a multi-line string, $ matches the end of the string and that would be problematic ).

  4. Point 3 means that point 2 is made with the assumption that you'd also want to use /m otherwise '$' would be basically meaningless for anything practical in a string with >1 lines, or, doing single line processing, an OS which actually understands $ and manages to find the \R* that proceed the $

Examples

while( my $line = <$foo> ){
      $line =~ $regex;
}

Given the above notation, an OS which does not understand whatever your files '\n' or '\r' delimiters, in the default scenario with the OS's default delimiter set for $/ will result in reading your whole file as one contiguous string ( unless your string has the $OS's delimiters in it, where it will delimit by that )

So in this case all of these regex are useless:

  • /\R*$// : Will only erase the last sequence of \R in the file
  • /\R*// : Will only erase the first sequence of \R in the file
  • /\012?\015?// : When will only erase the first 012\015 , \012 , or \015 sequence, \015\012 will result in either \012 or \015 being emitted.

  • /\R*$// : If there happens to be no byte sequences of '\015$OSDELIMITER' in the file, then then NO linebreaks will be removed except for the OS's own ones.

It would appear nobody gets what I'm talking about, so here is example code, that is tested to NOT remove line feeds. Run it, you'll see that it leaves the linefeeds in.

#!/usr/bin/perl 

use strict;
use warnings;

my $fn = 'TestFile.txt';

my $LF = "\012";
my $CR = "\015";

my $UnixNL = $LF;
my $DOSNL  = $CR . $LF;
my $MacNL  = $CR;

sub generate { 
    my $filename = shift;
    my $lineDelimiter = shift;

    open my $fh, '>', $filename;
    for ( 0 .. 10 )
    {
        print $fh "{0}";
        print $fh join "", map { chr( int( rand(26) + 60 ) ) } 0 .. 20;
        print $fh "{1}";
        print $fh $lineDelimiter->();
        print $fh "{2}";
    }
    close $fh;
}

sub parse { 
    my $filename = shift;
    my $osDelimiter = shift;
    my $message = shift;
    print "Parsing $message File $filename : \n";

    local $/ = $osDelimiter;

    open my $fh, '<', $filename;
    while ( my $line = <$fh> )
    {

        $line =~ s/\R*$//;
        print ">|" . $line . "|<";

    }
    print "Done.\n\n";
}


my @all = ( $DOSNL,$MacNL,$UnixNL);
generate 'Windows.txt' , sub { $DOSNL }; 
generate 'Mac.txt' , sub { $MacNL };
generate 'Unix.txt', sub { $UnixNL };
generate 'Mixed.txt', sub {
    return @all[ int(rand(2)) ];
};


for my $os ( ["$MacNL", "On Mac"], ["$DOSNL", "On Windows"], ["$UnixNL", "On Unix"]){
    for ( qw( Windows Mac Unix Mixed ) ){
        parse $_ . ".txt", @{ $os };
    }
}

For the CLEARLY Unprocessed output, see here: http://pastebin.com/f2c063d74

Note there are certain combinations that of course work, but they are likely the ones you yourself naívely tested.

Note that in this output, all results must be of the form >|$string|<>|$string|< with NO LINE FEEDS to be considered valid output.

and $string is of the general form {0}$data{1}$delimiter{2} where in all output sources, there should be either :

  1. Nothing between {1} and {2}
  2. only |<>| between {1} and {2}

Is the practice of returning a C++ reference variable evil?

Addition to the accepted answer:

struct immutableint {
    immutableint(int i) : i_(i) {}

    const int& get() const { return i_; }
private:
    int i_;
};

I'd argue that this example is not okay and should be avoided if possible. Why? It is very easy to end-up with a dangling reference.

To illustrate the point with an example:

struct Foo
{
    Foo(int i = 42) : boo_(i) {}
    immutableint boo()
    {
        return boo_;
    }  
private:
    immutableint boo_;
};

entering the danger-zone:

Foo foo;
const int& dangling = foo.boo().get(); // dangling reference!

How to nicely format floating numbers to string without unnecessary decimal 0's

On my machine, the following function is roughly 7 times faster than the function provided by JasonD's answer, since it avoids String.format:

public static String prettyPrint(double d) {
  int i = (int) d;
  return d == i ? String.valueOf(i) : String.valueOf(d);
}

SQL Server 2008 Windows Auth Login Error: The login is from an untrusted domain

In my case, in the host file, the machine name is hard coded with older IP. I replace the older IP with the new one, the issue is resolved.

Host file location

WindowsDrive:\Windows\System32\drivers\etc\hosts

Modifications done 159.xx.xx.xxx MachineName

SSIS Excel Import Forcing Incorrect Column Type

If multiple columns in the excel spreadsheet present with the same name, this kind of error occurs. The package will work after making the column name's distinct. Sometime the hidden columns are being ignored while checking the columnn names.

How do I return multiple values from a function?

For small projects I find it easiest to work with tuples. When that gets too hard to manage (and not before) I start grouping things into logical structures, however I think your suggested use of dictionaries and ReturnValue objects is wrong (or too simplistic).

Returning a dictionary with keys "y0", "y1", "y2", etc. doesn't offer any advantage over tuples. Returning a ReturnValue instance with properties .y0, .y1, .y2, etc. doesn't offer any advantage over tuples either. You need to start naming things if you want to get anywhere, and you can do that using tuples anyway:

def get_image_data(filename):
    [snip]
    return size, (format, version, compression), (width,height)

size, type, dimensions = get_image_data(x)

IMHO, the only good technique beyond tuples is to return real objects with proper methods and properties, like you get from re.match() or open(file).

Are HTTPS headers encrypted?

New answer to old question, sorry. I thought I'd add my $.02

The OP asked if the headers were encrypted.

They are: in transit.

They are NOT: when not in transit.

So, your browser's URL (and title, in some cases) can display the querystring (which usually contain the most sensitive details) and some details in the header; the browser knows some header information (content type, unicode, etc); and browser history, password management, favorites/bookmarks, and cached pages will all contain the querystring. Server logs on the remote end can also contain querystring as well as some content details.

Also, the URL isn't always secure: the domain, protocol, and port are visible - otherwise routers don't know where to send your requests.

Also, if you've got an HTTP proxy, the proxy server knows the address, usually they don't know the full querystring.

So if the data is moving, it's generally protected. If it's not in transit, it's not encrypted.

Not to nit pick, but data at the end is also decrypted, and can be parsed, read, saved, forwarded, or discarded at will. And, malware at either end can take snapshots of data entering (or exiting) the SSL protocol - such as (bad) Javascript inside a page inside HTTPS which can surreptitiously make http (or https) calls to logging websites (since access to local harddrive is often restricted and not useful).

Also, cookies are not encrypted under the HTTPS protocol, either. Developers wanting to store sensitive data in cookies (or anywhere else for that matter) need to use their own encryption mechanism.

As to cache, most modern browsers won't cache HTTPS pages, but that fact is not defined by the HTTPS protocol, it is entirely dependent on the developer of a browser to be sure not to cache pages received through HTTPS.

So if you're worried about packet sniffing, you're probably okay. But if you're worried about malware or someone poking through your history, bookmarks, cookies, or cache, you are not out of the water yet.

How to generate a random string in Ruby

This is almost as ugly but perhaps as step in right direction?

 (1..8).map{|i| ('a'..'z').to_a[rand(26)]}.join

How do I get a string format of the current date time, in python?

If you don't care about formatting and you just need some quick date, you can use this:

import time
print(time.ctime())

Find the maximum value in a list of tuples in Python

You could loop through the list and keep the tuple in a variable and then you can see both values from the same variable...

num=(0, 0)
for item in tuplelist:
  if item[1]>num[1]:
    num=item #num has the whole tuple with the highest y value and its x value

Delete all items from a c++ std::vector

If your vector look like this std::vector<MyClass*> vecType_pt you have to explicitly release memory ,Or if your vector look like : std::vector<MyClass> vecType_obj , constructor will be called by vector.Please execute example given below , and understand the difference :

  class MyClass
    {
    public:
        MyClass()
        {
            cout<<"MyClass"<<endl;
        }
        ~MyClass()
        {
            cout<<"~MyClass"<<endl;
        }
    };
    int main() 
    {
        typedef std::vector<MyClass*> vecType_ptr;
        typedef std::vector<MyClass> vecType_obj;
        vecType_ptr myVec_ptr;
        vecType_obj myVec_obj;
        MyClass obj;
        for(int i=0;i<5;i++)
        {
            MyClass *ptr=new MyClass();
            myVec_ptr.push_back(ptr);
            myVec_obj.push_back(obj);
        }
        cout<<"\n\n---------------------If pointer stored---------------------"<<endl;
        myVec_ptr.erase (myVec_ptr.begin(),myVec_ptr.end());
        cout<<"\n\n---------------------If object stored---------------------"<<endl;
        myVec_obj.erase (myVec_obj.begin(),myVec_obj.end());
        return 0;
    }

In C#, why is String a reference type that behaves like a value type?

It is mainly a performance issue.

Having strings behave LIKE value type helps when writing code, but having it BE a value type would make a huge performance hit.

For an in-depth look, take a peek at a nice article on strings in the .net framework.

Difference between thread's context class loader and normal classloader

Each class will use its own classloader to load other classes. So if ClassA.class references ClassB.class then ClassB needs to be on the classpath of the classloader of ClassA, or its parents.

The thread context classloader is the current classloader for the current thread. An object can be created from a class in ClassLoaderC and then passed to a thread owned by ClassLoaderD. In this case the object needs to use Thread.currentThread().getContextClassLoader() directly if it wants to load resources that are not available on its own classloader.

How do I duplicate a line or selection within Visual Studio Code?

The commands your are looking for are editor.action.copyLinesDownAction and editor.action.copyLinesUpAction.

You can see the associated keybindings by picking: File > Preferences > Keyboard Shortcuts

Windows:

Shift+Alt+Down and Shift+Alt+Up

Mac:

Shift+Option+Down and Shift+OptionUp

Linux:

Ctrl+Shift+Alt+Down and Ctrl+Shift+Alt+Up

(Might need to use numpad Down and Up for Linux)

Furthermore, commands editor.action.moveLinesUpAction and editor.action.moveLinesDownAction are the ones to move lines and they are bound to Alt+Down and Alt+Up on Windows and Mac and Ctrl+Down and Ctrl+Up on Linux.

Installing RubyGems in Windows

To setup you Ruby development environment on Windows:

  1. Install Ruby via RubyInstaller: http://rubyinstaller.org/downloads/

  2. Check your ruby version: Start - Run - type in cmd to open a windows console

  3. Type in ruby -v
  4. You will get something like that: ruby 2.0.0p353 (2013-11-22) [i386-mingw32]

For Ruby 2.4 or later, run the extra installation at the end to install the DevelopmentKit. If you forgot to do that, run ridk install in your windows console to install it.

For earlier versions:

  1. Download and install DevelopmentKit from the same download page as Ruby Installer. Choose an ?exe file corresponding to your environment (32 bits or 64 bits and working with your version of Ruby).
  2. Follow the installation instructions for DevelopmentKit described at: https://github.com/oneclick/rubyinstaller/wiki/Development-Kit#installation-instructions. Adapt it for Windows.
  3. After installing DevelopmentKit you can install all needed gems by just running from the command prompt (windows console or terminal): gem install {gem name}. For example, to install rails, just run gem install rails.

Hope this helps.

Failed to decode downloaded font, OTS parsing error: invalid version tag + rails 4

For it is fixed by using below statement in app.web.scss
    $fa-font-path:   "../../node_modules/font-awesome/fonts/" !default;
    @import "../../node_modules/font-awesome/scss/font-awesome";

Is there a way to define a min and max value for EditText in Android?

Kotlin if any one needs it (Use Utilities)

class InputFilterMinMax: InputFilter {
    private var min:Int = 0
    private var max:Int = 0
    constructor(min:Int, max:Int) {
        this.min = min
        this.max = max
    }
    constructor(min:String, max:String) {
        this.min = Integer.parseInt(min)
        this.max = Integer.parseInt(max)
    }
    override fun filter(source:CharSequence, start:Int, end:Int, dest: Spanned, dstart:Int, dend:Int): CharSequence? {
        try
        {
            val input = Integer.parseInt(dest.toString() + source.toString())
            if (isInRange(min, max, input))
                return null
        }
        catch (nfe:NumberFormatException) {}
        return ""
    }
    private fun isInRange(a:Int, b:Int, c:Int):Boolean {
        return if (b > a) c in a..b else c in b..a
    }
}

Then use this from your Kotlin class

percentage_edit_text.filters = arrayOf(Utilities.InputFilterMinMax(1, 100))

This EditText allows from 1 to 100.

Then use this from your XML

android:inputType="number"

Optional query string parameters in ASP.NET Web API

Default values cannot be supplied for parameters that are not declared 'optional'

 Function GetFindBooks(id As Integer, ByVal pid As Integer, Optional sort As String = "DESC", Optional limit As Integer = 99)

In your WebApiConfig

 config.Routes.MapHttpRoute( _
          name:="books", _
          routeTemplate:="api/{controller}/{action}/{id}/{pid}/{sort}/{limit}", _
          defaults:=New With {.id = RouteParameter.Optional, .pid = RouteParameter.Optional, .sort = UrlParameter.Optional, .limit = UrlParameter.Optional} _
      )

JavaScript/jQuery - "$ is not defined- $function()" error

I have solved it as follow.

import $ from 'jquery';

(function () {
    // ... code let script = $(..)
})();

Why do we have to override the equals() method in Java?

Let me give you an example that I find very helpful.

You can think of reference as the page number of a book. Suppose now you have two pages a and b like below.

BookPage a = getSecondPage();

BookPage b = getThirdPage();

In this case, a == b will give you false. But, why? The reason is that what == is doing is like comparing the page number. So, even if the content on these two pages is exactly the same, you will still get false.

But what do we do if you we want to compare the content?

The answer is to write your own equals method and specify what you really want to compare.

Jasmine JavaScript Testing - toBe vs toEqual

Looking at the Jasmine source code sheds more light on the issue.

toBe is very simple and just uses the identity/strict equality operator, ===:

  function(actual, expected) {
    return {
      pass: actual === expected
    };
  }

toEqual, on the other hand, is nearly 150 lines long and has special handling for built in objects like String, Number, Boolean, Date, Error, Element and RegExp. For other objects it recursively compares properties.

This is very different from the behavior of the equality operator, ==. For example:

var simpleObject = {foo: 'bar'};
expect(simpleObject).toEqual({foo: 'bar'}); //true
simpleObject == {foo: 'bar'}; //false

var castableObject = {toString: function(){return 'bar'}};
expect(castableObject).toEqual('bar'); //false
castableObject == 'bar'; //true

Validate decimal numbers in JavaScript - IsNumeric()

This way seems to work well:

function IsNumeric(input){
    var RE = /^-{0,1}\d*\.{0,1}\d+$/;
    return (RE.test(input));
}

In one line:

const IsNumeric = (num) => /^-{0,1}\d*\.{0,1}\d+$/.test(num);

And to test it:

_x000D_
_x000D_
const IsNumeric = (num) => /^-{0,1}\d*\.{0,1}\d+$/.test(num);_x000D_
    _x000D_
    function TestIsNumeric(){_x000D_
        var results = ''_x000D_
        results += (IsNumeric('-1')?"Pass":"Fail") + ": IsNumeric('-1') => true\n";_x000D_
        results += (IsNumeric('-1.5')?"Pass":"Fail") + ": IsNumeric('-1.5') => true\n";_x000D_
        results += (IsNumeric('0')?"Pass":"Fail") + ": IsNumeric('0') => true\n";_x000D_
        results += (IsNumeric('0.42')?"Pass":"Fail") + ": IsNumeric('0.42') => true\n";_x000D_
        results += (IsNumeric('.42')?"Pass":"Fail") + ": IsNumeric('.42') => true\n";_x000D_
        results += (!IsNumeric('99,999')?"Pass":"Fail") + ": IsNumeric('99,999') => false\n";_x000D_
        results += (!IsNumeric('0x89f')?"Pass":"Fail") + ": IsNumeric('0x89f') => false\n";_x000D_
        results += (!IsNumeric('#abcdef')?"Pass":"Fail") + ": IsNumeric('#abcdef') => false\n";_x000D_
        results += (!IsNumeric('1.2.3')?"Pass":"Fail") + ": IsNumeric('1.2.3') => false\n";_x000D_
        results += (!IsNumeric('')?"Pass":"Fail") + ": IsNumeric('') => false\n";_x000D_
        results += (!IsNumeric('blah')?"Pass":"Fail") + ": IsNumeric('blah') => false\n";_x000D_
        _x000D_
        return results;_x000D_
    }_x000D_
_x000D_
console.log(TestIsNumeric());
_x000D_
.as-console-wrapper { max-height: 100% !important; top: 0; }
_x000D_
_x000D_
_x000D_

I borrowed that regex from http://www.codetoad.com/javascript/isnumeric.asp. Explanation:

/^ match beginning of string
-{0,1} optional negative sign
\d* optional digits
\.{0,1} optional decimal point
\d+ at least one digit
$/ match end of string

What is the easiest way to disable/enable buttons and links (jQuery + Bootstrap)

Suppose you have these buttons on page like :

<input type="submit" class="byBtn" disabled="disabled" value="Change"/>
<input type="submit" class="byBtn" disabled="disabled" value="Change"/>
<input type="submit" class="byBtn" disabled="disabled" value="Change"/>
<input type="submit" class="byBtn" disabled="disabled" value="Change"/>
<input type="submit" class="byBtn" disabled="disabled" value="Change"/>
<input type="submit"value="Enable All" onclick="change()"/>

The js code:

function change(){
   var toenable = document.querySelectorAll(".byBtn");        
    for (var k in toenable){
         toenable[k].removeAttribute("disabled");
    }
}

How do you use Intent.FLAG_ACTIVITY_CLEAR_TOP to clear the Activity Stack?

Add android:noHistory="true" in manifest file .

<manifest >
        <activity
            android:name="UI"
            android:noHistory="true"/>

</manifest>

Simplest/cleanest way to implement a singleton in JavaScript

function Once() {
    return this.constructor.instance || (this.constructor.instance = this);
}

function Application(name) {
    let app = Once.call(this);

    app.name = name;

    return app;
}

If you are into classes:

class Once {
    constructor() {
        return this.constructor.instance || (this.constructor.instance = this);
    }
}

class Application extends Once {
    constructor(name) {
        super();

        this.name = name;
    }
}

Test:

console.log(new Once() === new Once());

let app1 = new Application('Foobar');
let app2 = new Application('Barfoo');

console.log(app1 === app2);
console.log(app1.name); // Barfoo

How to redirect the output of print to a TXT file

Building on previous answers, I think it's a perfect use case for doing it (simple) context manager style:

import sys

class StdoutRedirection:
    """Standard output redirection context manager"""

    def __init__(self, path):
        self._path = path

    def __enter__(self):
        sys.stdout = open(self._path, mode="w")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        sys.stdout.close()
        sys.stdout = sys.__stdout__

and then:

with StdoutRedirection("path/to/file"):
    print("Hello world")

Also it would be really easy to add some functionality to StdoutRedirection class (e.g. a method that lets you change the path)

Pass array to MySQL stored routine

This helps for me to do IN condition Hope this will help you..

CREATE  PROCEDURE `test`(IN Array_String VARCHAR(100))
BEGIN
    SELECT * FROM Table_Name
    WHERE FIND_IN_SET(field_name_to_search, Array_String);

END//;

Calling:

 call test('3,2,1');

CURRENT_DATE/CURDATE() not working as default DATE value

create table the_easy_way(
  capture_ts DATETIME DEFAULT CURRENT_TIMESTAMP,
  capture_dt DATE AS (DATE(capture_ts))
)

(MySQL 5.7)

how to mysqldump remote db from local machine

mysqldump from remote server use SSL

1- Security with SSL

192.168.0.101 - remote server

192.168.0.102 - local server

Remore server

CREATE USER 'backup_remote_2'@'192.168.0.102' IDENTIFIED WITH caching_sha2_password BY '3333333' REQUIRE SSL;

GRANT ALL PRIVILEGES ON *.* TO 'backup_remote_2'@'192.168.0.102';

FLUSH PRIVILEGES;

-

Local server

sudo /usr/local/mysql/bin/mysqldump \
 --databases test_1 \
 --host=192.168.0.101 \
 --user=backup_remote_2 \
 --password=3333333 \
 --master-data \
 --set-gtid-purged \
 --events \
 --triggers \
 --routines \
 --verbose \
 --ssl-mode=REQUIRED \
 --result-file=/home/db_1.sql

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

2 - Security with SSL (REQUIRE X509)

192.168.0.101 - remote server

192.168.0.102 - local server

Remore server

CREATE USER 'backup_remote'@'192.168.0.102' IDENTIFIED WITH caching_sha2_password BY '1111111' REQUIRE X509;

GRANT ALL PRIVILEGES ON *.* TO 'backup_remote'@'192.168.0.102';

FLUSH PRIVILEGES;

-

Local server

sudo /usr/local/mysql/bin/mysqldump \
 --databases test_1 \
 --host=192.168.0.101 \
 --user=backup_remote \
 --password=1111111 \
 --events \
 --triggers \
 --routines \
 --verbose \
 --ssl-mode=VERIFY_CA \
 --ssl-ca=/usr/local/mysql/data/ssl/ca.pem \
 --ssl-cert=/usr/local/mysql/data/ssl/client-cert.pem \
 --ssl-key=/usr/local/mysql/data/ssl/client-key.pem \
 --result-file=/home/db_name.sql

[Note]

On local server

/usr/local/mysql/data/ssl/

-rw------- 1 mysql mysql 1.7K Apr 16 22:28 ca-key.pem
-rw-r--r-- 1 mysql mysql 1.1K Apr 16 22:28 ca.pem
-rw-r--r-- 1 mysql mysql 1.1K Apr 16 22:28 client-cert.pem
-rw------- 1 mysql mysql 1.7K Apr 16 22:28 client-key.pem

Copy this files from remote server for (REQUIRE X509) or if SSL without (REQUIRE X509) do not copy


On remote server

/usr/local/mysql/data/

-rw------- 1 mysql mysql 1.7K Apr 16 22:28  ca-key.pem
-rw-r--r-- 1 mysql mysql 1.1K Apr 16 22:28  ca.pem
-rw-r--r-- 1 mysql mysql 1.1K Apr 16 22:28  client-cert.pem
-rw------- 1 mysql mysql 1.7K Apr 16 22:28  client-key.pem
-rw------- 1 mysql mysql 1.7K Apr 16 22:28  private_key.pem
-rw-r--r-- 1 mysql mysql  451 Apr 16 22:28  public_key.pem
-rw-r--r-- 1 mysql mysql 1.1K Apr 16 22:28  server-cert.pem
-rw------- 1 mysql mysql 1.7K Apr 16 22:28  server-key.pem

my.cnf

[mysqld]
# SSL
ssl_ca=/usr/local/mysql/data/ca.pem
ssl_cert=/usr/local/mysql/data/server-cert.pem
ssl_key=/usr/local/mysql/data/server-key.pem

Increase Password Security

https://dev.mysql.com/doc/refman/8.0/en/password-security-user.html

CMake output/build directory

It sounds like you want an out of source build. There are a couple of ways you can create an out of source build.

  1. Do what you were doing, run

    cd /path/to/my/build/folder
    cmake /path/to/my/source/folder
    

    which will cause cmake to generate a build tree in /path/to/my/build/folder for the source tree in /path/to/my/source/folder.

    Once you've created it, cmake remembers where the source folder is - so you can rerun cmake on the build tree with

    cmake /path/to/my/build/folder
    

    or even

    cmake .
    

    if your current directory is already the build folder.

  2. For CMake 3.13 or later, use these options to set the source and build folders

    cmake -B/path/to/my/build/folder -S/path/to/my/source/folder
    
  3. For older CMake, use some undocumented options to set the source and build folders:

    cmake -B/path/to/my/build/folder -H/path/to/my/source/folder
    

    which will do exactly the same thing as (1), but without the reliance on the current working directory.

CMake puts all of its outputs in the build tree by default, so unless you are liberally using ${CMAKE_SOURCE_DIR} or ${CMAKE_CURRENT_SOURCE_DIR} in your cmake files, it shouldn't touch your source tree.

The biggest thing that can go wrong is if you have previously generated a build tree in your source tree (i.e. you have an in source build). Once you've done this the second part of (1) above kicks in, and cmake doesn't make any changes to the source or build locations. Thus, you cannot create an out-of-source build for a source directory with an in-source build. You can fix this fairly easily by removing (at a minimum) CMakeCache.txt from the source directory. There are a few other files (mostly in the CMakeFiles directory) that CMake generates that you should remove as well, but these won't cause cmake to treat the source tree as a build tree.

Since out-of-source builds are often more desirable than in-source builds, you might want to modify your cmake to require out of source builds:

# Ensures that we do an out of source build

MACRO(MACRO_ENSURE_OUT_OF_SOURCE_BUILD MSG)
     STRING(COMPARE EQUAL "${CMAKE_SOURCE_DIR}"
     "${CMAKE_BINARY_DIR}" insource)
     GET_FILENAME_COMPONENT(PARENTDIR ${CMAKE_SOURCE_DIR} PATH)
     STRING(COMPARE EQUAL "${CMAKE_SOURCE_DIR}"
     "${PARENTDIR}" insourcesubdir)
    IF(insource OR insourcesubdir)
        MESSAGE(FATAL_ERROR "${MSG}")
    ENDIF(insource OR insourcesubdir)
ENDMACRO(MACRO_ENSURE_OUT_OF_SOURCE_BUILD)

MACRO_ENSURE_OUT_OF_SOURCE_BUILD(
    "${CMAKE_PROJECT_NAME} requires an out of source build."
)

The above macro comes from a commonly used module called MacroOutOfSourceBuild. There are numerous sources for MacroOutOfSourceBuild.cmake on google but I can't seem to find the original and it's short enough to include here in full.

Unfortunately cmake has usually written a few files by the time the macro is invoked, so although it will stop you from actually performing the build you will still need to delete CMakeCache.txt and CMakeFiles.

You may find it useful to set the paths that binaries, shared and static libraries are written to - in which case see how do I make cmake output into a 'bin' dir? (disclaimer, I have the top voted answer on that question...but that's how I know about it).

Twitter bootstrap progress bar animation on page load

In contribution to ellabeauty's answer. you can also use this dynamic percentage values

$('.bar').css('width',  function(){ return ($(this).attr('data-percentage')+'%')});

And probably add custom easing to your css

.bar {
 -webkit-transition: width 2.50s ease !important;
 -moz-transition: width 2.50s ease !important;
   -o-transition: width 2.50s ease !important;
      transition: width 2.50s ease !important;
 }

Setting HttpContext.Current.Session in a unit test

Milox solution is better than the accepted one IMHO but I had some problems with this implementation when handling urls with querystring.

I made some changes to make it work properly with any urls and to avoid Reflection.

public static HttpContext FakeHttpContext(string url)
{
    var uri = new Uri(url);
    var httpRequest = new HttpRequest(string.Empty, uri.ToString(),
                                        uri.Query.TrimStart('?'));
    var stringWriter = new StringWriter();
    var httpResponse = new HttpResponse(stringWriter);
    var httpContext = new HttpContext(httpRequest, httpResponse);

    var sessionContainer = new HttpSessionStateContainer("id",
                                    new SessionStateItemCollection(),
                                    new HttpStaticObjectsCollection(),
                                    10, true, HttpCookieMode.AutoDetect,
                                    SessionStateMode.InProc, false);

    SessionStateUtility.AddHttpSessionStateToContext(
                                         httpContext, sessionContainer);

    return httpContext;
}

How do I upgrade PHP in Mac OS X?

You may want to check out Marc Liyanage's PHP package. It comes in a nice Mac OS X installer package that you can double-click. He keeps it pretty up to date.

http://php-osx.liip.ch/

Also, although upgrading to Snow Leopard won't help you do PHP updates in the future, it will probably give you a newer version of PHP. I'm running OS X 10.6.2 and it has PHP 5.3.0.

How to kill an Android activity when leaving it so that it cannot be accessed from the back button?

Setting android:noHistory="true" on the activity in your manifest will remove an activity from the stack whenever it is navigated away from. see here

How to show DatePickerDialog on Button click?

it works for me. if you want to enable future time for choose, you have to delete maximum date. You need to to do like followings.

 btnDate.setOnClickListener(new View.OnClickListener() {
                       @Override
                       public void onClick(View v) {
                              DialogFragment newFragment = new DatePickerFragment();
                                    newFragment.show(getSupportFragmentManager(), "datePicker");
                            }
                        });

            public static class DatePickerFragment extends DialogFragment
                        implements DatePickerDialog.OnDateSetListener {

                    @Override
                    public Dialog onCreateDialog(Bundle savedInstanceState) {
                        final Calendar c = Calendar.getInstance();
                        int year = c.get(Calendar.YEAR);
                        int month = c.get(Calendar.MONTH);
                        int day = c.get(Calendar.DAY_OF_MONTH);
                        DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
                        dialog.getDatePicker().setMaxDate(c.getTimeInMillis());
                        return  dialog;
                    }

                    public void onDateSet(DatePicker view, int year, int month, int day) {
                       btnDate.setText(ConverterDate.ConvertDate(year, month + 1, day));
                    }
                }

How to get the Touch position in android?

Here is the Koltin style, I use this in my project and it works very well:

this.yourview.setOnTouchListener(View.OnTouchListener { _, event ->
        val x = event.x
        val y = event.y

        when(event.action) {
            MotionEvent.ACTION_DOWN -> {
                Log.d(TAG, "ACTION_DOWN \nx: $x\ny: $y")
            }
            MotionEvent.ACTION_MOVE -> {
                Log.d(TAG, "ACTION_MOVE \nx: $x\ny: $y")
            }
            MotionEvent.ACTION_UP -> {
                Log.d(TAG, "ACTION_UP \nx: $x\ny: $y")
            }
        }
        return@OnTouchListener  true
    })

Google Maps API v3: InfoWindow not sizing correctly

add to css

.gm-style-iw{
    overflow: hidden !important;
}

info window text:

<div style="width: 200px; height:150px;">
  here text of the info window
</div>

Git merge with force overwrite

You can try "ours" option in git merge,

git merge branch -X ours

This option forces conflicting hunks to be auto-resolved cleanly by favoring our version. Changes from the other tree that do not conflict with our side are reflected to the merge result. For a binary file, the entire contents are taken from our side.

Create a CSS rule / class with jQuery at runtime

Here's a setup that gives command over colors with this json object

 "colors": {
    "Backlink": ["rgb(245,245,182)","rgb(160,82,45)"],
    "Blazer": ["rgb(240,240,240)"],
    "Body": ["rgb(192,192,192)"],
    "Tags": ["rgb(182,245,245)","rgb(0,0,0)"],
    "Crosslink": ["rgb(245,245,182)","rgb(160,82,45)"],
    "Key": ["rgb(182,245,182)","rgb(0,118,119)"],
    "Link": ["rgb(245,245,182)","rgb(160,82,45)"],
    "Link1": ["rgb(245,245,182)","rgb(160,82,45)"],
    "Link2": ["rgb(245,245,182)","rgb(160,82,45)"],
    "Manager": ["rgb(182,220,182)","rgb(0,118,119)"],
    "Monitor": ["rgb(255,230,225)","rgb(255,80,230)"],
    "Monitor1": ["rgb(255,230,225)","rgb(255,80,230)"],
    "Name": ["rgb(255,255,255)"],
    "Trail": ["rgb(240,240,240)"],
    "Option": ["rgb(240,240,240)","rgb(150,150,150)"]
  }

this function

 function colors(fig){
    var html,k,v,entry,
    html = []
    $.each(fig.colors,function(k,v){
        entry  = "." + k ;
        entry += "{ background-color :"+ v[0]+";";
        if(v[1]) entry += " color :"+ v[1]+";";
        entry += "}"
        html.push(entry)
    });
    $("head").append($(document.createElement("style"))
        .html(html.join("\n"))
    )
}

to produce this style element

.Backlink{ background-color :rgb(245,245,182); color :rgb(160,82,45);}
.Blazer{ background-color :rgb(240,240,240);}
.Body{ background-color :rgb(192,192,192);}
.Tags{ background-color :rgb(182,245,245); color :rgb(0,0,0);}
.Crosslink{ background-color :rgb(245,245,182); color :rgb(160,82,45);}
.Key{ background-color :rgb(182,245,182); color :rgb(0,118,119);}
.Link{ background-color :rgb(245,245,182); color :rgb(160,82,45);}
.Link1{ background-color :rgb(245,245,182); color :rgb(160,82,45);}
.Link2{ background-color :rgb(245,245,182); color :rgb(160,82,45);}
.Manager{ background-color :rgb(182,220,182); color :rgb(0,118,119);}
.Monitor{ background-color :rgb(255,230,225); color :rgb(255,80,230);}
.Monitor1{ background-color :rgb(255,230,225); color :rgb(255,80,230);}
.Name{ background-color :rgb(255,255,255);}
.Trail{ background-color :rgb(240,240,240);}
.Option{ background-color :rgb(240,240,240); color :rgb(150,150,150);}

Is there a naming convention for MySQL?

Consistency is the key to any naming standard. As long as it's logical and consistent, you're 99% there.

The standard itself is very much personal preference - so if you like your standard, then run with it.

To answer your question outright - no, MySQL doesn't have a preferred naming convention/standard, so rolling your own is fine (and yours seems logical).

String method cannot be found in a main class method

It seem like your Resort method doesn't declare a compareTo method. This method typically belongs to the Comparable interface. Make sure your class implements it.

Additionally, the compareTo method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String argument, but rather a Resort.

Alternatively, you can compare the names of the resorts. For example

if (resortList[mid].getResortName().compareTo(resortName)>0)  

Behaviour of increment and decrement operators in Python

Python does not have these operators, but if you really need them you can write a function having the same functionality.

def PreIncrement(name, local={}):
    #Equivalent to ++name
    if name in local:
        local[name]+=1
        return local[name]
    globals()[name]+=1
    return globals()[name]

def PostIncrement(name, local={}):
    #Equivalent to name++
    if name in local:
        local[name]+=1
        return local[name]-1
    globals()[name]+=1
    return globals()[name]-1

Usage:

x = 1
y = PreIncrement('x') #y and x are both 2
a = 1
b = PostIncrement('a') #b is 1 and a is 2

Inside a function you have to add locals() as a second argument if you want to change local variable, otherwise it will try to change global.

x = 1
def test():
    x = 10
    y = PreIncrement('x') #y will be 2, local x will be still 10 and global x will be changed to 2
    z = PreIncrement('x', locals()) #z will be 11, local x will be 11 and global x will be unaltered
test()

Also with these functions you can do:

x = 1
print(PreIncrement('x'))   #print(x+=1) is illegal!

But in my opinion following approach is much clearer:

x = 1
x+=1
print(x)

Decrement operators:

def PreDecrement(name, local={}):
    #Equivalent to --name
    if name in local:
        local[name]-=1
        return local[name]
    globals()[name]-=1
    return globals()[name]

def PostDecrement(name, local={}):
    #Equivalent to name--
    if name in local:
        local[name]-=1
        return local[name]+1
    globals()[name]-=1
    return globals()[name]+1

I used these functions in my module translating javascript to python.

How to change a dataframe column from String type to Double type in PySpark?

Preserve the name of the column and avoid extra column addition by using the same name as input column:

changedTypedf = joindf.withColumn("show", joindf["show"].cast(DoubleType()))

How do I find the CPU and RAM usage using PowerShell?

I have combined all the above answers into a script that polls the counters and writes the measurements in the terminal:

$totalRam = (Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property capacity -Sum).Sum
while($true) {
    $date = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $cpuTime = (Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples.CookedValue
    $availMem = (Get-Counter '\Memory\Available MBytes').CounterSamples.CookedValue
    $date + ' > CPU: ' + $cpuTime.ToString("#,0.000") + '%, Avail. Mem.: ' + $availMem.ToString("N0") + 'MB (' + (104857600 * $availMem / $totalRam).ToString("#,0.0") + '%)'
    Start-Sleep -s 2
}

This produces the following output:

2020-02-01 10:56:55 > CPU: 0.797%, Avail. Mem.: 2,118MB (51.7%)
2020-02-01 10:56:59 > CPU: 0.447%, Avail. Mem.: 2,118MB (51.7%)
2020-02-01 10:57:03 > CPU: 0.089%, Avail. Mem.: 2,118MB (51.7%)
2020-02-01 10:57:07 > CPU: 0.000%, Avail. Mem.: 2,118MB (51.7%)

You can hit Ctrl+C to abort the loop.

So, you can connect to any Windows machine with this command:

Enter-PSSession -ComputerName MyServerName -Credential MyUserName

...paste it in, and run it, to get a "live" measurement. If connecting to the machine doesn't work directly, take a look here.

Recursive query in SQL Server

Try this:

;WITH CTE
AS
(
    SELECT DISTINCT
        M1.Product_ID Group_ID,
        M1.Product_ID
    FROM matches M1
        LEFT JOIN matches M2
            ON M1.Product_Id = M2.matching_Product_Id
    WHERE M2.matching_Product_Id IS NULL
    UNION ALL
    SELECT
        C.Group_ID,
        M.matching_Product_Id
    FROM CTE C
        JOIN matches M
            ON C.Product_ID = M.Product_ID
)
SELECT * FROM CTE ORDER BY Group_ID

You can use OPTION(MAXRECURSION n) to control recursion depth.

SQL FIDDLE DEMO

Load JSON text into class object in c#

This will take a json string and turn it into any class you specify

public static T ConvertJsonToClass<T>(this string json)
    {
        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        return serializer.Deserialize<T>(json);
    }

Input type "number" won't resize

Use an on onkeypress event. Example for a zip code box. It allows a maximum of 5 characters, and checks to make sure input is only numbers.

Nothing beats a server side validation of course, but this is a nifty way to go.

_x000D_
_x000D_
function validInput(e) {_x000D_
  e = (e) ? e : window.event;_x000D_
  a = document.getElementById('zip-code');_x000D_
  cPress = (e.which) ? e.which : e.keyCode;_x000D_
_x000D_
  if (cPress > 31 && (cPress < 48 || cPress > 57)) {_x000D_
    return false;_x000D_
  } else if (a.value.length >= 5) {_x000D_
    return false;_x000D_
  }_x000D_
_x000D_
  return true;_x000D_
}
_x000D_
#zip-code {_x000D_
  overflow: hidden;_x000D_
  width: 60px;_x000D_
}
_x000D_
<label for="zip-code">Zip Code:</label>_x000D_
<input type="number" id="zip-code" name="zip-code" onkeypress="return validInput(event);" required="required">
_x000D_
_x000D_
_x000D_

CSS fill remaining width

I know its quite late to answer this, but I guess it will help anyone ahead.

Well using CSS3 FlexBox. It can be acheived. Make you header as display:flex and divide its entire width into 3 parts. In the first part I have placed the logo, the searchbar in second part and buttons container in last part. apply justify-content: between to the header container and flex-grow:1 to the searchbar. That's it. The sample code is below.

_x000D_
_x000D_
#header {_x000D_
  background-color: #323C3E;_x000D_
  justify-content: space-between;_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
#searchBar, img{_x000D_
  align-self: center;_x000D_
}_x000D_
_x000D_
#searchBar{_x000D_
  flex-grow:1;_x000D_
  background-color: orange;_x000D_
  padding: 10px;_x000D_
}_x000D_
_x000D_
#searchBar input {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.button {_x000D_
  padding: 22px;_x000D_
}_x000D_
_x000D_
.buttonsHolder{_x000D_
  display:flex;_x000D_
}
_x000D_
<div id="header" class="d-flex justify-content-between">_x000D_
    <img src="img/logo.png" />_x000D_
    <div id="searchBar">_x000D_
      <input type="text" />_x000D_
    </div>_x000D_
    <div class="buttonsHolder">_x000D_
      <div class="button orange inline" id="myAccount">_x000D_
        My Account_x000D_
      </div>_x000D_
      <div class="button red inline" id="basket">_x000D_
        Basket (2)_x000D_
      </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Wrapping a react-router Link in an html button

If you are using react-router-dom and material-ui you can use ...

import { Link } from 'react-router-dom'
import Button from '@material-ui/core/Button';

<Button component={Link} to="/open-collective">
  Link
</Button>

You can read more here.

Pass parameters in setInterval function

By far the most practical answer is the one given by tvanfosson, all i can do is give you an updated version with ES6:

setInterval( ()=>{ funca(10,3); }, 500);

Creating a segue programmatically

I thought I would add another possibility. One of the things you can do is you can connect two scenes in a storyboard using a segue that is not attached to an action, and then programmatically trigger the segue inside your view controller. The way you do this, is that you have to drag from the file's owner icon at the bottom of the storyboard scene that is the segueing scene, and right drag to the destination scene. I'll throw in an image to help explain.

enter image description here

A popup will show for "Manual Segue". I picked Push as the type. Tap on the little square and make sure you're in the attributes inspector. Give it an identifier which you will use to refer to it in code.

enter image description here

Ok, next I'm going to segue using a programmatic bar button item. In viewDidLoad or somewhere else I'll create a button item on the navigation bar with this code:

UIBarButtonItem *buttonizeButton = [[UIBarButtonItem alloc] initWithTitle:@"Buttonize"
                                                                    style:UIBarButtonItemStyleDone
                                                                   target:self
                                                                   action:@selector(buttonizeButtonTap:)];
self.navigationItem.rightBarButtonItems = @[buttonizeButton];

Ok, notice that the selector is buttonizeButtonTap:. So write a void method for that button and within that method you will call the segue like this:

-(void)buttonizeButtonTap:(id)sender{
    [self performSegueWithIdentifier:@"Associate" sender:sender];
    }

The sender parameter is required to identify the button when prepareForSegue is called. prepareForSegue is the framework method where you will instantiate your scene and pass it whatever values it will need to do its work. Here's what my method looks like:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"Associate"])
    {
        TranslationQuizAssociateVC *translationQuizAssociateVC = [segue destinationViewController];
        translationQuizAssociateVC.nodeID = self.nodeID; //--pass nodeID from ViewNodeViewController
        translationQuizAssociateVC.contentID = self.contentID;
        translationQuizAssociateVC.index = self.index;
        translationQuizAssociateVC.content = self.content;
    }
}

Ok, just tested it and it works. Hope it helps you.

How to create a temporary directory?

Here is a simple explanation about how to create a temp dir using templates.

  1. Creates a temporary file or directory, safely, and prints its name.
  2. TEMPLATE must contain at least 3 consecutive 'X's in last component.
  3. If TEMPLATE is not specified, it will use tmp.XXXXXXXXXX
  4. directories created are u+rwx, minus umask restrictions.

PARENT_DIR=./temp_dirs # (optional) specify a dir for your tempdirs
mkdir $PARENT_DIR

TEMPLATE_PREFIX='tmp' # prefix of your new tempdir template
TEMPLATE_RANDOM='XXXX' # Increase the Xs for more random characters
TEMPLATE=${PARENT_DIR}/${TEMPLATE_PREFIX}.${TEMPLATE_RANDOM}

# create the tempdir using your custom $TEMPLATE, which may include
# a path such as a parent dir, and assign the new path to a var
NEW_TEMP_DIR_PATH=$(mktemp -d $TEMPLATE)
echo $NEW_TEMP_DIR_PATH

# create the tempdir in parent dir, using default template
# 'tmp.XXXXXXXXXX' and assign the new path to a var
NEW_TEMP_DIR_PATH=$(mktemp -p $PARENT_DIR)
echo $NEW_TEMP_DIR_PATH

# create a tempdir in your systems default tmp path e.g. /tmp 
# using the default template 'tmp.XXXXXXXXXX' and assign path to var
NEW_TEMP_DIR_PATH=$(mktemp -d)
echo $NEW_TEMP_DIR_PATH

# Do whatever you want with your generated temp dir and var holding its path

What's the difference between Cache-Control: max-age=0 and no-cache?

By the way, it's worth noting that some mobile devices, particularly Apple products like iPhone/iPad completely ignore headers like no-cache, no-store, Expires: 0, or whatever else you may try to force them to not re-use expired form pages.

This has caused us no end of headaches as we try to get the issue of a user's iPad say, being left asleep on a page they have reached through a form process, say step 2 of 3, and then the device totally ignores the store/cache directives, and as far as I can tell, simply takes what is a virtual snapshot of the page from its last state, that is, ignoring what it was told explicitly, and, not only that, taking a page that should not be stored, and storing it without actually checking it again, which leads to all kinds of strange Session issues, among other things.

I'm just adding this in case someone comes along and can't figure out why they are getting session errors with particularly iphones and ipads, which seem by far to be the worst offenders in this area.

I've done fairly extensive debugger testing with this issue, and this is my conclusion, the devices ignore these directives completely.

Even in regular use, I've found that some mobiles also totally fail to check for new versions via say, Expires: 0 then checking last modified dates to determine if it should get a new one.

It simply doesn't happen, so what I was forced to do was add query strings to the css/js files I needed to force updates on, which tricks the stupid mobile devices into thinking it's a file it does not have, like: my.css?v=1, then v=2 for a css/js update. This largely works.

User browsers also, by the way, if left to their defaults, as of 2016, as I continuously discover (we do a LOT of changes and updates to our site) also fail to check for last modified dates on such files, but the query string method fixes that issue. This is something I've noticed with clients and office people who tend to use basic normal user defaults on their browsers, and have no awareness of caching issues with css/js etc, almost invariably fail to get the new css/js on change, which means the defaults for their browsers, mostly MSIE / Firefox, are not doing what they are told to do, they ignore changes and ignore last modified dates and do not validate, even with Expires: 0 set explicitly.

This was a good thread with a lot of good technical information, but it's also important to note how bad the support for this stuff is in particularly mobile devices. Every few months I have to add more layers of protection against their failure to follow the header commands they receive, or to properly interpet those commands.

Dynamically generating a QR code with PHP

qrcode-generator on Github. Simplest script and works like charm.

Pros:

  • No third party dependency
  • No limitations for the number of QR code generations

Reset the database (purge all), then seed a database

on Rails 6 you can now do something like

rake db:seed:replant This Truncates tables of each database for current environment and loads the seeds

https://blog.saeloun.com/2019/09/30/rails-6-adds-db-seed-replant-task-and-db-truncate_all.html

$ rails db:seed:replant --trace
** Invoke db:seed:replant (first_time)
** Invoke db:load_config (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute db:load_config
** Invoke db:truncate_all (first_time)
** Invoke db:load_config
** Invoke db:check_protected_environments (first_time)
** Invoke db:load_config
** Execute db:check_protected_environments
** Execute db:truncate_all
** Invoke db:seed (first_time)
** Invoke db:load_config
** Execute db:seed
** Invoke db:abort_if_pending_migrations (first_time)
** Invoke db:load_config
** Execute db:abort_if_pending_migrations
** Execute db:seed:replant

Best way to check if an PowerShell Object exist?

In your particular example perhaps you do not have to perform any checks at all. Is that possible that New-Object return null? I have never seen that. The command should fail in case of a problem and the rest of the code in the example will not be executed. So why should we do that checks at all?

Only in the code like below we need some checks (explicit comparison with $null is the best):

# we just try to get a new object
$ie = $null
try {
    $ie = New-Object -ComObject InternetExplorer.Application
}
catch {
    Write-Warning $_
}

# check and continuation
if ($ie -ne $null) {
    ...
}

How to set image for bar button with swift?

Initialize barbuttonItem like following:

let pauseButton = UIBarButtonItem(image: UIImage(named: "big"),
                                  style: .plain,
                                  target: self,
                                  action: #selector(PlaybackViewController.pause))

How to pass data from 2nd activity to 1st activity when pressed back? - android

and I Have an issue which I wanted to do this sending data type in a Soft Button which I'd made and the softKey which is the default in every Android Device, so I've done this, first I've made an Intent in my "A" Activity:

            Intent intent = new Intent();
            intent.setClass(context, _AddNewEmployee.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivityForResult(intent, 6969);
            setResult(60);

Then in my second Activity, I've declared a Field in my "B" Activity:

private static int resultCode = 40;

then after I made my request successfully or whenever I wanted to tell the "A" Activity that this job is successfully done here change the value of resultCode to the same I've said in "A" Activity which in my case is "60" and then:

private void backToSearchActivityAndRequest() {
    Intent data = new Intent();
    data.putExtra("PhoneNumber", employeePhoneNumber);
    setResult(resultCode, data);
    finish();
}

@Override
public void onBackPressed() {
    backToSearchActivityAndRequest();
}

PS: Remember to remove the Super from the onBackPressed Method if you want this to work properly.

then I should call the onActivityResult Method in my "A" Activity as well:

   @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 6969 && resultCode == 60) {
            if (data != null) {
                    user_mobile = data.getStringExtra("PhoneNumber");
                    numberTextField.setText(user_mobile);
                    getEmployeeByNumber();
            }
        }
    }

that's it, hope it helps you out. #HappyCoding;

How to use XPath preceding-sibling correctly

I also like to build locators from up to bottom like:

//div[contains(@class,'btn-group')][./button[contains(.,'Arcade Reader')]]/button[@name='settings']

It's pretty simple, as we just search btn-group with button[contains(.,'Arcade Reader')] and get it's button[@name='settings']

That's just another option to build xPath locators

What is the profit of searching wrapper element: you can return it by method (example in java) and just build selenium constructions like:

getGroupByName("Arcade Reader").find("button[name='settings']");
getGroupByName("Arcade Reader").find("button[name='delete']");

or even simplify more

getGroupButton("Arcade Reader", "delete").click();

What is "runtime"?

Runtime basically means when program interacts with the hardware and operating system of a machine. C does not have it's own runtime but instead, it requests runtime from an operating system (which is basically a part of ram) to execute itself.

Clearing coverage highlighting in Eclipse

For people who are not able to find the coverage view , follow these steps :

Go to Windows Menu bar > Show View > Other > Type coverage and open it.

enter image description here

Click on Coverage.

To clear highlightings, click on X or XX icon as per convenience.

enter image description here

Java check to see if a variable has been initialized

Instance variables or fields, along with static variables, are assigned default values based on the variable type:

  • int: 0
  • char: \u0000 or 0
  • double: 0.0
  • boolean: false
  • reference: null

Just want to clarify that local variables (ie. declared in block, eg. method, for loop, while loop, try-catch, etc.) are not initialized to default values and must be explicitly initialized.

How can I compare two dates in PHP?

I would'nt do this with PHP. A database should know, what day is today.( use MySQL->NOW() for example ), so it will be very easy to compare within the Query and return the result, without any problems depending on the used Date-Types

SELECT IF(expireDate < NOW(),TRUE,FALSE) as isExpired FROM tableName

How to call a C# function from JavaScript?

.CS File    
    namespace Csharp
    {
      public void CsharpFunction()
      {
        //Code;
      }
    }

    JS code:
    function JSFunction() {
            <%#ProjectName.Csharp.CsharpFunction()%> ;
    }

Note :in JS Function when call your CS page function.... first name of project then name of name space of CS page then function name

Timeout a command in bash without unnecessary delay

Building on @loup's answer...

If you want to timeout a process and silence the kill job/pid output, run:

( (sleep 1 && killall program 2>/dev/null) &) && program --version 

This puts the backgrounded process into a subshell so you don't see the job output.

Cloudfront custom-origin distribution returns 502 "ERROR The request could not be satisfied." for some URLs

I had this error today with Amazon Cloudfront. It was because the cname I used (e.g cdn.example.com) was not added to the distribution settings under "alternate cnames", I only had cdn.example.com forwarded to the cloudfront domain in my site/hosting control panel, but you need to add it to Amazon CloudFront panel too.

How to get base64 encoded data from html image

You can also use the FileReader class :

    var reader = new FileReader();
    reader.onload = function (e) {
        var data = this.result;
    }
    reader.readAsDataURL( file );

How to connect to MongoDB in Windows?

If you are getting these type of errors when running mongod from command line or running mongodb server, enter image description here
then follow these steps,

  1. Create db and log directories in C: drive
    C:/data/db and C:data/log
  2. Create an empty log file in log dir named mongo.log
  3. Run mongod from command line to run the mongodb server or create a batch file on desktop which can run the mongod.exe file from your mongodb installation direction. That way you just have to click the batch file from your desktop and mongodb will start.
  4. If you have 32-bit system, try using --journal with mongod command.

Embedding JavaScript engine into .NET

i believe all the major opensource JS engines (JavaScriptCore, SpiderMonkey, V8, and KJS) provide embedding APIs. The only one I am actually directly familiar with is JavaScriptCore (which is name of the JS engine the SquirrelFish lives in) which provides a pure C API. If memory serves (it's been a while since i used .NET) .NET has fairly good support for linking in C API's.

I'm honestly not sure what the API's for the other engines are like, but I do know that they all provide them.

That said, depending on your purposes JScript.NET may be best, as all of these other engines will require you to include them with your app, as JSC is the only one that actually ships with an OS, but that OS is MacOS :D

Put a Delay in Javascript

Actually only setTimeout is fine for that job and normally you cannot set exact delays with non determined methods as busy loops.

Reducing the gap between a bullet and text in a list item

Reduce text-indent to a negative number to decrease the space between the list item's bullet and its text.

li {
  text-indent: -4px;
}

You can also use margin-left to adjust any space between the list-item's bullet and the edge of its surrounding element.

li {
  margin-left: 24px;
}

Both text-indent and padding-left can add space between the bullet and text, but only text-indent can reduce space to negative.

li { padding-left: -4px; } /* Doesn't work. */

Understanding colors on Android (six characters)

Going off the answer from @BlondeFurious, here is some Java code to get each hexadecimal value from 100% to 0% alpha:

for (double i = 1; i >= 0; i -= 0.01) {
    i = Math.round(i * 100) / 100.0d;
    int alpha = (int) Math.round(i * 255);
    String hex = Integer.toHexString(alpha).toUpperCase();
    if (hex.length() == 1)
        hex = "0" + hex;
    int percent = (int) (i * 100);
    System.out.println(String.format("%d%% — %s", percent, hex));
}

Output:

100% — FF
99% — FC
98% — FA
97% — F7
96% — F5
95% — F2
94% — F0
93% — ED
92% — EB
91% — E8
90% — E6
89% — E3
88% — E0
87% — DE
86% — DB
85% — D9
84% — D6
83% — D4
82% — D1
81% — CF
80% — CC
79% — C9
78% — C7
77% — C4
76% — C2
75% — BF
74% — BD
73% — BA
72% — B8
71% — B5
70% — B3
69% — B0
68% — AD
67% — AB
66% — A8
65% — A6
64% — A3
63% — A1
62% — 9E
61% — 9C
60% — 99
59% — 96
58% — 94
57% — 91
56% — 8F
55% — 8C
54% — 8A
53% — 87
52% — 85
51% — 82
50% — 80
49% — 7D
48% — 7A
47% — 78
46% — 75
45% — 73
44% — 70
43% — 6E
42% — 6B
41% — 69
40% — 66
39% — 63
38% — 61
37% — 5E
36% — 5C
35% — 59
34% — 57
33% — 54
32% — 52
31% — 4F
30% — 4D
29% — 4A
28% — 47
27% — 45
26% — 42
25% — 40
24% — 3D
23% — 3B
22% — 38
21% — 36
20% — 33
19% — 30
18% — 2E
17% — 2B
16% — 29
15% — 26
14% — 24
13% — 21
12% — 1F
11% — 1C
10% — 1A
9% — 17
8% — 14
7% — 12
6% — 0F
5% — 0D
4% — 0A
3% — 08
2% — 05
1% — 03
0% — 00

A JavaScript version is below:

_x000D_
_x000D_
var text = document.getElementById('text');_x000D_
for (var i = 1; i >= 0; i -= 0.01) {_x000D_
    i = Math.round(i * 100) / 100;_x000D_
    var alpha = Math.round(i * 255);_x000D_
    var hex = (alpha + 0x10000).toString(16).substr(-2).toUpperCase();_x000D_
    var perc = Math.round(i * 100);_x000D_
    text.innerHTML += perc + "% — " + hex + " (" + alpha + ")</br>";_x000D_
}
_x000D_
<div id="text"></div>
_x000D_
_x000D_
_x000D_


You can also just Google "number to hex" where 'number' is any value between 0 and 255.

Replace multiple strings at once

Common Mistake

Nearly all answers on this page use cumulative replacement and thus suffer the same flaw where replacement strings are themselves subject to replacement. Here are a couple examples where this pattern fails (h/t @KurokiKaze @derekdreery):

_x000D_
_x000D_
function replaceCumulative(str, find, replace) {_x000D_
  for (var i = 0; i < find.length; i++)_x000D_
    str = str.replace(new RegExp(find[i],"g"), replace[i]);_x000D_
  return str;_x000D_
};_x000D_
_x000D_
// Fails in some cases:_x000D_
console.log( replaceCumulative( "tar pit", ['tar','pit'], ['capitol','house'] ) );_x000D_
console.log( replaceCumulative( "you & me", ['you','me'], ['me','you'] ) );
_x000D_
_x000D_
_x000D_

Solution

_x000D_
_x000D_
function replaceBulk( str, findArray, replaceArray ){_x000D_
  var i, regex = [], map = {}; _x000D_
  for( i=0; i<findArray.length; i++ ){ _x000D_
    regex.push( findArray[i].replace(/([-[\]{}()*+?.\\^$|#,])/g,'\\$1') );_x000D_
    map[findArray[i]] = replaceArray[i]; _x000D_
  }_x000D_
  regex = regex.join('|');_x000D_
  str = str.replace( new RegExp( regex, 'g' ), function(matched){_x000D_
    return map[matched];_x000D_
  });_x000D_
  return str;_x000D_
}_x000D_
_x000D_
// Test:_x000D_
console.log( replaceBulk( "tar pit", ['tar','pit'], ['capitol','house'] ) );_x000D_
console.log( replaceBulk( "you & me", ['you','me'], ['me','you'] ) );
_x000D_
_x000D_
_x000D_

Note:

This is a more compatible variation of @elchininet's solution, which uses map() and Array.indexOf() and thus won't work in IE8 and older.

@elchininet's implementation holds truer to PHP's str_replace(), because it also allows strings as find/replace parameters, and will use the first find array match if there are duplicates (my version will use the last). I didn't accept strings in this implementation because that case is already handled by JS's built-in String.replace().

How do I list loaded plugins in Vim?

:set runtimepath?

This lists the path of all plugins loaded when a file is opened with Vim.

JavaFX and OpenJDK

Also answering this question:

Where can I get pre-built JavaFX libraries for OpenJDK (Windows)

On Linux its not really a problem, but on Windows its not that easy, especially if you want to distribute the JRE.

You can actually use OpenJFX with OpenJDK 8 on windows, you just have to assemble it yourself:

Download the OpenJDK from here: https://github.com/AdoptOpenJDK/openjdk8-releases/releases/tag/jdk8u172-b11

Download OpenJFX from here: https://github.com/SkyLandTW/OpenJFX-binary-windows/releases/tag/v8u172-b11

copy all the files from the OpenFX zip on top of the JDK, voila, you have an OpenJDK with JavaFX.

Update:

Fortunately from Azul there is now a OpenJDK+OpenJFX build which can be downloaded at their community page: https://www.azul.com/downloads/zulu-community/?&version=java-8-lts&os=windows&package=jdk-fx

Delete files or folder recursively on Windows CMD

For completely wiping a folder with native commands and getting a log on what's been done.

here's an unusual way to do it :

let's assume we want to clear the d:\temp dir

mkdir d:\empty
robocopy /mir d:\empty d:\temp
rmdir d:\empty

How do I clone a generic List in Java?

Be advised that Object.clone() has some major problems, and its use is discouraged in most cases. Please see Item 11, from "Effective Java" by Joshua Bloch for a complete answer. I believe you can safely use Object.clone() on primitive type arrays, but apart from that you need to be judicious about properly using and overriding clone. You are probably better off defining a copy constructor or a static factory method that explicitly clones the object according to your semantics.

How to create a string with format?

nothing special

let str = NSString(format:"%d , %f, %ld, %@", INT_VALUE, FLOAT_VALUE, LONG_VALUE, STRING_VALUE)

How can I get an HTTP response body as a string?

Every library I can think of returns a stream. You could use IOUtils.toString() from Apache Commons IO to read an InputStream into a String in one method call. E.g.:

URL url = new URL("http://www.example.com/");
URLConnection con = url.openConnection();
InputStream in = con.getInputStream();
String encoding = con.getContentEncoding();
encoding = encoding == null ? "UTF-8" : encoding;
String body = IOUtils.toString(in, encoding);
System.out.println(body);

Update: I changed the example above to use the content encoding from the response if available. Otherwise it'll default to UTF-8 as a best guess, instead of using the local system default.

Remove a parameter to the URL with JavaScript

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

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

To use it, simply do something like this:

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

The var alteredURL will be the output you desire.

Hope it helps!

Run a single migration file

Looks like at least in the latest Rails release (5.2 at the time of writing) there is one more way of filtering the migrations being ran. One can pass a filter in a SCOPE environment variable which would be then used to select migration files.

Assuming you have two migration files 1_add_foos.rb and 2_add_foos.run_this_one.rb running

SCOPE=run_this_one rails db:migrate:up

will select and run only 2_add_foos.run_this_one.rb. Keep in mind that all migration files matching the scope will be ran.

How do you remove an array element in a foreach loop?

There are already answers which are giving light on how to unset. Rather than repeating code in all your classes make function like below and use it in code whenever required. In business logic, sometimes you don't want to expose some properties. Please see below one liner call to remove

public static function removeKeysFromAssociativeArray($associativeArray, $keysToUnset)
{
    if (empty($associativeArray) || empty($keysToUnset))
        return array();

    foreach ($associativeArray as $key => $arr) {
        if (!is_array($arr)) {
            continue;
        }

        foreach ($keysToUnset as $keyToUnset) {
            if (array_key_exists($keyToUnset, $arr)) {
                unset($arr[$keyToUnset]);
            }
        }
        $associativeArray[$key] = $arr;
    }
    return $associativeArray;
}

Call like:

removeKeysFromAssociativeArray($arrValues, $keysToRemove);

How to remove focus border (outline) around text/input boxes? (Chrome)

This border is used to show that the element is focused (i.e. you can type in the input or press the button with Enter). You can remove it with outline property, though:

textarea:focus, input:focus{
    outline: none;
}

You may want to add some other way for users to know what element has keyboard focus though for usability.

Chrome will also apply highlighting to other elements such as DIV's used as modals. To prevent the highlight on those and all other elements as well, you can do:

*:focus {
    outline: none;
}


?? Accessibility warning

Please notice that removing outline from input is an accessibility bad practice. Users using screen readers will not be able to see where their pointer is focused at. More info at a11yproject

Can a relative sitemap url be used in a robots.txt?

Google crawlers are not smart enough, they can't crawl relative URLs, that's why it's always recommended to use absolute URL's for better crawlability and indexability.

Therefore, you can not use this variation

> sitemap: /sitemap.xml

Recommended syntax is

Sitemap: https://www.yourdomain.com/sitemap.xml

Note:

  • Don't forgot to capitalise the first letter in "sitemap"
  • Don't forgot to put space after "Sitemap:"

JQuery, select first row of table

Ok so if an image in a table is clicked you want the data of the first row of the table this image is in.

//image click stuff here {
$(this). // our image
closest('table'). // Go upwards through our parents untill we hit the table
children('tr:first'); // Select the first row we find

var $row = $(this).closest('table').children('tr:first');

parent() will only get the direct parent, closest should do what we want here. From jQuery docs: Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.

String Resource new line /n not possible?

don't put space after \n, otherwise, it won't work. I don't know the reason, but this trick worked for me pretty well.

Replacement for deprecated sizeWithFont: in iOS 7?

As the @Ayush answer:

As you can see sizeWithFont at Apple Developer site it is deprecated so we need to use sizeWithAttributes.

Well, supposing that in 2019+ you are probably using Swift and String instead of Objective-c and NSString, here's the correct way do get the size of a String with predefined font:

let stringSize = NSString(string: label.text!).size(withAttributes: [.font : UIFont(name: "OpenSans-Regular", size: 15)!])

How to vertically center an image inside of a div element in HTML using CSS?

I've posted about vertical alignment it in cross-browser way (Vertically center multiple boxes with CSS)

Create one-cell table. Only table has cross-browser vertical-align

Remove the last chars of the Java String variable

Another way:

if (s.size > 5) s.reverse.substring(5).reverse

BTW, this is Scala code. May need brackets to work in Java.

Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap

As an alternative you may want to check out BridgeIt at bridgeit.mobi. Open source, it has resolved the browser performance / consistency issue discussed above in that it leverages the standard browser on the device vs. the web-view browser. It also allows you to access the native features without having to worry about app store deployments and/or native containers.

I've used if for simple camera based access and scanner access and it works well for simple apps. Documentation is a bit light. Not sure how it would do on more complex apps.

Retrieving parameters from a URL

In pure Python:

def get_param_from_url(url, param_name):
    return [i.split("=")[-1] for i in url.split("?", 1)[-1].split("&") if i.startswith(param_name + "=")][0]

How to start a Process as administrator mode in C#

Here is an example of run process as administrator without Windows Prompt

  Process p = new Process();
  p.StartInfo.FileName = Server.MapPath("process.exe");
  p.StartInfo.Arguments = "";
  p.StartInfo.UseShellExecute = false;
  p.StartInfo.CreateNoWindow = true;
  p.StartInfo.RedirectStandardOutput = true;
  p.StartInfo.Verb = "runas";
  p.Start();
  p.WaitForExit();

How would I get a cron job to run every 30 minutes?

crontab does not understand "intervals", it only understands "schedule"

valid hours: 0-23 -- valid minutes: 0-59

example #1

30 * * * * your_command

this means "run when the minute of each hour is 30" (would run at: 1:30, 2:30, 3:30, etc)

example #2

*/30 * * * * your_command

this means "run when the minute of each hour is evenly divisible by 30" (would run at: 1:30, 2:00, 2:30, 3:00, etc)

example #3

0,30 * * * * your_command

this means "run when the minute of each hour is 0 or 30" (would run at: 1:30, 2:00, 2:30, 3:00, etc)

it's another way to accomplish the same results as example #2

example #4

19 * * * * your_command

this means "run when the minute of each hour is 19" (would run at: 1:19, 2:19, 3:19, etc)

example #5

*/19 * * * * your_command

this means "run when the minute of each hour is evenly divisible by 19" (would run at: 1:19, 1:38, 1:57, 2:19, 2:38, 2:57 etc)

note: several refinements have been made to this post by various users including the author

How to create a foreign key in phpmyadmin

When you create table than you can give like follows.

CREATE TABLE categories(
cat_id int not null auto_increment primary key,
cat_name varchar(255) not null,
cat_description text
) ENGINE=InnoDB;


CREATE TABLE products(
   prd_id int not null auto_increment primary key,
   prd_name varchar(355) not null,
   prd_price decimal,
   cat_id int not null,
   FOREIGN KEY fk_cat(cat_id)
   REFERENCES categories(cat_id)
   ON UPDATE CASCADE
   ON DELETE RESTRICT
)ENGINE=InnoDB;

and when after the table create like this

   ALTER table_name
    ADD CONSTRAINT constraint_name
    FOREIGN KEY foreign_key_name(columns)
    REFERENCES parent_table(columns)
    ON DELETE action
    ON UPDATE action;

Following on example for it.

CREATE TABLE vendors(
    vdr_id int not null auto_increment primary key,
    vdr_name varchar(255)
)ENGINE=InnoDB;

ALTER TABLE products 
ADD COLUMN vdr_id int not null AFTER cat_id;

To add a foreign key to the products table, you use the following statement:

ALTER TABLE products
ADD FOREIGN KEY fk_vendor(vdr_id)
REFERENCES vendors(vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE;

For drop the key

ALTER TABLE table_name 
DROP FOREIGN KEY constraint_name;

Hope this help to learn FOREIGN keys works

How can I see function arguments in IPython Notebook Server 3?

Shift-Tab works for me to view the dcoumentation

What is the difference between max-device-width and max-width for mobile web?

Don't use device-width/height anymore.

device-width, device-height and device-aspect-ratio are deprecated in Media Queries Level 4: https://developer.mozilla.org/en-US/docs/Web/CSS/@media#Media_features

Just use width/height (without min/max) in combination with orientation & (min/max-)resolution to target specific devices. On mobile width/height should be the same as device-width/height.

HtmlEncode from Class Library

In case you're using SharePoint 2010, using the following line of code will avoid having to reference the whole System.Web library:

Microsoft.SharePoint.Utilities.SPHttpUtility.HtmlEncode(stringToEncode);

"Primary Filegroup is Full" in SQL Server 2008 Standard for no apparent reason

please chceck the type of file growth of the database, if its restricted make it unrestricted

Should I use past or present tense in git commit messages?

Your project should almost always use the past tense. In any case, the project should always use the same tense for consistency and clarity.

I understand some of the other arguments arguing to use the present tense, but they usually don't apply. The following bullet points are common arguments for writing in the present tense, and my response.

  • Writing in the present tense tells someone what applying the commit will do, rather than what you did.

This is the most correct reason one would want to use the present tense, but only with the right style of project. This manner of thinking considers all commits as optional improvements or features, and you are free to decide which commits to keep and which to reject in your particular repository.

This argument works if you are dealing with a truly distributed project. If you are dealing with a distributed project, you are probably working on an open source project. And it is probably a very large project if it is really distributed. In fact, it's probably either the Linux kernel or Git. Since Linux is likely what caused Git to spread and gain in popularity, it's easy to understand why people would consider its style the authority. Yes, the style makes sense with those two projects. Or, in general, it works with large, open source, distributed projects.

That being said, most projects in source control do not work like this. It is usually incorrect for most repositories. It's a modern way of thinking about a commits: Subversion (SVN) and CVS repositories could barely support this style of repository check-ins. Usually an integration branch handled filtering bad check-ins, but those generally weren't considered "optional" or "nice-to-have features".

In most scenarios, when you are making commits to a source repository, you are writing a journal entry which describes what changed with this update, to make it easier for others in the future to understand why a change was made. It generally isn't an optional change - other people in the project are required to either merge or rebase on it. You don't write a diary entry such as "Dear diary, today I meet a boy and he says hello to me.", but instead you write "I met a boy and he said hello to me."

Finally, for such non-distributed projects, 99.99% of the time a person will be reading a commit message is for reading history - history is read in the past tense. 0.01% of the time it will be deciding whether or not they should apply this commit or integrate it into their branch/repository.

  • Consistency. That's how it is in many projects (including git itself). Also git tools that generate commits (like git merge or git revert) do it.

No, I guarantee you that the majority of projects ever logged in a version control system have had their history in the past tense (I don't have references, but it's probably right, considering the present tense argument is new since Git). "Revision" messages or commit messages in the present tense only started making sense in truly distributed projects - see the first point above.

  • People not only read history to know "what happened to this codebase", but also to answer questions like "what happens when I cherry-pick this commit", or "what kind of new things will happen to my code base because of these commits I may or may not merge in the future".

See the first point. 99.99% of the time a person will be reading a commit message is for reading history - history is read in the past tense. 0.01% of the time it will be deciding whether or not they should apply this commit or integrate it into their branch/repository. 99.99% beats 0.01%.

  • It's usually shorter

I've never seen a good argument that says use improper tense/grammar because it's shorter. You'll probably only save 3 characters on average for a standard 50 character message. That being said, the present tense on average will probably be a few characters shorter.

  • You can name commits more consistently with titles of tickets in your issue/feature tracker (which don't use past tense, although sometimes future)

Tickets are written as either something that is currently happening (e.g. the app is showing the wrong behavior when I click this button), or something that needs to be done in the future (e.g. the text will need a review by the editor).

History (i.e. commit messages) is written as something that was done in the past (e.g. the problem was fixed).

python-pandas and databases like mysql

For the record, here is an example using a sqlite database:

import pandas as pd
import sqlite3

with sqlite3.connect("whatever.sqlite") as con:
    sql = "SELECT * FROM table_name"
    df = pd.read_sql_query(sql, con)
    print df.shape

scrollIntoView Scrolls just too far

Fix it in 20 seconds:

This solution belongs to @Arseniy-II, I have just simplified it into a function.

function _scrollTo(selector, yOffset = 0){
  const el = document.querySelector(selector);
  const y = el.getBoundingClientRect().top + window.pageYOffset + yOffset;

  window.scrollTo({top: y, behavior: 'smooth'});
}

Usage (you can open up the console right here in StackOverflow and test it out):

_scrollTo('#question-header', 0);

I'm currently using this in production and it is working just fine.

Difference between Dictionary and Hashtable

The Hashtable class is a specific type of dictionary class that uses an integer value (called a hash) to aid in the storage of its keys. The Hashtable class uses the hash to speed up the searching for a specific key in the collection. Every object in .NET derives from the Object class. This class supports the GetHash method, which returns an integer that uniquely identifies the object. The Hashtable class is a very efficient collection in general. The only issue with the Hashtable class is that it requires a bit of overhead, and for small collections (fewer than ten elements) the overhead can impede performance.

There is Some special difference between two which must be considered:

HashTable: is non-generic collection ,the biggest overhead of this collection is that it does boxing automatically for your values and in order to get your original value you need to perform unboxing , these to decrease your application performance as penalty.

Dictionary: This is generic type of collection where no implicit boxing, so no need to unboxing you will always get your original values which you were stored so it will improve your application performance.

the Second Considerable difference is:

if your were trying to access a value on from hash table on the basis of key that does not exist it will return null.But in the case of Dictionary it will give you KeyNotFoundException.

How to make custom error pages work in ASP.NET MVC 4

I do something that requires less coding than the other solutions posted.

First, in my web.config, I have the following:

<customErrors mode="On" defaultRedirect="~/ErrorPage/Oops">
   <error redirect="~/ErrorPage/Oops/404" statusCode="404" />
   <error redirect="~/ErrorPage/Oops/500" statusCode="500" />
</customErrors>

And the controller (/Controllers/ErrorPageController.cs) contains the following:

public class ErrorPageController : Controller
{
    public ActionResult Oops(int id)
    {
        Response.StatusCode = id;

        return View();
    }
}

And finally, the view contains the following (stripped down for simplicity, but it can conta:

_x000D_
_x000D_
@{ ViewBag.Title = "Oops! Error Encountered"; }_x000D_
_x000D_
<section id="Page">_x000D_
  <div class="col-xs-12 well">_x000D_
    <table cellspacing="5" cellpadding="3" style="background-color:#fff;width:100%;" class="table-responsive">_x000D_
      <tbody>_x000D_
        <tr>_x000D_
          <td valign="top" align="left" id="tableProps">_x000D_
            <img width="25" height="33" src="~/Images/PageError.gif" id="pagerrorImg">_x000D_
          </td>_x000D_
          <td width="360" valign="middle" align="left" id="tableProps2">_x000D_
            <h1 style="COLOR: black; FONT: 13pt/15pt verdana" id="errortype"><span id="errorText">@Response.Status</span></h1>_x000D_
          </td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td width="400" colspan="2" id="tablePropsWidth"><font style="COLOR: black; FONT: 8pt/11pt verdana">Possible causes:</font>_x000D_
          </td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td width="400" colspan="2" id="tablePropsWidth2">_x000D_
            <font style="COLOR: black; FONT: 8pt/11pt verdana" id="LID1">_x000D_
                            <hr>_x000D_
                            <ul>_x000D_
                                <li id="list1">_x000D_
                                    <span class="infotext">_x000D_
                                        <strong>Baptist explanation: </strong>There_x000D_
                                        must be sin in your life. Everyone else opened it fine.<br>_x000D_
                                    </span>_x000D_
                                </li>_x000D_
                                <li>_x000D_
                                    <span class="infotext">_x000D_
                                        <strong>Presbyterian explanation: </strong>It's_x000D_
                                        not God's will for you to open this link.<br>_x000D_
                                    </span>_x000D_
                                </li>_x000D_
                                <li>_x000D_
                                    <span class="infotext">_x000D_
                                        <strong> Word of Faith explanation:</strong>_x000D_
                                        You lack the faith to open this link. Your negative words have prevented_x000D_
                                        you from realizing this link's fulfillment.<br>_x000D_
                                    </span>_x000D_
                                </li>_x000D_
                                <li>_x000D_
                                    <span class="infotext">_x000D_
                                        <strong>Charismatic explanation: </strong>Thou_x000D_
                                        art loosed! Be commanded to OPEN!<br>_x000D_
                                    </span>_x000D_
                                </li>_x000D_
                                <li>_x000D_
                                    <span class="infotext">_x000D_
                                        <strong>Unitarian explanation:</strong> All_x000D_
                                        links are equal, so if this link doesn't work for you, feel free to_x000D_
                                        experiment with other links that might bring you joy and fulfillment.<br>_x000D_
                                    </span>_x000D_
                                </li>_x000D_
                                <li>_x000D_
                                    <span class="infotext">_x000D_
                                        <strong>Buddhist explanation:</strong> .........................<br>_x000D_
                                    </span>_x000D_
                                </li>_x000D_
                                <li>_x000D_
                                    <span class="infotext">_x000D_
                                        <strong>Episcopalian explanation:</strong>_x000D_
                                        Are you saying you have something against homosexuals?<br>_x000D_
                                    </span>_x000D_
                                </li>_x000D_
                                <li>_x000D_
                                    <span class="infotext">_x000D_
                                        <strong>Christian Science explanation: </strong>There_x000D_
                                        really is no link.<br>_x000D_
                                    </span>_x000D_
                                </li>_x000D_
                                <li>_x000D_
                                    <span class="infotext">_x000D_
                                        <strong>Atheist explanation: </strong>The only_x000D_
                                        reason you think this link exists is because you needed to invent it.<br>_x000D_
                                    </span>_x000D_
                                </li>_x000D_
                                <li>_x000D_
                                    <span class="infotext">_x000D_
                                        <strong>Church counselor's explanation:</strong>_x000D_
                                        And what did you feel when the link would not open?_x000D_
                                    </span>_x000D_
                                </li>_x000D_
                            </ul>_x000D_
                            <p>_x000D_
                                <br>_x000D_
                            </p>_x000D_
                            <h2 style="font:8pt/11pt verdana; color:black" id="ietext">_x000D_
                                <img width="16" height="16" align="top" src="~/Images/Search.gif">_x000D_
                                HTTP @Response.StatusCode - @Response.StatusDescription <br>_x000D_
                            </h2>_x000D_
                        </font>_x000D_
          </td>_x000D_
        </tr>_x000D_
      </tbody>_x000D_
    </table>_x000D_
  </div>_x000D_
</section>
_x000D_
_x000D_
_x000D_

It's just as simple as that. It could be easily extended to offer more detailed error info, but ELMAH handles that for me & the statusCode & statusDescription is all that I usually need.

How to get the absolute coordinates of a view

Use This code to find exact X and Y cordinates :

int[] array = new int[2];
ViewForWhichLocationIsToBeFound.getLocationOnScreen(array);
if (AppConstants.DEBUG)
    Log.d(AppConstants.TAG, "array  X = " + array[0] + ", Y = " + array[1]);
ViewWhichToBeMovedOnFoundLocation.setTranslationX(array[0] + 21);
ViewWhichToBeMovedOnFoundLocation.setTranslationY(array[1] - 165);

I have added/subtracted some values to adjust my view. Please do these lines only after whole view has been inflated.

How to get the Enum Index value in C#

You can directly cast it:

enum MyMonthEnum { January = 1, February, March, April, May, June, July, August, September, October, November, December };

public static string GetMyMonthName(int MonthIndex)
{
  MyMonthEnum MonthName = (MyMonthEnum)MonthIndex;
  return MonthName.ToString();
}

For Example:

string MySelectedMonthName=GetMyMonthName(8);
 //then MySelectedMonthName value will be August.

Command to change the default home directory of a user

You can do it with:

/etc/passwd

Edit the user home directory and then move the required files and directories to it:

cp/mv -r /home/$user/.bash* /home/newdir

.bash_profile
.ssh/ 

Set the correct permission

chmod -R $user:$user /home/newdir/.bash*

Apply CSS Style to child elements

The > selector matches direct children only, not descendants.

You want

div.test th, td, caption {}

or more likely

div.test th, div.test td, div.test caption {}

Edit:

The first one says

  div.test th, /* any <th> underneath a <div class="test"> */
  td,          /* or any <td> anywhere at all */
  caption      /* or any <caption> */

Whereas the second says

  div.test th,     /* any <th> underneath a <div class="test"> */
  div.test td,     /* or any <td> underneath a <div class="test"> */
  div.test caption /* or any <caption> underneath a <div class="test">  */

In your original the div.test > th says any <th> which is a **direct** child of <div class="test">, which means it will match <div class="test"><th>this</th></div> but won't match <div class="test"><table><th>this</th></table></div>

Search File And Find Exact Match And Print Line?

you should use regular expressions to find all you need:

import re
p = re.compile(r'(\d+)')  # a pattern for a number

for line in file :
    if num in p.findall(line) :
        print line

regular expression will return you all numbers in a line as a list, for example:

>>> re.compile(r'(\d+)').findall('123kh234hi56h9234hj29kjh290')
['123', '234', '56', '9234', '29', '290']

so you don't match '200' or '220' for '20'.

Converting a PDF to PNG

For a PDF that ImageMagick was giving inaccurate colors I found that GraphicsMagick did a better job:

$ gm convert -quality 100 -thumbnail x300 -flatten journal.pdf\[0\] cover.jpg

PowerShell on Windows 7: Set-ExecutionPolicy for regular users

Set-ExecutionPolicy Unrestricted -Scope CurrentUser

This will set the execution policy for the current user (stored in HKEY_CURRENT_USER) rather than the local machine (HKEY_LOCAL_MACHINE). This is useful if you don't have administrative control over the computer.

Adding new column to existing DataFrame in Python pandas

To add a new column, 'e', to the existing data frame

 df1.loc[:,'e'] = Series(np.random.randn(sLength))

Cygwin - Makefile-error: recipe for target `main.o' failed

You see the two empty -D entries in the g++ command line? They're causing the problem. You must have values in the -D items e.g. -DWIN32

if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:

SYSTEM ?= generic
ENVIRONMENT ?= generic

in the makefile which gives them default values.

Your output looks to be missing the all important output:

<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers

just to clarify, what actually got sent to g++ was -D -DWindows_NT, i.e. define a preprocessor macro called -DWindows_NT; which is of course not a valid identifier (similarly for -D -I.)

Why does the Visual Studio editor show dots in blank spaces?

In Visual Studio vesrion 1.34.0 View -> Toggle Render Whitespace

What does += mean in Python?

a += b is essentially the same as a = a + b, except that:

  • + always returns a newly allocated object, but += should (but doesn't have to) modify the object in-place if it's mutable (e.g. list or dict, but int and str are immutable).

  • In a = a + b, a is evaluated twice.

  • Python: Simple Statements

    • A simple statement is comprised within a single logical line.

If this is the first time you encounter the += operator, you may wonder why it matters that it may modify the object in-place instead of building a new one. Here is an example:

# two variables referring to the same list
>>> list1 = []
>>> list2 = list1

# += modifies the object pointed to by list1 and list2
>>> list1 += [0]
>>> list1, list2
([0], [0])

# + creates a new, independent object
>>> list1 = []
>>> list2 = list1
>>> list1 = list1 + [0]
>>> list1, list2
([0], [])

Example of waitpid() in use?

Syntax of waitpid():

pid_t waitpid(pid_t pid, int *status, int options);

The value of pid can be:

  • < -1: Wait for any child process whose process group ID is equal to the absolute value of pid.
  • -1: Wait for any child process.
  • 0: Wait for any child process whose process group ID is equal to that of the calling process.
  • > 0: Wait for the child whose process ID is equal to the value of pid.

The value of options is an OR of zero or more of the following constants:

  • WNOHANG: Return immediately if no child has exited.
  • WUNTRACED: Also return if a child has stopped. Status for traced children which have stopped is provided even if this option is not specified.
  • WCONTINUED: Also return if a stopped child has been resumed by delivery of SIGCONT.

For more help, use man waitpid.

No Multiline Lambda in Python: Why not?

In Python 3.8/3.9 there is Assignment Expression, so it could be used in lambda, greatly expanding functionality

E.g., code

#%%
x = 1
y = 2

q = list(map(lambda t: (tx := t*x, ty := t*y, tx+ty)[-1], [1, 2, 3]))

print(q)

will print [3, 6, 9]

Doctrine - How to print out the real sql, not just the prepared statement?

$sql = $query->getSQL();
$obj->mapDQLParametersNamesToSQL($query->getDQL(), $sql);
echo $sql;//to see parameters names in sql
$obj->mapDQLParametersValuesToSQL($query->getParameters(), $sql);
echo $sql;//to see parameters values in sql

public function mapDQLParametersNamesToSQL($dql, &$sql)
{
    $matches = [];
    $parameterNamePattern = '/:\w+/';
    /** Found parameter names in DQL */
    preg_match_all($parameterNamePattern, $dql, $matches);
    if (empty($matches[0])) {
        return;
    }
    $needle = '?';
    foreach ($matches[0] as $match) {
        $strPos = strpos($sql, $needle);
        if ($strPos !== false) {
            /** Paste parameter names in SQL */
            $sql = substr_replace($sql, $match, $strPos, strlen($needle));
        }
    }
}

public function mapDQLParametersValuesToSQL($parameters, &$sql)
{
    $matches = [];
    $parameterNamePattern = '/:\w+/';
    /** Found parameter names in SQL */
    preg_match_all($parameterNamePattern, $sql, $matches);
    if (empty($matches[0])) {
        return;
    }
    foreach ($matches[0] as $parameterName) {
        $strPos = strpos($sql, $parameterName);
        if ($strPos !== false) {
            foreach ($parameters as $parameter) {
                /** @var \Doctrine\ORM\Query\Parameter $parameter */
                if ($parameterName !== ':' . $parameter->getName()) {
                    continue;
                }
                $parameterValue = $parameter->getValue();
                if (is_string($parameterValue)) {
                    $parameterValue = "'$parameterValue'";
                }
                if (is_array($parameterValue)) {
                    foreach ($parameterValue as $key => $value) {
                        if (is_string($value)) {
                            $parameterValue[$key] = "'$value'";
                        }
                    }
                    $parameterValue = implode(', ', $parameterValue);
                }
                /** Paste parameter values in SQL */
                $sql = substr_replace($sql, $parameterValue, $strPos, strlen($parameterName));
            }
        }
    }
}

Aborting a stash pop in Git

Simple one-liner

I have always used

git reset --merge

I can't remember it ever failing.

"if not exist" command in batch file

When testing for directories remember that every directory contains two special files.

One is called '.' and the other '..'

. is the directory's own name while .. is the name of it's parent directory.

To avoid trailing backslash problems just test to see if the directory knows it's own name.

eg:

if not exist %temp%\buffer\. mkdir %temp%\buffer

Makefile If-Then Else and Loops

Have you tried the GNU make documentation? It has a whole section about conditionals with examples.

python multithreading wait till all threads finished

You can have class something like below from which you can add 'n' number of functions or console_scripts you want to execute in parallel passion and start the execution and wait for all jobs to complete..

from multiprocessing import Process

class ProcessParallel(object):
    """
    To Process the  functions parallely

    """    
    def __init__(self, *jobs):
        """
        """
        self.jobs = jobs
        self.processes = []

    def fork_processes(self):
        """
        Creates the process objects for given function deligates
        """
        for job in self.jobs:
            proc  = Process(target=job)
            self.processes.append(proc)

    def start_all(self):
        """
        Starts the functions process all together.
        """
        for proc in self.processes:
            proc.start()

    def join_all(self):
        """
        Waits untill all the functions executed.
        """
        for proc in self.processes:
            proc.join()


def two_sum(a=2, b=2):
    return a + b

def multiply(a=2, b=2):
    return a * b


#How to run:
if __name__ == '__main__':
    #note: two_sum, multiply can be replace with any python console scripts which
    #you wanted to run parallel..
    procs =  ProcessParallel(two_sum, multiply)
    #Add all the process in list
    procs.fork_processes()
    #starts  process execution 
    procs.start_all()
    #wait until all the process got executed
    procs.join_all()

ActiveModel::ForbiddenAttributesError when creating new user

If you are on Rails 4 and you get this error, it could happen if you are using enum on the model if you've defined with symbols like this:

class User
  enum preferred_phone: [:home_phone, :mobile_phone, :work_phone]
end

The form will pass say a radio selector as a string param. That's what happened in my case. The simple fix is to change enum to strings instead of symbols

enum preferred_phone: %w[home_phone mobile_phone work_phone]
# or more verbose
enum preferred_phone: ['home_phone', 'mobile_phone', 'work_phone']

How can I truncate a double to only two decimal places in Java?

Here is the method I use:

double a=3.545555555; // just assigning your decimal to a variable
a=a*100;              // this sets a to 354.555555
a=Math.floor(a);      // this sets a to 354
a=a/100;              // this sets a to 3.54 and thus removing all your 5's

This can also be done:

a=Math.floor(a*100) / 100;

Set auto height and width in CSS/HTML for different screen sizes

Using bootstrap with a little bit of customization, the following seems to work for me:

I need 3 partitions in my container and I tried this:

CSS:

.row.content {height: 100%; width:100%; position: fixed; }
.sidenav {
  padding-top: 20px;
  border: 1px solid #cecece;
  height: 100%;
}
.midnav {
  padding: 0px;
}

HTML:

  <div class="container-fluid text-center"> 
    <div class="row content">
    <div class="col-md-2 sidenav text-left">Some content 1</div>
    <div class="col-md-9 midnav text-left">Some content 2</div>
    <div class="col-md-1 sidenav text-center">Some content 3</div>
    </div>
  </div>

Jquery set radio button checked, using id and class selectors

"...by a class and a div."

I assume when you say "div" you mean "id"? Try this:

$('#test2.test1').prop('checked', true);

No need to muck about with your [attributename=value] style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".

Or more generally to select an input where you want to specify a multiple attribute selector:

$('input:radio[class=test1][id=test2]').prop('checked', true);

That is, list each attribute with its own square brackets.

Note that unless you have a pretty old version of jQuery you should use .prop() rather than .attr() for this purpose.

Declare a variable as Decimal

To declare a variable as a Decimal, first declare it as a Variant and then convert to Decimal with CDec. The type would be Variant/Decimal in the watch window:

enter image description here

Considering that programming floating point arithmetic is not what one has studied during Maths classes at school, one should always try to avoid common pitfalls by converting to decimal whenever possible.

In the example below, we see that the expression:

0.1 + 0.11 = 0.21

is either True or False, depending on whether the collectibles (0.1,0.11) are declared as Double or as Decimal:

Public Sub TestMe()

    Dim preciseA As Variant: preciseA = CDec(0.1)
    Dim preciseB As Variant: preciseB = CDec(0.11)

    Dim notPreciseA As Double: notPreciseA = 0.1
    Dim notPreciseB As Double: notPreciseB = 0.11

    Debug.Print preciseA + preciseB
    Debug.Print preciseA + preciseB = 0.21 'True

    Debug.Print notPreciseA + notPreciseB
    Debug.Print notPreciseA + notPreciseB = 0.21 'False

End Sub

enter image description here

How do I trim whitespace?

(re.sub(' +', ' ',(my_str.replace('\n',' ')))).strip()

This will remove all the unwanted spaces and newline characters. Hope this help

import re
my_str = '   a     b \n c   '
formatted_str = (re.sub(' +', ' ',(my_str.replace('\n',' ')))).strip()

This will result :

' a      b \n c ' will be changed to 'a b c'

Fix columns in horizontal scrolling

SOLVED

http://jsfiddle.net/DJqPf/7/

.table-wrapper { 
    overflow-x:scroll;
    overflow-y:visible;
    width:250px;
    margin-left: 120px;
}
td, th {
    padding: 5px 20px;
    width: 100px;
}
th:first-child {
    position: fixed;
    left: 5px
}

UPDATE

_x000D_
_x000D_
$(function () {  _x000D_
  $('.table-wrapper tr').each(function () {_x000D_
    var tr = $(this),_x000D_
        h = 0;_x000D_
    tr.children().each(function () {_x000D_
      var td = $(this),_x000D_
          tdh = td.height();_x000D_
      if (tdh > h) h = tdh;_x000D_
    });_x000D_
    tr.css({height: h + 'px'});_x000D_
  });_x000D_
});
_x000D_
body {_x000D_
    position: relative;_x000D_
}_x000D_
.table-wrapper { _x000D_
    overflow-x:scroll;_x000D_
    overflow-y:visible;_x000D_
    width:200px;_x000D_
    margin-left: 120px;_x000D_
}_x000D_
_x000D_
_x000D_
td, th {_x000D_
    padding: 5px 20px;_x000D_
    width: 100px;_x000D_
}_x000D_
tbody tr {_x000D_
  _x000D_
}_x000D_
th:first-child {_x000D_
    position: absolute;_x000D_
    left: 5px_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>_x000D_
  <meta charset="utf-8">_x000D_
  <title>JS Bin</title>_x000D_
</head>_x000D_
<body>_x000D_
<div>_x000D_
    <h1>SOME RANDOM TEXT</h1>_x000D_
</div>_x000D_
<div class="table-wrapper">_x000D_
    <table id="consumption-data" class="data">_x000D_
        <thead class="header">_x000D_
            <tr>_x000D_
                <th>Month</th>_x000D_
                <th>Item 1</th>_x000D_
                <th>Item 2</th>_x000D_
                <th>Item 3</th>_x000D_
                <th>Item 4</th>_x000D_
            </tr>_x000D_
        </thead>_x000D_
        <tbody class="results">_x000D_
            <tr>_x000D_
                <th>Jan is an awesome month</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Feb</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Mar</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Apr</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>  _x000D_
            </tr>_x000D_
            <tr>    _x000D_
                <th>May</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Jun</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
_x000D_
            <tr>_x000D_
                <th>...</th>_x000D_
                <td>...</td>_x000D_
                <td>...</td>_x000D_
                <td>...</td>_x000D_
                <td>...</td>_x000D_
            </tr>_x000D_
        </tbody>_x000D_
    </table>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Where does Console.WriteLine go in ASP.NET?

If you look at the Console class in .NET Reflector, you'll find that if a process doesn't have an associated console, Console.Out and Console.Error are backed by Stream.Null (wrapped inside a TextWriter), which is a dummy implementation of Stream that basically ignores all input, and gives no output.

So it is conceptually equivalent to /dev/null, but the implementation is more streamlined: there's no actual I/O taking place with the null device.

Also, apart from calling SetOut, there is no way to configure the default.

Update 2020-11-02: As this answer is still gathering votes in 2020, it should probably be noted that under ASP.NET Core, there usually is a console attached. You can configure the ASP.NET Core IIS Module to redirect all stdout and stderr output to a log file via the stdoutLogEnabled and stdoutLogFile settings:

<system.webServer>
  <aspNetCore processPath="dotnet"
              arguments=".\MyApp.dll"
              hostingModel="inprocess"
              stdoutLogEnabled="true"
              stdoutLogFile=".\logs\stdout" />
<system.webServer>

How to subtract a day from a date?

Subtract datetime.timedelta(days=1)

html <input type="text" /> onchange event not working

I encountered issues where Safari wasn't firing "onchange" events on a text input field. I used a jQuery 1.7.2 "change" event and it didn't work either. I ended up using ZURB's textchange event. It works with mouseevents and can fire without leaving the field:
http://www.zurb.com/playground/jquery-text-change-custom-event

$('.inputClassToBind').bind('textchange', function (event, previousText) {
    alert($(this).attr('id'));
});

PHP Get name of current directory

getcwd();

or

dirname(__FILE__);

or (PHP5)

basename(__DIR__) 

http://php.net/manual/en/function.getcwd.php

http://php.net/manual/en/function.dirname.php

You can use basename() to get the trailing part of the path :)

In your case, I'd say you are most likely looking to use getcwd(), dirname(__FILE__) is more useful when you have a file that needs to include another library and is included in another library.

Eg:

main.php
libs/common.php
libs/images/editor.php

In your common.php you need to use functions in editor.php, so you use

common.php:

require_once dirname(__FILE__) . '/images/editor.php';

main.php:

require_once libs/common.php

That way when common.php is require'd in main.php, the call of require_once in common.php will correctly includes editor.php in images/editor.php instead of trying to look in current directory where main.php is run.

How to initialize an array in angular2 and typescript

hi @JackSlayer94 please find the below example to understand how to make an array of size 5.

_x000D_
_x000D_
class Hero {_x000D_
    name: string;_x000D_
    constructor(text: string) {_x000D_
        this.name = text;_x000D_
    }_x000D_
_x000D_
    display() {_x000D_
        return "Hello, " + this.name;_x000D_
    }_x000D_
_x000D_
}_x000D_
_x000D_
let heros:Hero[] = new Array(5);_x000D_
for (let i = 0; i < 5; i++){_x000D_
    heros[i] = new Hero("Name: " + i);_x000D_
}_x000D_
_x000D_
for (let i = 0; i < 5; i++){_x000D_
    console.log(heros[i].display());_x000D_
}
_x000D_
_x000D_
_x000D_

Get column index from column name in python pandas

In case you want the column name from the column location (the other way around to the OP question), you can use:

>>> df.columns.get_values()[location]

Using @DSM Example:

>>> df = DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})

>>> df.columns

Index(['apple', 'orange', 'pear'], dtype='object')

>>> df.columns.get_values()[1]

'orange'

Other ways:

df.iloc[:,1].name

df.columns[location] #(thanks to @roobie-nuby for pointing that out in comments.) 

How to hide columns in HTML table?

You can use the nth-child CSS selector to hide a whole column:

#myTable tr > *:nth-child(2) {
    display: none;
}

This works under assumption that a cell of column N (be it a th or td) is always the Nth child element of its row.

Here's a demo.


? If you want the column number to be dynamic, you could do that using querySelectorAll or any framework presenting similar functionality, like jQuery here:

$('#myTable tr > *:nth-child(2)').hide();

Demo with jQuery

(The jQuery solution also works on legacy browsers that don't support nth-child).

Javascript string/integer comparisons

Comparing Numbers to String Equivalents Without Using parseInt

console.log(Number('2') > Number('10'));
console.log( ('2'/1) > ('10'/1) );

var item = { id: 998 }, id = '998';
var isEqual = (item.id.toString() === id.toString());
isEqual;

How to remove entry from $PATH on mac

Use sudo pico /etc/paths inside the terminal window and change the entries to the one you want to remove, then open a new terminal session.

How to display svg icons(.svg files) in UI using React Component?

if you have .svg or an image locally. first you have to install the loader needed for svg and file-loader for images. Then you have to import your icon or image first for example:

import logo from './logos/myLogo.svg' ;
import image from './images/myimage.png';

const temp = (
     <div>
         <img src={logo} />
         <img src={image} />
     </div>
);

ReactDOM.render(temp,document.getElementByID("app"));

Happy Coding :")

resources from react website and worked for me after many searches: https://create-react-app.dev/docs/adding-images-fonts-and-files/

std::queue iteration

I use something like this. Not very sophisticated but should work.

    queue<int> tem; 

    while(!q1.empty()) // q1 is your initial queue. 
    {
        int u = q1.front(); 

        // do what you need to do with this value.  

        q1.pop(); 
        tem.push(u); 
    }


    while(!tem.empty())
    {
        int u = tem.front(); 
        tem.pop(); 
        q1.push(u); // putting it back in our original queue. 
    }

It will work because when you pop something from q1, and push it into tem, it becomes the first element of tem. So, in the end tem becomes a replica of q1.

How to catch exception output from Python subprocess.check_output()?

This did the trick for me. It captures all the stdout output from the subprocess(For python 3.8):

from subprocess import check_output, STDOUT
cmd = "Your Command goes here"
try:
    cmd_stdout = check_output(cmd, stderr=STDOUT, shell=True).decode()
except Exception as e:
    print(e.output.decode()) # print out the stdout messages up to the exception
    print(e) # To print out the exception message

How to find where gem files are installed

if you are using rvm tool you can run this command to print gem path:

rvm gemdir

OR

echo $GEM_HOME

com.sun.jdi.InvocationException occurred invoking method

Well, it might be because of several things as mentioned by others before and after. In my case the problem was same but reason was something else.

In a class (A), I had several objects and one of object was another class (B) with some other objects. During the process, one of the object (String) from class B was null, and then I tried to access that object via parent class (A).

Thus, console will throw null point exception but eclipse debugger will show above mentioned error.

I hope you can do the remaining.

"Cannot allocate an object of abstract type" error

In C++ a class with at least one pure virtual function is called abstract class. You can not create objects of that class, but may only have pointers or references to it.

If you are deriving from an abstract class, then make sure you override and define all pure virtual functions for your class.

From your snippet Your class AliceUniversity seems to be an abstract class. It needs to override and define all the pure virtual functions of the classes Graduate and UniversityGraduate.

Pure virtual functions are the ones with = 0; at the end of declaration.

Example: virtual void doSomething() = 0;

For a specific answer, you will need to post the definition of the class for which you get the error and the classes from which that class is deriving.

What does "\r" do in the following script?

\r is the ASCII Carriage Return (CR) character.

There are different newline conventions used by different operating systems. The most common ones are:

  • CR+LF (\r\n);
  • LF (\n);
  • CR (\r).

The \n\r (LF+CR) looks unconventional.

edit: My reading of the Telnet RFC suggests that:

  1. CR+LF is the standard newline sequence used by the telnet protocol.
  2. LF+CR is an acceptable substitute:

The sequence "CR LF", as defined, will cause the NVT to be positioned at the left margin of the next print line (as would, for example, the sequence "LF CR").

Vim autocomplete for Python

I ran into this on my Mac using the MacPorts vim with +python. Problem was that the MacPorts vim will only bind to python 2.5 with +python, while my extensions were installed under python 2.7. Installing the extensions using pip-2.5 solved it.

python: order a list of numbers without built-in sort, min, max function

This is the unsorted list and we want is 1234567

list = [3,1,2,5,4,7,6]

def sort(list):
    for i in range(len(list)-1):
        if list[i] > list[i+1]:
            a = list[i]
            list[i] = list[i+1]
            list[i+1] = a
        print(list)       

sort(list)

simplest in simplest method to sort a array. Im using currently bubble sorting that is: it checks first 2 location and moves the smallest number to left so on. "-n"in loop is to avoid the indentation error you will understand it by doing it so.

Java integer to byte array

public static byte[] intToBytes(int x) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(bos);
    out.writeInt(x);
    out.close();
    byte[] int_bytes = bos.toByteArray();
    bos.close();
    return int_bytes;
}

Bash if statement with multiple conditions throws an error

You can use either [[ or (( keyword. When you use [[ keyword, you have to use string operators such as -eq, -lt. I think, (( is most preferred for arithmetic, because you can directly use operators such as ==, < and >.

Using [[ operator

a=$1
b=$2
if [[ a -eq 1 || b -eq 2 ]] || [[ a -eq 3 && b -eq 4 ]]
then
     echo "Error"
else
     echo "No Error"
fi

Using (( operator

a=$1
b=$2
if (( a == 1 || b == 2 )) || (( a == 3 && b == 4 ))
then
     echo "Error"
else
     echo "No Error"
fi

Do not use -a or -o operators Since it is not Portable.

How do you add an ActionListener onto a JButton in Java

I'm didn't totally follow, but to add an action listener, you just call addActionListener (from Abstract Button). If this doesn't totally answer your question, can you provide some more details?

Import data.sql MySQL Docker Container

you can follow these simple steps:

FIRST WAY :

first copy the SQL dump file from your local directory to the mysql container. use docker cp command

docker cp [SRC-Local path to sql file] [container-name or container-id]:[DEST-path to copy to]

docker cp ./data.sql mysql-container:/home

and then execute the mysql-container using (NOTE: in case you are using alpine version you need to replace bash with sh in the given below command.)

docker exec -it -u root mysql-container bash

and then you can simply import this SQL dump file.

mysql [DB_NAME] < [SQL dump file path]

mysql movie_db < /home/data.sql

SECOND WAY : SIMPLE

docker cp ./data.sql mysql-container:/docker-entrypoint-initdb.d/

As mentioned in the mysql Docker hub official page.

Whenever a container starts for the first time, a new database is created with the specified name in MYSQL_DATABASE variable - which you can pass by setting up the environment variable see here how to set environment variables

By default container will execute files with extensions .sh, .sql and .sql.gz that are found in /docker-entrypoint-initdb.d folder. Files will be executed in alphabetical order. this way your SQL files will be imported by default to the database specified by the MYSQL_DATABASE variable.

for more details you can always visit the official page

Iterate through a HashMap

for (Map.Entry<String, String> item : hashMap.entrySet()) {
    String key = item.getKey();
    String value = item.getValue();
}

What is an API key?

What "exactly" an API key is used for depends very much on who issues it, and what services it's being used for. By and large, however, an API key is the name given to some form of secret token which is submitted alongside web service (or similar) requests in order to identify the origin of the request. The key may be included in some digest of the request content to further verify the origin and to prevent tampering with the values.

Typically, if you can identify the source of a request positively, it acts as a form of authentication, which can lead to access control. For example, you can restrict access to certain API actions based on who's performing the request. For companies which make money from selling such services, it's also a way of tracking who's using the thing for billing purposes. Further still, by blocking a key, you can partially prevent abuse in the case of too-high request volumes.

In general, if you have both a public and a private API key, then it suggests that the keys are themselves a traditional public/private key pair used in some form of asymmetric cryptography, or related, digital signing. These are more secure techniques for positively identifying the source of a request, and additionally, for protecting the request's content from snooping (in addition to tampering).

How to get the path of a running JAR file?

For getting the path of running jar file I have studied the above solutions and tried all methods which exist some difference each other. If these code are running in Eclipse IDE they all should be able to find the path of the file including the indicated class and open or create an indicated file with the found path.

But it is tricky, when run the runnable jar file directly or through the command line, it will be failed as the path of jar file gotten from the above methods will give an internal path in the jar file, that is it always gives a path as

rsrc:project-name (maybe I should say that it is the package name of the main class file - the indicated class)

I can not convert the rsrc:... path to an external path, that is when run the jar file outside the Eclipse IDE it can not get the path of jar file.

The only possible way for getting the path of running jar file outside Eclipse IDE is

System.getProperty("java.class.path")

this code line may return the living path (including the file name) of the running jar file (note that the return path is not the working directory), as the java document and some people said that it will return the paths of all class files in the same directory, but as my tests if in the same directory include many jar files, it only return the path of running jar (about the multiple paths issue indeed it happened in the Eclipse).

Count with IF condition in MySQL query

Replace this line:

count(if(ccc_news_comments.id = 'approved', ccc_news_comments.id, 0)) AS comments

With this one:

coalesce(sum(ccc_news_comments.id = 'approved'), 0) comments

Pseudo-terminal will not be allocated because stdin is not a terminal

All relevant information is in the existing answers, but let me attempt a pragmatic summary:

tl;dr:

  • DO pass the commands to run using a command-line argument:
    ssh jdoe@server '...'

    • '...' strings can span multiple lines, so you can keep your code readable even without the use of a here-document:
      ssh jdoe@server ' ... '
  • Do NOT pass the commands via stdin, as is the case when you use a here-document:
    ssh jdoe@server <<'EOF' # Do NOT do this ... EOF

Passing the commands as an argument works as-is, and:

  • the problem with the pseudo-terminal will not even arise.
  • you won't need an exit statement at the end of your commands, because the session will automatically exit after the commands have been processed.

In short: passing commands via stdin is a mechanism that is at odds with ssh's design and causes problems that must then be worked around.
Read on, if you want to know more.


Optional background information:

ssh's mechanism for accepting commands to execute on the target server is a command-line argument: the final operand (non-option argument) accepts a string containing one or more shell commands.

  • By default, these commands run unattended, in an non-interactive shell, without the use of a (pseudo) terminal (option -T is implied), and the session automatically ends when the last command finishes processing.

  • In the event that your commands require user interaction, such as responding to an interactive prompt, you can explicitly request the creation of a pty (pseudo-tty), a pseudo terminal, that enables interacting with the remote session, using the -t option; e.g.:

    • ssh -t jdoe@server 'read -p "Enter something: "; echo "Entered: [$REPLY]"'

    • Note that the interactive read prompt only works correctly with a pty, so the -t option is needed.

    • Using a pty has a notable side effect: stdout and stderr are combined and both reported via stdout; in other words: you lose the distinction between regular and error output; e.g.:

      • ssh jdoe@server 'echo out; echo err >&2' # OK - stdout and stderr separate

      • ssh -t jdoe@server 'echo out; echo err >&2' # !! stdout + stderr -> stdout

In the absence of this argument, ssh creates an interactive shell - including when you send commands via stdin, which is where the trouble begins:

  • For an interactive shell, ssh normally allocates a pty (pseudo-terminal) by default, except if its stdin is not connected to a (real) terminal.

    • Sending commands via stdin means that ssh's stdin is no longer connected to a terminal, so no pty is created, and ssh warns you accordingly:
      Pseudo-terminal will not be allocated because stdin is not a terminal.

    • Even the -t option, whose express purpose is to request creation of a pty, is not enough in this case: you'll get the same warning.

      • Somewhat curiously, you must then double the -t option to force creation of a pty: ssh -t -t ... or ssh -tt ... shows that you really, really mean it.

      • Perhaps the rationale for requiring this very deliberate step is that things may not work as expected. For instance, on macOS 10.12, the apparent equivalent of the above command, providing the commands via stdin and using -tt, does not work properly; the session gets stuck after responding to the read prompt:
        ssh -tt jdoe@server <<<'read -p "Enter something: "; echo "Entered: [$REPLY]"'


In the unlikely event that the commands you want to pass as an argument make the command line too long for your system (if its length approaches getconf ARG_MAX - see this article), consider copying the code to the remote system in the form of a script first (using, e.g., scp), and then send a command to execute that script.

In a pinch, use -T, and provide the commands via stdin, with a trailing exit command, but note that if you also need interactive features, using -tt in lieu of -T may not work.

Python locale error: unsupported locale setting

first, make sure you have the language pack installed by doing :

sudo apt-get install language-pack-en-base


sudo dpkg-reconfigure locales

Disable building workspace process in Eclipse

if needed programmatic from a PDE or JDT code:

public static void setWorkspaceAutoBuild(boolean flag) throws CoreException 
{
IWorkspace workspace = ResourcesPlugin.getWorkspace();
final IWorkspaceDescription description = workspace.getDescription();
description.setAutoBuilding(flag);
workspace.setDescription(description);
}

SyntaxError: Use of const in strict mode?

cd /
npm install -g nave
nave use 6.11.1
node app.js

Intellij Cannot resolve symbol on import

Had the same problem till I noticed that the src folder was marked as root source instead of java! Changing to only the java (src/main/java) to be the source root solved my problem enter image description here

Pass Javascript variable to PHP via ajax

Since you're not using JSON as the data type no your AJAX call, I would assume that you can't access the value because the PHP you gave will only ever be true or false. isset is a function to check if something exists and has a value, not to get access to the value.

Change your PHP to be:

$uid = (isset($_POST['userID'])) ? $_POST['userID'] : 0;

The above line will check to see if the post variable exists. If it does exist it will set $uid to equal the posted value. If it does not exist then it will set $uid equal to 0.

Later in your code you can check the value of $uid and react accordingly

if($uid==0) {
    echo 'User ID not found';
}

This will make your code more readable and also follow what I consider to be best practices for handling data in PHP.

How to create a new text file using Python

# Method 1
f = open("Path/To/Your/File.txt", "w")   # 'r' for reading and 'w' for writing
f.write("Hello World from " + f.name)    # Write inside file 
f.close()                                # Close file 

# Method 2
with open("Path/To/Your/File.txt", "w") as f:   # Opens file and casts as f 
    f.write("Hello World form " + f.name)       # Writing
    # File closed automatically

There are many more methods but these two are most common. Hope this helped!

How can I find my php.ini on wordpress?

Create a file yourself php.ini anywhere in your root or wp-admin folder and add the necessary code to the file it should work

A cron job for rails: best practices?

Assuming your tasks don't take too long to complete, just create a new controller with an action for each task. Implement the logic of the task as controller code, Then set up a cronjob at the OS level that uses wget to invoke the URL of this controller and action at the appropriate time intervals. The advantages of this method are you:

  1. Have full access to all your Rails objects just as in a normal controller.
  2. Can develop and test just as you do normal actions.
  3. Can also invoke your tasks adhoc from a simple web page.
  4. Don't consume any more memory by firing up additional ruby/rails processes.

How to disable HTML links

I would do something like

$('td').find('a').each(function(){
 $(this).addClass('disabled-link');
});

$('.disabled-link').on('click', false);

something like this should work. You add a class for links you want to have disabled and then you return false when someone click them. To enable them just remove the class.

Twitter Bootstrap hide css class and jQuery

If an element has bootstrap's "hide" class and you want to display it with some sliding effect such as .slideDown(), you can cheat bootstrap like:

$('#hiddenElement').hide().removeClass('hide').slideDown('fast')

Draw text in OpenGL ES

According to this link:

http://code.neenbedankt.com/how-to-render-an-android-view-to-a-bitmap

You can render any View to a bitmap. It's probably worth assuming that you can layout a view as you require (including text, images etc.) and then render it to a Bitmap.

Using JVitela's code above you should be able to use that Bitmap as an OpenGL texture.

Programmatically navigate to another view controller/scene

I already found the answer

Swift 4

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

Swift 3

let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("nextView") as NextViewController
self.presentViewController(nextViewController, animated:true, completion:nil)

What's the "average" requests per second for a production web application?

OpenStreetMap seems to have 10-20 per second

Wikipedia seems to be 30000 to 70000 per second spread over 300 servers (100 to 200 requests per second per machine, most of which is caches)

Geograph is getting 7000 images per week (1 upload per 95 seconds)

Generate getters and setters in NetBeans

Position the cursor inside the class, then press ALT + Ins and select Getters and Setters from the contextual menu.

How to get key names from JSON using jq

In combination with the above answer, you want to ask jq for raw output, so your last filter should be eg.:

     cat input.json | jq -r 'keys'

From jq help:

     -r     output raw strings, not JSON texts;

How can I get the latest JRE / JDK as a zip file rather than EXE or MSI installer?

You can download a portable Zulu .zip archive from Azul Systems, which are builds of OpenJDK for Windows, Linux (RHEL, SUSE, Debian, Ubuntu, CentOS) and Mac OS X.

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.

More technical information on different JVMs (including Zulu) with their architectures and OS support here.

Updating a dataframe column in spark

Just as maasg says you can create a new DataFrame from the result of a map applied to the old DataFrame. An example for a given DataFrame df with two rows:

val newDf = sqlContext.createDataFrame(df.map(row => 
  Row(row.getInt(0) + SOMETHING, applySomeDef(row.getAs[Double]("y")), df.schema)

Note that if the types of the columns change, you need to give it a correct schema instead of df.schema. Check out the api of org.apache.spark.sql.Row for available methods: https://spark.apache.org/docs/latest/api/java/org/apache/spark/sql/Row.html

[Update] Or using UDFs in Scala:

import org.apache.spark.sql.functions._

val toLong = udf[Long, String] (_.toLong)

val modifiedDf = df.withColumn("modifiedColumnName", toLong(df("columnName"))).drop("columnName")

and if the column name needs to stay the same you can rename it back:

modifiedDf.withColumnRenamed("modifiedColumnName", "columnName")

C error: Expected expression before int

This is actually a fairly interesting question. It's not as simple as it looks at first. For reference, I'm going to be basing this off of the latest C11 language grammar defined in N1570

I guess the counter-intuitive part of the question is: if this is correct C:

if (a == 1) {
  int b = 10;
}

then why is this not also correct C?

if (a == 1)
  int b = 10;

I mean, a one-line conditional if statement should be fine either with or without braces, right?

The answer lies in the grammar of the if statement, as defined by the C standard. The relevant parts of the grammar I've quoted below. Succinctly: the int b = 10 line is a declaration, not a statement, and the grammar for the if statement requires a statement after the conditional that it's testing. But if you enclose the declaration in braces, it becomes a statement and everything's well.

And just for the sake of answering the question completely -- this has nothing to do with scope. The b variable that exists inside that scope will be inaccessible from outside of it, but the program is still syntactically correct. Strictly speaking, the compiler shouldn't throw an error on it. Of course, you should be building with -Wall -Werror anyways ;-)

(6.7) declaration:
            declaration-speci?ers init-declarator-listopt ;
            static_assert-declaration

(6.7) init-declarator-list:
            init-declarator
            init-declarator-list , init-declarator

(6.7) init-declarator:
            declarator
            declarator = initializer

(6.8) statement:
            labeled-statement
            compound-statement
            expression-statement
            selection-statement
            iteration-statement
            jump-statement

(6.8.2) compound-statement:
            { block-item-listopt }

(6.8.4) selection-statement:
            if ( expression ) statement
            if ( expression ) statement else statement
            switch ( expression ) statement

What is char ** in C?

It is a pointer to a pointer, so yes, in a way it's a 2D character array. In the same way that a char* could indicate an array of chars, a char** could indicate that it points to and array of char*s.

background: fixed no repeat not working on mobile

See my answer to this question: Detect support for background-attachment: fixed?

  • Detecting touch capability alone doesn't work for laptops with touch screens, and the code for detecting touch giving by Christina will fail on some devices.
  • Hector's answer will work, but the animation will be very choppy, so it'll look better to replace fixed with scrolling on devices that don't support fixed.
  • Unfortunately, Taylon is incorrect that iOS 5+ supports background-attachment:fixed. It does not. I can't find any list of devices that don't support fixed backgrounds. It's likely that most mobile phone and tablets do not.

Make a link open a new window (not tab)

I know that its bit old Q but if u get here by searching a solution so i got a nice one via jquery

  jQuery('a[target^="_new"]').click(function() {
    var width = window.innerWidth * 0.66 ;
    // define the height in
    var height = width * window.innerHeight / window.innerWidth ;
    // Ratio the hight to the width as the user screen ratio
    window.open(this.href , 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));

});

it will open all the <a target="_new"> in a new window

EDIT:

1st, I did some little changes in the original code now it open the new window perfectly followed the user screen ratio (for landscape desktops)

but, I would like to recommend you to use the following code that open the link in new tab if you in mobile (thanks to zvona answer in other question):

jQuery('a[target^="_new"]').click(function() {
    return openWindow(this.href);
}


function openWindow(url) {

    if (window.innerWidth <= 640) {
        // if width is smaller then 640px, create a temporary a elm that will open the link in new tab
        var a = document.createElement('a');
        a.setAttribute("href", url);
        a.setAttribute("target", "_blank");

        var dispatch = document.createEvent("HTMLEvents");
        dispatch.initEvent("click", true, true);

        a.dispatchEvent(dispatch);
    }
    else {
        var width = window.innerWidth * 0.66 ;
        // define the height in
        var height = width * window.innerHeight / window.innerWidth ;
        // Ratio the hight to the width as the user screen ratio
        window.open(url , 'newwindow', 'width=' + width + ', height=' + height + ', top=' + ((window.innerHeight - height) / 2) + ', left=' + ((window.innerWidth - width) / 2));
    }
    return false;
}

Formatting floats in a numpy array

You're confusing actual precision and display precision. Decimal rounding cannot be represented exactly in binary. You should try:

> np.set_printoptions(precision=2)
> np.array([5.333333])
array([ 5.33])

How do I dump an object's fields to the console?

You might find a use for the methods method which returns an array of methods for an object. It's not the same as print_r, but still useful at times.

>> "Hello".methods.sort
=> ["%", "*", "+", "<", "<<", "<=", "<=>", "==", "===", "=~", ">", ">=", "[]", "[]=", "__id__", "__send__", "all?", "any?", "between?", "capitalize", "capitalize!", "casecmp", "center", "chomp", "chomp!", "chop", "chop!", "class", "clone", "collect", "concat", "count", "crypt", "delete", "delete!", "detect", "display", "downcase", "downcase!", "dump", "dup", "each", "each_byte", "each_line", "each_with_index", "empty?", "entries", "eql?", "equal?", "extend", "find", "find_all", "freeze", "frozen?", "grep", "gsub", "gsub!", "hash", "hex", "id", "include?", "index", "inject", "insert", "inspect", "instance_eval", "instance_of?", "instance_variable_defined?", "instance_variable_get", "instance_variable_set", "instance_variables", "intern", "is_a?", "is_binary_data?", "is_complex_yaml?", "kind_of?", "length", "ljust", "lstrip", "lstrip!", "map", "match", "max", "member?", "method", "methods", "min", "next", "next!", "nil?", "object_id", "oct", "partition", "private_methods", "protected_methods", "public_methods", "reject", "replace", "respond_to?", "reverse", "reverse!", "rindex", "rjust", "rstrip", "rstrip!", "scan", "select", "send", "singleton_methods", "size", "slice", "slice!", "sort", "sort_by", "split", "squeeze", "squeeze!", "strip", "strip!", "sub", "sub!", "succ", "succ!", "sum", "swapcase", "swapcase!", "taguri", "taguri=", "taint", "tainted?", "to_a", "to_f", "to_i", "to_s", "to_str", "to_sym", "to_yaml", "to_yaml_properties", "to_yaml_style", "tr", "tr!", "tr_s", "tr_s!", "type", "unpack", "untaint", "upcase", "upcase!", "upto", "zip"]

Get text from pressed button

Button btn=(Button)findViewById(R.id.btn);
String btnText=btn.getText().toString();

Later this btnText can be used .

For example:

if(btnText == "Text for comparison")

Set up Python 3 build system with Sublime Text 3

Run Python Files in Sublime Text3

For Sublime Text 3, First Install Package Control:

  • Press Ctrl + Shift + P, a search bar will open
  • Type Install package and then press enter Click here to see Install Package Search Pic

  • After the package got installed. It may prompt to restart SublimeText

  • After completing the above step
  • Just again repeat the 1st and 2nd step, it will open the repositories this time
  • Search for Python 3 and Hit enter.
  • There you go.
  • Just press Ctrl + B in your python file and you'll get the output. Click here to see Python 3 repo pic

It perfectly worked for me. Hopefully, it helped you too. For any left requirements, visit https://packagecontrol.io/installation#st3 here.

Should I use `import os.path` or `import os`?

Couldn't find any definitive reference, but I see that the example code for os.walk uses os.path but only imports os

Exiting out of a FOR loop in a batch file?

As jeb noted, the rest of the loop is skipped but evaluated, which makes the FOR solution too slow for this purpose. An alternative:

set F=1
:nextpart
if not exist "%F%" goto :EOF
echo %F%
set /a F=%F%+1
goto nextpart

You might need to use delayed expansion and call subroutines when using this in loops.

Undefined reference to main - collect2: ld returned 1 exit status

It means that es3.c does not define a main function, and you are attempting to create an executable out of it. An executable needs to have an entry point, thereby the linker complains.

To compile only to an object file, use the -c option:

gcc es3.c -c
gcc es3.o main.c -o es3

The above compiles es3.c to an object file, then compiles a file main.c that would contain the main function, and the linker merges es3.o and main.o into an executable called es3.

Test if characters are in a string

Use the grepl function

grepl( needle, haystack, fixed = TRUE)

like so:

grepl(value, chars, fixed = TRUE)
# TRUE

Use ?grepl to find out more.

File Not Found when running PHP with Nginx

The error message “Primary script unknown or in your case is file not found.” is almost always related to a wrongly set in line SCRIPT_FILENAME in the Nginx fastcgi_param directive (Quote from https://serverfault.com/a/517327/560171).

In my case, I use Nginx 1.17.10 and my configuration is:

    location ~ \.php$ {
      fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
      fastcgi_index index.php;
      fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
      include fastcgi_params;
      fastcgi_read_timeout 600;
    }

You just change $document_root to $realpath_root, so whatever your root location, like /var/www/html/project/, you don't need write fastcgi_param SCRIPT_FILENAME /var/www/html/project$fastcgi_script_name; each time your root is changes. This configuration is more flexible. May this helps.

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

For more information, if you got unix:/run/php/php7.2-fpm.sock failed (13: Permission denied) while connecting to upstream, just change in /etc/nginx/nginx.conf, from user nginx; to user www-data;.

Because the default user and group of PHP-FPM process is www-data as can be seen in /etc/php/7.2/fpm/pool.d/www.conf file (Qoute from https://www.linuxbabe.com/ubuntu/install-nginx-latest-version-ubuntu-18-04):

user = www-data
group = www-data

May this information gives a big help

Get PHP class property by string

If you want to access the property without creating an intermediate variable, use the {} notation:

$something = $object->{'something'};

That also allows you to build the property name in a loop for example:

for ($i = 0; $i < 5; $i++) {
    $something = $object->{'something' . $i};
    // ...
}

Git error: src refspec master does not match any error: failed to push some refs

It doesn't recognize that you have a master branch, but I found a way to get around it. I found out that there's nothing special about a master branch, you can just create another branch and call it master branch and that's what I did.

To create a master branch:

git checkout -b master

And you can work off of that.

MySQL - length() vs char_length()

LENGTH() returns the length of the string measured in bytes.
CHAR_LENGTH() returns the length of the string measured in characters.

This is especially relevant for Unicode, in which most characters are encoded in two bytes. Or UTF-8, where the number of bytes varies. For example:

select length(_utf8 '€'), char_length(_utf8 '€')
--> 3, 1

As you can see the Euro sign occupies 3 bytes (it's encoded as 0xE282AC in UTF-8) even though it's only one character.

How to write UPDATE SQL with Table alias in SQL Server 2008?

You can always take the CTE, (Common Tabular Expression), approach.

;WITH updateCTE AS
(
    SELECT ID, TITLE 
    FROM HOLD_TABLE
    WHERE ID = 101
)

UPDATE updateCTE
SET TITLE = 'TEST';

How to properly reference local resources in HTML?

  • A leading slash tells the browser to start at the root directory.
  • If you don't have the leading slash, you're referencing from the current directory.
  • If you add two dots before the leading slash, it means you're referencing the parent of the current directory.

Take the following folder structure

demo folder structure

notice:

  • the ROOT checkmark is green,
  • the second checkmark is orange,
  • the third checkmark is purple,
  • the forth checkmark is yellow

Now in the index.html.en file you'll want to put the following markup

<p>
    <span>src="check_mark.png"</span>
    <img src="check_mark.png" />
    <span>I'm purple because I'm referenced from this current directory</span>
</p>

<p>
    <span>src="/check_mark.png"</span>
    <img src="/check_mark.png" />
    <span>I'm green because I'm referenced from the ROOT directory</span>
</p>

<p>
    <span>src="subfolder/check_mark.png"</span>
    <img src="subfolder/check_mark.png" />
    <span>I'm yellow because I'm referenced from the child of this current directory</span>
</p>

<p>
    <span>src="/subfolder/check_mark.png"</span>
    <img src="/subfolder/check_mark.png" />
    <span>I'm orange because I'm referenced from the child of the ROOT directory</span>
</p>

<p>
    <span>src="../subfolder/check_mark.png"</span>
    <img src="../subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced from the parent of this current directory</span>
</p>

<p>
    <span>src="subfolder/subfolder/check_mark.png"</span>
    <img src="subfolder/subfolder/check_mark.png" />
    <span>I'm [broken] because there is no subfolder two children down from this current directory</span>
</p>

<p>
    <span>src="/subfolder/subfolder/check_mark.png"</span>
    <img src="/subfolder/subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced two children down from the ROOT directory</span>
</p>

Now if you load up the index.html.en file located in the second subfolder
http://example.com/subfolder/subfolder/

This will be your output

enter image description here

How to make a <ul> display in a horizontal row

As @alex said, you could float it right, but if you wanted to keep the markup the same, float it to the left!

#ul_top_hypers li {
    float: left;
}

SQL Server 2008 Insert with WHILE LOOP

First of all I'd like to say that I 100% agree with John Saunders that you must avoid loops in SQL in most cases especially in production.

But occasionally as a one time thing to populate a table with a hundred records for testing purposes IMHO it's just OK to indulge yourself to use a loop.

For example in your case to populate your table with records with hospital ids between 16 and 100 and make emails and descriptions distinct you could've used

CREATE PROCEDURE populateHospitals
AS
DECLARE @hid INT;
SET @hid=16;
WHILE @hid < 100
BEGIN 
    INSERT hospitals ([Hospital ID], Email, Description) 
    VALUES(@hid, 'user' + LTRIM(STR(@hid)) + '@mail.com', 'Sample Description' + LTRIM(STR(@hid))); 
    SET @hid = @hid + 1;
END

And result would be

ID   Hospital ID Email            Description          
---- ----------- ---------------- ---------------------
1    16          [email protected]  Sample Description16 
2    17          [email protected]  Sample Description17 
...                                                    
84   99          [email protected]  Sample Description99 

Pandas get the most frequent values of a column

to get top 5:

dataframe['name'].value_counts()[0:5]

Unicode character for "X" cancel / close?

You can use text that is only accessible to screen readers by placing it in a span which you hide in an accessible way. Place the x in the CSS which can't be read by screen readers, thus won't confuse, but is visible on the page, and also accessible by keyboard users.

<style>
.hidden {opacity:0; position:absolute; width:0;}
.close {padding:4px 8px; border:1px solid #000; background-color:#fff; cursor:pointer;}
.close:before {content:'\00d7'; color:red; font-size:2em;}
</style>

<button class="close"><span class="hidden">close</span></button>

Identifying country by IP address

I agree with above answers, the best way to get country from ip address is Maxmind.

If you want to write code in java, you might want to use i.e. geoip-api-1.2.10.jar and geoIP dat files (GeoIPCity.dat), which can be found via google.

Following code may be useful for you to get almost all information related to location, I am also using the same code.

public static String getGeoDetailsUsingMaxmind(String ipAddress, String desiredValue) 
    {
        Location getLocation;
        String returnString = "";
        try
        {
            String geoIPCity_datFile = System.getenv("AUTOMATION_HOME").concat("/tpt/GeoIP/GeoIPCity.dat");
            LookupService isp = new LookupService(geoIPCity_datFile);
            getLocation = isp.getLocation(ipAddress);
            isp.close();

            //Getting all location details 
            if(desiredValue.equalsIgnoreCase("latitude") || desiredValue.equalsIgnoreCase("lat"))
            {
                returnString = String.valueOf(getLocation.latitude);
            }
            else if(desiredValue.equalsIgnoreCase("longitude") || desiredValue.equalsIgnoreCase("lon"))
            {
                returnString = String.valueOf(getLocation.longitude);
            }
            else if(desiredValue.equalsIgnoreCase("countrycode") || desiredValue.equalsIgnoreCase("country"))
            {
                returnString = getLocation.countryCode;
            }
            else if(desiredValue.equalsIgnoreCase("countryname"))
            {
                returnString = getLocation.countryName;
            }
            else if(desiredValue.equalsIgnoreCase("region"))
            {
                returnString = getLocation.region;
            }
            else if(desiredValue.equalsIgnoreCase("metro"))
            {
                returnString = String.valueOf(getLocation.metro_code);
            }
            else if(desiredValue.equalsIgnoreCase("city"))
            {
                returnString = getLocation.city;
            }
            else if(desiredValue.equalsIgnoreCase("zip") || desiredValue.equalsIgnoreCase("postalcode"))
            {
                returnString = getLocation.postalCode;
            }
            else
            {
                returnString = "";
                System.out.println("There is no value found for parameter: "+desiredValue);
            }

            System.out.println("Value of: "+desiredValue + " is: "+returnString + " for ip address: "+ipAddress);
        }
        catch (Exception e) 
        {
            System.out.println("Exception occured while getting details from max mind. " + e);
        }
        finally
        {
            return returnString;
        }
    }

VBA Macro to compare all cells of two Excel files

A very simple check you can do with Cell formulas:

Sheet 1 (new - old)

=(if(AND(Ref_New<>"";Ref_Old="");Ref_New;"")

Sheet 2 (old - new)

=(if(AND(Ref_Old<>"";Ref_New="");Ref_Old;"")

This formulas should work for an ENGLISH Excel. For other languages they need to be translated. (For German i can assist)

You need to open all three Excel Documents, then copy the first formula into A1 of your sheet 1 and the second into A1 of sheet 2. Now click in A1 of the first cell and mark "Ref_New", now you can select your reference, go to the new file and click in the A1, go back to sheet1 and do the same for "Ref_Old" with the old file. Replace also the other "Ref_New".

Doe the same for Sheet two.

Now copy the formaula form A1 over the complete range where zour data is in the old and the new file.

But two cases are not covered here:

  1. In the compared cell of New and Old is the same data (Resulting Cell will be empty)
  2. In the compared cell of New and Old is diffe data (Resulting Cell will be empty)

To cover this two cases also, you should create your own function, means learn VBA. A very useful Excel page is cpearson.com

How do I include a path to libraries in g++

In your MakeFile or CMakeLists.txt you can set CMAKE_CXX_FLAGS as below:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/path/to/your/folder")

Adding a y-axis label to secondary y-axis in matplotlib

I don't have access to Python right now, but off the top of my head:

fig = plt.figure()

axes1 = fig.add_subplot(111)
# set props for left y-axis here

axes2 = axes1.twinx()   # mirror them
axes2.set_ylabel(...)

Passing $_POST values with cURL

$url='Your url'; // Specify your url
$data= array('parameterkey1'=>value,'parameterkey2'=>value); // Add parameters in key value
$ch = curl_init(); // Initialize cURL
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);

Batch file for PuTTY/PSFTP file transfer automation

You need to store the psftp script (lines from open to bye) into a separate file and pass that to psftp using -b switch:

cd "C:\Program Files (x86)\PuTTY"
psftp -b "C:\path\to\script\script.txt"

Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-option-b


EDIT: For username+password: As you cannot use psftp commands in a batch file, for the same reason, you cannot specify the username and the password as psftp commands. These are inputs to the open command. While you can specify the username with the open command (open <user>@<IP>), you cannot specify the password this way. This can be done on a psftp command line only. Then it's probably cleaner to do all on the command-line:

cd "C:\Program Files (x86)\PuTTY"
psftp -b script.txt <user>@<IP> -pw <PW>

And remove the open, <user> and <PW> lines from your script.txt.

Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-starting
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-pw


What you are doing atm is that you run psftp without any parameter or commands. Once you exit it (like by typing bye), your batch file continues trying to run open command (and others), what Windows shell obviously does not understand.


If you really want to keep everything in one file (the batch file), you can write commands to psftp standard input, like:

(
    echo cd ...
    echo lcd ...
    echo put log.sh
) | psftp -b script.txt <user>@<IP> -pw <PW>

UPDATE multiple tables in MySQL using LEFT JOIN

                DECLARE @cols VARCHAR(max),@colsUpd VARCHAR(max), @query VARCHAR(max),@queryUpd VARCHAR(max), @subQuery VARCHAR(max)
DECLARE @TableNameTest NVARCHAR(150)
SET @TableNameTest = @TableName+ '_Staging';
SELECT  @colsUpd = STUF  ((SELECT DISTINCT '], T1.[' + name,']=T2.['+name+'' FROM sys.columns
                 WHERE object_id = (
                                    SELECT top 1 object_id 
                                      FROM sys.objects
                                     WHERE name = ''+@TableNameTest+''
                                    )
                and name not in ('Action','Record_ID')
                FOR XML PATH('')
            ), 1, 2, ''
        ) + ']'


  Select @queryUpd ='Update T1
SET '+@colsUpd+'
FROM '+@TableName+' T1
INNER JOIN '+@TableNameTest+' T2
ON T1.Record_ID = T2.Record_Id
WHERE T2.[Action] = ''Modify'''
EXEC (@queryUpd)

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

My problem was that I forgot that I added a proxy in gradle.properties in C:\Users\(current user)\.gradle like:

systemProp.http.proxyHost=****
systemProp.http.proxyPort=8850

How to prevent robots from automatically filling up a form?

I have a simple approach to stopping spammers which is 100% effective, at least in my experience, and avoids the use of reCAPTCHA and similar approaches. I went from close to 100 spams per day on one of my sites' html forms to zero for the last 5 years once I implemented this approach.

It works by taking advantage of the e-mail ALIAS capabilities of most html form handling scripts (I use FormMail.pl), along with a graphic submission "code", which is easily created in the most simple of graphics programs. One such graphic includes the code M19P17nH and the prompt "Please enter the code at left".

This particular example uses a random sequence of letters and numbers, but I tend to use non-English versions of words familiar to my visitors (e.g. "pnofrtay"). Note that the prompt for the form field is built into the graphic, rather than appearing on the form. Thus, to a robot, that form field presents no clue as to its purpose.

The only real trick here is to make sure that your form html assigns this code to the "recipient" variable. Then, in your mail program, make sure that each such code you use is set as an e-mail alias, which points to whatever e-mail addresses you want to use. Since there is no prompt of any kind on the form for a robot to read and no e-mail addresses, it has no idea what to put in the blank form field. If it puts nothing in the form field or anything except acceptable codes, the form submission fails with a "bad recipient" error. You can use a different graphic on different forms, although it isn't really necessary in my experience.

Of course, a human being can solve this problem in a flash, without all the problems associated with reCAPTCHA and similar, more elegant, schemes. If a human spammer does respond to the recipient failure and programs the image code into the robot, you can change it easily, once you realize that the robot has been hard-coded to respond. In five years of using this approach, I've never had a spam from any of the forms on which I use it nor have I ever had a complaint from any human user of the forms. I'm certain that this could be beaten with OCR capability in the robot, but I've never had it happen on any of my sites which use html forms. I have also used "spam traps" (hidden "come hither" html code which points to my anti-spam policies) to good effect, but they were only about 90% effective.

Newline in markdown table?

Use an HTML line break (<br />) to force a line break within a table cell:

|Something|Something else<br />that's rather long|Something else|

Java: How to stop thread?

One possible way is to do something like this:

public class MyThread extends Thread {
    @Override
    public void run() {
        while (!this.isInterrupted()) {
            //
        }
    }
}

And when you want to stop your thread, just call a method interrupt():

myThread.interrupt();

Of course, this won't stop thread immediately, but in the following iteration of the loop above. In the case of downloading, you need to write a non-blocking code. It means, that you will attempt to read new data from the socket only for a limited amount of time. If there are no data available, it will just continue. It may be done using this method from the class Socket:

mySocket.setSoTimeout(50);

In this case, timeout is set up to 50 ms. After this time has gone and no data was read, it throws an SocketTimeoutException. This way, you may write iterative and non-blocking thread, which may be killed using the construction above.

It's not possible to kill thread in any other way and you've to implement such a behavior yourself. In past, Thread had some method (not sure if kill() or stop()) for this, but it's deprecated now. My experience is, that some implementations of JVM doesn't even contain that method currently.

Filter dataframe rows if value in column is in a set list of values

You can also achieve similar results by using 'query' and @:

eg:

df = pd.DataFrame({'A': [1, 2, 3], 'B': ['a', 'b', 'f']})
df = pd.DataFrame({'A' : [5,6,3,4], 'B' : [1,2,3, 5]})
list_of_values = [3,6]
result= df.query("A in @list_of_values")
result
   A  B
1  6  2
2  3  3

Determine the type of an object?

be careful using isinstance

isinstance(True, bool)
True
>>> isinstance(True, int)
True

but type

type(True) == bool
True
>>> type(True) == int
False