Programs & Examples On #Stingray

Failed to resolve version for org.apache.maven.archetypes

The problem may also come from that you haven't set MAVEN_HOME environment variable. So the Maven embedded in Eclipse can't do its job to download the archetype.Check if that variable is set upfront.

How to convert an integer to a character array using C

Make use of the log10 function to determine the number of digits and do like below:

char * toArray(int number)
{
    int n = log10(number) + 1;
    int i;
    char *numberArray = calloc(n, sizeof(char));
    for (i = n-1; i >= 0; --i, number /= 10)
    {
        numberArray[i] = (number % 10) + '0';
    }
    return numberArray;
}

Or the other option is sprintf(yourCharArray,"%ld", intNumber);

How correctly produce JSON by RESTful web service?

You can annotate your bean with jaxb annotations.

  @XmlRootElement
  public class MyJaxbBean {
    public String name;
    public int age;

    public MyJaxbBean() {} // JAXB needs this

    public MyJaxbBean(String name, int age) {
      this.name = name;
      this.age = age;
    }
  }

and then your method would look like this:

   @GET @Produces("application/json")
   public MyJaxbBean getMyBean() {
      return new MyJaxbBean("Agamemnon", 32);
   }

There is a chapter in the latest documentation that deals with this:

https://jersey.java.net/documentation/latest/user-guide.html#json

What's the simplest way to extend a numpy array in 2 dimensions?

I find it much easier to "extend" via assigning in a bigger matrix. E.g.

import numpy as np
p = np.array([[1,2], [3,4]])
g = np.array(range(20))
g.shape = (4,5)
g[0:2, 0:2] = p

Here are the arrays:

p

   array([[1, 2],
       [3, 4]])

g:

array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

and the resulting g after assignment:

   array([[ 1,  2,  2,  3,  4],
       [ 3,  4,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

How do I download a file from the internet to my linux server with Bash

I guess you could use curl and wget, but since Oracle requires you to check of some checkmarks this will be painfull to emulate with the tools mentioned. You would have to download the page with the license agreement and from looking at it figure out what request is needed to get to the actual download.

Of course you could simply start a browser, but this might not qualify as 'from the command line'. So you might want to look into lynx, a text based browser.

Changing MongoDB data store directory

Create a file called mongod.cfg in MongoDB folder if you dont have it. In my case: C:\Users\ivanbtrujillo\MongoDB

Then, edit mongod.cfg with notepad and add a line with the following (our custom dbpath):

dbpath=C:\Users\ivanbtrujillo\MongoDB\data\db

In this file you should especify the logpath too. My mongod.cfg file is:

logpath=C:\Users\ivanbtrujillo\MongoDB\log\mongo.log
dbpath=C:\Users\ivanbtrujillo\MongoDB\data\db

If you uses mongoDB as a windows service, you have to change this key and especify the mongod.cfg file.

To install mongodb as a windows service run this command:

**"C:\Users\ivanbtrujillo\MongoDB\bin\mongod.exe" --config "C:\Users\ivanbtrujillo\MongoDB\mongod.cfg" –install**

Open regedit.exe and go to the following route:

HKEYLOCALMACHINE\SYSTEM\CurrentControlSet\services\MongoDB

MongoDB service does not work, we have to edit the ImagePath key, delete its content and put the following:

**"C:\Users\ivanbtrujillo\MongoDB\bin\mongod.exe" --config "C:\Users\ivanbtrujillo\MongoDB\mongod.cfg" 
--logpath="C:\Users\ivanbtrujillo\MongoDB\log\mongo.log" –service**

We indicates to mongo it's config file and its logpath.

Then when you init the mongodb service, it works.

Here is a full tutorial to install mongoDB in windows: http://ivanbtrujillo.herokuapp.com/2014/07/24/installing-mongodb-as-a-service-windows/

Hope it helps,

Get a substring of a char*

You can use strstr. Example code here.

Note that the returned result is not null terminated.

Dynamically access object property using variable

Following is an ES6 example of how you can access the property of an object using a property name that has been dynamically generated by concatenating two strings.

var suffix = " name";

var person = {
    ["first" + suffix]: "Nicholas",
    ["last" + suffix]: "Zakas"
};

console.log(person["first name"]);      // "Nicholas"
console.log(person["last name"]);       // "Zakas"

This is called computed property names

Permissions error when connecting to EC2 via SSH on Mac OSx

After about a half hour of searching and trying to debug this I was able to figure it out. My situation involved me using the same pem file for two different ec2 instance and it working for one and not the other.

My first instance it worked on was the standard aws linux ami amzn-ami-hvm-2014.03.2.x86_64-ebs. I simply used

ssh -i mypemfile.pem ec2-user@myec2ipaddress 

and it worked.

I then launched a fedora instance Fedora-x86_64-19-20140407-sda and tried the same command but kept getting:

Permission denied (publickey,gssapi-keyex,gssapi-with-mic).

After changing my username from ec2-user to fedora it worked!

ssh -i mypemfile.pem fedora@myec2address

Best way to convert IList or IEnumerable to Array

In case you don't have Linq, I solved it the following way:

    private T[] GetArray<T>(IList<T> iList) where T: new()
    {
        var result = new T[iList.Count];

        iList.CopyTo(result, 0);

        return result;
    }

Hope it helps

AngularJS ng-style with a conditional expression

As @Yoshi said, from angular 1.1.5 you can use-it without any change.

If you use angular < 1.1.5, you can use ng-class.

.largeWidth {
    width: 100%;
}

.smallWidth {
    width: 0%;
}

// [...]

ng-class="{largeWidth: myVar == 'ok', smallWidth: myVar != 'ok'}"

When to use SELECT ... FOR UPDATE?

The only portable way to achieve consistency between rooms and tags and making sure rooms are never returned after they had been deleted is locking them with SELECT FOR UPDATE.

However in some systems locking is a side effect of concurrency control, and you achieve the same results without specifying FOR UPDATE explicitly.


To solve this problem, Thread 1 should SELECT id FROM rooms FOR UPDATE, thereby preventing Thread 2 from deleting from rooms until Thread 1 is done. Is that correct?

This depends on the concurrency control your database system is using.

  • MyISAM in MySQL (and several other old systems) does lock the whole table for the duration of a query.

  • In SQL Server, SELECT queries place shared locks on the records / pages / tables they have examined, while DML queries place update locks (which later get promoted to exclusive or demoted to shared locks). Exclusive locks are incompatible with shared locks, so either SELECT or DELETE query will lock until another session commits.

  • In databases which use MVCC (like Oracle, PostgreSQL, MySQL with InnoDB), a DML query creates a copy of the record (in one or another way) and generally readers do not block writers and vice versa. For these databases, a SELECT FOR UPDATE would come handy: it would lock either SELECT or the DELETE query until another session commits, just as SQL Server does.

When should one use REPEATABLE_READ transaction isolation versus READ_COMMITTED with SELECT ... FOR UPDATE?

Generally, REPEATABLE READ does not forbid phantom rows (rows that appeared or disappeared in another transaction, rather than being modified)

  • In Oracle and earlier PostgreSQL versions, REPEATABLE READ is actually a synonym for SERIALIZABLE. Basically, this means that the transaction does not see changes made after it has started. So in this setup, the last Thread 1 query will return the room as if it has never been deleted (which may or may not be what you wanted). If you don't want to show the rooms after they have been deleted, you should lock the rows with SELECT FOR UPDATE

  • In InnoDB, REPEATABLE READ and SERIALIZABLE are different things: readers in SERIALIZABLE mode set next-key locks on the records they evaluate, effectively preventing the concurrent DML on them. So you don't need a SELECT FOR UPDATE in serializable mode, but do need them in REPEATABLE READ or READ COMMITED.

Note that the standard on isolation modes does prescribe that you don't see certain quirks in your queries but does not define how (with locking or with MVCC or otherwise).

When I say "you don't need SELECT FOR UPDATE" I really should have added "because of side effects of certain database engine implementation".

Centering a Twitter Bootstrap button

Since you want to center the button, and not the text, what I've done in the past is add a class, then use that class to center the button:

<button class="btn btn-large btn-primary newclass" type="button">Submit</button>

and the CSS would be:

.btn.newclass {width:25%; display:block; margin: 0 auto;}

The "width" value is up to you, and you can play with that to get the right look.

Steve

How to produce a range with step n in bash? (generate a sequence of numbers with increments)

#!/bin/bash
for i in $(seq 1 2 10)
do
   echo "skip by 2 value $i"
done

Jenkins Host key verification failed

  • Make sure we are not editing any of the default sshd_config properties to skip the error

  • Host Verification Failed - Definitely a missing entry of hostname in known_hosts file

  • Login to the server where the process is failing and do the following:

    1. Sudo to the user running the process

    2. ssh-copy-id destinationuser@destinationhostname

    3. It will prompt like this for the first time, say yes and it will also ask password for the first time:

      The authenticity of host 'sample.org (205.214.640.91)' can't be established.
      RSA key fingerprint is 97:8c:1b:f2:6f:14:6b:5c:3b:ec:aa:46:46:74:7c:40.
      Are you sure you want to continue connecting (yes/no)? *yes*
      

      Password prompt ? give password

    4. Now from the server where process is running, do ssh destinationuser@destinationhostname. It should login without a password.

      Note: Do not change the default permissions of files in the user's .ssh directory, you will end up with different issues

Why do I get an error instantiating an interface?

IUser is the interface, you can't instantiate the interface.

You need to instantiate the concrete class that implements the interface.

IUser user = new User();

or

User user = new User();

C++ cout hex values?

std::hex is defined in <ios> which is included by <iostream>. But to use things like std::setprecision/std::setw/std::setfill/etc you have to include <iomanip>.

Operation must use an updatable query. (Error 3073) Microsoft Access

The answer given above by iDevlop worked for me. Note that I wasn't able to find the RecordsetType property in my update query. However, I was able to find that property by changing my query to a select query, setting that property as iDevlop noted and then changing my query to an update query. This worked, no need for a temp table.

I'd have liked for this to just be a comment to what iDevlop posted so that it flowed from his solution, but I don't have a high enough score.

How to resolve the error on 'react-native start'

As a general rule, I don't modify files within node_modules/ (or anything which does not get committed as part of a repository) as the next clean, build or update will regress them. I definitely have done so in the past and it has bitten me a couple of times. But this does work as a short-term/local dev fix until/unless metro-config is updated.

Thanks!

LDAP Authentication using Java

Following Code authenticates from LDAP using pure Java JNDI. The Principle is:-

  1. First Lookup the user using a admin or DN user.
  2. The user object needs to be passed to LDAP again with the user credential
  3. No Exception means - Authenticated Successfully. Else Authentication Failed.

Code Snippet

public static boolean authenticateJndi(String username, String password) throws Exception{
    Properties props = new Properties();
    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    props.put(Context.PROVIDER_URL, "ldap://LDAPSERVER:PORT");
    props.put(Context.SECURITY_PRINCIPAL, "uid=adminuser,ou=special users,o=xx.com");//adminuser - User with special priviledge, dn user
    props.put(Context.SECURITY_CREDENTIALS, "adminpassword");//dn user password


    InitialDirContext context = new InitialDirContext(props);

    SearchControls ctrls = new SearchControls();
    ctrls.setReturningAttributes(new String[] { "givenName", "sn","memberOf" });
    ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    NamingEnumeration<javax.naming.directory.SearchResult> answers = context.search("o=xx.com", "(uid=" + username + ")", ctrls);
    javax.naming.directory.SearchResult result = answers.nextElement();

    String user = result.getNameInNamespace();

    try {
        props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        props.put(Context.PROVIDER_URL, "ldap://LDAPSERVER:PORT");
        props.put(Context.SECURITY_PRINCIPAL, user);
        props.put(Context.SECURITY_CREDENTIALS, password);

   context = new InitialDirContext(props);
    } catch (Exception e) {
        return false;
    }
    return true;
}

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object

To prevent inserting a record that exist already. I'd check if the ID value exists in the database. For the example of a Table created with an IDENTITY PRIMARY KEY:

CREATE TABLE [dbo].[Persons] (    
    ID INT IDENTITY(1,1) PRIMARY KEY,
    LastName VARCHAR(40) NOT NULL,
    FirstName VARCHAR(40)
);

When JANE DOE and JOE BROWN already exist in the database.

SET IDENTITY_INSERT [dbo].[Persons] OFF;
INSERT INTO [dbo].[Persons] (FirstName,LastName)
VALUES ('JANE','DOE'); 
INSERT INTO Persons (FirstName,LastName) 
VALUES ('JOE','BROWN');

DATABASE OUTPUT of TABLE [dbo].[Persons] will be:

ID    LastName   FirstName
1     DOE        Jane
2     BROWN      JOE

I'd check if i should update an existing record or insert a new one. As the following JAVA example:

int NewID = 1;
boolean IdAlreadyExist = false;
// Using SQL database connection
// STEP 1: Set property
System.setProperty("java.net.preferIPv4Stack", "true");
// STEP 2: Register JDBC driver
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// STEP 3: Open a connection
try (Connection conn1 = DriverManager.getConnection(DB_URL, USER,pwd) {
    conn1.setAutoCommit(true);
    String Select = "select * from Persons where  ID = " + ID;
    Statement st1 = conn1.createStatement();
    ResultSet rs1 = st1.executeQuery(Select);
    // iterate through the java resultset
    while (rs1.next()) {
        int ID = rs1.getInt("ID");
        if (NewID==ID) {
            IdAlreadyExist = true;
        }

    }
    conn1.close();
} catch (SQLException e1) {
    System.out.println(e1);
}
if (IdAlreadyExist==false) {
    //Insert new record code here
} else {
    //Update existing record code here
}

How to list all the files in a commit?

OK, there are couple of ways to show all files in a particular commit...

To reduce the info and show only names of the files which committed, you simply can add --name-only or --name-status flag..., these flags just show you the file names which are different from previous commits as you want...

So you can do git diff followed by --name-only, with two commit hashes after <sha0> <sha1>, something like below:

git diff --name-only 5f12f15 kag9f02 

I also create the below image to show all steps to go through in these situation:

git diff --name-only 5f12f15 kag9f02

what is difference between success and .done() method of $.ajax

success is the callback that is invoked when the request is successful and is part of the $.ajax call. done is actually part of the jqXHR object returned by $.ajax(), and replaces success in jQuery 1.8.

Java - Convert int to Byte Array of 4 Bytes?

This should work:

public static final byte[] intToByteArray(int value) {
    return new byte[] {
            (byte)(value >>> 24),
            (byte)(value >>> 16),
            (byte)(value >>> 8),
            (byte)value};
}

Code taken from here.

Edit An even simpler solution is given in this thread.

What's the actual use of 'fail' in JUnit test case?

I, for example, use fail() to indicate tests that are not yet finished (it happens); otherwise, they would show as successful.

This is perhaps due to the fact that I am unaware of some sort of incomplete() functionality, which exists in NUnit.

RegEx match open tags except XHTML self-contained tags

It's true that when programming it's usually best to use dedicated parsers and APIs instead of regular expressions when dealing with HTML, especially if accuracy is paramount (e.g., if your processing might have security implications). However, I don’t ascribe to a dogmatic view that XML-style markup should never be processed with regular expressions. There are cases when regular expressions are a great tool for the job, such as when making one-time edits in a text editor, fixing broken XML files, or dealing with file formats that look like but aren’t quite XML. There are some issues to be aware of, but they're not insurmountable or even necessarily relevant.

A simple regex like <([^>"']|"[^"]*"|'[^']*')*> is usually good enough, in cases such as those I just mentioned. It's a naive solution, all things considered, but it does correctly allow unencoded > symbols in attribute values. If you're looking for, e.g., a table tag, you could adapt it as </?table\b([^>"']|"[^"]*"|'[^']*')*>.

Just to give a sense of what a more "advanced" HTML regex would look like, the following does a fairly respectable job of emulating real-world browser behavior and the HTML5 parsing algorithm:

</?([A-Za-z][^\s>/]*)(?:=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)|[^>])*(?:>|$)

The following matches a fairly strict definition of XML tags (although it doesn't account for the full set of Unicode characters allowed in XML names):

<(?:([_:A-Z][-.:\w]*)(?:\s+[_:A-Z][-.:\w]*\s*=\s*(?:"[^"]*"|'[^']*'))*\s*/?|/([_:A-Z][-.:\w]*)\s*)>

Granted, these don't account for surrounding context and a few edge cases, but even such things could be dealt with if you really wanted to (e.g., by searching between the matches of another regex).

At the end of the day, use the most appropriate tool for the job, even in the cases when that tool happens to be a regex.

How to use pip with python 3.4 on windows?

I know this is a very old topic, but in case someone needs it

there is no pip in python 3.4, so we have to use python -m ensurepip to install pip

Python JSON dump / append to .txt with each variable on new line

To avoid confusion, paraphrasing both question and answer. I am assuming that user who posted this question wanted to save dictionary type object in JSON file format but when the user used json.dump, this method dumped all its content in one line. Instead, he wanted to record each dictionary entry on a new line. To achieve this use:

with g as outfile:
  json.dump(hostDict, outfile,indent=2)

Using indent = 2 helped me to dump each dictionary entry on a new line. Thank you @agf. Rewriting this answer to avoid confusion.

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

ALTER TABLE [table name] MODIFY COLUMN [column name] datatype

What is $@ in Bash?

Just from reading that i would have never understood that "$@" expands into a list of separate parameters. Whereas, "$*" is one parameter consisting of all the parameters added together.

If it still makes no sense do this.

http://www.thegeekstuff.com/2010/05/bash-shell-special-parameters/

How to use su command over adb shell?

Well, if your phone is rooted you can run commands with the su -c command.

Here is an example of a cat command on the build.prop file to get a phone's product information.

adb shell "su -c 'cat /system/build.prop |grep "product"'"

This invokes root permission and runs the command inside the ' '.

Notice the 5 end quotes, that is required that you close ALL your end quotes or you will get an error.

For clarification the format is like this.

adb shell "su -c '[your command goes here]'"

Make sure you enter the command EXACTLY the way that you normally would when running it in shell.

How to set thousands separator in Java?

If you are using thousand separator for Integer data type use 1.

  1. For integer data Type

String.format("%,d\n", 58625) and output will be 58,625

  1. For Floating Point data Type String.format("%,.2f",58625.21) and output will be 58,625.21

SyntaxError: cannot assign to operator

Python is upset because you are attempting to assign a value to something that can't be assigned a value.

((t[1])/length) * t[1] += string

When you use an assignment operator, you assign the value of what is on the right to the variable or element on the left. In your case, there is no variable or element on the left, but instead an interpreted value: you are trying to assign a value to something that isn't a "container".

Based on what you've written, you're just misunderstanding how this operator works. Just switch your operands, like so.

string += str(((t[1])/length) * t[1])

Note that I've wrapped the assigned value in str in order to convert it into a str so that it is compatible with the string variable it is being assigned to. (Numbers and strings can't be added together.)

Failed binder transaction when putting an bitmap dynamically in a widget

The right approach is to use setImageViewUri() (slower) or the setImageViewBitmap() and recreating RemoteViews every time you update the notification.

Eslint: How to disable "unexpected console statement" in Node.js?

2018 October,

just do:

// tslint:disable-next-line:no-console

the anothers answer with

// eslint-disable-next-line no-console

does not work !

How to change text color of simple list item

you can use setTextColor(int) method or add style to change text color.

<style name="ReviewScreenKbbViewMoreStyle">
<item name="android:textColor">#2F2E86</item>
<item name="android:textStyle">bold</item>
<item name="android:textSize">10dip</item>

Error: «Could not load type MvcApplication»

Could not load type MVCApplication1.MVCApplication

Problem: Web.Config might be corrupted because of some updates in the machine. When I compared the web.config with server web.config then I realized that all the basic configuration were missing like build providers, modules, handlers, namespaces etc.

Resolution: Replace the web.config from the below location with web.config from server from same location (application is running fine in server). C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config

I have spent more than 10 days, hence I thought it might be helpful for someone.

Deny access to one specific folder in .htaccess

We will set the directory to be very secure, denying access for all file types. Below is the code you want to insert into the .htaccess file.

Order Allow,Deny 
Deny from all 

Since we have now set the security, we now want to allow access to our desired file types. To do that, add the code below to the .htaccess file under the security code you just inserted.

<FilesMatch "\.(jpg|gif|png|php)$">
Order Deny,Allow
   Allow from all
</FilesMatch>

your final .htaccess file will look like

Order Allow,Deny 
Deny from all 

<FilesMatch "\.(jpg|gif|png|php)$">
Order Deny,Allow
   Allow from all
</FilesMatch>

Source from Allow access to specific file types in a protected directory

./xx.py: line 1: import: command not found

It's not an issue related to authentication at the first step. Your import is not working. So, try writing this on first line:

#!/usr/bin/python

and for the time being run using

python xx.py

For you here is one explanation:

>>> abc = "Hei Buddy"
>>> print "%s" %abc
Hei Buddy
>>> 

>>> print "%s" %xyz

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    print "%s" %xyz
NameError: name 'xyz' is not defined

At first, I initialized abc variable and it works fine. On the otherhand, xyz doesn't work as it is not initialized!

Insert at first position of a list in Python

Use insert:

In [1]: ls = [1,2,3]

In [2]: ls.insert(0, "new")

In [3]: ls
Out[3]: ['new', 1, 2, 3]

Javascript receipt printing using POS Printer

EDIT: NOV 27th, 2017 - BROKEN LINKS

Links below about the posts written by David Kelley are broken.

There are cached versions of the repository, just add cache: before the URL in the Chrome Browser and hit enter.


This solution is only for Google Chrome and Chromium-based browsers.

EDIT:

(*)The links are broken. Fortunately I found this repository that contains the source of the post in the following markdown files: A | B

This link* explains how to make a Javascript Interface for ESC/POS printers using Chrome/Chromium USB API (1)(2). This link* explains how to Connect to USB devices using the chrome.usb.* API.

How to change the style of alert box?

Styling alert()-boxes ist not possible. You could use a javascript modal overlay instead.

Why was the name 'let' chosen for block-scoped variable declarations in JavaScript?

Adding to exebook's response, the mathematics usage of the keyword let also encapsulates well the scoping implications of let when used in Javascript/ES6. Specifically, just as the following ES6 code is not aware of the assignment in braces of toPrint when it prints out the value of 'Hello World',

let toPrint = 'Hello World.';
{
    let toPrint = 'Goodbye World.';
}
console.log(toPrint); // Prints 'Hello World'

let as used in formalized mathematics (especially the writing of proofs) indicates that the current instance of a variable exists only for the scope of that logical idea. In the following example, x immediately gains a new identity upon entering the new idea (usually these are concepts necessary to prove the main idea) and reverts immediately to the old x upon the conclusion of the sub-proof. Of course, just as in coding, this is considered somewhat confusing and so is usually avoided by choosing a different name for the other variable.

Let x be so and so...

  Proof stuff

 New Idea { Let x be something else ... prove something } Conclude New Idea

 Prove main idea with old x

Default text which won't be shown in drop-down list

Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML. Adding a value of selected to the item we want to appear as a header forces it to show in the first place as a placeholder. Something like:

<option selected disabled>Choose here</option>

The complete markup should be along these lines:

<select>
    <option selected disabled>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

You can take a look at this fiddle, and here's the result:

enter image description here

If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden attribute like so:

<select>
    <option selected disabled hidden>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

Check the fiddle here and the screenshot below.

enter image description here


Here is the solution:

<select>
    <option style="display:none;" selected>Select language</option>
    <option>Option 1</option>
    <option>Option 2</option>
</select>

How to create javascript delay function

Ah yes. Welcome to Asynchronous execution.

Basically, pausing a script would cause the browser and page to become unresponsive for 3 seconds. This is horrible for web apps, and so isn't supported.

Instead, you have to think "event-based". Use setTimeout to call a function after a certain amount of time, which will continue to run the JavaScript on the page during that time.

What is the email subject length limit?

What's important is which mechanism you are using the send the email. Most modern libraries (i.e. System.Net.Mail) will hide the folding from you. You just put a very long email subject line in without (CR,LF,HTAB). If you start trying to do your own folding all bets are off. It will start reporting errors. So if you are having this issue just filter out the CR,LF,HTAB and let the library do the work for you. You can usually also set the encoding text type as a separate field. No need for iso encoding in the subject line.

Reading a string with spaces with sscanf

Since you want the trailing string from the input, you can use %n (number of characters consumed thus far) to get the position at which the trailing string starts. This avoids memory copies and buffer sizing issues, but comes at the cost that you may need to do them explicitly if you wanted a copy.

const char *input = "19  cool kid";
int age;
int nameStart = 0;
sscanf(input, "%d %n", &age, &nameStart);
printf("%s is %d years old\n", input + nameStart, age);

outputs:

cool kid is 19 years old

How to debug a GLSL shader?

The existing answers are all good stuff, but I wanted to share one more little gem that has been valuable in debugging tricky precision issues in a GLSL shader. With very large int numbers represented as a floating point, one needs to take care to use floor(n) and floor(n + 0.5) properly to implement round() to an exact int. It is then possible to render a float value that is an exact int by the following logic to pack the byte components into R, G, and B output values.

  // Break components out of 24 bit float with rounded int value
  // scaledWOB = (offset >> 8) & 0xFFFF
  float scaledWOB = floor(offset / 256.0);
  // c2 = (scaledWOB >> 8) & 0xFF
  float c2 = floor(scaledWOB / 256.0);
  // c0 = offset - (scaledWOB << 8)
  float c0 = offset - floor(scaledWOB * 256.0);
  // c1 = scaledWOB - (c2 << 8)
  float c1 = scaledWOB - floor(c2 * 256.0);

  // Normalize to byte range
  vec4 pix;  
  pix.r = c0 / 255.0;
  pix.g = c1 / 255.0;
  pix.b = c2 / 255.0;
  pix.a = 1.0;
  gl_FragColor = pix;

cleanup php session files

Use cron with find to delete files older than given threshold. For example to delete files that haven't been accessed for at least a week.

find .session/ -atime +7  -exec rm {} \;

C# Set collection?

Have a look at PowerCollections over at CodePlex. Apart from Set and OrderedSet it has a few other usefull collection types such as Deque, MultiDictionary, Bag, OrderedBag, OrderedDictionary and OrderedMultiDictionary.

For more collections, there is also the C5 Generic Collection Library.

Javascript "Not a Constructor" Exception while creating objects

An additional cause of this can be ES2015 arrow functions. They cannot be used as constructors.

const f = () => {};
new f(); // This throws "f is not a constructor"

Base64 decode snippet in C++

My variation on DaedalusAlpha's answer:

It avoids copying the parameters at the expense of a couple of tests.

Uses uint8_t instead of BYTE.

Adds some handy functions for dealing with strings, although usually the input data is binary and may have zero bytes inside, so typically should not be manipulated as a string (which often implies null-terminated data).

Also adds some casts to fix compiler warnings (at least on GCC, I haven't run it through MSVC yet).

Part of file base64.hpp:

void base64_encode(string & out, const vector<uint8_t>& buf);
void base64_encode(string & out, const uint8_t* buf, size_t bufLen);
void base64_encode(string & out, string const& buf);

void base64_decode(vector<uint8_t> & out, string const& encoded_string);

// Use this if you know the output should be a valid string
void base64_decode(string & out, string const& encoded_string);

File base64.cpp:

static const uint8_t from_base64[128] = {
    // 8 rows of 16 = 128
    // Note: only requires 123 entries, as we only lookup for <= z , which z=122

    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
    255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,  62, 255,  62, 255,  63,
     52,  53,  54,  55,  56,  57,  58,  59,  60,  61, 255, 255,   0, 255, 255, 255,
    255,   0,   1,   2,   3,   4,   5,   6,   7,   8,   9,  10,  11,  12,  13,  14,
     15,  16,  17,  18,  19,  20,  21,  22,  23,  24,  25, 255, 255, 255, 255,  63,
    255,  26,  27,  28,  29,  30,  31,  32,  33,  34,  35,  36,  37,  38,  39,  40,
     41,  42,  43,  44,  45,  46,  47,  48,  49,  50,  51, 255, 255, 255, 255, 255
};

static const char to_base64[65] =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "abcdefghijklmnopqrstuvwxyz"
    "0123456789+/";


void base64_encode(string & out, string const& buf)
{
   if (buf.empty())
      base64_encode(out, NULL, 0);
   else
      base64_encode(out, reinterpret_cast<uint8_t const*>(&buf[0]), buf.size());
}


void base64_encode(string & out, std::vector<uint8_t> const& buf)
{
   if (buf.empty())
      base64_encode(out, NULL, 0);
   else
      base64_encode(out, &buf[0], buf.size());
}

void base64_encode(string & ret, uint8_t const* buf, size_t bufLen)
{
   // Calculate how many bytes that needs to be added to get a multiple of 3
   size_t missing = 0;
   size_t ret_size = bufLen;
   while ((ret_size % 3) != 0)
   {
      ++ret_size;
      ++missing;
   }

   // Expand the return string size to a multiple of 4
   ret_size = 4*ret_size/3;

   ret.clear();
   ret.reserve(ret_size);

   for (size_t i = 0; i < ret_size/4; ++i)
   {
      // Read a group of three bytes (avoid buffer overrun by replacing with 0)
      const size_t index = i*3;
      const uint8_t b3_0 = (index+0 < bufLen) ? buf[index+0] : 0;
      const uint8_t b3_1 = (index+1 < bufLen) ? buf[index+1] : 0;
      const uint8_t b3_2 = (index+2 < bufLen) ? buf[index+2] : 0;

      // Transform into four base 64 characters
      const uint8_t b4_0 =                        ((b3_0 & 0xfc) >> 2);
      const uint8_t b4_1 = ((b3_0 & 0x03) << 4) + ((b3_1 & 0xf0) >> 4);
      const uint8_t b4_2 = ((b3_1 & 0x0f) << 2) + ((b3_2 & 0xc0) >> 6);
      const uint8_t b4_3 = ((b3_2 & 0x3f) << 0);

      // Add the base 64 characters to the return value
      ret.push_back(to_base64[b4_0]);
      ret.push_back(to_base64[b4_1]);
      ret.push_back(to_base64[b4_2]);
      ret.push_back(to_base64[b4_3]);
   }

   // Replace data that is invalid (always as many as there are missing bytes)
   for (size_t i = 0; i != missing; ++i)
      ret[ret_size - i - 1] = '=';
}


template <class Out>
void base64_decode_any( Out & ret, std::string const& in)
{
   typedef typename Out::value_type T;

   // Make sure the *intended* string length is a multiple of 4
   size_t encoded_size = in.size();

   while ((encoded_size % 4) != 0)
      ++encoded_size;

   const size_t N = in.size();
   ret.clear();
   ret.reserve(3*encoded_size/4);

   for (size_t i = 0; i < encoded_size; i += 4)
   {
      // Note: 'z' == 122

      // Get values for each group of four base 64 characters
      const uint8_t b4_0 = (            in[i+0] <= 'z') ? from_base64[static_cast<uint8_t>(in[i+0])] : 0xff;
      const uint8_t b4_1 = (i+1 < N and in[i+1] <= 'z') ? from_base64[static_cast<uint8_t>(in[i+1])] : 0xff;
      const uint8_t b4_2 = (i+2 < N and in[i+2] <= 'z') ? from_base64[static_cast<uint8_t>(in[i+2])] : 0xff;
      const uint8_t b4_3 = (i+3 < N and in[i+3] <= 'z') ? from_base64[static_cast<uint8_t>(in[i+3])] : 0xff;

      // Transform into a group of three bytes
      const uint8_t b3_0 = ((b4_0 & 0x3f) << 2) + ((b4_1 & 0x30) >> 4);
      const uint8_t b3_1 = ((b4_1 & 0x0f) << 4) + ((b4_2 & 0x3c) >> 2);
      const uint8_t b3_2 = ((b4_2 & 0x03) << 6) + ((b4_3 & 0x3f) >> 0);

      // Add the byte to the return value if it isn't part of an '=' character (indicated by 0xff)
      if (b4_1 != 0xff) ret.push_back( static_cast<T>(b3_0) );
      if (b4_2 != 0xff) ret.push_back( static_cast<T>(b3_1) );
      if (b4_3 != 0xff) ret.push_back( static_cast<T>(b3_2) );
   }
}

void base64_decode(vector<uint8_t> & out, string const& encoded_string)
{
   base64_decode_any(out, encoded_string);
}

void base64_decode(string & out, string const& encoded_string)
{
   base64_decode_any(out, encoded_string);
}

Python Hexadecimal

Use the format() function with a '02x' format.

>>> format(255, '02x')
'ff'
>>> format(2, '02x')
'02'

The 02 part tells format() to use at least 2 digits and to use zeros to pad it to length, x means lower-case hexadecimal.

The Format Specification Mini Language also gives you X for uppercase hex output, and you can prefix the field width with # to include a 0x or 0X prefix (depending on wether you used x or X as the formatter). Just take into account that you need to adjust the field width to allow for those extra 2 characters:

>>> format(255, '02X')
'FF'
>>> format(255, '#04x')
'0xff'
>>> format(255, '#04X')
'0XFF'

How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?

There is a way to accomplish this. The magic is to create a combined jacoco.exec file. And with maven 3.3.1 there is an easy way to get this. Here my profile:

<profile>
    <id>runSonar</id>
    <activation>
        <property>
            <name>runSonar</name>
            <value>true</value>
        </property>
    </activation>
    <properties>
        <sonar.language>java</sonar.language>
        <sonar.host.url>http://sonar.url</sonar.host.url>
        <sonar.login>tokenX</sonar.login>
        <sonar.jacoco.reportMissing.force.zero>true</sonar.jacoco.reportMissing.force.zero>
        <sonar.jacoco.reportPath>${jacoco.destFile}</sonar.jacoco.reportPath>
        <jacoco.destFile>${maven.multiModuleProjectDirectory}/target/jacoco_analysis/jacoco.exec</jacoco.destFile>
    </properties>
    <build>
        <plugins>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <id>default-prepare-agent</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                        <configuration>
                            <append>true</append>
                            <destFile>${jacoco.destFile}</destFile>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.sonarsource.scanner.maven</groupId>
                    <artifactId>sonar-maven-plugin</artifactId>
                    <version>3.2</version>
                </plugin>
                <plugin>
                    <groupId>org.jacoco</groupId>
                    <artifactId>jacoco-maven-plugin</artifactId>
                    <version>0.7.8</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</profile>

If you add this profile to your parent pom and call mvn clean install sonar:sonar -DrunSonar you get the complete coverage.

The magic here is maven.multiModuleProjectDirectory. This folder is always the folder where you started your maven build.

What's the difference between SHA and AES encryption?

SHA stands for Secure Hash Algorithm while AES stands for Advanced Encryption Standard. So SHA is a suite of hashing algorithms. AES on the other hand is a cipher which is used to encrypt. SHA algorithms (SHA-1, SHA-256 etc...) will take an input and produce a digest (hash), this is typically used in a digital signing process (produce a hash of some bytes and sign with a private key).

How to change css property using javascript

You can use style property for this. For example, if you want to change border -

document.elm.style.border = "3px solid #FF0000";

similarly for color -

 document.getElementById("p2").style.color="blue";

Best thing is you define a class and do this -

document.getElementById("p2").className = "classname";

(Cross Browser artifacts must be considered accordingly).

Word count from a txt file program

FILE_NAME = 'file.txt'

wordCounter = {}

with open(FILE_NAME,'r') as fh:
  for line in fh:
    # Replacing punctuation characters. Making the string to lower.
    # The split will spit the line into a list.
    word_list = line.replace(',','').replace('\'','').replace('.','').lower().split()
    for word in word_list:
      # Adding  the word into the wordCounter dictionary.
      if word not in wordCounter:
        wordCounter[word] = 1
      else:
        # if the word is already in the dictionary update its count.
        wordCounter[word] = wordCounter[word] + 1

print('{:15}{:3}'.format('Word','Count'))
print('-' * 18)

# printing the words and its occurrence.
for  (word,occurance)  in wordCounter.items(): 
  print('{:15}{:3}'.format(word,occurance))
#
    Word           Count
    ------------------
    of               6
    examples         2
    used             2
    development      2
    modified         2
    open-source      2

Disable HttpClient logging

The best solution I found was to use the maven enforcer plugin in order to prevent commons-logging from being used altogether. Then I added the slf4j dependency for logging instead. So add the following to your pom.xml

<dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>[your version here]</version>
    </dependency>

and also add the maven-enforcer plugin

<plugin>
           <groupId>org.apache.maven.plugins</groupId>
           <artifactId>maven-enforcer-plugin</artifactId>
           <version>[your version here]</version>
           <executions>
               <execution>
                   <id>enforce</id>
                   <configuration>
                       <rules>
                           <DependencyConvergence />
                           <bannedDependencies>
                               <excludes>
                                   <exclude>commons-logging:commons-logging</exclude>
                               </excludes>
                           </bannedDependencies>
                       </rules>
                   </configuration>
                   <goals>
                       <goal>enforce</goal>
                   </goals>
               </execution>
           </executions>
       </plugin>

How to force HTTPS using a web.config file

You need URL Rewrite module, preferably v2 (I have no v1 installed, so cannot guarantee that it will work there, but it should).

Here is an example of such web.config -- it will force HTTPS for ALL resources (using 301 Permanent Redirect):

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <clear />
                <rule name="Redirect to https" stopProcessing="true">
                    <match url=".*" />
                    <conditions>
                        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

P.S. This particular solution has nothing to do with ASP.NET/PHP or any other technology as it's done using URL rewriting module only -- it is processed at one of the initial/lower levels -- before request gets to the point where your code gets executed.

finding multiples of a number in Python

Does this do what you want?

print range(0, (m+1)*n, n)[1:]

For m=5, n=20

[20, 40, 60, 80, 100]

Or better yet,

>>> print range(n, (m+1)*n, n)
[20, 40, 60, 80, 100] 

For Python3+

>>> print(list(range(n, (m+1)*n, n)))
[20, 40, 60, 80, 100] 

How to keep an iPhone app running on background fully operational

May be the link will Help bcz u might have to implement the code in Appdelegate in app run in background method .. Also consult the developer.apple.com site for application class Here is link for runing app in background

Python - add PYTHONPATH during command line module run

For Mac/Linux;

PYTHONPATH=/foo/bar/baz python somescript.py somecommand

For Windows, setup a wrapper pythonpath.bat;

@ECHO OFF
setlocal
set PYTHONPATH=%1
python %2 %3
endlocal

and call pythonpath.bat script file like;

pythonpath.bat /foo/bar/baz somescript.py somecommand

C++ pointer to objects

if you want to access a method :

1) while using an object of a class:

Myclass myclass;
myclass.DoSomething();

2) while using a pointer to an object of a class:

Myclass *myclass=&abc;
myclass->DoSomething();

How to include a class in PHP

Your code should be something like

require_once('class.twitter.php');

$t = new twitter;
$t->username = 'user';
$t->password = 'password';

$data = $t->publicTimeline();

How to disable anchor "jump" when loading a page?

Solved my promlem by doing this:

// navbar height 
var navHeigth = $('nav.navbar').height();    

// Scroll to anchor function
var scrollToAnchor = function(hash) {
  // If got a hash
  if (hash) {
    // Scroll to the top (prevention for Chrome)
    window.scrollTo(0, 0);
    // Anchor element
    var term = $(hash);

    // If element with hash id is defined
    if (term) {

      // Get top offset, including header height
      var scrollto = term.offset().top - navHeigth;

      // Capture id value
      var id = term.attr('id');
      // Capture name value
      var name = term.attr('name');

      // Remove attributes for FF scroll prevention
      term.removeAttr('id').removeAttr('name');
      // Scroll to element
      $('html, body').animate({scrollTop:scrollto}, 0);

      // Returning id and name after .5sec for the next scroll
      setTimeout(function() {
        term.attr('id', id).attr('name', name);
      }, 500);
    }
  }
};

// if we are opening the page by url
if (location.hash) {
  scrollToAnchor(location.hash);
}

// preventing default click on links with an anchor
$('a[href*="#"]').click(function(e) {
  e.preventDefault();
  // hash value
  var hash = this.href.substr(this.href.indexOf("#"));
  scrollToAnchor(hash);
});`

how to send multiple data with $.ajax() jquery

Change var data = 'id='+ id & 'name='+ name; as below,

use this instead.....

var data = "id="+ id + "&name=" + name;

this will going to work fine:)

Simple logical operators in Bash

very close

if [[ $varA -eq 1 ]] && [[ $varB == 't1' || $varC == 't2' ]]; 
  then 
    scale=0.05
  fi

should work.

breaking it down

[[ $varA -eq 1 ]] 

is an integer comparison where as

$varB == 't1'

is a string comparison. otherwise, I am just grouping the comparisons correctly.

Double square brackets delimit a Conditional Expression. And, I find the following to be a good reading on the subject: "(IBM) Demystify test, [, [[, ((, and if-then-else"

Get row-index values of Pandas DataFrame as list?

To get the index values as a list/list of tuples for Index/MultiIndex do:

df.index.values.tolist()  # an ndarray method, you probably shouldn't depend on this

or

list(df.index.values)  # this will always work in pandas

Function to calculate distance between two coordinates

I have written the function to find distance between two coordinates. It will return distance in meter.

 function findDistance() {
   var R = 6371e3; // R is earth’s radius
   var lat1 = 23.18489670753479; // starting point lat
   var lat2 = 32.726601;         // ending point lat
   var lon1 = 72.62524545192719; // starting point lon
   var lon2 = 74.857025;         // ending point lon
   var lat1radians = toRadians(lat1);
   var lat2radians = toRadians(lat2);

   var latRadians = toRadians(lat2-lat1);
   var lonRadians = toRadians(lon2-lon1);

   var a = Math.sin(latRadians/2) * Math.sin(latRadians/2) +
        Math.cos(lat1radians) * Math.cos(lat2radians) *
        Math.sin(lonRadians/2) * Math.sin(lonRadians/2);
   var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

   var d = R * c;

   console.log(d)
}

function toRadians(val){
    var PI = 3.1415926535;
    return val / 180.0 * PI;
}

port forwarding in windows

nginx is useful for forwarding HTTP on many platforms including Windows. It's easy to setup and extend with more advanced configuration. A basic configuration could look something like this:

events {}

http {
     server {

        listen 192.168.1.111:4422;

        location / {
            proxy_pass http://192.168.2.33:80/;
        }
     }
}

Build an iOS app without owning a mac?

Short answer : theoretically YES, but this has to be a VERY GOOD friend of yours, but again, you might prefer to buy a used mac-mini

TLDR : You will need this Mac for a really long time, depending on your app requirements, your development skills, and your luck with Apple. For example:

  1. You might need some days to set up Xcode and the required SDKs and Libraries.
  2. It might take some time to get that Developer Account, sometimes you can wait too much even to get your request reviewed.
  3. When you submit your application for the first time, you will have to wait sometime, maybe up to several weeks, or even months, to get your app reviewed.
  4. Each time your app gets rejected, you will need to find and fix your issues (without much help from Apple, other that pointing out the guideline rule that you broke ), then re-submit your app for review, and wait again.
  5. Each time you try to apply a patch for your already deployed app, you will have to get your app reviewed and there is a chance that your previously legit app, now breaks a new guideline, so you re-submit and wait

So, from my experience the development of an iOS app is a very lengthy procedure, without even considering the actual code-development time. Can you borrow a Mac for that long ?

What are these attributes: `aria-labelledby` and `aria-hidden`

HTML5 ARIA attribute is what you're looking for. It can be used in your code even without bootstrap.

Accessible Rich Internet Applications (ARIA) defines ways to make Web content and Web applications (especially those developed with Ajax and JavaScript) more accessible to people with disabilities.

To be precise for your question, here is what your attributes are called as ARIA attribute states and model

aria-labelledby: Identifies the element (or elements) that labels the current element.

aria-hidden (state): Indicates that the element and all of its descendants are not visible or perceivable to any user as implemented by the author.

Warning: mysqli_query() expects parameter 1 to be mysqli, resource given

You are using improper syntax. If you read the docs mysqli_query() you will find that it needs two parameter.

mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

mysql $link generally means, the resource object of the established mysqli connection to query the database.

So there are two ways of solving this problem

mysqli_query();

$myConnection= mysqli_connect("$db_host","$db_username","$db_pass", "mrmagicadam") or die ("could not connect to mysql"); 
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysqli_query($myConnection, $sqlCommand) or die(mysqli_error($myConnection));

Or, Using mysql_query() (This is now obselete)

$myConnection= mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysql_select_db("mrmagicadam") or die ("no database");        
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysql_query($sqlCommand) or die(mysql_error());

As pointed out in the comments, be aware of using die to just get the error. It might inadvertently give the viewer some sensitive information .

How to merge a specific commit in Git

Let's try to take an example and understand:

I have a branch, say master, pointing to X <commit-id>, and I have a new branch pointing to Y <sha1>.

Where Y <commit-id> = <master> branch commits - few commits

Now say for Y branch I have to gap-close the commits between the master branch and the new branch. Below is the procedure we can follow:

Step 1:

git checkout -b local origin/new

where local is the branch name. Any name can be given.

Step 2:

  git merge origin/master --no-ff --stat -v --log=300

Merge the commits from master branch to new branch and also create a merge commit of log message with one-line descriptions from at most <n> actual commits that are being merged.

For more information and parameters about Git merge, please refer to:

git merge --help

Also if you need to merge a specific commit, then you can use:

git cherry-pick <commit-id>

How to find the kth largest element in an unsorted array of length n in O(n)?

There is also one algorithm, that outperforms quickselect algorithm. It's called Floyd-Rivets (FR) algorithm.

Original article: https://doi.org/10.1145/360680.360694

Downloadable version: http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.309.7108&rep=rep1&type=pdf

Wikipedia article https://en.wikipedia.org/wiki/Floyd%E2%80%93Rivest_algorithm

I tried to implement quickselect and FR algorithm in C++. Also I compared them to the standard C++ library implementations std::nth_element (which is basically introselect hybrid of quickselect and heapselect). The result was quickselect and nth_element ran comparably on average, but FR algorithm ran approx. twice as fast compared to them.

Sample code that I used for FR algorithm:

template <typename T>
T FRselect(std::vector<T>& data, const size_t& n)
{
    if (n == 0)
        return *(std::min_element(data.begin(), data.end()));
    else if (n == data.size() - 1)
        return *(std::max_element(data.begin(), data.end()));
    else
        return _FRselect(data, 0, data.size() - 1, n);
}

template <typename T>
T _FRselect(std::vector<T>& data, const size_t& left, const size_t& right, const size_t& n)
{
    size_t leftIdx = left;
    size_t rightIdx = right;

    while (rightIdx > leftIdx)
    {
        if (rightIdx - leftIdx > 600)
        {
            size_t range = rightIdx - leftIdx + 1;
            long long i = n - (long long)leftIdx + 1;
            long long z = log(range);
            long long s = 0.5 * exp(2 * z / 3);
            long long sd = 0.5 * sqrt(z * s * (range - s) / range) * sgn(i - (long long)range / 2);

            size_t newLeft = fmax(leftIdx, n - i * s / range + sd);
            size_t newRight = fmin(rightIdx, n + (range - i) * s / range + sd);

            _FRselect(data, newLeft, newRight, n);
        }
        T t = data[n];
        size_t i = leftIdx;
        size_t j = rightIdx;
        // arrange pivot and right index
        std::swap(data[leftIdx], data[n]);
        if (data[rightIdx] > t)
            std::swap(data[rightIdx], data[leftIdx]);

        while (i < j)
        {
            std::swap(data[i], data[j]);
            ++i; --j;
            while (data[i] < t) ++i;
            while (data[j] > t) --j;
        }

        if (data[leftIdx] == t)
            std::swap(data[leftIdx], data[j]);
        else
        {
            ++j;
            std::swap(data[j], data[rightIdx]);
        }
        // adjust left and right towards the boundaries of the subset
        // containing the (k - left + 1)th smallest element
        if (j <= n)
            leftIdx = j + 1;
        if (n <= j)
            rightIdx = j - 1;
    }

    return data[leftIdx];
}

template <typename T>
int sgn(T val) {
    return (T(0) < val) - (val < T(0));
}

Unrecognized SSL message, plaintext connection? Exception

As EJP said, it's a message shown because of a call to a non-https protocol. If you are sure it is HTTPS, check your bypass proxy settings, and in case add your webservice host url to the bypass proxy list

Why does using from __future__ import print_function breaks Python2-style print?

First of all, from __future__ import print_function needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print as a function now. That's the whole point of from __future__ import print_function; to bring the print function from Python 3 into Python 2.6+.

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__ statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

The documentation also mentions that the only things that can precede a __future__ statement are the module docstring, comments, blank lines, and other future statements.

Nodejs - Redirect url

404 with Content/Body

res.writeHead(404, {'Content-Type': 'text/plain'});                    // <- redirect
res.write("Looked everywhere, but couldn't find that page at all!\n"); // <- content!
res.end();                                                             // that's all!

Redirect to Https

res.writeHead(302, {'Location': 'https://example.com' + req.url});
res.end();

Just consider where you use this (e.g. only for http request), so you don't get endless redirects ;-)

Properly close mongoose's connection once you're done

You can set the connection to a variable then disconnect it when you are done:

var db = mongoose.connect('mongodb://localhost:27017/somedb');

// Do some stuff

db.disconnect();

SQL Left Join first match only

Try this

 SELECT *
 FROM people P 
 where P.IDNo in (SELECT DISTINCT IDNo
              FROM people)

TypeError("'bool' object is not iterable",) when trying to return a Boolean

Look at the traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Your code isn't iterating the value, but the code receiving it is.

The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)) or enclose it in a tuple ((False,)).

Always read the traceback: it's correct, and it's helpful.

How to check for file lock?

Same thing but in Powershell

function Test-FileOpen
{
    Param
    ([string]$FileToOpen)
    try
    {
        $openFile =([system.io.file]::Open($FileToOpen,[system.io.filemode]::Open))
        $open =$true
        $openFile.close()
    }
    catch
    {
        $open = $false
    }
    $open
}

indexOf and lastIndexOf in PHP?

You need the following functions to do this in PHP:

strpos Find the position of the first occurrence of a substring in a string

strrpos Find the position of the last occurrence of a substring in a string

substr Return part of a string

Here's the signature of the substr function:

string substr ( string $string , int $start [, int $length ] )

The signature of the substring function (Java) looks a bit different:

string substring( int beginIndex, int endIndex )

substring (Java) expects the end-index as the last parameter, but substr (PHP) expects a length.

It's not hard, to get the desired length by the end-index in PHP:

$sub = substr($str, $start, $end - $start);

Here is the working code

$start = strpos($message, '-') + 1;
if ($req_type === 'RMT') {
    $pt_password = substr($message, $start);
}
else {
    $end = strrpos($message, '-');
    $pt_password = substr($message, $start, $end - $start);
}

how to stop a loop arduino

just use this line to exit function:

return;

How to pull specific directory with git

For all that struggle with theoretical file paths and examples like I did, here a real world example: Microsoft offers their docs and examples on git hub, unfortunately they do gather all their example files for a large amount of topics in this repository:

https://github.com/microsoftarchive/msdn-code-gallery-community-s-z

I only was interested in the Microsoft Dynamics js files in the path

msdn-code-gallery-community-s-z/Sdk.Soap.js/

so I did the following

create a

msdn-code-gallery-community-s-zSdkSoapjs\.git\info\sparse-checkout

file in my repositories folder on the disk

git sparse-checkout init

in that directory using cmd on windows

The file contents of

msdn-code-gallery-community-s-zSdkSoapjs\.git\info\sparse-checkout

is

Sdk.Soap.js/*

finally do a

git pull origin master

Get generic type of class at runtime

public static final Class<?> getGenericArgument(final Class<?> clazz)
{
    return (Class<?>) ((ParameterizedType) clazz.getGenericSuperclass()).getActualTypeArguments()[0];
}

Reloading submodules in IPython

Another option:

$ cat << EOF > ~/.ipython/profile_default/startup/50-autoreload.ipy
%load_ext autoreload
%autoreload 2
EOF

Verified on ipython and ipython3 v5.1.0 on Ubuntu 14.04.

How to configure PostgreSQL to accept all incoming connections

0.0.0.0/0 for all IPv4 addresses

::0/0 for all IPv6 addresses

all to match any IP address

samehost to match any of the server's own IP addresses

samenet to match any address in any subnet that the server is directly connected to.

e.g.

host    all             all             0.0.0.0/0            md5

Pointer arithmetic for void pointer in C

Pointer arithmetic is not allowed on void* pointers.

rotate image with css

Give the parent a style of overflow: hidden. If it is overlapping sibling elements, you will have to put it inside of a container with a fixed height/width and give that a style of overflow: hidden.

c# Best Method to create a log file

We did a lot of research into logging, and decided that NLog was the best one to use.

See http://nlog-project.org/

Also see log4net vs. Nlog and http://www.dotnetlogging.com/comparison/

Best way to Format a Double value to 2 Decimal places

No, there is no better way.

Actually you have an error in your pattern. What you want is:

DecimalFormat df = new DecimalFormat("#.00"); 

Note the "00", meaning exactly two decimal places.

If you use "#.##" (# means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d); prints just "3", not "3.00".

Convert a Pandas DataFrame to a dictionary

DataFrame.to_dict() converts DataFrame to dictionary.

Example

>>> df = pd.DataFrame(
    {'col1': [1, 2], 'col2': [0.5, 0.75]}, index=['a', 'b'])
>>> df
   col1  col2
a     1   0.1
b     2   0.2
>>> df.to_dict()
{'col1': {'a': 1, 'b': 2}, 'col2': {'a': 0.5, 'b': 0.75}}

See this Documentation for details

How do I disable a Button in Flutter?

For a specific and limited number of widgets, wrapping them in a widget IgnorePointer does exactly this: when its ignoring property is set to true, the sub-widget (actually, the entire subtree) is not clickable.

IgnorePointer(
    ignoring: true, // or false
    child: RaisedButton(
        onPressed: _logInWithFacebook,
        child: Text("Facebook sign-in"),
        ),
),

Otherwise, if you intend to disable an entire subtree, look into AbsorbPointer().

Close Window from ViewModel

You can close the current window just by using the following code:

Application.Current.Windows[0].Close();

ARM compilation error, VFP registers used by executable, not object file

Also the error can be solved by adding several flags, like -marm -mthumb-interwork. It was helpful for me to avoid this same error.

Image change every 30 seconds - loop

You should take a look at various javascript libraries, they should be able to help you out:

All of them have tutorials, and fade in/fade out is a basic usage.

For e.g. in jQuery:

var $img = $("img"), i = 0, speed = 200;
window.setInterval(function() {
  $img.fadeOut(speed, function() {
    $img.attr("src", images[(++i % images.length)]);
    $img.fadeIn(speed);
  });
}, 30000);

Shall we always use [unowned self] inside closure in Swift

I thought I would add some concrete examples specifically for a view controller. Many of the explanations, not just here on Stack Overflow, are really good, but I work better with real world examples (@drewag had a good start on this):

  • If you have a closure to handle a response from a network requests use weak, because they are long lived. The view controller could close before the request completes so self no longer points to a valid object when the closure is called.
  • If you have closure that handles an event on a button. This can be unowned because as soon as the view controller goes away, the button and any other items it may be referencing from self goes away at the same time. The closure block will also go away at the same time.

    class MyViewController: UIViewController {
          @IBOutlet weak var myButton: UIButton!
          let networkManager = NetworkManager()
          let buttonPressClosure: () -> Void // closure must be held in this class. 
    
          override func viewDidLoad() {
              // use unowned here
              buttonPressClosure = { [unowned self] in
                  self.changeDisplayViewMode() // won't happen after vc closes. 
              }
              // use weak here
              networkManager.fetch(query: query) { [weak self] (results, error) in
                  self?.updateUI() // could be called any time after vc closes
              }
          }
          @IBAction func buttonPress(self: Any) {
             buttonPressClosure()
          }
    
          // rest of class below.
     }
    

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

By default, your "Project bytecode version isn't set in maven project.

It thinks that your current version is 5.

Solution 1:

Just go to "Project Settings>Build, Execution...>compiler>java compiler" and then change your bytecode version to your current java version.

Solution 2:

Adding below build plugin in POM file:

 <properties>
        <java.version>1.8</java.version>
        <maven.compiler.version>3.8.1</maven.compiler.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.version}</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

Adding a user on .htpasswd

FWIW, htpasswd -n username will output the result directly to stdout, and avoid touching files altogether.

Error: Unexpected value 'undefined' imported by the module

The issue is that there is at least one import for which source file is missing.

For example I got the same error when I was using

       import { AppRoutingModule } from './app-routing.module';

But the file './app-routing.module' was not there in given path.

I removed this import and error went away.

error: Unable to find vcvarsall.bat

I have python 2.73 and windows 7 .The solution that worked for me was:

  1. Added mingw32's bin directory to environment variable: append PATH with C:\programs\mingw\bin;
  2. Created distutils.cfg located at C:\Python27\Lib\distutils\distutils.cfg containing:

    [build]
    compiler=mingw32
    

To deal with MinGW not recognizing the -mno-cygwin flag anymore, remove the flag in C:\Python27\Lib\distutils\cygwincompiler.py line 322 to 326, so it looks like this:

  self.set_executables(compiler='gcc -O -Wall',
                         compiler_so='gcc -mdll -O -Wall',
                         compiler_cxx='g++ -O -Wall',
                         linker_exe='gcc',
                         linker_so='%s %s %s'
                                    % (self.linker_dll, shared_option,
                                       entry_point))

Create an Android GPS tracking application

Basically you need following things to make location detector android app

Now if you write each of these module yourself then it needs much time and efforts. So it would be better to use ready resources that are being maintained already.

Using all these resources, you will be able to create an flawless android location detection app.

1. Location Listening

You will first need to listen for current location of user. You can use any of below libraries to quick start.

Google Play Location Samples

This library provide last known location, location updates

Location Manager

With this library you just need to provide a Configuration object with your requirements, and you will receive a location or a fail reason with all the stuff are described above handled.

Live Location Sharing

Use this open source repo of the Hypertrack Live app to build live location sharing experience within your app within a few hours. HyperTrack Live app helps you share your Live Location with friends and family through your favorite messaging app when you are on the way to meet up. HyperTrack Live uses HyperTrack APIs and SDKs.

2. Markers Library

Google Maps Android API utility library

  • Marker clustering — handles the display of a large number of points
  • Heat maps — display a large number of points as a heat map
  • IconGenerator — display text on your Markers
  • Poly decoding and encoding — compact encoding for paths, interoperability with Maps API web services
  • Spherical geometry — for example: computeDistance, computeHeading, computeArea
  • KML — displays KML data
  • GeoJSON — displays and styles GeoJSON data

3. Polyline Libraries

DrawRouteMaps

If you want to add route maps feature in your apps you can use DrawRouteMaps to make you work more easier. This is lib will help you to draw route maps between two point LatLng.

trail-android

Simple, smooth animation for route / polylines on google maps using projections. (WIP)

Google-Directions-Android

This project allows you to calculate the direction between two locations and display the route on a Google Map using the Google Directions API.

A map demo app for quick start with maps

Spark difference between reduceByKey vs groupByKey vs aggregateByKey vs combineByKey

  • groupByKey() is just to group your dataset based on a key. It will result in data shuffling when RDD is not already partitioned.
  • reduceByKey() is something like grouping + aggregation. We can say reduceBykey() equvelent to dataset.group(...).reduce(...). It will shuffle less data unlike groupByKey().
  • aggregateByKey() is logically same as reduceByKey() but it lets you return result in different type. In another words, it lets you have a input as type x and aggregate result as type y. For example (1,2),(1,4) as input and (1,"six") as output. It also takes zero-value that will be applied at the beginning of each key.

Note : One similarity is they all are wide operations.

How can I prevent java.lang.NumberFormatException: For input string: "N/A"?

Obviously you can't parse N/A to int value. you can do something like following to handle that NumberFormatException .

   String str="N/A";
   try {
        int val=Integer.parseInt(str);
   }catch (NumberFormatException e){
       System.out.println("not a number"); 
   } 

Convert pyQt UI to python

You can use pyuic4 command on shell: pyuic4 input.ui -o output.py

Parse String to Date with Different Format in Java

While SimpleDateFormat will indeed work for your needs, additionally you might want to check out Joda Time, which is apparently the basis for the redone Date library in Java 7. While I haven't used it a lot, I've heard nothing but good things about it and if your manipulating dates extensively in your projects it would probably be worth looking into.

Best tool for inspecting PDF files?

If you want to work programmatically from within Python, pdfminer is a good option. It allows you to work with PDF structure in memory as an object hierarchy or serialize it as XML.

How to append new data onto a new line

I presume that all you are wanting is simple string concatenation:

def storescores():

   hs = open("hst.txt","a")
   hs.write(name + " ")
   hs.close() 

Alternatively, change the " " to "\n" for a newline.

Attaching click event to a JQuery object not yet added to the DOM

Maybe bind() would help:

button.bind('click', function() {
  alert('User clicked');
});

Checking if a variable is an integer

Basically, an integer n is a power of three, if there exists an integer x such that n == 3x.

So to verify that you can use this functions

def is_power_of_three(n)
  return false unless n.positive?

  n == 3**(Math.log10(n)/Math.log10(3)).to_f.round(2)
end

Tensorflow set CUDA_VISIBLE_DEVICES within jupyter

You can set environment variables in the notebook using os.environ. Do the following before initializing TensorFlow to limit TensorFlow to first GPU.

import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"   # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"]="0"

You can double check that you have the correct devices visible to TF

from tensorflow.python.client import device_lib
print device_lib.list_local_devices()

I tend to use it from utility module like notebook_util

import notebook_util
notebook_util.pick_gpu_lowest_memory()
import tensorflow as tf

How to redirect DNS to different ports

You can use SRV records:

_service._proto.name. TTL class SRV priority weight port target.

Service: the symbolic name of the desired service.

Proto: the transport protocol of the desired service; this is usually either TCP or UDP.

Name: the domain name for which this record is valid, ending in a dot.

TTL: standard DNS time to live field.

Class: standard DNS class field (this is always IN).

Priority: the priority of the target host, lower value means more preferred.

Weight: A relative weight for records with the same priority.

Port: the TCP or UDP port on which the service is to be found.

Target: the canonical hostname of the machine providing the service, ending in a dot.

Example:

_sip._tcp.example.com. 86400 IN SRV 0 5 5060 sipserver.example.com.

So what I think you're looking for is to add something like this to your DNS hosts file:

_sip._tcp.arboristal.com. 86400 IN SRV 10 40 25565 mc.arboristal.com.
_sip._tcp.arboristal.com. 86400 IN SRV 10 30 25566 tekkit.arboristal.com.
_sip._tcp.arboristal.com. 86400 IN SRV 10 30 25567 pvp.arboristal.com.

On a side note, I highly recommend you go with a hosting company rather than hosting the servers yourself. It's just asking for trouble with your home connection (DDoS and Bandwidth/Connection Speed), but it's up to you.

Target elements with multiple classes, within one rule

Just in case someone stumbles upon this like I did and doesn't realise, the two variations above are for different use cases.

The following:

.blue-border, .background {
    border: 1px solid #00f;
    background: #fff;
}

is for when you want to add styles to elements that have either the blue-border or background class, for example:

<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>

would all get a blue border and white background applied to them.

However, the accepted answer is different.

.blue-border.background {
    border: 1px solid #00f;
    background: #fff;
}

This applies the styles to elements that have both classes so in this example only the <div> with both classes should get the styles applied (in browsers that interpret the CSS properly):

<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>

So basically think of it like this, comma separating applies to elements with one class OR another class and dot separating applies to elements with one class AND another class.

MessageBodyWriter not found for media type=application/json

Uncommenting the below code helped

<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-moxy</artifactId>
</dependency>

which was present in pom.xml in my maven based project resolved this error for me.

How to find Current open Cursors in Oracle

This could work:

SELECT    sql_text "SQL Query", 
          Count(*) AS "Open Cursors" 
FROM      v$open_cursor 
GROUP BY  sql_text 
HAVING    Count(*) > 2 
ORDER BY  Count(*) DESC; 

Is there a math nCr function in python?

Do you want iteration? itertools.combinations. Common usage:

>>> import itertools
>>> itertools.combinations('abcd',2)
<itertools.combinations object at 0x01348F30>
>>> list(itertools.combinations('abcd',2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> [''.join(x) for x in itertools.combinations('abcd',2)]
['ab', 'ac', 'ad', 'bc', 'bd', 'cd']

If you just need to compute the formula, use math.factorial:

import math

def nCr(n,r):
    f = math.factorial
    return f(n) / f(r) / f(n-r)

if __name__ == '__main__':
    print nCr(4,2)

In Python 3, use the integer division // instead of / to avoid overflows:

return f(n) // f(r) // f(n-r)

Output

6

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

This is the most common issue faced by Windows users for running Docker Containers. IMO this is the "million dollar question on Docker"; @"Rocco Smit" has rightly pointed out "inbound traffic for it was disabled by default on my host machine's firewall"; in my case, my McAfee Anti Virus software. I added additional ports to be allowed for inbound traffic from other computers on the same Wifi LAN in the Firewall Settings of McAfee; then it was magic. I had struggled for more than a week browsing all over internet, SO, Docker documentations, Tutorials after Tutorials related to the Networking of Docker, and the many illustrations of "not supported on Windows" for "macvlan", "ipvlan", "user defined bridge" and even this same SO thread couple of times. I even started browsing google with "anybody using Docker in Production?", (yes I know Linux is more popular for Prod workloads compared to Windows servers) as I was not able to access (from my mobile in the same Home wifi) an nginx app deployed in Docker Container on Windows. After all, what good it is, if you cannot access the application (deployed on a Docker Container) from other computers / devices in the same LAN at-least; Ultimately in my case, the issue was just with a firewall blocking inbound traffic;

ConvergenceWarning: Liblinear failed to converge, increase the number of iterations

Normally when an optimization algorithm does not converge, it is usually because the problem is not well-conditioned, perhaps due to a poor scaling of the decision variables. There are a few things you can try.

  1. Normalize your training data so that the problem hopefully becomes more well conditioned, which in turn can speed up convergence. One possibility is to scale your data to 0 mean, unit standard deviation using Scikit-Learn's StandardScaler for an example. Note that you have to apply the StandardScaler fitted on the training data to the test data.
  2. Related to 1), make sure the other arguments such as regularization weight, C, is set appropriately.
  3. Set max_iter to a larger value. The default is 1000.
  4. Set dual = True if number of features > number of examples and vice versa. This solves the SVM optimization problem using the dual formulation. Thanks @Nino van Hooff for pointing this out, and @JamesKo for spotting my mistake.
  5. Use a different solver, for e.g., the L-BFGS solver if you are using Logistic Regression. See @5ervant's answer.

Note: One should not ignore this warning.

This warning came about because

  1. Solving the linear SVM is just solving a quadratic optimization problem. The solver is typically an iterative algorithm that keeps a running estimate of the solution (i.e., the weight and bias for the SVM). It stops running when the solution corresponds to an objective value that is optimal for this convex optimization problem, or when it hits the maximum number of iterations set.

  2. If the algorithm does not converge, then the current estimate of the SVM's parameters are not guaranteed to be any good, hence the predictions can also be complete garbage.

Edit

In addition, consider the comment by @Nino van Hooff and @5ervant to use the dual formulation of the SVM. This is especially important if the number of features you have, D, is more than the number of training examples N. This is what the dual formulation of the SVM is particular designed for and helps with the conditioning of the optimization problem. Credit to @5ervant for noticing and pointing this out.

Furthermore, @5ervant also pointed out the possibility of changing the solver, in particular the use of the L-BFGS solver. Credit to him (i.e., upvote his answer, not mine).

I would like to provide a quick rough explanation for those who are interested (I am :)) why this matters in this case. Second-order methods, and in particular approximate second-order method like the L-BFGS solver, will help with ill-conditioned problems because it is approximating the Hessian at each iteration and using it to scale the gradient direction. This allows it to get better convergence rate but possibly at a higher compute cost per iteration. That is, it takes fewer iterations to finish but each iteration will be slower than a typical first-order method like gradient-descent or its variants.

For e.g., a typical first-order method might update the solution at each iteration like

x(k + 1) = x(k) - alpha(k) * gradient(f(x(k)))

where alpha(k), the step size at iteration k, depends on the particular choice of algorithm or learning rate schedule.

A second order method, for e.g., Newton, will have an update equation

x(k + 1) = x(k) - alpha(k) * Hessian(x(k))^(-1) * gradient(f(x(k)))

That is, it uses the information of the local curvature encoded in the Hessian to scale the gradient accordingly. If the problem is ill-conditioned, the gradient will be pointing in less than ideal directions and the inverse Hessian scaling will help correct this.

In particular, L-BFGS mentioned in @5ervant's answer is a way to approximate the inverse of the Hessian as computing it can be an expensive operation.

However, second-order methods might converge much faster (i.e., requires fewer iterations) than first-order methods like the usual gradient-descent based solvers, which as you guys know by now sometimes fail to even converge. This can compensate for the time spent at each iteration.

In summary, if you have a well-conditioned problem, or if you can make it well-conditioned through other means such as using regularization and/or feature scaling and/or making sure you have more examples than features, you probably don't have to use a second-order method. But these days with many models optimizing non-convex problems (e.g., those in DL models), second order methods such as L-BFGS methods plays a different role there and there are evidence to suggest they can sometimes find better solutions compared to first-order methods. But that is another story.

form with no action and where enter does not reload page

You'll want to include action="javascript:void(0);" to your form to prevent page reloads and maintain HTML standard.

Calculate a MD5 hash from a string

A MD5 hash is 128 bits, so you can't represent it in hex with less than 32 characters...

ImportError: No module named dateutil.parser

You can find the dateutil package at https://pypi.python.org/pypi/python-dateutil. Extract it to somewhere and run the command:

python setup.py install

It worked for me!

jquery append div inside div with id and manipulate

var e = $('<div style="display:block; id="myid" float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
$("#box").html(e);

Postgresql query between date ranges

Read the documentation.

http://www.postgresql.org/docs/9.1/static/functions-datetime.html

I used a query like that:

WHERE
(
    date_trunc('day',table1.date_eval) = '2015-02-09'
)

or

WHERE(date_trunc('day',table1.date_eval) >='2015-02-09'AND date_trunc('day',table1.date_eval) <'2015-02-09')    

Juanitos Ingenier.

Stretch Image to Fit 100% of Div Height and Width

You're mixing notations. It should be:

<img src="folder/file.jpg" width="200" height="200">

(note, no px). Or:

<img src="folder/file.jpg" style="width: 200px; height: 200px;">

(using the style attribute) The style attribute could be replaced with the following CSS:

#mydiv img {
    width: 200px;
    height: 200px;
}

or

#mydiv img {
    width: 100%;
    height: 100%;
}

Dynamically Changing log4j log level

You can use following code snippet

((ch.qos.logback.classic.Logger)LoggerFactory.getLogger(packageName)).setLevel(ch.qos.logback.classic.Level.toLevel(logLevel));

What is the difference between parseInt() and Number()?

If you are looking for performance then probably best results you'll get with bitwise right shift "10">>0. Also multiply ("10" * 1) or not not (~~"10"). All of them are much faster of Number and parseInt. They even have "feature" returning 0 for not number argument. Here are Performance tests.

What's the use of session.flush() in Hibernate

Flushing the session forces Hibernate to synchronize the in-memory state of the Session with the database (i.e. to write changes to the database). By default, Hibernate will flush changes automatically for you:

  • before some query executions
  • when a transaction is committed

Allowing to explicitly flush the Session gives finer control that may be required in some circumstances (to get an ID assigned, to control the size of the Session,...).

Get integer value from string in swift

I wrote an extension for that purpose. It always returns an Int. If the string does not fit into an Int, 0 is returned.

extension String {
    func toTypeSafeInt() -> Int {
        if let safeInt = self.toInt() {
            return safeInt
        } else {
            return 0
        }
    }
}

Excel 2013 horizontal secondary axis

You should follow the guidelines on Add a secondary horizontal axis:

Add a secondary horizontal axis

To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.

  1. Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.

  2. On the Layout tab, in the Axes group, click Axes.

    enter image description here

  3. Click Secondary Horizontal Axis, and then click the display option that you want.

enter image description here


Add a secondary vertical axis

You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.

  1. In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:

    • Click the chart.

      This displays the Chart Tools, adding the Design, Layout, and Format tabs.

    • On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.

      enter image description here

  2. On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.

    Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.

  3. On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.

    A secondary vertical axis is displayed in the chart.

  4. To change the display of the secondary vertical axis, do the following:

    • On the Layout tab, in the Axes group, click Axes.

    • Click Secondary Vertical Axis, and then click the display option that you want.

  5. To change the axis options of the secondary vertical axis, do the following:

    • Right-click the secondary vertical axis, and then click Format Axis.

    • Under Axis Options, select the options that you want to use.

Text in HTML Field to disappear when clicked?

try this one out.

<label for="user">user</label>
<input type="text" name="user" 
onfocus="if(this.value==this.defaultValue)this.value=''"    
onblur="if(this.value=='')this.value=this.defaultValue" 
value="username" maxlength="19" />

hope this helps.

How to use NSURLConnection to connect with SSL for an untrusted cert?

With AFNetworking I have successfully consumed https webservice with below code,

NSString *aStrServerUrl = WS_URL;

// Initialize AFHTTPRequestOperationManager...
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];

[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
manager.securityPolicy.allowInvalidCertificates = YES; 
[manager POST:aStrServerUrl parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
{
    successBlock(operation, responseObject);

} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
    errorBlock(operation, error);
}];

Remove Sub String by using Python

import re
re.sub('<.*?>', '', string)
"i think mabe 124 + but I don't have a big experience it just how I see it in my eyes fun stuff"

The re.sub function takes a regular expresion and replace all the matches in the string with the second parameter. In this case, we are searching for all tags ('<.*?>') and replacing them with nothing ('').

The ? is used in re for non-greedy searches.

More about the re module.

How should I edit an Entity Framework connection string?

No, you can't edit the connection string in the designer. The connection string is not part of the EDMX file it is just referenced value from the configuration file and probably because of that it is just readonly in the properties window.

Modifying configuration file is common task because you sometimes wants to make change without rebuilding the application. That is the reason why configuration files exist.

window.history.pushState refreshing the browser

window.history.pushState({urlPath:'/page1'},"",'/page1')

Only works after page is loaded, and when you will click on refresh it doesn't mean that there is any real URL.

What you should do here is knowing to which URL you are getting redirected when you reload this page. And on that page you can get the conditions by getting the current URL and making all of your conditions.

Bitwise and in place of modulus operator

There is only a simple way to find modulo of 2^i numbers using bitwise.

There is an ingenious way to solve Mersenne cases as per the link such as n % 3, n % 7... There are special cases for n % 5, n % 255, and composite cases such as n % 6.

For cases 2^i, ( 2, 4, 8, 16 ...)

n % 2^i = n & (2^i - 1)

More complicated ones are hard to explain. Read up only if you are very curious.

How do I position one image on top of another in HTML?

Here's code that may give you ideas:

<style>
.containerdiv { float: left; position: relative; } 
.cornerimage { position: absolute; top: 0; right: 0; } 
</style>

<div class="containerdiv">
    <img border="0" src="https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png" alt=""">
    <img class="cornerimage" border="0" src="http://www.gravatar.com/avatar/" alt="">
<div>

JSFiddle

I suspect that Espo's solution may be inconvenient because it requires you to position both images absolutely. You may want the first one to position itself in the flow.

Usually, there is a natural way to do that is CSS. You put position: relative on the container element, and then absolutely position children inside it. Unfortunately, you cannot put one image inside another. That's why I needed container div. Notice that I made it a float to make it autofit to its contents. Making it display: inline-block should theoretically work as well, but browser support is poor there.

EDIT: I deleted size attributes from the images to illustrate my point better. If you want the container image to have its default sizes and you don't know the size beforehand, you cannot use the background trick. If you do, it is a better way to go.

Django - limiting query results

Django querysets are lazy. That means a query will hit the database only when you specifically ask for the result.

So until you print or actually use the result of a query you can filter further with no database access.

As you can see below your code only executes one sql query to fetch only the last 10 items.

In [19]: import logging                                 
In [20]: l = logging.getLogger('django.db.backends')    
In [21]: l.setLevel(logging.DEBUG)                      
In [22]: l.addHandler(logging.StreamHandler())      
In [23]: User.objects.all().order_by('-id')[:10]          
(0.000) SELECT "auth_user"."id", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user" ORDER BY "auth_user"."id" DESC LIMIT 10; args=()
Out[23]: [<User: hamdi>]

CMake: How to build external projects and include their targets

I think you're mixing up two different paradigms here.

As you noted, the highly flexible ExternalProject module runs its commands at build time, so you can't make direct use of Project A's import file since it's only created once Project A has been installed.

If you want to include Project A's import file, you'll have to install Project A manually before invoking Project B's CMakeLists.txt - just like any other third-party dependency added this way or via find_file / find_library / find_package.

If you want to make use of ExternalProject_Add, you'll need to add something like the following to your CMakeLists.txt:

ExternalProject_Add(project_a
  URL ...project_a.tar.gz
  PREFIX ${CMAKE_CURRENT_BINARY_DIR}/project_a
  CMAKE_ARGS -DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR>
)

include(${CMAKE_CURRENT_BINARY_DIR}/lib/project_a/project_a-targets.cmake)

ExternalProject_Get_Property(project_a install_dir)
include_directories(${install_dir}/include)

add_dependencies(project_b_exe project_a)
target_link_libraries(project_b_exe ${install_dir}/lib/alib.lib)

How to check what user php is running as?

You can try using backticks like this:

echo `whoami`;

setOnItemClickListener on custom ListView

I too had that same problem.. If we think logically little bit we can get the answer.. It worked for me very well.. I hope u will get it..

  1. listviewdemo.xml

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="30dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp" />
    

  2. listviewcontent.xml - note that TextView - android:id="@+id/txtLstItem"

    <LinearLayout
        android:id="@+id/listviewcontentlayout"
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:orientation="horizontal">
    
        <ImageView
            android:id="@+id/img1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="6dp" />
    
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:orientation="vertical">
    
            <TextView
                android:id="@+id/txtLstItem"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="left"
                android:shadowColor="@android:color/black"
                android:shadowRadius="5"
                android:textColor="@android:color/white" />
    
        </LinearLayout>
    
        <ImageView
            android:id="@+id/img2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="6dp" />
    </LinearLayout>
    

  3. ListViewActivity.java - Note that view.findViewById(R.id.txtLstItem) - as we setting the value to TextView by setText() method we getting text from TextView by View object returned by onItemClick method. OnItemClick() returns the current view.

    TextView v=(TextView) view.findViewById(R.id.txtLstItem);
    Toast.makeText(getApplicationContext(), "selected Item Name is "+v.getText(), Toast.LENGTH_LONG).show();**
    

    Using this simple logic we can get other values like CheckBox, RadioButton, ImageView etc.

    ListView List = (ListView) findViewById(R.id.listview);
    cursor = cr.query(CONTENT_URI,projection,null,null,null);
    adapter = new ListViewCursorAdapter(ListViewActivity.this, R.layout.listviewcontent, cursor, from, to);
    
    cursor.moveToFirst();
    
    // Let activity manage the cursor
    startManagingCursor(cursor);
    
    List.setAdapter(adapter);
    List.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick (AdapterView < ? > adapter, View view,int position, long arg){
                // TODO Auto-generated method stub
                TextView v = (TextView) view.findViewById(R.id.txtLstItem);
                Toast.makeText(getApplicationContext(), "selected Item Name is " + v.getText(), Toast.LENGTH_LONG).show();
            }
        }
    );
    

Getting or changing CSS class property with Javascript using DOM style

I think this is not the best way, but in my cases other methods did not work.

stylesheet = document.styleSheets[0]
stylesheet.insertRule(".have-border { border: 1px solid black;}", 0);

Example from https://www.w3.org/wiki/Dynamic_style_-_manipulating_CSS_with_JavaScript

How to set upload_max_filesize in .htaccess?

php_value upload_max_filesize 30M is correct.

You will have to contact your hosters -- some don't allow you to change values in php.ini

How do you do a ‘Pause’ with PowerShell 2.0?

cmd /c pause | out-null

(It is not the PowerShell way, but it's so much more elegant.)

Save trees. Use one-liners.

Groovy - How to compare the string?

This should be an answer

str2.equals( str )

If you want to ignore case

str2.equalsIgnoreCase( str )

Removing items from a ListBox in VB.net

   Dim ca As Integer = ListBox1.Items.Count().ToString
    While Not ca = 0
        ca = ca - 1
        ListBox1.Items.RemoveAt(ca)
    End While

What is the best way to measure execution time of a function?

Use a Profiler

Your approach will work nevertheless, but if you are looking for more sophisticated approaches. I'd suggest using a C# Profiler.

The advantages they have is:

  • You can even get a statement level breakup
  • No changes required in your codebase
  • Instrumentions generally have very less overhead, hence very accurate results can be obtained.

There are many available open-source as well.

T-SQL Substring - Last 3 Characters

SELECT RIGHT(column, 3)

That's all you need.

You can also do LEFT() in the same way.

Bear in mind if you are using this in a WHERE clause that the RIGHT() can't use any indexes.

Instagram: Share photo from webpage

As of November 17, 2015. This rule has officially changed. Instagram has deprecated the rule against using their API to upload images.

Good luck.

What does <value optimized out> mean in gdb?

It means you compiled with e.g. gcc -O3 and the gcc optimiser found that some of your variables were redundant in some way that allowed them to be optimised away. In this particular case you appear to have three variables a, b, c with the same value and presumably they can all be aliassed to a single variable. Compile with optimisation disabled, e.g. gcc -O0, if you want to see such variables (this is generally a good idea for debug builds in any case).

Counting inversions in an array

I recently had to do this in R:

inversionNumber <- function(x){
    mergeSort <- function(x){
        if(length(x) == 1){
            inv <- 0
        } else {
            n <- length(x)
            n1 <- ceiling(n/2)
            n2 <- n-n1
            y1 <- mergeSort(x[1:n1])
            y2 <- mergeSort(x[n1+1:n2])
            inv <- y1$inversions + y2$inversions
            x1 <- y1$sortedVector
            x2 <- y2$sortedVector
            i1 <- 1
            i2 <- 1
            while(i1+i2 <= n1+n2+1){
                if(i2 > n2 || i1 <= n1 && x1[i1] <= x2[i2]){
                    x[i1+i2-1] <- x1[i1]
                    i1 <- i1 + 1
                } else {
                    inv <- inv + n1 + 1 - i1
                    x[i1+i2-1] <- x2[i2]
                    i2 <- i2 + 1
                }
            }
        }
        return (list(inversions=inv,sortedVector=x))
    }
    r <- mergeSort(x)
    return (r$inversions)
}

how to use List<WebElement> webdriver

List<WebElement> myElements = driver.findElements(By.xpath("some/path//a"));
        System.out.println("Size of List: "+myElements.size());
        for(WebElement e : myElements) 
        {        
            System.out.print("Text within the Anchor tab"+e.getText()+"\t");
            System.out.println("Anchor: "+e.getAttribute("href"));
        }

//NOTE: "//a" will give you all the anchors there on after the point your XPATH has reached.

Global variable Python classes

What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut or via an instance e.g. shape.lolwut but be careful while setting it as it will set an instance level attribute not class attribute

class Shape(object):
    lolwut = 1

shape = Shape()

print Shape.lolwut,  # 1
print shape.lolwut,  # 1

# setting shape.lolwut would not change class attribute lolwut 
# but will create it in the instance
shape.lolwut = 2

print Shape.lolwut,  # 1
print shape.lolwut,  # 2

# to change class attribute access it via class
Shape.lolwut = 3

print Shape.lolwut,  # 3
print shape.lolwut   # 2 

output:

1 1 1 2 3 2

Somebody may expect output to be 1 1 2 2 3 3 but it would be incorrect

Is there a way to collapse all code blocks in Eclipse?

Right click on the circles +/- sign and under Foldings select Collapse All

Set width of a "Position: fixed" div relative to parent div

You need to give the same style of the fixed element and its parent element. One of these examples is created with max widths and in the other example with paddings.

_x000D_
_x000D_
* {_x000D_
  box-sizing: border-box_x000D_
}_x000D_
body {_x000D_
  margin: 0;_x000D_
}_x000D_
.container {_x000D_
  max-width: 500px;_x000D_
  height: 100px;_x000D_
  width: 100%;_x000D_
  margin-left: auto;_x000D_
  margin-right: auto;_x000D_
  background-color: lightgray;_x000D_
}_x000D_
.content {_x000D_
  max-width: 500px;_x000D_
  width: 100%;_x000D_
  position: fixed;_x000D_
}_x000D_
h2 {_x000D_
  border: 1px dotted black;_x000D_
  padding: 10px;_x000D_
}_x000D_
.container-2 {_x000D_
  height: 100px;_x000D_
  padding-left: 32px;_x000D_
  padding-right: 32px;_x000D_
  margin-top: 10px;_x000D_
  background-color: lightgray;_x000D_
}_x000D_
.content-2 {_x000D_
  width: 100%;_x000D_
  position: fixed;_x000D_
  left: 0;_x000D_
  padding-left: 32px;_x000D_
  padding-right: 32px;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="content">_x000D_
    <h2>container with max widths</h2>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<div class="container-2">_x000D_
  <div class="content-2">_x000D_
    <div>_x000D_
      <h2>container with paddings</h2>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get the last N rows of a pandas DataFrame?

This is because of using integer indices (ix selects those by label over -3 rather than position, and this is by design: see integer indexing in pandas "gotchas"*).

*In newer versions of pandas prefer loc or iloc to remove the ambiguity of ix as position or label:

df.iloc[-3:]

see the docs.

As Wes points out, in this specific case you should just use tail!

Display current time in 12 hour format with AM/PM

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.S aa");
String formattedDate = dateFormat.format(new Date()).toString();
System.out.println(formattedDate);

Output: 11-Sep-13 12.25.15.375 PM

Export HTML page to PDF on user click using JavaScript

This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.

change it to:

$(function () {

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };
 $('#cmd').click(function () {
        var doc = new jsPDF();
        doc.fromHTML(
            $('#target').html(), 15, 15, 
            { 'width': 170, 'elementHandlers': specialElementHandlers }, 
            function(){ doc.save('sample-file.pdf'); }
        );

    });  
});

and it will work.

Composer - the requested PHP extension mbstring is missing from your system

For php 7.1

sudo apt-get install php7.1-mbstring

Cheers!

Angular 4 - Select default value in dropdown [Reactive Forms]

You can use the patch function for setting defaults with some of the values in your form group.

component.html

<form [formGroup]="countryForm">
    <select id="country" formControlName="country">
        <option *ngFor="let c of countries" [ngValue]="c">{{ c }}</option>
    </select>
</form>

component.ts

import { FormControl, FormGroup, Validators } from '@angular/forms';

export class Component implements OnInit{

    countries: string[] = ['USA', 'UK', 'Canada'];
    default: string = 'UK';

    countryForm: FormGroup;

    constructor() {

        this.countryForm.controls['country'].setValue(this.default, {onlySelf: true});
    }
}

ngOnInit() {
    this.countryForm = new FormGroup({
      'country': new FormControl(null)
    }); 

    this.countryForm.patchValue({
      'country': default
    });

  }

"Cannot open include file: 'config-win.h': No such file or directory" while installing mysql-python

The accepted answer is out of date. Some of the suggestions were already incorporated in the package, and I was still getting the error about missing config-win.h & mysqlclient.lib.

  • Install mysql-connector-c-6.0.2-win32.msi

    There's a zip file for the conenctor too but that didn't work because mysqlclient.lib is in lib directory whereas the installer expects it in lib/opt. Instead of hacking site.cfg or setup_windows.py, the msi does the job.

  • pip install mysql-python

P.S. Since I don't use MySQL anymore, my answer may be out of date as well.

Set custom attribute using JavaScript

Please use dataset

var article = document.querySelector('#electriccars'),
    data = article.dataset;

// data.columns -> "3"
// data.indexnumber -> "12314"
// data.parent -> "cars"

so in your case for setting data:

getElementById('item1').dataset.icon = "base2.gif";

How to remove all leading zeroes in a string

Similar to another suggestion, except will not obliterate actual zero:

if (ltrim($str, '0') != '') {
    $str = ltrim($str, '0');
} else {
    $str = '0';
}

Or as was suggested (as of PHP 5.3), shorthand ternary operator can be used:

$str = ltrim($str, '0') ?: '0'; 

Set the space between Elements in Row Flutter

You can use Spacers if all you want is a little bit of spacing between items in a row. The example below centers 2 Text widgets within a row with some spacing between them.

Spacer creates an adjustable, empty spacer that can be used to tune the spacing between widgets in a Flex container, like Row or Column.

In a row, if we want to put space between two widgets such that it occupies all remaining space.

    widget = Row (
    children: <Widget>[
      Spacer(flex: 20),
      Text(
        "Item #1",
      ),
      Spacer(),  // Defaults to flex: 1
      Text(
        "Item #2",
      ),
      Spacer(flex: 20),
    ]
  );

Formatting numbers (decimal places, thousands separators, etc) with CSS

Well, for any numbers in Javascript I use next one:

var a = "1222333444555666777888999";
a = a.replace(new RegExp("^(\\d{" + (a.length%3?a.length%3:0) + "})(\\d{3})", "g"), "$1 $2").replace(/(\d{3})+?/gi, "$1 ").trim();

and if you need to use any other separator as comma for example:

var sep = ",";
a = a.replace(/\s/g, sep);

or as a function:

function numberFormat(_number, _sep) {
    _number = typeof _number != "undefined" && _number > 0 ? _number : "";
    _number = _number.replace(new RegExp("^(\\d{" + (_number.length%3? _number.length%3:0) + "})(\\d{3})", "g"), "$1 $2").replace(/(\d{3})+?/gi, "$1 ").trim();
    if(typeof _sep != "undefined" && _sep != " ") {
        _number = _number.replace(/\s/g, _sep);
    }
    return _number;
}

Android: how to draw a border to a LinearLayout

Do you really need to do that programmatically?

Just considering the title: You could use a ShapeDrawable as android:background…

For example, let's define res/drawable/my_custom_background.xml as:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
  <corners
      android:radius="2dp"
      android:topRightRadius="0dp"
      android:bottomRightRadius="0dp"
      android:bottomLeftRadius="0dp" />
  <stroke
      android:width="1dp"
      android:color="@android:color/white" />
</shape>

and define android:background="@drawable/my_custom_background".

I've not tested but it should work.

Update:

I think that's better to leverage the xml shape drawable resource power if that fits your needs. With a "from scratch" project (for android-8), define res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/border"
    android:padding="10dip" >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World, SOnich"
        />
    [... more TextView ...]
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World, SOnich"
        />
</LinearLayout>

and a res/drawable/border.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
   <stroke
        android:width="5dip"
        android:color="@android:color/white" />
</shape>

Reported to work on a gingerbread device. Note that you'll need to relate android:padding of the LinearLayout to the android:width shape/stroke's value. Please, do not use @android:color/white in your final application but rather a project defined color.

You could apply android:background="@drawable/border" android:padding="10dip" to each of the LinearLayout from your provided sample.

As for your other posts related to display some circles as LinearLayout's background, I'm playing with Inset/Scale/Layer drawable resources (see Drawable Resources for further information) to get something working to display perfect circles in the background of a LinearLayout but failed at the moment…

Your problem resides clearly in the use of getBorder.set{Width,Height}(100);. Why do you do that in an onClick method?

I need further information to not miss the point: why do you do that programmatically? Do you need a dynamic behavior? Your input drawables are png or ShapeDrawable is acceptable? etc.

To be continued (maybe tomorrow and as soon as you provide more precisions on what you want to achieve)…

How to append strings using sprintf?

Using strcat(buffer,"Your new string...here"), as an option.

Error in eval(expr, envir, enclos) : object not found

Don't know why @Janos deleted his answer, but it's correct: your data frame Train doesn't have a column named pre. When you pass a formula and a data frame to a model-fitting function, the names in the formula have to refer to columns in the data frame. Your Train has columns called residual.sugar, total.sulfur, alcohol and quality. You need to change either your formula or your data frame so they're consistent with each other.

And just to clarify: Pre is an object containing a formula. That formula contains a reference to the variable pre. It's the latter that has to be consistent with the data frame.

Conflict with dependency 'com.android.support:support-annotations'. Resolved versions for app (23.1.0) and test app (23.0.1) differ

you can try to use

  androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
})

instead of

androidTestCompile 'com.android.support.test:runner:0.4.1'

androidTestCompile 'com.android.support.test:rules:0.4.1'

androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
androidTestCompile 'com.android.support.test.espresso:espresso-contrib:2.2.1'

No function matches the given name and argument types

In my particular case the function was actually missing. The error message is the same. I am using the Postgresql plugin PostGIS and I had to reinstall that for whatever reason.

Get month and year from a datetime in SQL Server 2005

cast(cast(sq.QuotaDate as date) as varchar(7))

gives "2006-04" format

Printing to the console in Google Apps Script?

The console is not available because the code is running in the cloud, not in your browser. Instead, use the Logger class provided by GAS:

Logger.log(playerArray[3])

and then view the results in the IDE under View > Logs...

Here's some documentation on logging with GAS.

Edit: 2017-07-20 Apps script now also provides Stackdriver Logging. View these logs in the script editor under View - Console Logs.

MySQL string replace

Yes, MySQL has a REPLACE() function:

mysql> SELECT REPLACE('www.mysql.com', 'w', 'Ww');
    -> 'WwWwWw.mysql.com'

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace

Note that it's easier if you make that an alias when using SELECT

SELECT REPLACE(string_column, 'search', 'replace') as url....

Why is quicksort better than mergesort?

Consider time and space complexity both. For Merge sort : Time complexity : O(nlogn) , Space complexity : O(nlogn)

For Quick sort : Time complexity : O(n^2) , Space complexity : O(n)

Now, they both win in one scenerio each. But, using a random pivot you can almost always reduce Time complexity of Quick sort to O(nlogn).

Thus, Quick sort is preferred in many applications instead of Merge sort.

How do I install a custom font on an HTML site

If you are using an external style sheet, the code could look something like this:

@font-face { font-family: Junebug; src: url('Junebug.ttf'); } 
.junebug { font-family: Junebug; font-size: 4.2em; }

And should be saved in a separate .css file (eg styles.css). If your .css file is in a location separate from the page code, the actual font file should have the same path as the .css file, NOT the .html or .php web page file. Then the web page needs something like:

<link rel="stylesheet" href="css/styles.css">

in the <head> section of your html page. In this example, the font file should be located in the css folder along with the stylesheet. After this, simply add the class="junebug" inside any tag in your html to use Junebug font in that element.

If you're putting the css in the actual web page, add the style tag in the head of the html like:

<style>
    @font-face { font-family: Junebug; src: url('Junebug.ttf'); } 
</style>

And the actual element style can either be included in the above <style> and called per element by class or id, or you can just declare the style inline with the element. By element I mean <div>, <p>, <h1> or any other element within the html that needs to use the Junebug font. With both of these options, the font file (Junebug.ttf) should be located in the same path as the html page. Of these two options, the best practice would look like:

<style>
    @font-face { font-family: Junebug; src: url('Junebug.ttf'); } 
    .junebug { font-family: Junebug; font-size: 4.2em; }
</style>

and

<h1 class="junebug">This is Junebug</h1>

And the least acceptable way would be:

<style>
    @font-face { font-family: Junebug; src: url('Junebug.ttf'); } 
</style>

and

<h1 style="font-family: Junebug;">This is Junebug</h1>

The reason it's not good to use inline styles is best practice dictates that styles should be kept all in one place so editing is practical. This is also the main reason that I recommend using the very first option of using external style sheets. I hope this helps.

How to convert list data into json in java

Using gson it is much simpler. Use following code snippet:

 // create a new Gson instance
 Gson gson = new Gson();
 // convert your list to json
 String jsonCartList = gson.toJson(cartList);
 // print your generated json
 System.out.println("jsonCartList: " + jsonCartList);

Converting back from JSON string to your Java object

 // Converts JSON string into a List of Product object
 Type type = new TypeToken<List<Product>>(){}.getType();
 List<Product> prodList = gson.fromJson(jsonCartList, type);

 // print your List<Product>
 System.out.println("prodList: " + prodList);

How to create a fixed sidebar layout with Bootstrap 4?

I'm using the J.S. to fix a sidebar menu. I've tried a lot of solutions with CSS but it's the simplest way to solve it, just add J.S. adding and removing a native BootStrap class: "position-fixed".

The J.S.:

var lateral = false;
function fixar() {

            var element, name, arr;
            element = document.getElementById("minhasidebar");

            if (lateral) {
                element.className = element.className.replace(
                        /\bposition-fixed\b/g, "");
                lateral = false;
            } else {

                name = "position-fixed";
                arr = element.className.split(" ");
                if (arr.indexOf(name) == -1) {
                    element.className += " " + name;
                }
                lateral = true;
            }

        }

The HTML:

Sidebar:

<aside>
        <nav class="sidebar ">
             <div id="minhasidebar">
                 <ul class="nav nav-pills">
                     <li class="nav-item"><a class="nav-link active" 
                     th:href="@{/hoje/inicial}"> <i class="oi oi-clipboard"></i> 
                     <span>Hoje</span>
                     </a></li>
                 </ul>
             </div>
        </nav>            
</aside>

Fit cell width to content

Simple :

    <div style='overflow-x:scroll;overflow-y:scroll;width:100%;height:100%'>

Adding sheets to end of workbook in Excel (normal method not working?)

Be sure to fully qualify your sheets with which workbook they are referencing!

 mainWB.Sheets.Add(After:=mainWB.Sheets(mainWB.Sheets.Count)).Name = new_sheet_name

Rename a table in MySQL

Right Click on View > New Query

And Type: EXEC sp_rename 'Table', 'NewName'

Then Click on Run button at the top left corner of the page.

fetch in git doesn't get all branches

The problem can be seen when checking the remote.origin.fetch setting
(The lines starting with $ are bash prompts with the commands I typed. The other lines are the resulting output)

$ git config --get remote.origin.fetch
+refs/heads/master:refs/remotes/origin/master

As you can see, in my case, the remote was set to fetch the master branch specifically and only. I fixed it as per below, including the second command to check the results.

$ git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*"
$ git config --get remote.origin.fetch
+refs/heads/*:refs/remotes/origin/*

The wildcard * of course means everything under that path.

Unfortunately I saw this comment after I had already dug through and found the answer by trial and error.

apache server reached MaxClients setting, consider raising the MaxClients setting

When you use Apache with mod_php apache is enforced in prefork mode, and not worker. As, even if php5 is known to support multi-thread, it is also known that some php5 libraries are not behaving very well in multithreaded environments (so you would have a locale call on one thread altering locale on other php threads, for example).

So, if php is not running in cgi way like with php-fpm you have mod_php inside apache and apache in prefork mode. On your tests you have simply commented the prefork settings and increased the worker settings, what you now have is default values for prefork settings and some altered values for the shared ones :

StartServers       20
MinSpareServers    5
MaxSpareServers    10
MaxClients         1024
MaxRequestsPerChild  0

This means you ask apache to start with 20 process, but you tell it that, if there is more than 10 process doing nothing it should reduce this number of children, to stay between 5 and 10 process available. The increase/decrease speed of apache is 1 per minute. So soon you will fall back to the classical situation where you have a fairly low number of free available apache processes (average 2). The average is low because usually you have something like 5 available process, but as soon as the traffic grows they're all used, so there's no process available as apache is very slow in creating new forks. This is certainly increased by the fact your PHP requests seems to be quite long, they do not finish early and the apache forks are not released soon enough to treat another request.

See on the last graphic the small amount of green before the red peak? If you could graph this on a 1 minute basis instead of 5 minutes you would see that this green amount was not big enough to take the incoming traffic without any error message.

Now you set 1024 MaxClients. I guess the cacti graph are not taken after this configuration modification, because with such modification, when no more process are available, apache would continue to fork new children, with a limit of 1024 busy children. Take something like 20MB of RAM per child (or maybe you have a big memory_limit in PHP and allows something like 64MB or 256MB and theses PHP requests are really using more RAM), maybe a DB server... your server is now slowing down because you have only 768MB of RAM. Maybe when apache is trying to initiate the first 20 children you already reach the available RAM limit.

So. a classical way of handling that is to check the amount of memory used by an apache fork (make some top commands while it is running), then find how many parallel request you can handle with this amount of RAM (that mean parallel apache children in prefork mode). Let's say it's 12, for example. Put this number in apache mpm settings this way:

<IfModule prefork.c>
  StartServers       12
  MinSpareServers    12
  MaxSpareServers    12
  MaxClients         12
  MaxRequestsPerChild  300
</IfModule>

That means you do not move the number of fork while traffic increase or decrease, because you always want to use all the RAM and be ready for traffic peaks. The 300 means you recyclate each fork after 300 requests, it's better than 0, it means you will not have potential memory leaks issues. MaxClients is set to 12 25 or 50 which is more than 12 to handle the ListenBacklog queue, which can enqueue some requests, you may take a bigger queue, but you would get some timeouts maybe (removed this strange sentende, I can't remember why I said that, if more than 12 requests are incoming the next one will be pushed in the Backlog queue, but you should set MaxClient to your targeted number of processes).

And yes, that means you cannot handle more than 12 parallel requests.

If you want to handle more requests:

  • buy some more RAM
  • try to use apache in worker mode, but remove mod_php and use php as a parallel daemon with his own pooler settings (this is called php-fpm), connect it with fastcgi. Note that you will certainly need to buy some RAM to allow a big number of parallel php-fpm process, but maybe less than with mod_php
  • Reduce the time spent in your php process. From your cacti graphs you have to potential problems: a real traffic peak around 11:25-11:30 or some php code getting very slow. Fast requests will reduce the number of parallel requests.

If your problem is really traffic peaks, solutions could be available with caches, like a proxy-cache server. If the problem is a random slowness in PHP then... it's an application problem, do you do some HTTP query to another site from PHP, for example?

And finally, as stated by @Jan Vlcinsky you could try nginx, where php will only be available as php-fpm. If you cannot buy RAM and must handle a big traffic that's definitively desserve a test.

Update: About internal dummy connections (if it's your problem, but maybe not).

Check this link and this previous answer. This is 'normal', but if you do not have a simple virtualhost theses requests are maybe hitting your main heavy application, generating slow http queries and preventing regular users to acces your apache processes. They are generated on graceful reload or children managment.

If you do not have a simple basic "It works" default Virtualhost prevent theses requests on your application by some rewrites:

  RewriteCond %{HTTP_USER_AGENT} ^.*internal\ dummy\ connection.*$ [NC]
  RewriteRule .* - [F,L]

Update:

Having only one Virtualhost does not protect you from internal dummy connections, it is worst, you are sure now that theses connections are made on your unique Virtualhost. So you should really avoid side effects on your application by using the rewrite rules.

Reading your cacti graphics, it seems your apache is not in prefork mode bug in worker mode. Run httpd -l or apache2 -l on debian, and check if you have worker.c or prefork.c. If you are in worker mode you may encounter some PHP problems in your application, but you should check the worker settings, here is an example:

<IfModule worker.c>
  StartServers           3
  MaxClients           500
  MinSpareThreads       75
  MaxSpareThreads      250 
  ThreadsPerChild       25
  MaxRequestsPerChild  300
</IfModule>

You start 3 processes, each containing 25 threads (so 3*25=75 parallel requests available by default), you allow 75 threads doing nothing, as soon as one thread is used a new process is forked, adding 25 more threads. And when you have more than 250 threads doing nothing (10 processes) some process are killed. You must adjust theses settings with your memory. Here you allow 500 parallel process (that's 20 process of 25 threads). Your usage is maybe more:

<IfModule worker.c>
  StartServers           2
  MaxClients           250
  MinSpareThreads       50
  MaxSpareThreads      150 
  ThreadsPerChild       25
  MaxRequestsPerChild  300
</IfModule>

Set up git to pull and push all branches

The simplest way is to do:

git push --all origin

This will push tags and branches.

SQLite in Android How to update a specific row

just give rowId and type of data that is going to be update in ContentValues.

public void updateStatus(String id , int status){

SQLiteDatabase db = this.getWritableDatabase();

ContentValues data = new ContentValues();

data.put("status", status);

db.update(TableName, data, "columnName" + " = "+id , null);

}

Extracting first n columns of a numpy matrix

I know this is quite an old question -

A = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

Let's say, you want to extract the first 2 rows and first 3 columns

A_NEW = A[0:2, 0:3]
A_NEW = [[1, 2, 3],
         [4, 5, 6]]

Understanding the syntax

A_NEW = A[start_index_row : stop_index_row, 
          start_index_column : stop_index_column)]

If one wants row 2 and column 2 and 3

A_NEW = A[1:2, 1:3]

Reference the numpy indexing and slicing article - Indexing & Slicing

MySQL: What's the difference between float and double?

Thought I'd add my own example that helped me see the difference using the value 1.3 when adding or multiplying with another float, decimal, and double .

1.3 float ADDED to 1.3 of different types:

|float              | double | decimal |
+-------------------+------------+-----+
|2.5999999046325684 | 2.6    | 2.60000 |

1.3 float MULTIPLIED by 1.3 of different types:

| float              | double             | decimal      |
+--------------------+--------------------+--------------+
| 1.6899998760223411 | 1.6900000000000002 | 1.6900000000 |

This is using MySQL 6.7

Query:

SELECT 
    float_1 + float_2 as 'float add',
    double_1 + double_2 as 'double add',
    decimal_1 + decimal_2 as 'decimal add',

    float_1 * float_2 as 'float multiply',
    double_1 * double_2 as 'double multiply',
    decimal_1 * decimal_2 as 'decimal multiply'
FROM numerics

Create Table and Insert Data:

CREATE TABLE `numerics` (
  `float_1` float DEFAULT NULL,
  `float_2` float DEFAULT NULL,
  `double_1` double DEFAULT NULL,
  `double_2` double DEFAULT NULL,
  `decimal_1` decimal(10,5) DEFAULT NULL,
  `decimal_2` decimal(10,5) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `_numerics` 
    (
        `float_1`,
        `float_2`,
        `double_1`,
        `double_2`,
        `decimal_1`,
        `decimal_2`
    )
VALUES
    (
        1.3,
        1.3,
        1.3,
        1.3,
        1.30000,
        1.30000
    );

What is the difference between VFAT and FAT32 file systems?

Copied from http://technet.microsoft.com/en-us/library/cc750354.aspx

What's FAT?

FAT may sound like a strange name for a file system, but it's actually an acronym for File Allocation Table. Introduced in 1981, FAT is ancient in computer terms. Because of its age, most operating systems, including Microsoft Windows NT®, Windows 98, the Macintosh OS, and some versions of UNIX, offer support for FAT.

The FAT file system limits filenames to the 8.3 naming convention, meaning that a filename can have no more than eight characters before the period and no more than three after. Filenames in a FAT file system must also begin with a letter or number, and they can't contain spaces. Filenames aren't case sensitive.

What About VFAT?

Perhaps you've also heard of a file system called VFAT. VFAT is an extension of the FAT file system and was introduced with Windows 95. VFAT maintains backward compatibility with FAT but relaxes the rules. For example, VFAT filenames can contain up to 255 characters, spaces, and multiple periods. Although VFAT preserves the case of filenames, it's not considered case sensitive.

When you create a long filename (longer than 8.3) with VFAT, the file system actually creates two different filenames. One is the actual long filename. This name is visible to Windows 95, Windows 98, and Windows NT (4.0 and later). The second filename is called an MS-DOS® alias. An MS-DOS alias is an abbreviated form of the long filename. The file system creates the MS-DOS alias by taking the first six characters of the long filename (not counting spaces), followed by the tilde [~] and a numeric trailer. For example, the filename Brien's Document.txt would have an alias of BRIEN'~1.txt.

An interesting side effect results from the way VFAT stores its long filenames. When you create a long filename with VFAT, it uses one directory entry for the MS-DOS alias and another entry for every 13 characters of the long filename. In theory, a single long filename could occupy up to 21 directory entries. The root directory has a limit of 512 files, but if you were to use the maximum length long filenames in the root directory, you could cut this limit to a mere 24 files. Therefore, you should use long filenames very sparingly in the root directory. Other directories aren't affected by this limit.

You may be wondering why we're discussing VFAT. The reason is it's becoming more common than FAT, but aside from the differences I mentioned above, VFAT has the same limitations. When you tell Windows NT to format a partition as FAT, it actually formats the partition as VFAT. The only time you'll have a true FAT partition under Windows NT 4.0 is when you use another operating system, such as MS-DOS, to format the partition.

FAT32

FAT32 is actually an extension of FAT and VFAT, first introduced with Windows 95 OEM Service Release 2 (OSR2). FAT32 greatly enhances the VFAT file system but it does have its drawbacks.

The greatest advantage to FAT32 is that it dramatically increases the amount of free hard disk space. To illustrate this point, consider that a FAT partition (also known as a FAT16 partition) allows only a certain number of clusters per partition. Therefore, as your partition size increases, the cluster size must also increase. For example, a 512-MB FAT partition has a cluster size of 8K, while a 2-GB partition has a cluster size of 32K.

This may not sound like a big deal until you consider that the FAT file system only works in single cluster increments. For example, on a 2-GB partition, a 1-byte file will occupy the entire cluster, thereby consuming 32K, or roughly 32,000 times the amount of space that the file should consume. This rule applies to every file on your hard disk, so you can see how much space can be wasted.

Converting a partition to FAT32 reduces the cluster size (and overcomes the 2-GB partition size limit). For partitions 8 GB and smaller, the cluster size is reduced to a mere 4K. As you can imagine, it's not uncommon to gain back hundreds of megabytes by converting a partition to FAT32, especially if the partition contains a lot of small files.

Note: This section of the quote/ article (1999) is out of date. Updated info quote below.

As I mentioned, FAT32 does have limitations. Unfortunately, it isn't compatible with any operating system other than Windows 98 and the OSR2 version of Windows 95. However, Windows 2000 will be able to read FAT32 partitions.

The other disadvantage is that your disk utilities and antivirus software must be FAT32-aware. Otherwise, they could interpret the new file structure as an error and try to correct it, thus destroying data in the process.

Finally, I should mention that converting to FAT32 is a one-way process. Once you've converted to FAT32, you can't convert the partition back to FAT16. Therefore, before converting to FAT32, you need to consider whether the computer will ever be used in a dual-boot environment. I should also point out that although other operating systems such as Windows NT can't directly read a FAT32 partition, they can read it across the network. Therefore, it's no problem to share information stored on a FAT32 partition with other computers on a network that run older operating systems.

Updated mentioned in comment by Doktor-J (assimilated to update out of date answer in case comment is ever lost):

I'd just like to point out that most modern operating systems (WinXP/Vista/7/8, MacOS X, most if not all Linux variants) can read FAT32, contrary to what the second-to-last paragraph suggests.

The original article was written in 1999, and being posted on a Microsoft website, probably wasn't concerned with non-Microsoft operating systems anyways.

The operating systems "excluded" by that paragraph are probably the original Windows 95, Windows NT 4.0, Windows 3.1, DOS, etc.

Writing an mp4 video using python opencv

This worked for me.

self._name = name + '.mp4'
self._cap = VideoCapture(0)
self._fourcc = VideoWriter_fourcc(*'MP4V')
self._out = VideoWriter(self._name, self._fourcc, 20.0, (640,480))

Mockito test a void method throws an exception

The parentheses are poorly placed.

You need to use:

doThrow(new Exception()).when(mockedObject).methodReturningVoid(...);
                                          ^

and NOT use:

doThrow(new Exception()).when(mockedObject.methodReturningVoid(...));
                                                                   ^

This is explained in the documentation

Gradient of n colors ranging from color 1 and color 2

Try the following:

color.gradient <- function(x, colors=c("red","yellow","green"), colsteps=100) {
  return( colorRampPalette(colors) (colsteps) [ findInterval(x, seq(min(x),max(x), length.out=colsteps)) ] )
}
x <- c((1:100)^2, (100:1)^2)
plot(x,col=color.gradient(x), pch=19,cex=2)

enter image description here

Stretch and scale a CSS image in the background - with CSS only

Using the code I mentioned...

HTML

<div id="background">
    <img src="img.jpg" class="stretch" alt="" />
</div>

CSS

#background {
    width: 100%; 
    height: 100%; 
    position: fixed; 
    left: 0px; 
    top: 0px; 
    z-index: -1; /* Ensure div tag stays behind content; -999 might work, too. */
}

.stretch {
    width:100%;
    height:100%;
}

That produces the desired effect: only the content will scroll, not the background.

The background image resizes to the browser viewport for any screen size. When the content doesn't fit the browser viewport, and the user needs to scroll the page, the background image remains fixed in the viewport while the content scrolls.

With CSS 3 it seems this would be a lot easier.

How to install OpenJDK 11 on Windows?

You can use Amazon Corretto. It is free to use multiplatform, production-ready distribution of the OpenJDK. It comes with long-term support that will include performance enhancements and security fixes. Check the installation instructions here.

You can also check Zulu from Azul.

One more thing I like to highlight here is both Amazon Corretto and Zulu are TCK Compliant. You can see the OpenJDK builds comparison here and here.

Return HTML from ASP.NET Web API

Starting with AspNetCore 2.0, it's recommended to use ContentResult instead of the Produce attribute in this case. See: https://github.com/aspnet/Mvc/issues/6657#issuecomment-322586885

This doesn't rely on serialization nor on content negotiation.

[HttpGet]
public ContentResult Index() {
    return new ContentResult {
        ContentType = "text/html",
        StatusCode = (int)HttpStatusCode.OK,
        Content = "<html><body>Hello World</body></html>"
    };
}