Programs & Examples On #Glassfish 3

GlassFish is an open source, production-ready, Java EE-compatible application server.

How to set response header in JAX-RS so that user sees download popup for Excel?

I figured to set HTTP response header and stream to display download-popup in browser via standard servlet. note: I'm using Excella, excel output API.

package local.test.servlet;

import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import local.test.jaxrs.ExcellaTestResource;
import org.apache.poi.ss.usermodel.Workbook;
import org.bbreak.excella.core.BookData;
import org.bbreak.excella.core.exception.ExportException;
import org.bbreak.excella.reports.exporter.ExcelExporter;
import org.bbreak.excella.reports.exporter.ReportBookExporter;
import org.bbreak.excella.reports.model.ConvertConfiguration;
import org.bbreak.excella.reports.model.ReportBook;
import org.bbreak.excella.reports.model.ReportSheet;
import org.bbreak.excella.reports.processor.ReportProcessor;

@WebServlet(name="ExcelServlet", urlPatterns={"/ExcelServlet"})
public class ExcelServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        try {

            URL templateFileUrl = ExcellaTestResource.class.getResource("myTemplate.xls");
            //   /C:/Users/m-hugohugo/Documents/NetBeansProjects/KogaAlpha/build/web/WEB-INF/classes/local/test/jaxrs/myTemplate.xls
            System.out.println(templateFileUrl.getPath());
            String templateFilePath = URLDecoder.decode(templateFileUrl.getPath(), "UTF-8");
            String outputFileDir = "MasatoExcelHorizontalOutput";

            ReportProcessor reportProcessor = new ReportProcessor();
            ReportBook outputBook = new ReportBook(templateFilePath, outputFileDir, ExcelExporter.FORMAT_TYPE);

            ReportSheet outputSheet = new ReportSheet("MySheet");
            outputBook.addReportSheet(outputSheet);

            reportProcessor.addReportBookExporter(new OutputStreamExporter(response));
            System.out.println("wtf???");
            reportProcessor.process(outputBook);


            System.out.println("done!!");
        }
        catch(Exception e) {
            System.out.println(e);
        }

    } //end doGet()

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

}//end class



class OutputStreamExporter extends ReportBookExporter {

    private HttpServletResponse response;

    public OutputStreamExporter(HttpServletResponse response) {
        this.response = response;
    }

    @Override
    public String getExtention() {
        return null;
    }

    @Override
    public String getFormatType() {
        return ExcelExporter.FORMAT_TYPE;
    }

    @Override
    public void output(Workbook book, BookData bookdata, ConvertConfiguration configuration) throws ExportException {

        System.out.println(book.getFirstVisibleTab());
        System.out.println(book.getSheetName(0));

        //TODO write to stream
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=masatoExample.xls");
            book.write(response.getOutputStream());
            response.getOutputStream().close();
            System.out.println("booya!!");
        }
        catch(Exception e) {
            System.out.println(e);
        }
    }
}//end class

How can I set the Secure flag on an ASP.NET Session Cookie?

secure - This attribute tells the browser to only send the cookie if the request is being sent over a secure channel such as HTTPS. This will help protect the cookie from being passed over unencrypted requests. If the application can be accessed over both HTTP and HTTPS, then there is the potential that the cookie can be sent in clear text.

How to strip HTML tags with jQuery?

This is a example for get the url image, escape the p tag from some item.

Try this:

$('#img').attr('src').split('<p>')[1].split('</p>')[0]

Java - Reading XML file

If using another library is an option, the following may be easier:

package for_so;

import java.io.File;

import rasmus_torkel.xml_basic.read.TagNode;
import rasmus_torkel.xml_basic.read.XmlReadOptions;
import rasmus_torkel.xml_basic.read.impl.XmlReader;

public class Q7704827_SimpleRead
{
    public static void
    main(String[] args)
    {
        String fileName = args[0];

        TagNode emailNode = XmlReader.xmlFileToRoot(new File(fileName), "EmailSettings", XmlReadOptions.DEFAULT);
        String recipient = emailNode.nextTextFieldE("recipient");
        String sender = emailNode.nextTextFieldE("sender");
        String subject = emailNode.nextTextFieldE("subject");
        String description = emailNode.nextTextFieldE("description");
        emailNode.verifyNoMoreChildren();

        System.out.println("recipient =  " + recipient);
        System.out.println("sender =     " + sender);
        System.out.println("subject =    " + subject);
        System.out.println("desciption = " + description);
    }
}

The library and its documentation are at rasmustorkel.com

Implicit function declarations in C

To complete the picture, since -Werror might considered too "invasive",
for gcc (and llvm) a more precise solution is to transform just this warning in an error, using the option:

-Werror=implicit-function-declaration

See Make one gcc warning an error?

Regarding general use of -Werror: Of course, having warningless code is recommendable, but in some stage of development it might slow down the prototyping.

CSS Equivalent of the "if" statement

CSS has become a very powerful tool over the years and it has hacks for a lot of things javaScript can do

There is a hack in CSS for using conditional statements/logic.

It involves using the symbol '~'

Let me further illustrate with an example.

Let's say you want a background to slide into the page when a button is clicked. All you need to do is use a radio checkbox. Style the label for the radio underneath the button so that when the button is pressed the checkbox is also pressed.

Then you use the code below

.checkbox:checked ~ .background{
opacity:1
width: 100%
}

This code simply states IF the checkbox is CHECKED then open up the background ELSE leave it as it is.

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

May be its irrelevant answer but its working in my case...don't know what was wrong on my server...I just enable error log on Ubuntu 16.04 server.

//For PHP
error_reporting(E_ALL);
ini_set('display_errors', 1);

Error: ANDROID_HOME is not set and "android" command not in your PATH. You must fulfill at least one of these conditions.

I have MAC OS X Yosemite, Android Studio 1.0.1, JDK 1.8, and Cordova 4.1.2

When I tried to add the android project:

cordova platforms add android

I received the message: ANDROID_HOME is not set and "android" command not in your PATH

Based in cforcloud's answer... 'Error: the command "android" failed' using cordova and http://developer.android.com/sdk/installing/index.html?pkg=studio I used the following:

export ANDROID_HOME="/Users/<user_name>/Library/Android/sdk"
export ANDROID_TOOLS="/Users/<user_name>/Library/Android/sdk/tools/"
export ANDROID_PLATFORM_TOOLS="/Users/<user_name>/Library/Android/sdk/platform-tools/"
PATH=$PATH:$ANDROID_HOME:$ANDROID_TOOLS:$ANDROID_PLATFORM_TOOLS
echo $PATH

When I tried to create the android project, I received this message:

Creating android project...
/Users/lg/.cordova/lib/npm_cache/cordova-android/3.6.4/package/bin/node_modules/q/q.js:126
                    throw e;
                          ^
Error: Please install Android target "android-19".

I ran Android SDK Manager, and installed Android 4.4.2 (API 19) (everything but Glass Development Kit Preview). It worked for me.

===

This is the content of my .bash_profile file.

export PATH=$PATH:/usr/local/bin
export JAVA_HOME=`/usr/libexec/java_home -v 1.8`
launchctl setenv STUDIO_JDK /library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk
export ANDROID_HOME="/Users/<UserName>/Library/Android/sdk"
export ANDROID_TOOLS="/Users/<UserName>/Library/Android/sdk/tools"
export ANDROID_PLATFORM_TOOLS="/Users/<UserName>/Library/Android/sdk/platform-tools"
PATH=$PATH:$ANDROID_HOME:$ANDROID_TOOLS:$ANDROID_PLATFORM_TOOLS

To edit .bash_profile using Terminal, I use nano. It is easy to understand.

cd
nano .bash_profile

I hope it helps.

PostgreSQL Crosstab Query

You can use the crosstab() function of the additional module tablefunc - which you have to install once per database. Since PostgreSQL 9.1 you can use CREATE EXTENSION for that:

CREATE EXTENSION tablefunc;

In your case, I believe it would look something like this:

CREATE TABLE t (Section CHAR(1), Status VARCHAR(10), Count integer);

INSERT INTO t VALUES ('A', 'Active',   1);
INSERT INTO t VALUES ('A', 'Inactive', 2);
INSERT INTO t VALUES ('B', 'Active',   4);
INSERT INTO t VALUES ('B', 'Inactive', 5);

SELECT row_name AS Section,
       category_1::integer AS Active,
       category_2::integer AS Inactive
FROM crosstab('select section::text, status, count::text from t',2)
            AS ct (row_name text, category_1 text, category_2 text);

How do I copy the contents of one stream to another?

The following code to solve the issue copy the Stream to MemoryStream using CopyTo

Stream stream = new MemoryStream();

//any function require input the stream. In mycase to save the PDF file as stream document.Save(stream);

MemoryStream newMs = (MemoryStream)stream;

byte[] getByte = newMs.ToArray();

//Note - please dispose the stream in the finally block instead of inside using block as it will throw an error 'Access denied as the stream is closed'

Set Value of Input Using Javascript Function

document.getElementById('gadget_url').value = 'your value';

Limit file format when using <input type="file">?

There is the accept attribute for the input tag. However, it is not reliable in any way. Browsers most likely treat it as a "suggestion", meaning the user will, depending on the file manager as well, have a pre-selection that only displays the desired types. They can still choose "all files" and upload any file they want.

For example:

_x000D_
_x000D_
<form>_x000D_
    <input type="file" name="pic" id="pic" accept="image/gif, image/jpeg" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Read more in the HTML5 spec

Keep in mind that it is only to be used as a "help" for the user to find the right files. Every user can send any request he/she wants to your server. You always have to validated everything server-side.

So the answer is: no you cannot restrict, but you can set a pre-selection but you cannot rely on it.

Alternatively or additionally you can do something similar by checking the filename (value of the input field) with JavaScript, but this is nonsense because it provides no protection and also does not ease the selection for the user. It only potentially tricks a webmaster into thinking he/she is protected and opens a security hole. It can be a pain in the ass for users that have alternative file extensions (for example jpeg instead of jpg), uppercase, or no file extensions whatsoever (as is common on Linux systems).

Difference between Spring MVC and Struts MVC

The major difference between Spring MVC and Struts is: Spring MVC is loosely coupled framework whereas Struts is tightly coupled. For enterprise Application you need to build your application as loosely coupled as it would make your application more reusable and robust as well as distributed.

How do I write a "tab" in Python?

The Python reference manual includes several string literals that can be used in a string. These special sequences of characters are replaced by the intended meaning of the escape sequence.

Here is a table of some of the more useful escape sequences and a description of the output from them.

Escape Sequence       Meaning
\t                    Tab
\\                    Inserts a back slash (\)
\'                    Inserts a single quote (')
\"                    Inserts a double quote (")
\n                    Inserts a ASCII Linefeed (a new line)

Basic Example

If i wanted to print some data points separated by a tab space I could print this string.

DataString = "0\t12\t24"
print (DataString)

Returns

0    12    24

Example for Lists

Here is another example where we are printing the items of list and we want to sperate the items by a TAB.

DataPoints = [0,12,24]
print (str(DataPoints[0]) + "\t" + str(DataPoints[1]) + "\t" + str(DataPoints[2]))

Returns

0    12    24

Raw Strings

Note that raw strings (a string which include a prefix "r"), string literals will be ignored. This allows these special sequences of characters to be included in strings without being changed.

DataString = r"0\t12\t24"
print (DataString)

Returns

0\t12\t24

Which maybe an undesired output

String Lengths

It should also be noted that string literals are only one character in length.

DataString = "0\t12\t24"
print (len(DataString))

Returns

7

The raw string has a length of 9.

HTTP POST Returns Error: 417 "Expectation Failed."

System.Net.HttpWebRequest adds the header 'HTTP header "Expect: 100-Continue"' to every request unless you explicitly ask it not to by setting this static property to false:

System.Net.ServicePointManager.Expect100Continue = false;

Some servers choke on that header and send back the 417 error you're seeing.

Give that a shot.

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

For anyone still looking for a simpler method to transfer repos from Gitlab to Github while preserving all history.

Step 1. Login to Github, create a private repo with the exact same name as the repo you would like to transfer.

Step 2. Under "push an existing repository from the command" copy the link of the new repo, it will look something like this:

[email protected]:your-name/name-of-repo.git

Step 3. Open up your local project and look for the folder .git typically this will be a hidden folder. Inside the .git folder open up config.

The config file will contain something like:

[remote "origin"]
url = [email protected]:your-name/name-of-repo.git
fetch = +refs/heads/:refs/remotes/origin/

Under [remote "origin"], change the URL to the one that you copied on Github.

Step 4. Open your project folder in the terminal and run: git push --all. This will push your code to Github as well as all the commit history.

Step 5. To make sure everything is working as expected, make changes, commit, push and new commits should appear on the newly created Github repo.

Step 6. As a last step, you can now archive your Gitlab repo or set it to read only.

Pip install - Python 2.7 - Windows 7

Add the following to you environment variable PATH.

C:\Python27\Scripts

This path will contain the pip executable file. Make sure it exist. If it doesn't then you'll need to install it using the get-pip.py script.

Additonally, you can read the following link to get a better understanding.

What are metaclasses in Python?

Python classes are themselves objects - as in instance - of their meta-class.

The default metaclass, which is applied when when you determine classes as:

class foo:
    ...

meta class are used to apply some rule to an entire set of classes. For example, suppose you're building an ORM to access a database, and you want records from each table to be of a class mapped to that table (based on fields, business rules, etc..,), a possible use of metaclass is for instance, connection pool logic, which is share by all classes of record from all tables. Another use is logic to to support foreign keys, which involves multiple classes of records.

when you define metaclass, you subclass type, and can overrided the following magic methods to insert your logic.

class somemeta(type):
    __new__(mcs, name, bases, clsdict):
      """
  mcs: is the base metaclass, in this case type.
  name: name of the new class, as provided by the user.
  bases: tuple of base classes 
  clsdict: a dictionary containing all methods and attributes defined on class

  you must return a class object by invoking the __new__ constructor on the base metaclass. 
 ie: 
    return type.__call__(mcs, name, bases, clsdict).

  in the following case:

  class foo(baseclass):
        __metaclass__ = somemeta

  an_attr = 12

  def bar(self):
      ...

  @classmethod
  def foo(cls):
      ...

      arguments would be : ( somemeta, "foo", (baseclass, baseofbase,..., object), {"an_attr":12, "bar": <function>, "foo": <bound class method>}

      you can modify any of these values before passing on to type
      """
      return type.__call__(mcs, name, bases, clsdict)


    def __init__(self, name, bases, clsdict):
      """ 
      called after type has been created. unlike in standard classes, __init__ method cannot modify the instance (cls) - and should be used for class validaton.
      """
      pass


    def __prepare__():
        """
        returns a dict or something that can be used as a namespace.
        the type will then attach methods and attributes from class definition to it.

        call order :

        somemeta.__new__ ->  type.__new__ -> type.__init__ -> somemeta.__init__ 
        """
        return dict()

    def mymethod(cls):
        """ works like a classmethod, but for class objects. Also, my method will not be visible to instances of cls.
        """
        pass

anyhow, those two are the most commonly used hooks. metaclassing is powerful, and above is nowhere near and exhaustive list of uses for metaclassing.

How to mark a method as obsolete or deprecated?

With ObsoleteAttribute you can to show the deprecated method. Obsolete attribute has three constructor:

  1. [Obsolete]: is a no parameter constructor and is a default using this attribute.
  2. [Obsolete(string message)]: in this format you can get message of why this method is deprecated.
  3. [Obsolete(string message, bool error)]: in this format message is very explicit but error means, in compilation time, compiler must be showing error and cause to fail compiling or not.

enter image description here

How can I check whether an array is null / empty?

In Java 8+ you achieve this with the help of streams allMatch method.

For primitive:

int[] k = new int[3];
Arrays.stream(k).allMatch(element -> element != 0)

For Object:

Objects[] k = new Objects[3];
Arrays.stream(k).allMatch(Objects::nonNull)

Reading a single char in Java

i found this way worked nice:

    {
    char [] a;
    String temp;
    Scanner keyboard = new Scanner(System.in);
    System.out.println("please give the first integer :");
    temp=keyboard.next();
    a=temp.toCharArray();
    }

you can also get individual one with String.charAt()

How to reload a page using JavaScript

Automatic reload page after 20 seconds.

<script>
    window.onload = function() {
        setTimeout(function () {
            location.reload()
        }, 20000);
     };
</script>

Android Studio Gradle project "Unable to start the daemon process /initialization of VM"

It has to do with how much memory is available for AS to create a VM environment for your app to populate. The thing is that ever since the update to 2.2 I've had the same problem every time I try to create a new project in AS.

How I solve it is by going into Project (on the left hand side) > Gradle Scripts > gradle.properties. When it opens the file go to the line under "(Line 10)# Specifies the JVM arguments used for the daemon process. (Line 11)# The setting is particularly useful for tweaking memory settings." You're looking for the line that starts with "org.gradle.jvmargs". This should be line 12. Change line 12 to this

org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

After changing this line you can either sync the gradle with the project by clicking Try again on the notification telling you the gradle sync failed (it'll be at the top of the file you opened). Or you can simply close and restart the AS and it should sync.

Essentially what this is saying is for AS to allocate more memory to the app initialization. I know it's not a permanent fix but it should get you through actually starting your app.

How to read from a file or STDIN in Bash?

Here is the simplest way:

#!/bin/sh
cat -

Usage:

$ echo test | sh my_script.sh
test

To assign stdin to the variable, you may use: STDIN=$(cat -) or just simply STDIN=$(cat) as operator is not necessary (as per @mklement0 comment).


To parse each line from the standard input, try the following script:

#!/bin/bash
while IFS= read -r line; do
  printf '%s\n' "$line"
done

To read from the file or stdin (if argument is not present), you can extend it to:

#!/bin/bash
file=${1--} # POSIX-compliant; ${1:--} can be used either.
while IFS= read -r line; do
  printf '%s\n' "$line" # Or: env POSIXLY_CORRECT=1 echo "$line"
done < <(cat -- "$file")

Notes:

- read -r - Do not treat a backslash character in any special way. Consider each backslash to be part of the input line.

- Without setting IFS, by default the sequences of Space and Tab at the beginning and end of the lines are ignored (trimmed).

- Use printf instead of echo to avoid printing empty lines when the line consists of a single -e, -n or -E. However there is a workaround by using env POSIXLY_CORRECT=1 echo "$line" which executes your external GNU echo which supports it. See: How do I echo "-e"?

See: How to read stdin when no arguments are passed? at stackoverflow SE

How to redirect to the same page in PHP

My preferred method for reloading the same page is $_SERVER['PHP_SELF']

header('Location: '.$_SERVER['PHP_SELF']);
die;

Don't forget to die or exit after your header();

Edit: (Thanks @RafaelBarros )

If the query string is also necessary, use

header('Location:'.$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']);
die;

Edit: (thanks @HugoDelsing)

When htaccess url manipulation is in play the value of $_SERVER['PHP_SELF'] may take you to the wrong place. In that case the correct url data will be in $_SERVER['REQUEST_URI'] for your redirect, which can look like Nabil's answer below:

header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
exit;

You can also use $_SERVER[REQUEST_URI] to assign the correct value to $_SERVER['PHP_SELF'] if desired. This can help if you use a redirect function heavily and you don't want to change it. Just set the correct vale in your request handler like this:

$_SERVER['PHP_SELF'] = 'https://sample.com/controller/etc';

Update MySQL using HTML Form and PHP

you have error in your sql syntax.

please use this query and checkout.

$query = mysql_query("UPDATE `anstalld` SET mandag = '$mandag', tisdag = '$tisdag', onsdag = '$onsdag', torsdag = '$torsdag', fredag = '$fredag' WHERE namn = '$namn' ");

Variable interpolation in the shell

Use

"$filepath"_newstap.sh

or

${filepath}_newstap.sh

or

$filepath\_newstap.sh

_ is a valid character in identifiers. Dot is not, so the shell tried to interpolate $filepath_newstap.

You can use set -u to make the shell exit with an error when you reference an undefined variable.

How can I write output from a unit test?

Try using TestContext.WriteLine() which outputs text in test results.

Example:

[TestClass]
public class UnitTest1
{
    private TestContext testContextInstance;

    /// <summary>
    /// Gets or sets the test context which provides
    /// information about and functionality for the current test run.
    /// </summary>
    public TestContext TestContext
    {
        get { return testContextInstance; }
        set { testContextInstance = value; }
    }

    [TestMethod]
    public void TestMethod1()
    {
        TestContext.WriteLine("Message...");
    }
}

The "magic" is described in MSDN:

To use TestContext, create a member and property within your test class [...] The test framework automatically sets the property, which you can then use in unit tests.

Windows XP or later Windows: How can I run a batch file in the background with no window displayed?

Do you need the second batch file to run asynchronously? Typically one batch file runs another synchronously with the call command, and the second one would share the first one's window.

You can use start /b second.bat to launch a second batch file asynchronously from your first that shares your first one's window. If both batch files write to the console simultaneously, the output will be overlapped and probably indecipherable. Also, you'll want to put an exit command at the end of your second batch file, or you'll be within a second cmd shell once everything is done.

Android studio Gradle icon error, Manifest Merger

When an attribute value contains a placeholder (see format below), the manifest merger will swap this placeholder value with an injected value. Injected values are specified in the build.gradle. The syntax for placeholder values is ${name} since @ is reserved for links. After the last file merging occurred, and before the resulting merged android manifest file is written out, all values with a placeholder will be swapped with injected values. A build breakage will be generated if a variable name is unknown.

from http://tools.android.com/tech-docs/new-build-system/user-guide/manifest-merger#TOC-Build-error

Regular expression for validating names and surnames?

I'll try to give a proper answer myself:

The only punctuations that should be allowed in a name are full stop, apostrophe and hyphen. I haven't seen any other case in the list of corner cases.

Regarding numbers, there's only one case with an 8. I think I can safely disallow that.

Regarding letters, any letter is valid.

I also want to include space.

This would sum up to this regex:

^[\p{L} \.'\-]+$

This presents one problem, i.e. the apostrophe can be used as an attack vector. It should be encoded.

So the validation code should be something like this (untested):

var name = nameParam.Trim();
if (!Regex.IsMatch(name, "^[\p{L} \.\-]+$")) 
    throw new ArgumentException("nameParam");
name = name.Replace("'", "&#39;");  //&apos; does not work in IE

Can anyone think of a reason why a name should not pass this test or a XSS or SQL Injection that could pass?


complete tested solution

using System;
using System.Text.RegularExpressions;

namespace test
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            var names = new string[]{"Hello World", 
                "John",
                "João",
                "???",
                "???",
                "??",
                "??",
                "??????",
                "Te???e?a",
                "?????????",
                "???? ?????",
                "?????????",
                "??????",
                "?",
                "D'Addario",
                "John-Doe",
                "P.A.M.",
                "' --",
                "<xss>",
                "\""
            };
            foreach (var nameParam in names)
            {
                Console.Write(nameParam+" ");
                var name = nameParam.Trim();
                if (!Regex.IsMatch(name, @"^[\p{L}\p{M}' \.\-]+$"))
                {
                    Console.WriteLine("fail");
                    continue;
                }
                name = name.Replace("'", "&#39;");
                Console.WriteLine(name);
            }
        }
    }
}

Convert seconds value to hours minutes seconds?

for just minutes and seconds use this

String.format("%02d:%02d", (seconds / 3600 * 60 + ((seconds % 3600) / 60)), (seconds % 60))

When to use MyISAM and InnoDB?

Use MyISAM for very unimportant data or if you really need those minimal performance advantages. The read performance is not better in every case for MyISAM.

I would personally never use MyISAM at all anymore. Choose InnoDB and throw a bit more hardware if you need more performance. Another idea is to look at database systems with more features like PostgreSQL if applicable.

EDIT: For the read-performance, this link shows that innoDB often is actually not slower than MyISAM: https://www.percona.com/blog/2007/01/08/innodb-vs-myisam-vs-falcon-benchmarks-part-1/

What are the best JVM settings for Eclipse?

-vm
C:\Program Files\Java\jdk1.6.0_07\jre\bin\client\jvm.dll

To specify which java version you are using, and use the dll instead of launching a javaw process

Vertical rulers in Visual Studio Code

Visual Studio Code: Version 1.14.2 (1.14.2)

  1. Press Shift + Command + P to open panel
    • For non-macOS users, press Ctrl+P
  2. Enter "settings.json" to open setting files.
  3. At default setting, you can see this:

    // Columns at which to show vertical rulers
    "editor.rulers": [],
    

    This means the empty array won't show the vertical rulers.

  4. At right window "user setting", add the following:

    "editor.rulers": [140]

Save the file, and you will see the rulers.

Getting a 500 Internal Server Error on Laravel 5+ Ubuntu 14.04

Make sure a .env file, containing an APP_KEY, exists in root.

What should be in the .env hasn't been explicitly stated in other solutions, and thought I'd boil it down to the sentence above.

This fixed my 500 error on a fresh install of Laravel.

Steps:

  1. Create a .env file in root (e.g. touch .env)
  2. Make sure it contains at least one line: APP_KEY=
  3. Generate an app key in terminal: php artisan key:generate

Notes:

  • My particular installation didn't include any .env whatsoever (example or otherwise)

  • Simply having a blank .env does not work.

  • A .env containing parameters, but no APP_KEY parameter, does not work.

Bug?: When generating an app key in terminal, it may report as successful, however no key will actually get placed in the .env if the file has no pre-existing APP_KEY= line.

As a reference, here's the official .env with useful baseline parameters. Copy-paste what you need:

https://github.com/laravel/laravel/blob/master/.env.example

send bold & italic text on telegram bot with html

According to the docs you can set the parse_mode field to:

  • MarkdownV2
  • HTML

Markdown still works but it's now considered a legacy mode.

You can pass the parse_mode parameter like this:

https://api.telegram.org/bot[yourBotKey]/sendMessage?chat_id=[yourChatId]&parse_mode=MarkdownV2&text=[yourMessage]

For bold and italic using MarkdownV2:

*bold text*
_italic text_

And for HTML:

<b>bold</b> or <strong>bold</strong>
<i>italic</I> or <em>italic</em>

Make sure to encode your query-string parameters regardless the format you pick. For example:

val message = "*bold text*";
val encodedMsg = URLEncoder.encode(message, "UTF-8");
  • Javascript (ref)
var message = "*bold text*"
var encodedMsg = encodeURIComponent(message)
$message = "*bold text*";
$encodedMsg = urlencode($message);

Javascript Array Alert

If you want to see the array as an array, you can say

alert(JSON.stringify(aCustomers));

instead of all those document.writes.

http://jsfiddle.net/5b2eb/

However, if you want to display them cleanly, one per line, in your popup, do this:

alert(aCustomers.join("\n"));

http://jsfiddle.net/5b2eb/1/

HTML-parser on Node.js

Try https://github.com/tmpvar/jsdom - you give it some HTML and it gives you a DOM.

How can I delete all Git branches which have been merged?

There is no command in Git that will do this for you automatically. But you can write a script that uses Git commands to give you what you need. This could be done in many ways depending on what branching model you are using.

If you need to know if a branch has been merged into master the following command will yield no output if myTopicBranch has been merged (i.e. you can delete it)

$ git rev-list master | grep $(git rev-parse myTopicBranch)

You could use the Git branch command and parse out all branches in Bash and do a for loop over all branches. In this loop you check with above command if you can delete the branch or not.

MySQL ORDER BY rand(), name ASC

SELECT  *
FROM    (
        SELECT  *
        FROM    users
        WHERE   1
        ORDER BY
                rand()
        LIMIT 20
        ) q
ORDER BY
        name

Always show vertical scrollbar in <select>

add:

overflow-y: scroll

in your css bud.

Get Substring - everything before certain char

String str = "223232-1.jpg"
int index = str.IndexOf('-');
if(index > 0) {
    return str.Substring(0, index)
}

PostgreSQL: How to change PostgreSQL user password?

Then type:

$ sudo -u postgres psql

Then:

\password postgres

Then to quit psql:

\q

If that does not work, reconfigure authentication.

Edit /etc/postgresql/9.1/main/pg_hba.conf (path will differ) and change:

    local   all             all                                     peer

to:

    local   all             all                                     md5

Then restart the server:

$ sudo service postgresql restart

C# get string from textbox

In C#, unlike java we do not have to use any method. TextBox property Text is used to get or set its text.

Get

string username = txtusername.Text;
string password = txtpassword.Text;

Set

txtusername.Text = "my_username";
txtpassword.Text = "12345";

How do I format date in jQuery datetimepicker?

This works for me. Since it "extends" datepicker we can still use dateFormat:'dd/mm/yy'.

$(function() {
    $('.jqueryui-marker-datepicker').datetimepicker({
        showSecond: true,
        dateFormat: 'dd/mm/yy',
      timeFormat: 'hh:mm:ss',
      stepHour: 2,
      stepMinute: 10,
      stepSecond: 10

     });
});

iPhone SDK:How do you play video inside a view? Rather than fullscreen

Looking at your code, you need to set the frame of the movie player controller's view, and also add the movie player controller's view to your view. Also, don't forget to add MediaPlayer.framework to your target.

Here's some sample code:

#import <MediaPlayer/MediaPlayer.h>

@interface ViewController () {
    MPMoviePlayerController *moviePlayerController;
}

@property (weak, nonatomic) IBOutlet UIView *movieView; // this should point to a view where the movie will play

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    // Instantiate a movie player controller and add it to your view
    NSString *moviePath = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"mov"];
    NSURL *movieURL = [NSURL fileURLWithPath:moviePath];    
    moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:movieURL];
    [moviePlayerController.view setFrame:self.movieView.bounds];  // player's frame must match parent's
    [self.movieView addSubview:moviePlayerController.view];

    // Configure the movie player controller
    moviePlayerController.controlStyle = MPMovieControlStyleNone;        
    [moviePlayerController prepareToPlay];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    // Start the movie
    [moviePlayerController play];
}

@end

CSS Selector "(A or B) and C"?

is there a better syntax?

No. CSS' or operator (,) does not permit groupings. It's essentially the lowest-precedence logical operator in selectors, so you must use .a.c,.b.c.

Vertical alignment of text and icon in button

There is one rule that is set by font-awesome.css, which you need to override.

You should set overrides in your CSS files rather than inline, but essentially, the icon-ok class is being set to vertical-align: baseline; by default and which I've corrected here:

<button id="whatever" class="btn btn-large btn-primary" name="Continue" type="submit">
    <span>Continue</span>
    <i class="icon-ok" style="font-size:30px; vertical-align: middle;"></i>
</button>

Example here: http://jsfiddle.net/fPXFY/4/ and the output of which is:

enter image description here

I've downsized the font-size of the icon above in this instance to 30px, as it feels too big at 40px for the size of the button, but this is purely a personal viewpoint. You could increase the padding on the button to compensate if required:

<button id="whaever" class="btn btn-large btn-primary" style="padding: 20px;" name="Continue" type="submit">
    <span>Continue</span>
    <i class="icon-ok" style="font-size:30px; vertical-align: middle;"></i>
</button>

Producing: http://jsfiddle.net/fPXFY/5/ the output of which is:

enter image description here

Centering a canvas

in order to center the canvas within the window +"px" should be added to el.style.top and el.style.left.

el.style.top = (viewportHeight - canvasHeight) / 2 +"px";
el.style.left = (viewportWidth - canvasWidth) / 2 +"px";

CSS3 Continuous Rotate Animation (Just like a loading sundial)

I made a small library that lets you easily use a throbber without images.

It uses CSS3 but falls back onto JavaScript if the browser doesn't support it.

// First argument is a reference to a container element in which you
// wish to add a throbber to.
// Second argument is the duration in which you want the throbber to
// complete one full circle.
var throbber = throbbage(document.getElementById("container"), 1000);

// Start the throbber.
throbber.play();

// Pause the throbber.
throbber.pause();

Example.

Hiding elements in responsive layout?

In boostrap 4.1 (run snippet because I copied whole table code from Bootstrap documentation):

_x000D_
_x000D_
.fixed_headers {_x000D_
  width: 750px;_x000D_
  table-layout: fixed;_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
.fixed_headers th {_x000D_
  text-decoration: underline;_x000D_
}_x000D_
.fixed_headers th,_x000D_
.fixed_headers td {_x000D_
  padding: 5px;_x000D_
  text-align: left;_x000D_
}_x000D_
.fixed_headers td:nth-child(1),_x000D_
.fixed_headers th:nth-child(1) {_x000D_
  min-width: 200px;_x000D_
}_x000D_
.fixed_headers td:nth-child(2),_x000D_
.fixed_headers th:nth-child(2) {_x000D_
  min-width: 200px;_x000D_
}_x000D_
.fixed_headers td:nth-child(3),_x000D_
.fixed_headers th:nth-child(3) {_x000D_
  width: 350px;_x000D_
}_x000D_
.fixed_headers thead {_x000D_
  background-color: #333;_x000D_
  color: #FDFDFD;_x000D_
}_x000D_
.fixed_headers thead tr {_x000D_
  display: block;_x000D_
  position: relative;_x000D_
}_x000D_
.fixed_headers tbody {_x000D_
  display: block;_x000D_
  overflow: auto;_x000D_
  width: 100%;_x000D_
  height: 300px;_x000D_
}_x000D_
.fixed_headers tbody tr:nth-child(even) {_x000D_
  background-color: #DDD;_x000D_
}_x000D_
.old_ie_wrapper {_x000D_
  height: 300px;_x000D_
  width: 750px;_x000D_
  overflow-x: hidden;_x000D_
  overflow-y: auto;_x000D_
}_x000D_
.old_ie_wrapper tbody {_x000D_
  height: auto;_x000D_
}
_x000D_
<table class="fixed_headers">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Screen Size</th>_x000D_
      <th>Class</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>Hidden on all</td>_x000D_
      <td><code class="highlighter-rouge">.d-none</code></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Hidden only on xs</td>_x000D_
      <td><code class="highlighter-rouge">.d-none .d-sm-block</code></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Hidden only on sm</td>_x000D_
      <td><code class="highlighter-rouge">.d-sm-none .d-md-block</code></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Hidden only on md</td>_x000D_
      <td><code class="highlighter-rouge">.d-md-none .d-lg-block</code></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Hidden only on lg</td>_x000D_
      <td><code class="highlighter-rouge">.d-lg-none .d-xl-block</code></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Hidden only on xl</td>_x000D_
      <td><code class="highlighter-rouge">.d-xl-none</code></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Visible on all</td>_x000D_
      <td><code class="highlighter-rouge">.d-block</code></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Visible only on xs</td>_x000D_
      <td><code class="highlighter-rouge">.d-block .d-sm-none</code></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Visible only on sm</td>_x000D_
      <td><code class="highlighter-rouge">.d-none .d-sm-block .d-md-none</code></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Visible only on md</td>_x000D_
      <td><code class="highlighter-rouge">.d-none .d-md-block .d-lg-none</code></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Visible only on lg</td>_x000D_
      <td><code class="highlighter-rouge">.d-none .d-lg-block .d-xl-none</code></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Visible only on xl</td>_x000D_
      <td><code class="highlighter-rouge">.d-none .d-xl-block</code></td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

https://getbootstrap.com/docs/4.1/utilities/display/#hiding-elements

Passive Link in Angular 2 - <a href=""> equivalent

I am using this workaround with css:

/*** Angular 2 link without href ***/
a:not([href]){
    cursor: pointer; 
    -webkit-user-select: none; 
    -moz-user-select: none; 
    user-select: none
}

html

<a [routerLink]="/">My link</a>

Hope this helps

Python send POST with header

Thanks a lot for your link to the requests module. It's just perfect. Below the solution to my problem.

import requests
import json

url = 'https://www.mywbsite.fr/Services/GetFromDataBaseVersionned'
payload = {
    "Host": "www.mywbsite.fr",
    "Connection": "keep-alive",
    "Content-Length": 129,
    "Origin": "https://www.mywbsite.fr",
    "X-Requested-With": "XMLHttpRequest",
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5",
    "Content-Type": "application/json",
    "Accept": "*/*",
    "Referer": "https://www.mywbsite.fr/data/mult.aspx",
    "Accept-Encoding": "gzip,deflate,sdch",
    "Accept-Language": "fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4",
    "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3",
    "Cookie": "ASP.NET_SessionId=j1r1b2a2v2w245; GSFV=FirstVisit=; GSRef=https://www.google.fr/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CHgQFjAA&url=https://www.mywbsite.fr/&ei=FZq_T4abNcak0QWZ0vnWCg&usg=AFQjCNHq90dwj5RiEfr1Pw; HelpRotatorCookie=HelpLayerWasSeen=0; NSC_GSPOUGS!TTM=ffffffff09f4f58455e445a4a423660; GS=Site=frfr; __utma=1.219229010.1337956889.1337956889.1337958824.2; __utmb=1.1.10.1337958824; __utmc=1; __utmz=1.1337956889.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)"
}
# Adding empty header as parameters are being sent in payload
headers = {}
r = requests.post(url, data=json.dumps(payload), headers=headers)
print(r.content)

Hide/Show Column in an HTML Table

Without class? You can use the Tag then:

var tds = document.getElementsByTagName('TD'),i;
for (i in tds) {
  tds[i].style.display = 'none';
}

And to show them use:

...style.display = 'table-cell';            

How can I connect to MySQL in Python 3 on Windows?

Untested, but there are some binaries available at:

Unofficial Windows Binaries

frequent issues arising in android view, Error parsing XML: unbound prefix

I had the same problem, and found that the solution was to add the android:tools to the first node. In my case it is a LineraLayout:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:orientation="vertical">

How do you dynamically allocate a matrix?

arr = new int[cols*rows];

If you either don't mind syntax

arr[row * cols + col] = Aij;

or use operator[] overaloading somewhere. This may be more cache-friendly than array of arrays, or may be not, more probably you shouldn't care about it. I just want to point out that a) array of arrays is not only solution, b) some operations are more easier to implement if matrix located in one block of memory. E.g.

for(int i=0;i < rows*cols;++i)
   matrix[i]=someOtherMatrix[i];

one line shorter than

for(int r=0;i < rows;++r)
  for(int c=0;i < cols;++s)
     matrix[r][c]=someOtherMatrix[r][c];

though adding rows to such matrix is more painful

How many threads can a Java VM support?

Maximum number of threads depends on following things:

  • Hardware Configuration like microprocessor, RAM.
  • Operating System like whether it is 32-bit or 64-bit
  • Code inside the run method. If code inside the run method is huge then single thread object will have more memory requirement
  • How do I get bit-by-bit data from an integer value in C?

    #include <stdio.h>
    
    int main(void)
    {
        int number = 7; /* signed */
        int vbool[8 * sizeof(int)];
        int i;
            for (i = 0; i < 8 * sizeof(int); i++)
            {
                vbool[i] = number<<i < 0;   
                printf("%d", vbool[i]);
            }
        return 0;
    }
    

    Should __init__() call the parent class's __init__()?

    If you need something from super's __init__ to be done in addition to what is being done in the current class's __init__, you must call it yourself, since that will not happen automatically. But if you don't need anything from super's __init__, no need to call it. Example:

    >>> class C(object):
            def __init__(self):
                self.b = 1
    
    
    >>> class D(C):
            def __init__(self):
                super().__init__() # in Python 2 use super(D, self).__init__()
                self.a = 1
    
    
    >>> class E(C):
            def __init__(self):
                self.a = 1
    
    
    >>> d = D()
    >>> d.a
    1
    >>> d.b  # This works because of the call to super's init
    1
    >>> e = E()
    >>> e.a
    1
    >>> e.b  # This is going to fail since nothing in E initializes b...
    Traceback (most recent call last):
      File "<pyshell#70>", line 1, in <module>
        e.b  # This is going to fail since nothing in E initializes b...
    AttributeError: 'E' object has no attribute 'b'
    

    __del__ is the same way, (but be wary of relying on __del__ for finalization - consider doing it via the with statement instead).

    I rarely use __new__. I do all the initialization in __init__.

    Jquery select this + class

    Use $(this).find(), or pass this in context, using jQuery context with selector.

    Using $(this).find()

    $(".class").click(function(){
         $(this).find(".subclass").css("visibility","visible");
    });
    

    Using this in context, $( selector, context ), it will internally call find function, so better to use find on first place.

    $(".class").click(function(){
         $(".subclass", this).css("visibility","visible");
    });
    

    If input field is empty, disable submit button

    Try this code

    $(document).ready(function(){
        $('.sendButton').attr('disabled',true);
    
        $('#message').keyup(function(){
            if($(this).val().length !=0){
                $('.sendButton').attr('disabled', false);
            }
            else
            {
                $('.sendButton').attr('disabled', true);        
            }
        })
    });
    

    Check demo Fiddle

    You are missing the else part of the if statement (to disable the button again if textbox is empty) and parentheses () after val function in if($(this).val.length !=0){

    Java: How to set Precision for double value?

    Here's an efficient way of achieving the result with two caveats.

    1. Limits precision to 'maximum' N digits (not fixed to N digits).
    2. Rounds down the number (not round to nearest).

    See sample test cases here.

    123.12345678 ==> 123.123
    1.230000 ==> 1.23
    1.1 ==> 1.1
    1 ==> 1.0
    0.000 ==> 0.0
    0.00 ==> 0.0
    0.4 ==> 0.4
    0 ==> 0.0
    1.4999 ==> 1.499
    1.4995 ==> 1.499
    1.4994 ==> 1.499
    

    Here's the code. The two caveats I mentioned above can be addressed pretty easily, however, speed mattered more to me than accuracy, so i left it here. String manipulations like System.out.printf("%.2f",123.234); are computationally costly compared to mathematical operations. In my tests, the below code (without the sysout) took 1/30th the time compared to String manipulations.

    public double limitPrecision(String dblAsString, int maxDigitsAfterDecimal) {
        int multiplier = (int) Math.pow(10, maxDigitsAfterDecimal);
        double truncated = (double) ((long) ((Double.parseDouble(dblAsString)) * multiplier)) / multiplier;
        System.out.println(dblAsString + " ==> " + truncated);
        return truncated;
    }
    

    A terminal command for a rooted Android to remount /System as read/write

    I had the same problem. So here is the real answer: Mount the system under /proc. Here is my command:

    mount -o rw,remount /proc /system

    It works, and in fact is the only way I can overcome the Read-only System problem.

    MIME types missing in IIS 7 for ASP.NET - 404.17

    There are two reasons you might get this message:

    1. ASP.Net is not configured. For this run from Administrator command %FrameworkDir%\%FrameworkVersion%\aspnet_regiis -i. Read the message carefully. On Windows8/IIS8 it may say that this is no longer supported and you may have to use Turn Windows Features On/Off dialog in Install/Uninstall a Program in Control Panel.
    2. Another reason this may happen is because your App Pool is not configured correctly. For example, you created website for WordPress and you also want to throw in few aspx files in there, WordPress creates app pool that says don't run CLR stuff. To fix this just open up App Pool and enable CLR.

    string comparison in batch file

    While @ajv-jsy's answer works most of the time, I had the same problem as @MarioVilas. If one of the strings to be compared contains a double quote ("), the variable expansion throws an error.

    Example:

    @echo off
    SetLocal
    
    set Lhs="
    set Rhs="
    
    if "%Lhs%" == "%Rhs%" echo Equal
    

    Error:

    echo was unexpected at this time.
    

    Solution:

    Enable delayed expansion and use ! instead of %.

    @echo off
    SetLocal EnableDelayedExpansion
    
    set Lhs="
    set Rhs="
    
    if !Lhs! == !Rhs! echo Equal
    
    :: Surrounding with double quotes also works but appears (is?) unnecessary.
    if "!Lhs!" == "!Rhs!" echo Equal
    

    I have not been able to break it so far using this technique. It works with empty strings and all the symbols I threw at it.

    Test:

    @echo off
    SetLocal EnableDelayedExpansion
    
    :: Test empty string
    set Lhs=
    set Rhs=
    echo Lhs: !Lhs! & echo Rhs: !Rhs!
    if !Lhs! == !Rhs! (echo Equal) else (echo Not Equal)
    echo.
    
    :: Test symbols
    set Lhs= \ / : * ? " ' < > | %% ^^ ` ~ @ # $ [ ] & ( ) + - _ =
    set Rhs= \ / : * ? " ' < > | %% ^^ ` ~ @ # $ [ ] & ( ) + - _ =
    echo Lhs: !Lhs! & echo Rhs: !Rhs!
    if !Lhs! == !Rhs! (echo Equal) else (echo Not Equal)
    echo.
    

    Using :after to clear floating elements

    Write like this:

    .wrapper:after {
        content: '';
        display: block;
        clear: both;
    }
    

    Check this http://jsfiddle.net/EyNnk/1/

    What is this CSS selector? [class*="span"]

    It selects all elements where the class name contains the string "span" somewhere. There's also ^= for the beginning of a string, and $= for the end of a string. Here's a good reference for some CSS selectors.

    I'm only familiar with the bootstrap classes spanX where X is an integer, but if there were other selectors that ended in span, it would also fall under these rules.

    It just helps to apply blanket CSS rules.

    jQuery OR Selector?

    Finally I've found hack how to do it:

    div:not(:not(.classA,.classB)) > span
    

    (selects div with class classA OR classB with direct child span)

    C# Wait until condition is true

    you can use SpinUntil which is buildin in the .net-framework. Please note: This method causes high cpu-workload.

    Pandas unstack problems: ValueError: Index contains duplicate entries, cannot reshape

    Here's an example DataFrame which show this, it has duplicate values with the same index. The question is, do you want to aggregate these or keep them as multiple rows?

    In [11]: df
    Out[11]:
       0  1  2      3
    0  1  2  a  16.86
    1  1  2  a  17.18
    2  1  4  a  17.03
    3  2  5  b  17.28
    
    In [12]: df.pivot_table(values=3, index=[0, 1], columns=2, aggfunc='mean')  # desired?
    Out[12]:
    2        a      b
    0 1
    1 2  17.02    NaN
      4  17.03    NaN
    2 5    NaN  17.28
    
    In [13]: df1 = df.set_index([0, 1, 2])
    
    In [14]: df1
    Out[14]:
               3
    0 1 2
    1 2 a  16.86
        a  17.18
      4 a  17.03
    2 5 b  17.28
    
    In [15]: df1.unstack(2)
    ValueError: Index contains duplicate entries, cannot reshape
    

    One solution is to reset_index (and get back to df) and use pivot_table.

    In [16]: df1.reset_index().pivot_table(values=3, index=[0, 1], columns=2, aggfunc='mean')
    Out[16]:
    2        a      b
    0 1
    1 2  17.02    NaN
      4  17.03    NaN
    2 5    NaN  17.28
    

    Another option (if you don't want to aggregate) is to append a dummy level, unstack it, then drop the dummy level...

    Javascript: formatting a rounded number to N decimals

    I think below function can help

    function roundOff(value,round) {
       return (parseInt(value * (10 ** (round + 1))) - parseInt(value * (10 ** round)) * 10) > 4 ? (((parseFloat(parseInt((value + parseFloat(1 / (10 ** round))) * (10 ** round))))) / (10 ** round)) : (parseFloat(parseInt(value * (10 ** round))) / ( 10 ** round));
    }
    

    usage : roundOff(600.23458,2); will return 600.23

    Tips for using Vim as a Java IDE?

    Some tips:

    • Make sure you use vim (vi improved). Linux and some versions of UNIX symlink vi to vim.
    • You can get code completion with eclim
    • Or you can get vi functionality within Eclipse with viPlugin
    • Syntax highlighting is great with vim
    • Vim has good support for writing little macros like running ant/maven builds

    Have fun :-)

    Javascript: Easier way to format numbers?

    There's the NUMBERFORMATTER jQuery plugin, details below:

    https://code.google.com/p/jquery-numberformatter/

    From the above link:

    This plugin is a NumberFormatter plugin. Number formatting is likely familiar to anyone who's worked with server-side code like Java or PHP and who has worked with internationalization.

    EDIT: Replaced the link with a more direct one.

    <Django object > is not JSON serializable

    The easiest way is to use a JsonResponse.

    For a queryset, you should pass a list of the the values for that queryset, like so:

    from django.http import JsonResponse
    
    queryset = YourModel.objects.filter(some__filter="some value").values()
    return JsonResponse({"models_to_return": list(queryset)})
    

    How to install Visual C++ Build tools?

    The current version (2019/03/07) is Build Tools for Visual Studio 2017. It's an online installer, you need to include at least the individual components:

    • VC++ 2017 version xx.x tools
    • Windows SDK to use standard libraries.

    "’" showing on page instead of " ' "

    (Unicode codepoint U+2019 RIGHT SINGLE QUOTATION MARK) is encoded in UTF-8 as bytes:

    0xE2 0x80 0x99.

    ’ (Unicode codepoints U+00E2 U+20AC U+2122) is encoded in UTF-8 as bytes:

    0xC3 0xA2   0xE2 0x82 0xAC   0xE2 0x84 0xA2.

    These are the bytes your browser is actually receiving in order to produce ’ when processed as UTF-8.

    That means that your source data is going through two charset conversions before being sent to the browser:

    1. The source character (U+2019) is first encoded as UTF-8 bytes:

      0xE2 0x80 0x99

    2. those individual bytes were then being mis-interpreted and decoded to Unicode codepoints U+00E2 U+20AC U+2122 by one of the Windows-125X charsets (1252, 1254, 1256, and 1258 all map 0xE2 0x80 0x99 to U+00E2 U+20AC U+2122), and then those codepoints are being encoded as UTF-8 bytes:

      0xE2 -> U+00E2 -> 0xC3 0xA2
      0x80 -> U+20AC -> 0xE2 0x82 0xAC
      0x99 -> U+2122 -> 0xE2 0x84 0xA2

    You need to find where the extra conversion in step 2 is being performed and remove it.

    How to concatenate multiple column values into a single column in Panda dataframe

    The answer given by @allen is reasonably generic but can lack in performance for larger dataframes:

    Reduce does a lot better:

    from functools import reduce
    
    import pandas as pd
    
    # make data
    df = pd.DataFrame(index=range(1_000_000))
    df['1'] = 'CO'
    df['2'] = 'BOB'
    df['3'] = '01'
    df['4'] = 'BILL'
    
    
    def reduce_join(df, columns):
        assert len(columns) > 1
        slist = [df[x].astype(str) for x in columns]
        return reduce(lambda x, y: x + '_' + y, slist[1:], slist[0])
    
    
    def apply_join(df, columns):
        assert len(columns) > 1
        return df[columns].apply(lambda row:'_'.join(row.values.astype(str)), axis=1)
    
    # ensure outputs are equal
    df1 = reduce_join(df, list('1234'))
    df2 = apply_join(df, list('1234'))
    assert df1.equals(df2)
    
    # profile
    %timeit df1 = reduce_join(df, list('1234'))  # 733 ms
    %timeit df2 = apply_join(df, list('1234'))   # 8.84 s
    
    

    Check if a value exists in pandas dataframe index

    Multi index works a little different from single index. Here are some methods for multi-indexed dataframe.

    df = pd.DataFrame({'col1': ['a', 'b','c', 'd'], 'col2': ['X','X','Y', 'Y'], 'col3': [1, 2, 3, 4]}, columns=['col1', 'col2', 'col3'])
    df = df.set_index(['col1', 'col2'])
    

    in df.index works for the first level only when checking single index value.

    'a' in df.index     # True
    'X' in df.index     # False
    

    Check df.index.levels for other levels.

    'a' in df.index.levels[0] # True
    'X' in df.index.levels[1] # True
    

    Check in df.index for an index combination tuple.

    ('a', 'X') in df.index  # True
    ('a', 'Y') in df.index  # False
    

    "Instantiating" a List in Java?

    Use List<Integer> list = new ArrayList<Integer>();

    Alternative to deprecated getCellType

    It looks that 3.15 offers no satisfying solution: either one uses the old style with Cell.CELL_TYPE_*, or we use the method getCellTypeEnum() which is marked as deprecated. A lot of disturbances for little add value...

    How to fix Invalid AES key length?

    You can use this code, this code is for AES-256-CBC or you can use it for other AES encryption. Key length error mainly comes in 256-bit encryption.

    This error comes due to the encoding or charset name we pass in the SecretKeySpec. Suppose, in my case, I have a key length of 44, but I am not able to encrypt my text using this long key; Java throws me an error of invalid key length. Therefore I pass my key as a BASE64 in the function, and it converts my 44 length key in the 32 bytes, which is must for the 256-bit encryption.

    import javax.crypto.Cipher;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.SecretKeySpec;
    import java.security.MessageDigest;
    import java.security.Security;
    import java.util.Base64;
    
    public class Encrypt {
    
        static byte [] arr = {1,2,3,4,5,6,7,8,9};
    
        // static byte [] arr = new byte[16];
    
          public static void main(String...args) {
            try {
             //   System.out.println(Cipher.getMaxAllowedKeyLength("AES"));
                Base64.Decoder decoder = Base64.getDecoder();
                // static byte [] arr = new byte[16];
                Security.setProperty("crypto.policy", "unlimited");
                String key = "Your key";
           //     System.out.println("-------" + key);
    
                String value = "Hey, i am adnan";
                String IV = "0123456789abcdef";
           //     System.out.println(value);
                // log.info(value);
              IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
                //    IvParameterSpec iv = new IvParameterSpec(arr);
    
            //    System.out.println(key);
                SecretKeySpec skeySpec = new SecretKeySpec(decoder.decode(key), "AES");
             //   System.out.println(skeySpec);
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            //    System.out.println("ddddddddd"+IV);
                cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
           //     System.out.println(cipher.getIV());
    
                byte[] encrypted = cipher.doFinal(value.getBytes());
                String encryptedString = Base64.getEncoder().encodeToString(encrypted);
    
                System.out.println("encrypted string,,,,,,,,,,,,,,,,,,,: " + encryptedString);
                // vars.put("input-1",encryptedString);
                //  log.info("beanshell");
            }catch (Exception e){
                System.out.println(e.getMessage());
            }
        }
    }
    

    How to pass ArrayList of Objects from one to another activity using Intent in android?

    I do one of two things in this scenario

    1. Implement a serialize/deserialize system for my objects and pass them as Strings (in JSON format usually, but you can serialize them any way you'd like)

    2. Implement a container that lives outside of the activities so that all my activities can read and write to this container. You can make this container static or use some kind of dependency injection to retrieve the same instance in each activity.

    Parcelable works just fine, but I always found it to be an ugly looking pattern and doesn't really add any value that isn't there if you write your own serialization code outside of the model.

    How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers

    The simplest general function to find the positive modulo would be this- It would work on both positive and negative values of x.

    int modulo(int x,int N){
        return (x % N + N) %N;
    }
    

    How to get just the responsive grid from Bootstrap 3?

    Just choose Grid system and "responsive utilities" it gives you this: http://jsfiddle.net/7LVzs/

    Force page scroll position to top at page refresh in HTML

    The answer here does not works for safari, document.ready is often fired too early.

    Ought to use the beforeunload event which prevent you form doing some setTimeout

    $(window).on('beforeunload', function(){
      $(window).scrollTop(0);
    });
    

    Changing Java Date one hour back

    Or using the famous Joda Time library:

    DateTime dateTime = new DateTime();
    dateTime = dateTime.minusHours(1);
    Date modifiedDate = dateTime.toDate();
    

    How to reload a page after the OK click on the Alert Page

    Try this code..

    IN PHP Code

    echo "<script type='text/javascript'>".
          "alert('Success to add the task to a project.');
           location.reload;".
         "</script>";
    

    IN Javascript

    function refresh()
    {
        alert("click ok to refresh  page");
        location.reload();
    }
    

    AngularJS does not send hidden field value

    Here I would like to share my working code :

    _x000D_
    _x000D_
    <input type="text" name="someData" ng-model="data" ng-init="data=2" style="display: none;"/>_x000D_
    OR_x000D_
    <input type="hidden" name="someData" ng-model="data" ng-init="data=2"/>_x000D_
    OR_x000D_
    <input type="hidden" name="someData" ng-init="data=2"/>
    _x000D_
    _x000D_
    _x000D_

    Reference to a non-shared member requires an object reference occurs when calling public sub

    You either have to make the method Shared or use an instance of the class General:

    Dim gen = New General()
    gen.updateDynamics(get_prospect.dynamicsID)
    

    or

    General.updateDynamics(get_prospect.dynamicsID)
    
    Public Shared Sub updateDynamics(dynID As Int32)
        ' ... '
    End Sub
    

    Shared(VB.NET)

    How do I delete multiple rows in Entity Framework (without foreach)

    The quickest way to delete is using a stored procedure. I prefer stored procedures in a database project over dynamic SQL because renames will be handled correctly and have compiler errors. Dynamic SQL could refer to tables that have been deleted/renamed causing run time errors.

    In this example, I have two tables List and ListItems. I need a fast way to delete all the ListItems of a given list.

    CREATE TABLE [act].[Lists]
    (
        [Id] INT NOT NULL PRIMARY KEY IDENTITY, 
        [Name] NVARCHAR(50) NOT NULL
    )
    GO
    CREATE UNIQUE INDEX [IU_Name] ON [act].[Lists] ([Name])
    GO
    CREATE TABLE [act].[ListItems]
    (
        [Id] INT NOT NULL IDENTITY, 
        [ListId] INT NOT NULL, 
        [Item] NVARCHAR(100) NOT NULL, 
        CONSTRAINT PK_ListItems_Id PRIMARY KEY NONCLUSTERED (Id),
        CONSTRAINT [FK_ListItems_Lists] FOREIGN KEY ([ListId]) REFERENCES [act].[Lists]([Id]) ON DELETE CASCADE
    )
    go
    CREATE UNIQUE CLUSTERED INDEX IX_ListItems_Item 
    ON [act].[ListItems] ([ListId], [Item]); 
    GO
    
    CREATE PROCEDURE [act].[DeleteAllItemsInList]
        @listId int
    AS
        DELETE FROM act.ListItems where ListId = @listId
    RETURN 0
    

    Now the interesting part of deleting the items and updating Entity framework using an extension.

    public static class ListExtension
    {
        public static void DeleteAllListItems(this List list, ActDbContext db)
        {
            if (list.Id > 0)
            {
                var listIdParameter = new SqlParameter("ListId", list.Id);
                db.Database.ExecuteSqlCommand("[act].[DeleteAllItemsInList] @ListId", listIdParameter);
            }
            foreach (var listItem in list.ListItems.ToList())
            {
                db.Entry(listItem).State = EntityState.Detached;
            }
        }
    }
    

    The main code can now use it is as

    [TestMethod]
    public void DeleteAllItemsInListAfterSavingToDatabase()
    {
        using (var db = new ActDbContext())
        {
            var listName = "TestList";
            // Clean up
            var listInDb = db.Lists.Where(r => r.Name == listName).FirstOrDefault();
            if (listInDb != null)
            {
                db.Lists.Remove(listInDb);
                db.SaveChanges();
            }
    
            // Test
            var list = new List() { Name = listName };
            list.ListItems.Add(new ListItem() { Item = "Item 1" });
            list.ListItems.Add(new ListItem() { Item = "Item 2" });
            db.Lists.Add(list);
            db.SaveChanges();
            listInDb = db.Lists.Find(list.Id);
            Assert.AreEqual(2, list.ListItems.Count);
            list.DeleteAllListItems(db);
            db.SaveChanges();
            listInDb = db.Lists.Find(list.Id);
            Assert.AreEqual(0, list.ListItems.Count);
        }
    }
    

    Python PIP Install throws TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'

    Bizarrely if I remove the proxy from the environment and add it to the command line it works for me. For example to upgrade pip itself:

    env http_proxy= https_proxy= pip install pip --upgrade --proxy 'http://proxy-url:80'
    

    My issue was having the proxy in the environment. It seems that pip only honors the one in argument.

    How to set JAVA_HOME path on Ubuntu?

    add JAVA_HOME to the file:

    /etc/environment
    

    for it to be available to the entire system (you would need to restart Ubuntu though)

    How do I run msbuild from the command line using Windows SDK 7.1?

    Using the "Developer Command Prompt for Visual Studio 20XX" instead of "cmd" will set the path for msbuild automatically without having to add it to your environment variables.

    Why "Data at the root level is invalid. Line 1, position 1." for XML Document?

    Remove everything before <?xml version="1.0" encoding="utf-8"?>

    Sometimes, there is some "invisible" (not visible in all text editors). Some programs add this.

    It's called BOM, you can read more about it here: https://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding

    How to tell PowerShell to wait for each command to end before starting the next?

    If you use Start-Process <path to exe> -NoNewWindow -Wait

    You can also use the -PassThru option to echo output.

    How to use if statements in LESS

    LESS has guard expressions for mixins, not individual attributes.

    So you'd create a mixin like this:

    .debug(@debug) when (@debug = true) {
        header {
          background-color: yellow;
          #title {
              background-color: orange;
          }
        }
    
        article {
          background-color: red;
        }
    }
    

    And turn it on or off by calling .debug(true); or .debug(false) (or not calling it at all).

    Read input numbers separated by spaces

    By default, cin reads from the input discarding any spaces. So, all you have to do is to use a do while loop to read the input more than one time:

    do {
       cout<<"Enter a number, or numbers separated by a space, between 1 and 1000."<<endl;
       cin >> num;
    
       // reset your variables
    
       // your function stuff (calculations)
    }
    while (true); // or some condition
    

    CSS Transition doesn't work with top, bottom, left, right

    Try setting a default value in the css (to let it know where you want it to start out)

    CSS

    position: relative;
    transition: all 2s ease 0s;
    top: 0; /* start out at position 0 */
    

    how to delete all commit history in github?

    If you are sure you want to remove all commit history, simply delete the .git directory in your project root (note that it's hidden). Then initialize a new repository in the same folder and link it to the GitHub repository:

    git init
    git remote add origin [email protected]:user/repo
    

    now commit your current version of code

    git add *
    git commit -am 'message'
    

    and finally force the update to GitHub:

    git push -f origin master
    

    However, I suggest backing up the history (the .git folder in the repository) before taking these steps!

    Run task only if host does not belong to a group

    Here's another way to do this:

    - name: my command
      command: echo stuff
      when: "'groupname' not in group_names"
    

    group_names is a magic variable as documented here: https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#accessing-information-about-other-hosts-with-magic-variables :

    group_names is a list (array) of all the groups the current host is in.

    How to check whether a file is empty or not?

    import os    
    os.path.getsize(fullpathhere) > 0
    

    Getting HTML elements by their attribute names

    You can use querySelectorAll:

        document.querySelectorAll('span[property=name]');
    

    Core dump file is not generated

    Make sure your current directory (at the time of crash -- server may change directories) is writable. If the server calls setuid, the directory has to be writable by that user.

    Also check /proc/sys/kernel/core_pattern. That may redirect core dumps to another directory, and that directory must be writable. More info here.

    Checking session if empty or not

    You need to check that Session["emp_num"] is not null before trying to convert it to a string otherwise you will get a null reference exception.

    I'd go with your first example - but you could make it slightly more "elegant".

    There are a couple of ways, but the ones that springs to mind are:

    if (Session["emp_num"] is string)
    {
    }
    

    or

    if (!string.IsNullOrEmpty(Session["emp_num"] as string))
    {
    }
    

    This will return null if the variable doesn't exist or isn't a string.

    Convert JS Object to form data

    In my case my object also had property which was array of files. Since they are binary they should be dealt differently - index doesn't need to be part of the key. So i modified @Vladimir Novopashin's and @developer033's answer:

    export function convertToFormData(data, formData, parentKey) {
      if(data === null || data === undefined) return null;
    
      formData = formData || new FormData();
    
      if (typeof data === 'object' && !(data instanceof Date) && !(data instanceof File)) {
        Object.keys(data).forEach(key => 
          convertToFormData(data[key], formData, (!parentKey ? key : (data[key] instanceof File ? parentKey : `${parentKey}[${key}]`)))
        );
      } else {
        formData.append(parentKey, data);
      }
    
      return formData;
    }
    

    How to debug ORA-01775: looping chain of synonyms?

    We had the same ORA-01775 error but in our case, the schema user was missing some 'grant select' on a couple of the public synonyms.

    Run certain code every n seconds

    import threading
    
    def printit():
      threading.Timer(5.0, printit).start()
      print "Hello, World!"
    
    printit()
    
    # continue with the rest of your code
    

    https://docs.python.org/3/library/threading.html#timer-objects

    Delete all lines starting with # or ; in Notepad++

    Its possible, but not directly.

    In short, go to the search, use your regex, check "mark line" and click "Find all". It results in bookmarks for all those lines.

    In the search menu there is a point "delete bookmarked lines" voila.

    I found the answer here (the correct answer is the second one, not the accepted!): How to delete specific lines on Notepad++?

    Error:Execution failed for task ':app:transformClassesWithDexForDebug' in android studio

    Thank @Ironman for his complete answer, however I should add my solution according to what I've experienced facing this issue.

    In build.gradle (Module: app):

    compile 'com.android.support:multidex:1.0.1'
    
        ...
    
        dexOptions {
                javaMaxHeapSize "4g"
            }
    
        ...
    
        defaultConfig {
                multiDexEnabled true
        }
    

    Also, put the following in gradle.properties file:

    org.gradle.jvmargs=-Xmx4096m -XX\:MaxPermSize\=512m -XX\:+HeapDumpOnOutOfMemoryError -Dfile.encoding\=UTF-8
    

    I should mention, these numbers are for my laptop config (MacBook Pro with 16 GB RAM) therefore please edit them as your config.

    Convert JSON to DataTable

    Deserialize your jsonstring to some class

    List<User> UserList = JsonConvert.DeserializeObject<List<User>>(jsonString);
    

    Write following extension method to your project

    public static DataTable ToDataTable<T>(this IList<T> data)
    {
        PropertyDescriptorCollection props =
        TpeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        for(int i = 0 ; i < props.Count ; i++)
        {
            PropertyDescriptor prop = props[i];
            table.Columns.Add(prop.Name, prop.PropertyType);
        }
        object[] values = new object[props.Count];
        foreach (T item in data)
        {
            for (int i = 0; i < values.Length; i++)
            {
                values[i] = props[i].GetValue(item);
            }
            table.Rows.Add(values);
        }
        return table;        
    }
    

    Call extension method like

    UserList.ToDataTable<User>();
    

    Traversing text in Insert mode

    In GVim, you can use the mouse. But honestly, what's wrong with using the arrow keys? There's a reason why they are on a keyboard.

    How to get array keys in Javascript?

    Seems to work.

    var widthRange = new Array();
    widthRange[46] = { sel:46, min:0,  max:52 };
    widthRange[66] = { sel:66, min:52, max:70 };
    widthRange[90] = { sel:90, min:70, max:94 };
    
    for (var key in widthRange)
    {
        document.write(widthRange[key].sel + "<br />");
        document.write(widthRange[key].min + "<br />");
        document.write(widthRange[key].max + "<br />");
    }
    

    ZIP Code (US Postal Code) validation

    One way to check valid Canada postal code is-

    function isValidCAPostal(pcVal) {
       return ^[A-Za-z][0-9][A-Za-z]\s{0,1}[0-9][A-Za-z][0-9]$/.test(pcVal);
    }
    

    Hope this will help someone.

    Logging in Scala

    Writer, Monoid and a Monad implementation.

    What is the difference between `throw new Error` and `throw someObject`?

    The following article perhaps goes into some more detail as to which is a better choice; throw 'An error' or throw new Error('An error'):

    http://www.nczonline.net/blog/2009/03/10/the-art-of-throwing-javascript-errors-part-2/

    It suggests that the latter (new Error()) is more reliable, since browsers like Internet Explorer and Safari (unsure of versions) don't correctly report the message when using the former.

    Doing so will cause an error to be thrown, but not all browsers respond the way you’d expect. Firefox, Opera, and Chrome each display an “uncaught exception” message and then include the message string. Safari and Internet Explorer simply throw an “uncaught exception” error and don’t provide the message string at all. Clearly, this is suboptimal from a debugging point of view.

    How/when to generate Gradle wrapper files?

    Generating the Gradle Wrapper

    Project build gradle

    // Top-level build file where you can add configuration options common to all sub-projects/modules.
    
    // Running 'gradle wrapper' will generate gradlew - Getting gradle wrapper working and using it will save you a lot of pain.
    task wrapper(type: Wrapper) {
        gradleVersion = '2.2' 
    }
    
    // Look Google doesn't use Maven Central, they use jcenter now.
    buildscript {
        repositories {
            jcenter()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:1.0.1'
    
            // NOTE: Do not place your application dependencies here; they belong
            // in the individual module build.gradle files
        }
    }
    
    allprojects {
        repositories {
            jcenter()
        }
    }
    

    Then at the command-line run

    gradle wrapper
    

    If you're missing gradle on your system install it or the above won't work. On a Mac it is best to install via Homebrew.

    brew install gradle
    

    After you have successfully run the wrapper task and generated gradlew, don't use your system gradle. It will save you a lot of headaches.

    ./gradlew assemble
    

    What about the gradle plugin seen above?

    com.android.tools.build:gradle:1.0.1
    

    You should set the version to be the latest and you can check the tools page and edit the version accordingly.

    See what Android Studio generates

    The addition of gradle and the newest Android Studio have changed project layout dramatically. If you have an older project I highly recommend creating a clean one with the latest Android Studio and see what Google considers the standard project.

    Android Studio has facilities for importing older projects which can also help.

    Get only filename from url in php without any variable values which exist in the url

    This should work:

    echo basename($_SERVER['REQUEST_URI'], '?' . $_SERVER['QUERY_STRING']);
    

    But beware of any malicious parts in your URL.

    Is there a MessageBox equivalent in WPF?

    In WPF it seems this code,

    System.Windows.Forms.MessageBox.Show("Test");
    

    is replaced with:

    System.Windows.MessageBox.Show("Test");
    

    Is CSS Turing complete?

    This answer is not accurate because it mix description of UTM and UTM itself (Universal Turing Machine).

    We have good answer but from different perspective and it do not show directly flaws in current top answer.


    First of all we can agree that human can work as UTM. This mean if we do

    CSS + Human == UTM
    

    Then CSS part is useless because all work can be done by Human who will do UTM part. Act of clicking can be UTM, because you do not click at random but only in specific places.

    Instead of CSS I could use this text (Rule 110):

    000 -> 0
    001 -> 1
    010 -> 1
    011 -> 1
    100 -> 0
    101 -> 1
    110 -> 1
    111 -> 0
    

    To guide my actions and result will be same. This mean this text UTM? No this is only input (description) that other UTM (human or computer) can read and run. Clicking is enough to run any UTM.


    Critical part that CSS lack is ability to change of it own state in arbitrary way, if CSS could generate clicks then it would be UTM. Argument that your clicks are "crank" for CSS is not accurate because real "crank" for CSS is Layout Engine that run it and it should be enough to prove that CSS is UTM.

    Jetty: HTTP ERROR: 503/ Service Unavailable

    None of these answers worked for me.

    I had to remove all deployed java web app:

    • Windows/Show View/Other...
    • Go the the Server folder and select "Servers"
    • Right-click on the J2EE Preview at localhost
    • Click to Add and Remove... Click Remove all

    Then run the project on the server

    The Error is gone!

    You will have to stop the server before deploying another project because it will not be found by the server. Otherwise you will get a 404 error

    TCPDF Save file to folder?

    $pdf->Output() takes a second parameter $dest, which accepts a single character. The default, $dest='I' opens the PDF in the browser.

    Use F to save to file

    $pdf->Output('/path/to/file.pdf', 'F')
    

    Print the stack trace of an exception

    Apache commons provides utility to convert the stack trace from throwable to string.

    Usage:

    ExceptionUtils.getStackTrace(e)
    

    For complete documentation refer to https://commons.apache.org/proper/commons-lang/javadocs/api-release/index.html

    How to determine CPU and memory consumption from inside a process?

    Linux

    A portable way of reading memory and load numbers is the sysinfo call

    Usage

       #include <sys/sysinfo.h>
    
       int sysinfo(struct sysinfo *info);
    

    DESCRIPTION

       Until Linux 2.3.16, sysinfo() used to return information in the
       following structure:
    
           struct sysinfo {
               long uptime;             /* Seconds since boot */
               unsigned long loads[3];  /* 1, 5, and 15 minute load averages */
               unsigned long totalram;  /* Total usable main memory size */
               unsigned long freeram;   /* Available memory size */
               unsigned long sharedram; /* Amount of shared memory */
               unsigned long bufferram; /* Memory used by buffers */
               unsigned long totalswap; /* Total swap space size */
               unsigned long freeswap;  /* swap space still available */
               unsigned short procs;    /* Number of current processes */
               char _f[22];             /* Pads structure to 64 bytes */
           };
    
       and the sizes were given in bytes.
    
       Since Linux 2.3.23 (i386), 2.3.48 (all architectures) the structure
       is:
    
           struct sysinfo {
               long uptime;             /* Seconds since boot */
               unsigned long loads[3];  /* 1, 5, and 15 minute load averages */
               unsigned long totalram;  /* Total usable main memory size */
               unsigned long freeram;   /* Available memory size */
               unsigned long sharedram; /* Amount of shared memory */
               unsigned long bufferram; /* Memory used by buffers */
               unsigned long totalswap; /* Total swap space size */
               unsigned long freeswap;  /* swap space still available */
               unsigned short procs;    /* Number of current processes */
               unsigned long totalhigh; /* Total high memory size */
               unsigned long freehigh;  /* Available high memory size */
               unsigned int mem_unit;   /* Memory unit size in bytes */
               char _f[20-2*sizeof(long)-sizeof(int)]; /* Padding to 64 bytes */
           };
    
       and the sizes are given as multiples of mem_unit bytes.
    

    Difference between binary tree and binary search tree

    Binary Tree stands for a data structure which is made up of nodes that can only have two children references.

    Binary Search Tree (BST) on the other hand, is a special form of Binary Tree data structure where each node has a comparable value, and smaller valued children attached to left and larger valued children attached to the right.

    Thus, all BST's are Binary Tree however only some Binary Tree's may be also BST. Notify that BST is a subset of Binary Tree.

    So, Binary Tree is more of a general data-structure than Binary Search Tree. And also you have to notify that Binary Search Tree is a sorted tree whereas there is no such set of rules for generic Binary Tree.

    Binary Tree

    A Binary Tree which is not a BST;

             5
           /   \
          /     \
         9       2
        / \     / \
      15   17  19  21
    

    Binary Search Tree (sorted Tree)

    A Binary Search Tree which is also a Binary Tree;

             50
           /    \
          /      \
         25      75
        /  \    /  \
      20    30 70   80
    

    Binary Search Tree Node property

    Also notify that for any parent node in the BST;

    • All the left nodes have smaller value than the value of the parent node. In the upper example, the nodes with values { 20, 25, 30 } which are all located on the left (left descendants) of 50, are smaller than 50.

    • All the right nodes have greater value than the value of the parent node. In the upper example, the nodes with values { 70, 75, 80 } which are all located on the right (right descendants) of 50, are greater than 50.

    There is no such a rule for Binary Tree Node. The only rule for Binary Tree Node is having two childrens so it self-explains itself that why called binary.

    Calling dynamic function with dynamic number of parameters

    Your code only works for global functions, ie. members of the window object. To use it with arbitrary functions, pass the function itself instead of its name as a string:

    function dispatch(fn, args) {
        fn = (typeof fn == "function") ? fn : window[fn];  // Allow fn to be a function object or the name of a global function
        return fn.apply(this, args || []);  // args is optional, use an empty array by default
    }
    
    function f1() {}
    
    function f2() {
        var f = function() {};
        dispatch(f, [1, 2, 3]);
    }
    
    dispatch(f1, ["foobar"]);
    dispatch("f1", ["foobar"]);
    
    f2();  // calls inner-function "f" in "f2"
    dispatch("f", [1, 2, 3]);  // doesn't work since "f" is local in "f2"
    

    assign multiple variables to the same value in Javascript

    There is another option that does not introduce global gotchas when trying to initialize multiple variables to the same value. Whether or not it is preferable to the long way is a judgement call. It will likely be slower and may or may not be more readable. In your specific case, I think that the long way is probably more readable and maintainable as well as being faster.

    The other way utilizes Destructuring assignment.

    _x000D_
    _x000D_
    let [moveUp, moveDown,_x000D_
         moveLeft, moveRight,_x000D_
         mouseDown, touchDown] = Array(6).fill(false);_x000D_
    _x000D_
    console.log(JSON.stringify({_x000D_
        moveUp, moveDown,_x000D_
        moveLeft, moveRight,_x000D_
        mouseDown, touchDown_x000D_
    }, null, '  '));_x000D_
    _x000D_
    // NOTE: If you want to do this with objects, you would be safer doing this_x000D_
    let [obj1, obj2, obj3] = Array(3).fill(null).map(() => ({}));_x000D_
    console.log(JSON.stringify({_x000D_
        obj1, obj2, obj3_x000D_
    }, null, '  '));_x000D_
    // So that each array element is a unique object_x000D_
    _x000D_
    // Or another cool trick would be to use an infinite generator_x000D_
    let [a, b, c, d] = (function*() { while (true) yield {x: 0, y: 0} })();_x000D_
    console.log(JSON.stringify({_x000D_
        a, b, c, d_x000D_
    }, null, '  '));_x000D_
    _x000D_
    // Or generic fixed generator function_x000D_
    function* nTimes(n, f) {_x000D_
        for(let i = 0; i < n; i++) {_x000D_
            yield f();_x000D_
        }_x000D_
    }_x000D_
    let [p1, p2, p3] = [...nTimes(3, () => ({ x: 0, y: 0 }))];_x000D_
    console.log(JSON.stringify({_x000D_
        p1, p2, p3_x000D_
    }, null, '  '));
    _x000D_
    _x000D_
    _x000D_

    This allows you to initialize a set of var, let, or const variables to the same value on a single line all with the same expected scope.

    References:

    How to process a file in PowerShell line-by-line as a stream

    If you are really about to work on multi-gigabyte text files then do not use PowerShell. Even if you find a way to read it faster processing of huge amount of lines will be slow in PowerShell anyway and you cannot avoid this. Even simple loops are expensive, say for 10 million iterations (quite real in your case) we have:

    # "empty" loop: takes 10 seconds
    measure-command { for($i=0; $i -lt 10000000; ++$i) {} }
    
    # "simple" job, just output: takes 20 seconds
    measure-command { for($i=0; $i -lt 10000000; ++$i) { $i } }
    
    # "more real job": 107 seconds
    measure-command { for($i=0; $i -lt 10000000; ++$i) { $i.ToString() -match '1' } }
    

    UPDATE: If you are still not scared then try to use the .NET reader:

    $reader = [System.IO.File]::OpenText("my.log")
    try {
        for() {
            $line = $reader.ReadLine()
            if ($line -eq $null) { break }
            # process the line
            $line
        }
    }
    finally {
        $reader.Close()
    }
    

    UPDATE 2

    There are comments about possibly better / shorter code. There is nothing wrong with the original code with for and it is not pseudo-code. But the shorter (shortest?) variant of the reading loop is

    $reader = [System.IO.File]::OpenText("my.log")
    while($null -ne ($line = $reader.ReadLine())) {
        $line
    }
    

    node.js: read a text file into an array. (Each line an item in the array.)

    Essentially this will do the job: .replace(/\r\n/g,'\n').split('\n'). This works on Mac, Linux & Windows.

    Code Snippets

    Synchronous:

    const { readFileSync } = require('fs');
    
    const array = readFileSync('file.txt').toString().replace(/\r\n/g,'\n').split('\n');
    
    for(let i of array) {
        console.log(i);
    }
    

    Asynchronous:

    With the fs.promises API that provides an alternative set of asynchronous file system methods that return Promise objects rather than using callbacks. (No need to promisify, you can use async-await with this too, available on and after Node.js version 10.0.0)

    const { readFile } = require('fs').promises;
    
    readFile('file.txt', function(err, data) {
        if(err) throw err;
    
        const arr = data.toString().replace(/\r\n/g,'\n').split('\n');
    
        for(let i of arr) {
            console.log(i);
        }
    });
    

    More about \r & \n here: \r\n, \r and \n what is the difference between them?

    What is the best way to use a HashMap in C++?

    For those of us trying to figure out how to hash our own classes whilst still using the standard template, there is a simple solution:

    1. In your class you need to define an equality operator overload ==. If you don't know how to do this, GeeksforGeeks has a great tutorial https://www.geeksforgeeks.org/operator-overloading-c/

    2. Under the standard namespace, declare a template struct called hash with your classname as the type (see below). I found a great blogpost that also shows an example of calculating hashes using XOR and bitshifting, but that's outside the scope of this question, but it also includes detailed instructions on how to accomplish using hash functions as well https://prateekvjoshi.com/2014/06/05/using-hash-function-in-c-for-user-defined-classes/

    namespace std {
    
      template<>
      struct hash<my_type> {
        size_t operator()(const my_type& k) {
          // Do your hash function here
          ...
        }
      };
    
    }
    
    1. So then to implement a hashtable using your new hash function, you just have to create a std::map or std::unordered_map just like you would normally do and use my_type as the key, the standard library will automatically use the hash function you defined before (in step 2) to hash your keys.
    #include <unordered_map>
    
    int main() {
      std::unordered_map<my_type, other_type> my_map;
    }
    

    Print Html template in Angular 2 (ng-print in Angular 2)

    Shortest solution to be assign the window to a typescript variable then call the print method on that, like below

    in template file

    <button ... (click)="window.print()" ...>Submit</button>
    

    and, in typescript file

    window: any;
    constructor() {
      this.window = window;
    }
    

    How to send HTML-formatted email?

    Best way to send html formatted Email

    This code will be in "Customer.htm"

        <table>
        <tr>
            <td>
                Dealer's Company Name
            </td>
            <td>
                :
            </td>
            <td>
                #DealerCompanyName#
            </td>
        </tr>
    </table>
    

    Read HTML file Using System.IO.File.ReadAllText. get all HTML code in string variable.

    string Body = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("EmailTemplates/Customer.htm"));
    

    Replace Particular string to your custom value.

    Body = Body.Replace("#DealerCompanyName#", _lstGetDealerRoleAndContactInfoByCompanyIDResult[0].CompanyName);
    

    call SendEmail(string Body) Function and do procedure to send email.

     public static void SendEmail(string Body)
            {
                MailMessage message = new MailMessage();
                message.From = new MailAddress(Session["Email"].Tostring());
                message.To.Add(ConfigurationSettings.AppSettings["RequesEmail"].ToString());
                message.Subject = "Request from " + SessionFactory.CurrentCompany.CompanyName + " to add a new supplier";
                message.IsBodyHtml = true;
                message.Body = Body;
    
                SmtpClient smtpClient = new SmtpClient();
                smtpClient.UseDefaultCredentials = true;
    
                smtpClient.Host = ConfigurationSettings.AppSettings["SMTP"].ToString();
                smtpClient.Port = Convert.ToInt32(ConfigurationSettings.AppSettings["PORT"].ToString());
                smtpClient.EnableSsl = true;
                smtpClient.Credentials = new System.Net.NetworkCredential(ConfigurationSettings.AppSettings["USERNAME"].ToString(), ConfigurationSettings.AppSettings["PASSWORD"].ToString());
                smtpClient.Send(message);
            }
    

    Best practices for Storyboard login screen, handling clearing of data upon logout

    Here's my Swifty solution for any future onlookers.

    1) Create a protocol to handle both login and logout functions:

    protocol LoginFlowHandler {
        func handleLogin(withWindow window: UIWindow?)
        func handleLogout(withWindow window: UIWindow?)
    }
    

    2) Extend said protocol and provide the functionality here for logging out:

    extension LoginFlowHandler {
    
        func handleLogin(withWindow window: UIWindow?) {
    
            if let _ = AppState.shared.currentUserId {
                //User has logged in before, cache and continue
                self.showMainApp(withWindow: window)
            } else {
                //No user information, show login flow
                self.showLogin(withWindow: window)
            }
        }
    
        func handleLogout(withWindow window: UIWindow?) {
    
            AppState.shared.signOut()
    
            showLogin(withWindow: window)
        }
    
        func showLogin(withWindow window: UIWindow?) {
            window?.subviews.forEach { $0.removeFromSuperview() }
            window?.rootViewController = nil
            window?.rootViewController = R.storyboard.login.instantiateInitialViewController()
            window?.makeKeyAndVisible()
        }
    
        func showMainApp(withWindow window: UIWindow?) {
            window?.rootViewController = nil
            window?.rootViewController = R.storyboard.mainTabBar.instantiateInitialViewController()
            window?.makeKeyAndVisible()
        }
    
    }
    

    3) Then I can conform my AppDelegate to the LoginFlowHandler protocol, and call handleLogin on startup:

    class AppDelegate: UIResponder, UIApplicationDelegate, LoginFlowHandler {
    
        var window: UIWindow?
    
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    
            window = UIWindow.init(frame: UIScreen.main.bounds)
    
            initialiseServices()
    
            handleLogin(withWindow: window)
    
            return true
        }
    
    }
    

    From here, my protocol extension will handle the logic or determining if the user if logged in/out, and then change the windows rootViewController accordingly!

    How to delete a folder with files using Java

    we can use the spring-core dependency;

    boolean result = FileSystemUtils.deleteRecursively(file);
    

    START_STICKY and START_NOT_STICKY

    KISS answer

    Difference:

    START_STICKY

    the system will try to re-create your service after it is killed

    START_NOT_STICKY

    the system will not try to re-create your service after it is killed


    Standard example:

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }
    

    Using "&times" word in html changes to ×

    I suspect you did not know that there are different & escapes in HTML. The W3C you can see the codes. &times means × in HTML code. Use &amp;times instead.

    How to save and load numpy.array() data properly?

    np.save('data.npy', num_arr) # save
    new_num_arr = np.load('data.npy') # load
    

    How to increase dbms_output buffer?

    Here you go:

    DECLARE
    BEGIN
      dbms_output.enable(NULL); -- Disables the limit of DBMS
      -- Your print here !
    END;
    

    split string in two on given index and return both parts

    You can easily expand it to split on multiple indexes, and to take an array or string

    const splitOn = (slicable, ...indices) =>
      [0, ...indices].map((n, i, m) => slicable.slice(n, m[i + 1]));
    
    splitOn('foo', 1);
    // ["f", "oo"]
    
    splitOn([1, 2, 3, 4], 2);
    // [[1, 2], [3, 4]]
    
    splitOn('fooBAr', 1, 4);
    //  ["f", "ooB", "Ar"]
    

    lodash issue tracker: https://github.com/lodash/lodash/issues/3014

    Python syntax for "if a or b or c but not all of them"

    The English sentence:

    “if a or b or c but not all of them”

    Translates to this logic:

    (a or b or c) and not (a and b and c)
    

    The word "but" usually implies a conjunction, in other words "and". Furthermore, "all of them" translates to a conjunction of conditions: this condition, and that condition, and other condition. The "not" inverts that entire conjunction.

    I do not agree that the accepted answer. The author neglected to apply the most straightforward interpretation to the specification, and neglected to apply De Morgan's Law to simplify the expression to fewer operators:

     not a or not b or not c  ->  not (a and b and c)
    

    while claiming that the answer is a "minimal form".

    How to stop a function

    A simple return statement will 'stop' or return the function; in precise terms, it 'returns' function execution to the point at which the function was called - the function is terminated without further action.

    That means you could have a number of places throughout your function where it might return. Like this:

    def player():
        # do something here
        check_winner_variable = check_winner()  # check something 
        if check_winner_variable == '1': 
            return
        second_test_variable = second_test()
        if second_test_variable == '1': 
            return
           
        # let the computer do something
        computer()
    

    Typescript: How to define type for a function callback (as any function type, not universal any) used in a method parameter

    Following from Ryan's answer, I think that the interface you are looking for is defined as follows:

    interface Param {
        title: string;
        callback: () => void;
    }
    

    How to stretch div height to fill parent div - CSS

    http://jsfiddle.net/QWDxr/1/

    Use the "min-height" property
    Be wary of paddings, margins and borders :)

    html, body {
        margin: 0;
        padding: 0;
        border: 0;
    }
    #B, #C, #D {
        position: absolute;
    }
    #A{
        top: 0;
        width: 100%;
        height: 35px;
        background-color: #99CC00;
    }
    #B {
        top: 35px;
        width: 200px;
        bottom: 35px;
        background-color: #999999;
        z-index:100;
    }
    #B2 {
        min-height: 100%;
        height: 100%;
        margin-top: -35px;
        bottom: 0;
        background-color: red;
        width: 200px;
        overflow: scroll;
    }
    #B1 {
        height: 35px;
        width: 35px;
        margin-left: 200px;
        background-color: #CC0066;
    }
    #C {
        top: 35px;
        left: 200px;
        right: 0;
        bottom: 35px;
        background-color: #CCCCCC;
    }
    #D {
        bottom: 0;
        width: 100%;
        height: 35px;
        background-color: #3399FF;
    }
    

    Export data from R to Excel

    Another option is the openxlsx-package. It doesn't depend on and can read, edit and write Excel-files. From the description from the package:

    openxlsx simplifies the the process of writing and styling Excel xlsx files from R and removes the dependency on Java

    Example usage:

    library(openxlsx)
    
    # read data from an Excel file or Workbook object into a data.frame
    df <- read.xlsx('name-of-your-excel-file.xlsx')
    
    # for writing a data.frame or list of data.frames to an xlsx file
    write.xlsx(df, 'name-of-your-excel-file.xlsx')
    

    Besides these two basic functions, the openxlsx-package has a host of other functions for manipulating Excel-files.

    For example, with the writeDataTable-function you can create formatted tables in an Excel-file.

    Get response from PHP file using AJAX

    <?php echo 'apple'; ?> is pretty much literally all you need on the server.

    as for the JS side, the output of the server-side script is passed as a parameter to the success handler function, so you'd have

    success: function(data) {
       alert(data); // apple
    }
    

    How to pop an alert message box using PHP?

    You could use Javascript:

    // This is in the PHP file and sends a Javascript alert to the client
    $message = "wrong answer";
    echo "<script type='text/javascript'>alert('$message');</script>";
    

    What is difference between CrudRepository and JpaRepository interfaces in Spring Data JPA?

    Ken's answer is basically right but I'd like to chime in on the "why would you want to use one over the other?" part of your question.

    Basics

    The base interface you choose for your repository has two main purposes. First, you allow the Spring Data repository infrastructure to find your interface and trigger the proxy creation so that you inject instances of the interface into clients. The second purpose is to pull in as much functionality as needed into the interface without having to declare extra methods.

    The common interfaces

    The Spring Data core library ships with two base interfaces that expose a dedicated set of functionalities:

    • CrudRepository - CRUD methods
    • PagingAndSortingRepository - methods for pagination and sorting (extends CrudRepository)

    Store-specific interfaces

    The individual store modules (e.g. for JPA or MongoDB) expose store-specific extensions of these base interfaces to allow access to store-specific functionality like flushing or dedicated batching that take some store specifics into account. An example for this is deleteInBatch(…) of JpaRepository which is different from delete(…) as it uses a query to delete the given entities which is more performant but comes with the side effect of not triggering the JPA-defined cascades (as the spec defines it).

    We generally recommend not to use these base interfaces as they expose the underlying persistence technology to the clients and thus tighten the coupling between them and the repository. Plus, you get a bit away from the original definition of a repository which is basically "a collection of entities". So if you can, stay with PagingAndSortingRepository.

    Custom repository base interfaces

    The downside of directly depending on one of the provided base interfaces is two-fold. Both of them might be considered as theoretical but I think they're important to be aware of:

    1. Depending on a Spring Data repository interface couples your repository interface to the library. I don't think this is a particular issue as you'll probably use abstractions like Page or Pageable in your code anyway. Spring Data is not any different from any other general purpose library like commons-lang or Guava. As long as it provides reasonable benefit, it's just fine.
    2. By extending e.g. CrudRepository, you expose a complete set of persistence method at once. This is probably fine in most circumstances as well but you might run into situations where you'd like to gain more fine-grained control over the methods expose, e.g. to create a ReadOnlyRepository that doesn't include the save(…) and delete(…) methods of CrudRepository.

    The solution to both of these downsides is to craft your own base repository interface or even a set of them. In a lot of applications I have seen something like this:

    interface ApplicationRepository<T> extends PagingAndSortingRepository<T, Long> { }
    
    interface ReadOnlyRepository<T> extends Repository<T, Long> {
    
      // Al finder methods go here
    }
    

    The first repository interface is some general purpose base interface that actually only fixes point 1 but also ties the ID type to be Long for consistency. The second interface usually has all the find…(…) methods copied from CrudRepository and PagingAndSortingRepository but does not expose the manipulating ones. Read more on that approach in the reference documentation.

    Summary - tl;dr

    The repository abstraction allows you to pick the base repository totally driven by you architectural and functional needs. Use the ones provided out of the box if they suit, craft your own repository base interfaces if necessary. Stay away from the store specific repository interfaces unless unavoidable.

    What is the difference between FragmentPagerAdapter and FragmentStatePagerAdapter?

    FragmentPagerAdapter: the fragment of each page the user visits will be stored in memory, although the view will be destroyed. So when the page is visible again, the view will be recreated but the fragment instance is not recreated. This can result in a significant amount of memory being used. FragmentPagerAdapter should be used when we need to store the whole fragment in memory. FragmentPagerAdapter calls detach(Fragment) on the transaction instead of remove(Fragment).

    FragmentStatePagerAdapter: the fragment instance is destroyed when it is not visible to the User, except the saved state of the fragment. This results in using only a small amount of Memory and can be useful for handling larger data sets. Should be used when we have to use dynamic fragments, like fragments with widgets, as their data could be stored in the savedInstanceState.Also it won’t affect the performance even if there are large number of fragments.

    Why the switch statement cannot be applied on strings?

    In C++ you can only use a switch statement on int and char

    Why dict.get(key) instead of dict[key]?

    get takes a second optional value. If the specified key does not exist in your dictionary, then this value will be returned.

    dictionary = {"Name": "Harry", "Age": 17}
    dictionary.get('Year', 'No available data')
    >> 'No available data'
    

    If you do not give the second parameter, None will be returned.

    If you use indexing as in dictionary['Year'], nonexistent keys will raise KeyError.

    There is already an open DataReader associated with this Command which must be closed first

    I had the same error, when I tried to update some records within read loop. I've tried the most voted answer MultipleActiveResultSets=true and found, that it's just workaround to get the next error 

    New transaction is not allowed because there are other threads running in the session

    The best approach, that will work for huge ResultSets is to use chunks and open separate context for each chunk as described in  SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session

    How do I remove the first characters of a specific column in a table?

    The top answer is not suitable when values may have length less than 4.

    In T-SQL

    You will get "Invalid length parameter passed to the right function" because it doesn't accept negatives. Use a CASE statement:

    SELECT case when len(foo) >= 4 then RIGHT(foo, LEN(foo) - 4) else '' end AS myfoo from mytable;
    

    In Postgres

    Values less than 4 give the surprising behavior below instead of an error, because passing negative values to RIGHT trims the first characters instead of the entire string. It makes more sense to use RIGHT(MyColumn, -5) instead.

    An example comparing what you get when you use the top answer's "length - 5" instead of "-5":

    create temp table foo (foo) as values ('123456789'),('12345678'),('1234567'),('123456'),('12345'),('1234'),('123'),('12'),('1'), ('');
    
    select foo, right(foo, length(foo) - 5), right(foo, -5) from foo;
    
    foo       len(foo) - 5  just -5   
    --------- ------------  -------     
    123456789 6789          6789 
    12345678  678           678  
    1234567   67            67   
    123456    6             6    
    12345                       
    1234      234               
    123       3                 
    12                          
    1                           
    

    Convert NaN to 0 in javascript

    Methods that use isNaN do not work if you're trying to use parseInt, for example:

    parseInt("abc"); // NaN
    parseInt(""); // NaN
    parseInt("14px"); // 14
    

    But in the second case isNaN produces false (i.e. the null string is a number)

    n="abc"; isNaN(n) ? 0 : parseInt(n); // 0
    n=""; isNaN(n) ? 0: parseInt(n); // NaN
    n="14px"; isNaN(n) ? 0 : parseInt(n); // 14
    

    In summary, the null string is considered a valid number by isNaN but not by parseInt. Verified with Safari, Firefox and Chrome on OSX Mojave.

    Long press on UITableView

    I've used Anna-Karenina's answer, and it works almost great with a very serious bug.

    If you're using sections, long-pressing the section title will give you a wrong result of pressing the first row on that section, I've added a fixed version below (including the filtering of dummy calls based on the gesture state, per Anna-Karenina suggestion).

    - (IBAction)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
    {
        if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
    
            CGPoint p = [gestureRecognizer locationInView:self.tableView];
    
            NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];
            if (indexPath == nil) {
                NSLog(@"long press on table view but not on a row");
            } else {
                UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
                if (cell.isHighlighted) {
                    NSLog(@"long press on table view at section %d row %d", indexPath.section, indexPath.row);
                }
            }
        }
    }
    

    Svn switch from trunk to branch

    You don't need to --relocate since the branch is within the same repository URL. Just do:

    svn switch https://www.example.com/svn/branches/v1p2p3
    

    Python - A keyboard command to stop infinite loop?

    Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.

    Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.

    Why am I getting a " Traceback (most recent call last):" error?

    I don't know which version of Python you are using but I tried this in Python 3 and made a few changes and it looks like it works. The raw_input function seems to be the issue here. I changed all the raw_input functions to "input()" and I also made minor changes to the printing to be compatible with Python 3. AJ Uppal is correct when he says that you shouldn't name a variable and a function with the same name. See here for reference:

    TypeError: 'int' object is not callable

    My code for Python 3 is as follows:

    # https://stackoverflow.com/questions/27097039/why-am-i-getting-a-traceback-most-recent-call-last-error
    
    raw_input = 0
    M = 1.6
    # Miles to Kilometers
    # Celsius Celsius = (var1 - 32) * 5/9
    # Gallons to liters Gallons = 3.6
    # Pounds to kilograms Pounds = 0.45
    # Inches to centimete Inches = 2.54
    
    
    def intro():
        print("Welcome! This program will convert measures for you.")
        main()
    
    def main():
        print("Select operation.")
        print("1.Miles to Kilometers")
        print("2.Fahrenheit to Celsius")
        print("3.Gallons to liters")
        print("4.Pounds to kilograms")
        print("5.Inches to centimeters")
    
        choice = input("Enter your choice by number: ")
    
        if choice == '1':
            convertMK()
    
        elif choice == '2':
            converCF()
    
        elif choice == '3':
            convertGL()
    
        elif choice == '4':
            convertPK()
    
        elif choice == '5':
            convertPK()
    
        else:
            print("Error")
    
    
    def convertMK():
        input_M = float(input(("Miles: ")))
        M_conv = (M) * input_M
        print("Kilometers: {M_conv}\n")
        restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
        if restart == 'y':
            main()
        elif restart == 'n':
            end()
        else:
            print("I didn't quite understand that answer. Terminating.")
            main()
    
    def converCF():
        input_F = float(input(("Fahrenheit: ")))
        F_conv = (input_F - 32) * 5/9
        print("Celcius: {F_conv}\n")
        restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
        if restart == 'y':
            main()
        elif restart == 'n':
            end()
        else:
            print("I didn't quite understand that answer. Terminating.")
            main()
    
    def convertGL():
        input_G = float(input(("Gallons: ")))
        G_conv = input_G * 3.6
        print("Centimeters: {G_conv}\n")
        restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
        if restart == 'y':
            main()
        elif restart == 'n':
            end()
        else:
            print ("I didn't quite understand that answer. Terminating.")
            main()
    
    def convertPK():
        input_P = float(input(("Pounds: ")))
        P_conv = input_P * 0.45
        print("Centimeters: {P_conv}\n")
        restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
        if restart == 'y':
            main()
        elif restart == 'n':
            end()
        else:
            print ("I didn't quite understand that answer. Terminating.")
            main()
    
    def convertIC():
        input_cm = float(input(("Inches: ")))
        inches_conv = input_cm * 2.54
        print("Centimeters: {inches_conv}\n")
        restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
        if restart == 'y':
            main()
        elif restart == 'n':
            end()
        else:
            print ("I didn't quite understand that answer. Terminating.")
            main()
    
    def end():
        print("This program will close.")
        exit()
    
    intro()
    

    I noticed a small bug in your code as well. This function should ideally convert pounds to kilograms but it looks like when it prints, it is printing "Centimeters" instead of kilograms.

    def convertPK():
        input_P = float(input(("Pounds: ")))
        P_conv = input_P * 0.45
        # Printing error in the line below
        print("Centimeters: {P_conv}\n")
        restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
        if restart == 'y':
            main()
        elif restart == 'n':
            end()
        else:
            print ("I didn't quite understand that answer. Terminating.")
            main()
    

    I hope this helps.

    JQuery Find #ID, RemoveClass and AddClass

    jQuery('#testID2').find('.test2').replaceWith('.test3');
    

    Semantically, you are selecting the element with the ID testID2, then you are looking for any descendent elements with the class test2 (does not exist) and then you are replacing that element with another element (elements anywhere in the page with the class test3) that also do not exist.

    You need to do this:

    jQuery('#testID2').addClass('test3').removeClass('test2');
    

    This selects the element with the ID testID2, then adds the class test3 to it. Last, it removes the class test2 from that element.

    How to run Tensorflow on CPU

    You could use tf.config.set_visible_devices. One possible function that allows you to set if and which GPUs to use is:

    import tensorflow as tf
    
    def set_gpu(gpu_ids_list):
        gpus = tf.config.list_physical_devices('GPU')
        if gpus:
            try:
                gpus_used = [gpus[i] for i in gpu_ids_list]
                tf.config.set_visible_devices(gpus_used, 'GPU')
                logical_gpus = tf.config.experimental.list_logical_devices('GPU')
                print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPU")
            except RuntimeError as e:
                # Visible devices must be set before GPUs have been initialized
                print(e)
    

    Suppose you are on a system with 4 GPUs and you want to use only two GPUs, the one with id = 0 and the one with id = 2, then the first command of your code, immediately after importing the libraries, would be:

    set_gpu([0, 2])
    

    In your case, to use only the CPU, you can invoke the function with an empty list:

    set_gpu([])
    

    For completeness, if you want to avoid that the runtime initialization will allocate all memory on the device, you can use tf.config.experimental.set_memory_growth. Finally, the function to manage which devices to use, occupying the GPUs memory dynamically, becomes:

    import tensorflow as tf
    
    def set_gpu(gpu_ids_list):
        gpus = tf.config.list_physical_devices('GPU')
        if gpus:
            try:
                gpus_used = [gpus[i] for i in gpu_ids_list]
                tf.config.set_visible_devices(gpus_used, 'GPU')
                for gpu in gpus_used:
                    tf.config.experimental.set_memory_growth(gpu, True)
                logical_gpus = tf.config.experimental.list_logical_devices('GPU')
                print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPU")
            except RuntimeError as e:
                # Visible devices must be set before GPUs have been initialized
                print(e)
    

    How can I get dictionary key as variable directly in Python (not by searching from value)?

    You could simply use * which unpacks the dictionary keys. Example:

    d = {'x': 1, 'y': 2}
    t = (*d,)
    print(t) # ('x', 'y')
    

    How to use wget in php?

    lots of methods available in php to read a file like exec, file_get_contents, curl and fopen but it depend on your requirement and file permission

    Visit this file_get_contents vs cUrl

    Basically file_get_contents for for you

    $data = file_get_contents($file_url);
    

    Set Culture in an ASP.Net MVC app

    protected void Application_AcquireRequestState(object sender, EventArgs e)
            {
                if(Context.Session!= null)
                Thread.CurrentThread.CurrentCulture =
                        Thread.CurrentThread.CurrentUICulture = (Context.Session["culture"] ?? (Context.Session["culture"] = new CultureInfo("pt-BR"))) as CultureInfo;
            }
    

    How to check if a table contains an element in Lua?

    I know this is an old post, but I wanted to add something for posterity. The simple way of handling the issue that you have is to make another table, of value to key.

    ie. you have 2 tables that have the same value, one pointing one direction, one pointing the other.

    function addValue(key, value)
        if (value == nil) then
            removeKey(key)
            return
        end
        _primaryTable[key] = value
        _secodaryTable[value] = key
    end
    
    function removeKey(key)
        local value = _primaryTable[key]
        if (value == nil) then
            return
        end
        _primaryTable[key] = nil
        _secondaryTable[value] = nil
    end
    
    function getValue(key)
        return _primaryTable[key]
    end
    
    function containsValue(value)
        return _secondaryTable[value] ~= nil
    end
    

    You can then query the new table to see if it has the key 'element'. This prevents the need to iterate through every value of the other table.

    If it turns out that you can't actually use the 'element' as a key, because it's not a string for example, then add a checksum or tostring on it for example, and then use that as the key.

    Why do you want to do this? If your tables are very large, the amount of time to iterate through every element will be significant, preventing you from doing it very often. The additional memory overhead will be relatively small, as it will be storing 2 pointers to the same object, rather than 2 copies of the same object. If your tables are very small, then it will matter much less, infact it may even be faster to iterate than to have another map lookup.

    The wording of the question however strongly suggests that you have a large number of items to deal with.

    HTML5 record audio to file

    Update now Chrome also supports MediaRecorder API from v47. The same thing to do would be to use it( guessing native recording method is bound to be faster than work arounds), the API is really easy to use, and you would find tons of answers as to how to upload a blob for the server.

    Demo - would work in Chrome and Firefox, intentionally left out pushing blob to server...

    Code Source


    Currently, there are three ways to do it:

    1. as wav[ all code client-side, uncompressed recording], you can check out --> Recorderjs. Problem: file size is quite big, more upload bandwidth required.
    2. as mp3[ all code client-side, compressed recording], you can check out --> mp3Recorder. Problem: personally, I find the quality bad, also there is this licensing issue.
    3. as ogg [ client+ server(node.js) code, compressed recording, infinite hours of recording without browser crash ], you can check out --> recordOpus, either only client-side recording, or client-server bundling, the choice is yours.

      ogg recording example( only firefox):

      var mediaRecorder = new MediaRecorder(stream);
      mediaRecorder.start();  // to start recording.    
      ...
      mediaRecorder.stop();   // to stop recording.
      mediaRecorder.ondataavailable = function(e) {
          // do something with the data.
      }
      

      Fiddle Demo for ogg recording.

    How to connect to a docker container from outside the host (same network) [Windows]

    1. Open Oracle VM VirtualBox Manager
    2. Select the VM used by Docker
    3. Click Settings -> Network
    4. Adapter 1 should (default?) be "Attached to: NAT"
    5. Click Advanced -> Port Forwarding
    6. Add rule: Protocol TCP, Host Port 8080, Guest Port 8080 (leave Host IP and Guest IP empty)
    7. Guest is your docker container and Host is your machine

    You should now be able to browse to your container via localhost:8080 and your-internal-ip:8080.

    Highcharts - how to have a chart with dynamic height?

    I had the same problem and I fixed it with:

    <div id="container" style="width: 100%; height: 100%; position:absolute"></div>
    

    The chart fits perfect to the browser even if I resize it. You can change the percentage according to your needs.

    Using textures in THREE.js

    By the time the image is loaded, the renderer has already drawn the scene, hence it is too late. The solution is to change

    texture = THREE.ImageUtils.loadTexture('crate.gif'),
    

    into

    texture = THREE.ImageUtils.loadTexture('crate.gif', {}, function() {
        renderer.render(scene);
    }),
    

    Difference between parameter and argument

    Generally, the parameters are what are used inside the function and the arguments are the values passed when the function is called. (Unless you take the opposite view — Wikipedia mentions alternative conventions when discussing parameters and arguments).

    double sqrt(double x)
    {
        ...
        return x;
    }
    
    void other(void)
    {
         double two = sqrt(2.0);
    }
    

    Under my thesis, x is the parameter to sqrt() and 2.0 is the argument.

    The terms are often used at least somewhat interchangeably.

    how to count length of the JSON array element

    Before going to answer read this Documentation once. Then you clearly understand the answer.

    Try this It may work for you.

    Object.keys(data.shareInfo[i]).length
    

    Write string to text file and ensure it always overwrites the existing content.

    Generally, FileMode.Create is what you're looking for.

    Confusing error in R: Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, : line 1 did not have 42 elements)

    read.table wants to return a data.frame, which must have an element in each column. Therefore R expects each row to have the same number of elements and it doesn't fill in empty spaces by default. Try read.table("/PathTo/file.csv" , fill = TRUE ) to fill in the blanks.

    e.g.

    read.table( text= "Element1 Element2
    Element5 Element6 Element7" , fill = TRUE , header = FALSE )
    #        V1       V2       V3
    #1 Element1 Element2         
    #2 Element5 Element6 Element7
    

    A note on whether or not to set header = FALSE... read.table tries to automatically determine if you have a header row thus:

    header is set to TRUE if and only if the first row contains one fewer field than the number of columns

    How do I print debug messages in the Google Chrome JavaScript Console?

    Just a quick warning - if you want to test in Internet Explorer without removing all console.log()'s, you'll need to use Firebug Lite or you'll get some not particularly friendly errors.

    (Or create your own console.log() which just returns false.)

    How to activate the Bootstrap modal-backdrop?

    Just append a div with that class to body, then remove it when you're done:

    // Show the backdrop
    $('<div class="modal-backdrop"></div>').appendTo(document.body);
    
    // Remove it (later)
    $(".modal-backdrop").remove();
    

    Live Example:

    _x000D_
    _x000D_
    $("input").click(function() {_x000D_
      var bd = $('<div class="modal-backdrop"></div>');_x000D_
      bd.appendTo(document.body);_x000D_
      setTimeout(function() {_x000D_
        bd.remove();_x000D_
      }, 2000);_x000D_
    });
    _x000D_
    <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />_x000D_
    <script src="//code.jquery.com/jquery.min.js"></script>_x000D_
    <script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>_x000D_
    <p>Click the button to get the backdrop for two seconds.</p>_x000D_
    <input type="button" value="Click Me">
    _x000D_
    _x000D_
    _x000D_

    How to POST form data with Spring RestTemplate?

    Your url String needs variable markers for the map you pass to work, like:

    String url = "https://app.example.com/hr/email?{email}";
    

    Or you could explicitly code the query params into the String to begin with and not have to pass the map at all, like:

    String url = "https://app.example.com/hr/[email protected]";
    

    See also https://stackoverflow.com/a/47045624/1357094

    How to sort a dataFrame in python pandas by two or more columns?

    As of pandas 0.17.0, DataFrame.sort() is deprecated, and set to be removed in a future version of pandas. The way to sort a dataframe by its values is now is DataFrame.sort_values

    As such, the answer to your question would now be

    df.sort_values(['b', 'c'], ascending=[True, False], inplace=True)
    

    How to convert a Java 8 Stream to an Array?

    Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
    
    int[] arr=   stream.mapToInt(x->x.intValue()).toArray();
    

    Python: Binding Socket: "Address already in use"

    As Felipe Cruze mentioned, you must set the SO_REUSEADDR before binding. I found a solution on another site - solution on other site, reproduced below

    The problem is that the SO_REUSEADDR socket option must be set before the address is bound to the socket. This can be done by subclassing ThreadingTCPServer and overriding the server_bind method as follows:

    import SocketServer, socket
    
    class MyThreadingTCPServer(SocketServer.ThreadingTCPServer):
        def server_bind(self):
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.socket.bind(self.server_address)
    
    

    jQuery Upload Progress and AJAX file upload

    Uploading files is actually possible with AJAX these days. Yes, AJAX, not some crappy AJAX wannabes like swf or java.

    This example might help you out: https://webblocks.nl/tests/ajax/file-drag-drop.html

    (It also includes the drag/drop interface but that's easily ignored.)

    Basically what it comes down to is this:

    <input id="files" type="file" />
    
    <script>
    document.getElementById('files').addEventListener('change', function(e) {
        var file = this.files[0];
        var xhr = new XMLHttpRequest();
        (xhr.upload || xhr).addEventListener('progress', function(e) {
            var done = e.position || e.loaded
            var total = e.totalSize || e.total;
            console.log('xhr progress: ' + Math.round(done/total*100) + '%');
        });
        xhr.addEventListener('load', function(e) {
            console.log('xhr upload complete', e, this.responseText);
        });
        xhr.open('post', '/URL-HERE', true);
        xhr.send(file);
    });
    </script>
    

    (demo: http://jsfiddle.net/rudiedirkx/jzxmro8r/)

    So basically what it comes down to is this =)

    xhr.send(file);
    

    Where file is typeof Blob: http://www.w3.org/TR/FileAPI/

    Another (better IMO) way is to use FormData. This allows you to 1) name a file, like in a form and 2) send other stuff (files too), like in a form.

    var fd = new FormData;
    fd.append('photo1', file);
    fd.append('photo2', file2);
    fd.append('other_data', 'foo bar');
    xhr.send(fd);
    

    FormData makes the server code cleaner and more backward compatible (since the request now has the exact same format as normal forms).

    All of it is not experimental, but very modern. Chrome 8+ and Firefox 4+ know what to do, but I don't know about any others.

    This is how I handled the request (1 image per request) in PHP:

    if ( isset($_FILES['file']) ) {
        $filename = basename($_FILES['file']['name']);
        $error = true;
    
        // Only upload if on my home win dev machine
        if ( isset($_SERVER['WINDIR']) ) {
            $path = 'uploads/'.$filename;
            $error = !move_uploaded_file($_FILES['file']['tmp_name'], $path);
        }
    
        $rsp = array(
            'error' => $error, // Used in JS
            'filename' => $filename,
            'filepath' => '/tests/uploads/' . $filename, // Web accessible
        );
        echo json_encode($rsp);
        exit;
    }
    

    What is the Maximum Size that an Array can hold?

    I think it is linked with your RAM (or probably virtual memory) space and for the absolute maximum constrained to your OS version (e.g. 32 bit or 64 bit)

    in_array() and multidimensional array

    Shorter version, for multidimensional arrays created based on database result sets.

    function in_array_r($array, $field, $find){
        foreach($array as $item){
            if($item[$field] == $find) return true;
        }
        return false;
    }
    
    $is_found = in_array_r($os_list, 'os_version', 'XP');
    

    Will return if the $os_list array contains 'XP' in the os_version field.

    Testing Spring's @RequestBody using Spring MockMVC

    The issue is that you are serializing your bean with a custom Gson object while the application is attempting to deserialize your JSON with a Jackson ObjectMapper (within MappingJackson2HttpMessageConverter).

    If you open up your server logs, you should see something like

    Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of java.util.Date from String value '2013-34-10-10:34:31': not a valid representation (error: Failed to parse Date value '2013-34-10-10:34:31': Can not parse date "2013-34-10-10:34:31": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))
     at [Source: java.io.StringReader@baea1ed; line: 1, column: 20] (through reference chain: com.spring.Bean["publicationDate"])
    

    among other stack traces.

    One solution is to set your Gson date format to one of the above (in the stacktrace).

    The alternative is to register your own MappingJackson2HttpMessageConverter by configuring your own ObjectMapper to have the same date format as your Gson.

    Make div scrollable

    You need to remove the

    min-height:440px;
    

    to

    height:440px;
    

    and then add

    overflow: auto;
    

    property to the class of the required div

    Adding three months to a date in PHP

    The following should work, but you may need to change the format:

    echo date('l F jS, Y (m-d-Y)', strtotime('+3 months', strtotime($DateToAdjust)));
    

    Generics/templates in python?

    Python uses duck typing, so it doesn't need special syntax to handle multiple types.

    If you're from a C++ background, you'll remember that, as long as the operations used in the template function/class are defined on some type T (at the syntax level), you can use that type T in the template.

    So, basically, it works the same way:

    1. define a contract for the type of items you want to insert in the binary tree.
    2. document this contract (i.e. in the class documentation)
    3. implement the binary tree using only operations specified in the contract
    4. enjoy

    You'll note however, that unless you write explicit type checking (which is usually discouraged), you won't be able to enforce that a binary tree contains only elements of the chosen type.

    How to crop an image using C#?

    Simpler than the accepted answer is this:

    public static Bitmap cropAtRect(this Bitmap b, Rectangle r)
    {
        Bitmap nb = new Bitmap(r.Width, r.Height);
        using (Graphics g = Graphics.FromImage(nb))
        {
            g.DrawImage(b, -r.X, -r.Y);
            return nb;
        }
    }
    

    and it avoids the "Out of memory" exception risk of the simplest answer.

    Note that Bitmap and Graphics are IDisposable hence the using clauses.

    EDIT: I find this is fine with PNGs saved by Bitmap.Save or Paint.exe, but fails with PNGs saved by e.g. Paint Shop Pro 6 - the content is displaced. Addition of GraphicsUnit.Pixel gives a different wrong result. Perhaps just these failing PNGs are faulty.

    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'.

    How can I pass parameters to a partial view in mvc 4

    For Asp.Net core you better use

    <partial name="_MyPartialView" model="MyModel" />
    

    So for example

    @foreach (var item in Model)
    {
       <partial name="_MyItemView" model="item" />
    }
    

    Firebug-like debugger for Google Chrome

    There is a Firebug-like tool already built into Chrome. Just right click anywhere on a page and choose "Inspect element" from the menu. Chrome has a graphical tool for debugging (like in Firebug), so you can debug JavaScript. It also does CSS inspection well and can even change CSS rendering on the fly.

    For more information, see https://developers.google.com/chrome-developer-tools/

    Hide "NFC Tag type not supported" error on Samsung Galaxy devices

    Before Android 4.4

    What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.

    On a rooted device, you may be able to bypass the message using either

    1. Xposed to modify the behavior of the NFC service, or
    2. the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup> is set to any value but "mifareclassic" or "all". For instance, you could use:

      <CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
      

      You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet> that already exists in that file).

    Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).

    Since Android 4.4

    This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK.

    Using an HTML button to call a JavaScript function

    This looks correct. I guess you defined your function either with a different name or in a context which isn't visible to the button. Please add some code

    How to iterate through a table rows and get the cell values using jQuery

    You got your answer, but why iterate over the tr when you can go straight for the inputs? That way you can store them easier into an array and it reduce the number of CSS queries. Depends what you want to do of course, but for collecting data it is a more flexible approach.

    http://jsfiddle.net/zqpgq/

    var array = [];
    
    $("tr.item input").each(function() {
        array.push({
            name: $(this).attr('class'),
            value: $(this).val()
        });
    });
    
    console.log(array);?
    

    Provide schema while reading csv file as a dataframe

    // import Library
    import java.io.StringReader ;
    
    import au.com.bytecode.opencsv.CSVReader
    
    //filename
    
    var train_csv = "/Path/train.csv";
    
    //read as text file
    
    val train_rdd = sc.textFile(train_csv)   
    
    //use string reader to convert in proper format
    
    var full_train_data  = train_rdd.map{line =>  var csvReader = new CSVReader(new StringReader(line)) ; csvReader.readNext();  }   
    
    //declares  types
    
    type s = String
    
    // declare case class for schema
    
    case class trainSchema (Loan_ID :s ,Gender :s, Married :s, Dependents :s,Education :s,Self_Employed :s,ApplicantIncome :s,CoapplicantIncome :s,
        LoanAmount :s,Loan_Amount_Term :s, Credit_History :s, Property_Area :s,Loan_Status :s)
    
    //create DF RDD with custom schema 
    
    var full_train_data_with_schema = full_train_data.mapPartitionsWithIndex{(idx,itr)=> if (idx==0) itr.drop(1); 
                         itr.toList.map(x=> trainSchema(x(0),x(1),x(2),x(3),x(4),x(5),x(6),x(7),x(8),x(9),x(10),x(11),x(12))).iterator }.toDF
    
    

    How to change the data type of a column without dropping the column with query?

    ALTER TABLE YourTableNameHere ALTER COLUMN YourColumnNameHere VARCHAR(20)
    

    Android Google Maps API V2 Zoom to Current Location

        mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
            @Override
            public void onMyLocationChange(Location location) {
    
                    CameraUpdate center=CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
                    CameraUpdate zoom=CameraUpdateFactory.zoomTo(11);
                    mMap.moveCamera(center);
                    mMap.animateCamera(zoom);
    
            }
        });
    

    How can you integrate a custom file browser/uploader with CKEditor?

    For people wondering about a Servlet/JSP implementation here's how you go about doing it... I will be explaining uploadimage below also.

    1) First make sure you have added the filebrowser and uploadimage variable to your config.js file. Make you also have the uploadimage and filebrowser folder inside the plugins folder too.

    2) This part is where it tripped me up:

    The Ckeditor website documentation says you need to use these two methods:

    function getUrlParam( paramName ) {
        var reParam = new RegExp( '(?:[\?&]|&)' + paramName + '=([^&]+)', 'i' );
        var match = window.location.search.match( reParam );
        return ( match && match.length > 1 ) ? match[1] : null;
    }
    function returnFileUrl() {
        var funcNum = getUrlParam( 'CKEditorFuncNum' );
        var fileUrl = 'https://patiliyo.com/wp-content/uploads/2017/07/ruyada-kedi-gormek.jpg';
        window.opener.CKEDITOR.tools.callFunction( funcNum, fileUrl );
        window.close();
    }
    

    What they don't mention is that these methods have to be on a different page and not the page where you are clicking the browse server button from.

    So if you have ckeditor initialized in page editor.jsp then you need to create a file browser (with basic html/css/javascript) in page filebrowser.jsp.

    editor.jsp (all you need is this in your script tag) This page will open filebrowser.jsp in a mini window when you click on the browse server button.

    CKEDITOR.replace( 'editor', {
        filebrowserBrowseUrl: '../filebrowser.jsp', //jsp page with jquery to call servlet and get image files to view
        filebrowserUploadUrl: '../UploadImage', //servlet
    
    });
    

    filebrowser.jsp (is the custom file browser you built which will contain the methods mentioned above)

    <head>
    <script src="../../ckeditor/ckeditor.js"></script>
    </head>
    <body>
    <script>
    
    
    function getUrlParam( paramName ) {
        var reParam = new RegExp( '(?:[\?&]|&)' + paramName + '=([^&]+)', 'i' );
        var match = window.location.search.match( reParam );
        return ( match && match.length > 1 ) ? match[1] : null;
    }
    
    function returnFileUrl() {
        var funcNum = getUrlParam( 'CKEditorFuncNum' );
    var fileUrl = 'https://patiliyo.com/wp-content/uploads/2017/07/ruyada-kedi-gormek.jpg';
        window.opener.CKEDITOR.tools.callFunction( funcNum, fileUrl );
        window.close();
    }
    
    
    //when this window opens it will load all the images which you send from the FileBrowser Servlet. 
    getImages();
    function getImages(){
        $.get("../FileBrowser", function(responseJson) {    
            //do something with responseJson (like create <img> tags and update the src attributes) 
        });
    }
    
       //you call this function and pass 'fileUrl' when user clicks on an image that you loaded into this window from a servlet
    returnFileUrl();
    </script>
    </body>
    

    3) The FileBrowser Servlet

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Images i = new Images();
        List<ImageObject> images = i.getImages(); //get images from your database or some cloud service or whatever (easier if they are in a url ready format)
        String json = new Gson().toJson(images);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json);
    }
    

    4) UploadImage Servlet

    Go back to your config.js file for ckeditor and add the following line:

    //https://docs.ckeditor.com/ckeditor4/latest/guide/dev_file_upload.html
    config.uploadUrl = '/UploadImage';
    

    Then you can drag and drop files also:

       protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
                    Images i = new Images();
    
       //do whatever you usually do to upload your image to your server (in my case i uploaded to google cloud storage and saved the url in a database. 
    
       //Now this part is important. You need to return the response in json format. And it has to look like this:
    
    //      https://docs.ckeditor.com/ckeditor4/latest/guide/dev_file_upload.html
    //      response must be in this format:
    //      {
    //          "uploaded": 1,
    //          "fileName": "example.png",
    //          "url": "https://www.cats.com/example.png"
    //      }
    
                        String image = "https://www.cats.com/example.png";
                            ImageObject objResponse = i.getCkEditorObjectResponse(image);
                            String json = new Gson().toJson(objResponse);
                            response.setContentType("application/json");
                            response.setCharacterEncoding("UTF-8");
                            response.getWriter().write(json);
                        }
                    }
    

    And that's all folks. Hope it helps someone.

    Is it safe to expose Firebase apiKey to the public?

    I am making a blog website on github pages. I got an idea to embbed comments in the end of every blog page. I understand how firebase get and gives you data.

    I have tested many times with project and even using console. I am totally disagree the saying vlit is vulnerable. Believe me there is no issue of showing your api key publically if you have followed privacy steps recommend by firebase. Go to https://console.developers.google.com/apis and perfrom a security steup.

    How to select last one week data from today's date

    Yes, the syntax is accurate and it should be fine.

    Here is the SQL Fiddle Demo I created for your particular case

    create table sample2
    (
        id int primary key,
        created_date date,
        data varchar(10)
      )
    
    insert into sample2 values (1,'2012-01-01','testing');
    

    And here is how to select the data

    SELECT Created_Date
    FROM sample2
    WHERE Created_Date >= DATEADD(day,-11117, GETDATE())