Programs & Examples On #Servlet dispatching

No mapping found for HTTP request with URI [/WEB-INF/pages/apiForm.jsp]

I had the same problem, Of course there was a little difference. The story was that when I was removing the below line:

<mvc:resources mapping="/resources/**" location="classpath:/resources/" />

Everything was OK but in presence of that line the same error raise.

After some trial and error I found I have to add the below line to my spring application context file:

<mvc:annotation-driven />

Hope it helps!

What is Dispatcher Servlet in Spring?

Dispatcher Controller are displayed in the figure all the incoming request is in intercepted by the dispatcher servlet that works as front controller. The dispatcher servlet gets an entry to handler mapping from the XML file and forwords the request to the Controller.

How do I call a JavaScript function on page load?

Another way to do this is by using event listeners, here how you use them:

document.addEventListener("DOMContentLoaded", function() {
  you_function(...);
});

Explanation:

DOMContentLoaded It means when the DOM Objects of the document are fully loaded and seen by JavaScript, also this could have been "click", "focus"...

function() Anonymous function, will be invoked when the event occurs.

Conversion from 12 hours time to 24 hours time in java

SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a"); 

provided by Bart Kiers answer should be replaced with somethig like

SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a",Locale.UK);

Scanf/Printf double variable C

For variable argument functions like printf and scanf, the arguments are promoted, for example, any smaller integer types are promoted to int, float is promoted to double.

scanf takes parameters of pointers, so the promotion rule takes no effect. It must use %f for float* and %lf for double*.

printf will never see a float argument, float is always promoted to double. The format specifier is %f. But C99 also says %lf is the same as %f in printf:

C99 §7.19.6.1 The fprintf function

l (ell) Specifies that a following d, i, o, u, x, or X conversion specifier applies to a long int or unsigned long int argument; that a following n conversion specifier applies to a pointer to a long int argument; that a following c conversion specifier applies to a wint_t argument; that a following s conversion specifier applies to a pointer to a wchar_t argument; or has no effect on a following a, A, e, E, f, F, g, or G conversion specifier.

Ignore 'Security Warning' running script from command line

Assume that you need to launch ps script from shared folder

copy \\\server\script.ps1 c:\tmp.ps1 /y && PowerShell.exe -ExecutionPolicy Bypass -File c:\tmp.ps1 && del /f c:\tmp.ps1

P.S. Reduce googling)

Add table row in jQuery

In my opinion the fastest and clear way is

//Try to get tbody first with jquery children. works faster!
var tbody = $('#myTable').children('tbody');

//Then if no tbody just select your table 
var table = tbody.length ? tbody : $('#myTable');

//Add row
table.append('<tr><td>hello></td></tr>');

here is demo Fiddle

Also I can recommend a small function to make more html changes

//Compose template string
String.prototype.compose = (function (){
var re = /\{{(.+?)\}}/g;
return function (o){
        return this.replace(re, function (_, k){
            return typeof o[k] != 'undefined' ? o[k] : '';
        });
    }
}());

If you use my string composer you can do this like

var tbody = $('#myTable').children('tbody');
var table = tbody.length ? tbody : $('#myTable');
var row = '<tr>'+
    '<td>{{id}}</td>'+
    '<td>{{name}}</td>'+
    '<td>{{phone}}</td>'+
'</tr>';


//Add row
table.append(row.compose({
    'id': 3,
    'name': 'Lee',
    'phone': '123 456 789'
}));

Here is demo Fiddle

Installing Pandas on Mac OSX

I would recoment using macport or fink to install pandas:

  1. Install XCode from App Store, this will install 3 compilers, clang, gcc ("apple") and gcc ("normal")
  2. Install macports (www.macports.org) or fink (www.finkproject.org)
  3. Never use your mac python again, and install all python modules trough the fink/macport and enjoy it taking care dependencies for you.

Installing pandas in macports is as simple as: sudo port install py27-pandas

you usualy install macport in /opt/local and fink in /sw, I would advice (though this may be bad advice) you to symlink your fink/mac ports python to your system python as follows such that: /usr/bin/python -> /opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7

iPhone - Get Position of UIView within entire UIWindow

In Swift:

let globalPoint = aView.superview?.convertPoint(aView.frame.origin, toView: nil)

Get custom product attributes in Woocommerce

The answer to "Any idea for getting all attributes at once?" question is just to call function with only product id:

$array=get_post_meta($product->id);

key is optional, see http://codex.wordpress.org/Function_Reference/get_post_meta

Date format in dd/MM/yyyy hh:mm:ss

This can be done as follows :

select CONVERT(VARCHAR(10), GETDATE(), 103) + ' '  + convert(VARCHAR(8), GETDATE(), 14)

Hope it helps

compilation error: identifier expected

You must to wrap your following code into a block (Either method or static).

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is your name?");
String name = in.readLine(); ;
System.out.println("Hello " + name);

Without a block you can only declare variables and more than that assign them a value in single statement.

For method main() will be best choice for now:

public class details {
    public static void main(String[] args){
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

or If you want to use static block then...

public class details {
    static {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

or if you want to build another method then..

public class details {
    public static void main(String[] args){
        myMethod();
    }
    private static void myMethod(){
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

Also worry about exception due to BufferedReader .

Android: resizing imageview in XML

for example:

<ImageView android:id="@+id/image_view"     
  android:layout_width="wrap_content"  
  android:layout_height="wrap_content"  
  android:adjustViewBounds="true"  
  android:maxWidth="42dp"  
  android:maxHeight="42dp"  
  android:scaleType="fitCenter"  
  android:layout_marginLeft="3dp"  
  android:src="@drawable/icon"  
  /> 

Add property android:scaleType="fitCenter" and android:adjustViewBounds="true".

How can I suppress column header output for a single SQL statement?

Invoke mysql with the -N (the alias for -N is --skip-column-names) option:

mysql -N ...
use testdb;
select * from names;

+------+-------+
|    1 | pete  |
|    2 | john  |
|    3 | mike  |
+------+-------+
3 rows in set (0.00 sec)

Credit to ErichBSchulz for pointing out the -N alias.

To remove the grid (the vertical and horizontal lines) around the results use -s (--silent). Columns are separated with a TAB character.

mysql -s ...
use testdb;
select * from names;

id  name
1   pete
2   john
3   mike

To output the data with no headers and no grid just use both -s and -N.

mysql -sN ...

How can I return the difference between two lists?

You can convert them to Set collections, and perform a set difference operation on them.

Like this:

Set<Date> ad = new HashSet<Date>(a);
Set<Date> bd = new HashSet<Date>(b);
ad.removeAll(bd);

Run-time error '1004' - Method 'Range' of object'_Global' failed

Your range value is incorrect. You are referencing cell "75" which does not exist. You might want to use the R1C1 notation to use numeric columns easily without needing to convert to letters.

http://www.bettersolutions.com/excel/EED883/YI416010881.htm

Range("R" & DataImportRow & "C" & DataImportColumn).Offset(0, 2).Value = iFirstCustomerSales

This should fix your problem.

The zip() function in Python 3

Unlike in Python 2, the zip function in Python 3 returns an iterator. Iterators can only be exhausted (by something like making a list out of them) once. The purpose of this is to save memory by only generating the elements of the iterator as you need them, rather than putting it all into memory at once. If you want to reuse your zipped object, just create a list out of it as you do in your second example, and then duplicate the list by something like

 test2 = list(zip(lis1,lis2))
 zipped_list = test2[:]
 zipped_list_2 = list(test2)

IIS - 401.3 - Unauthorized

I have struggled on this same issue for several days. It can be solved by modifying the security user access properties of the file system folder on which your site is mapped. But IIS_IUSRS is not the only account you must authorize.

  • In IIS management console, in the Authentication part of the configuration of your site, modify the "Anonymous authentication" line and check the account set as "Specific user" (mine is IUSR).
  • Give read and execution permission on the folder of your site to the account listed as the specific user.

OR

  • In IIS management console, in the Authentication part of the configuration of your site, modify the "Anonymous authentication" line by selecting "Identity of the application pool" instead of "Specific user".

Oracle - how to remove white spaces?

Run below query replacing TABLE_NAME & COLUMN_NAME with your actual table & column names:

UPDATE TABLE_NAME SET COLUMN_NAME=TRIM(' ' from COLUMN_NAME);

How can I initialize base class member variables in derived class constructor?

If you don't specify visibility for a class member, it defaults to "private". You should make your members private or protected if you want to access them in a subclass.

Session 'app': Error Launching activity

I did all suggestions above, but they didn't work! I rebuilt the project, uninstalled the app from my real device, unplugged USB, then I run Android Studio and run the app on my real device and the issue was gone.

Hope this helps!

Removing All Items From A ComboBox?

The simplest way:

Combobox1.RowSource = ""  'Clear the list
Combobox1.Clear           'Clear the selected text

How to return HTTP 500 from ASP.NET Core RC2 Web Api?

return StatusCode((int)HttpStatusCode.InternalServerError, e);

Should be used in non-ASP.NET contexts (see other answers for ASP.NET Core).

HttpStatusCode is an enumeration in System.Net.

CodeIgniter: Unable to connect to your database server using the provided settings Error Message

Extending @Valeh Hajiyev great and clear answer for mysqli driver tests:

Debug your database connection using this script at the end of ./config/database.php:

/* Your db config here */ 
$db['default'] = array(
  // ...
  'dbdriver'     => 'mysqli',
  // ...
);

/* Connection test: */

echo '<pre>';
print_r($db['default']);
echo '</pre>';

echo 'Connecting to database: ' .$db['default']['database'];

$mysqli_connection = new MySQLi($db['default']['hostname'],
                                $db['default']['username'],
                                $db['default']['password'], 
                                $db['default']['database']);

if ($mysqli_connection->connect_error) {
   echo "Not connected, error: " . $mysqli_connection->connect_error;
}
else {
   echo "Connected.";
}
die( 'file: ' .__FILE__ . ' Line: ' .__LINE__);

How to get the file ID so I can perform a download of a file from Google Drive API on Android?

One way is to associating unique properties with your file while creation.

properties = "{ \
    key='somekey' and \
    value='somevalue'
}"

then create a query.

query = "title = " + "\'" + title + "\'" + \
        AND + "mimeType = " + "\'" + mimeType + "\'" + \
        AND + "trashed = false" + \
        AND + "properties has " + properties

All the file properties(title, etc) already known to you can go here + properties.

HTTP response code for POST when resource already exists

According to RFC 7231, a 303 See Other MAY be used If the result of processing a POST would be equivalent to a representation of an existing resource.

Restful API service

Also when I hit the post(Config.getURL("login"), values) the app seems to pause for a while (seems weird - thought the idea behind a service was that it runs on a different thread!)

In this case its better to use asynctask, which runs on a different thread and return result back to the ui thread on completion.

Optional args in MATLAB functions

A good way of going about this is not to use nargin, but to check whether the variables have been set using exist('opt', 'var').

Example:

function [a] = train(x, y, opt)
    if (~exist('opt', 'var'))
        opt = true;
    end
end

See this answer for pros of doing it this way: How to check whether an argument is supplied in function call?

Position of a string within a string using Linux shell script?

You can use grep to get the byte-offset of the matching part of a string:

echo $str | grep -b -o str

As per your example:

[user@host ~]$ echo "The cat sat on the mat" | grep -b -o cat
4:cat

you can pipe that to awk if you just want the first part

echo $str | grep -b -o str | awk 'BEGIN {FS=":"}{print $1}'

Convert INT to DATETIME (SQL)

you need to convert to char first because converting to int adds those days to 1900-01-01

select CONVERT (datetime,convert(char(8),rnwl_efctv_dt ))

here are some examples

select CONVERT (datetime,5)

1900-01-06 00:00:00.000

select CONVERT (datetime,20100101)

blows up, because you can't add 20100101 days to 1900-01-01..you go above the limit

convert to char first

declare @i int
select @i = 20100101
select CONVERT (datetime,convert(char(8),@i))

Initializing IEnumerable<string> In C#

You can create a static method that will return desired IEnumerable like this :

public static IEnumerable<T> CreateEnumerable<T>(params T[] values) =>
    values;
//And then use it
IEnumerable<string> myStrings = CreateEnumerable("first item", "second item");//etc..

Alternatively just do :

IEnumerable<string> myStrings = new []{ "first item", "second item"};

Serializing/deserializing with memory stream

BinaryFormatter may produce invalid output in some specific cases. For example it will omit unpaired surrogate characters. It may also have problems with values of interface types. Read this documentation page including community content.

If you find your error to be persistent you may want to consider using XML serializer like DataContractSerializer or XmlSerializer.

Given the lat/long coordinates, how can we find out the city/country?

An Open Source alternative is Nominatim from Open Street Map. All you have to do is set the variables in an URL and it returns the city/country of that location. Please check the following link for official documentation: Nominatim

How do I apply a style to all children of an element

Instead of the * selector you can use the :not(selector) with the > selector and set something that definitely wont be a child.

Edit: I thought it would be faster but it turns out I was wrong. Disregard.

Example:

.container > :not(marquee){
        color:red;
    }


<div class="container">
    <p></p>
    <span></span>
<div>

"cannot resolve symbol R" in Android Studio

I had the same problem, and it happens when I create a new project.

What I do is:

  • check for SDK updates
  • then android studio updates,
  • then reopen the project
  • open the andoridmanifest.xml
  • erase a space between a "_>" in the android:label and save.

That works for me.

MySQL add days to a date

Assuming your field is a date type (or similar):

SELECT DATE_ADD(`your_field_name`, INTERVAL 2 DAY) 
FROM `table_name`;

With the example you've provided it could look like this:

UPDATE classes 
SET `date` = DATE_ADD(`date` , INTERVAL 2 DAY)
WHERE `id` = 161;

This approach works with datetime , too.

How can I call a shell command in my Perl script?

Examples

  1. `ls -l`;
  2. system("ls -l");
  3. exec("ls -l");

MySQL show current connection info

You can use the status command in MySQL client.

mysql> status;
--------------
mysql  Ver 14.14 Distrib 5.5.8, for Win32 (x86)

Connection id:          1
Current database:       test
Current user:           ODBC@localhost
SSL:                    Not in use
Using delimiter:        ;
Server version:         5.5.8 MySQL Community Server (GPL)
Protocol version:       10
Connection:             localhost via TCP/IP
Server characterset:    latin1
Db     characterset:    latin1
Client characterset:    gbk
Conn.  characterset:    gbk
TCP port:               3306
Uptime:                 7 min 16 sec

Threads: 1  Questions: 21  Slow queries: 0  Opens: 33  Flush tables: 1  Open tables: 26  Queries per second avg: 0.48
--------------

mysql>

How can I add a class attribute to an HTML element generated by MVC's HTML Helpers?

Current best practice in CSS development is to create more general selectors with modifiers that can be applied as widely as possible throughout the web site. I would try to avoid defining separate styles for individual page elements.

If the purpose of the CSS class on the <form/> element is to control the style of elements within the form, you could add the class attribute the existing <fieldset/> element which encapsulates any form by default in web pages generated by ASP.NET MVC. A CSS class on the form is rarely necessary.

Explanation of polkitd Unregistered Authentication Agent

I found this problem too. Because centos service depend on multi-user.target for none desktop Cenots 7.2. so I delete multi-user.target from my .service file. It had missed.

Center a popup window on screen?

My version with ES6 JavaScript.
Works well on Chrome and Chromium with dual screen setup.

function openCenteredWindow({url, width, height}) {
    const pos = {
        x: (screen.width / 2) - (width / 2),
        y: (screen.height/2) - (height / 2)
    };

    const features = `width=${width} height=${height} left=${pos.x} top=${pos.y}`;

    return window.open(url, '_blank', features);
}

Example

openCenteredWindow({
    url: 'https://stackoverflow.com/', 
    width: 500, 
    height: 600
}).focus();

How to generate entire DDL of an Oracle schema (scriptable)?

You can spool the schema out to a file via SQL*Plus and dbms_metadata package. Then replace the schema name with another one via sed. This works for Oracle 10 and higher.

sqlplus<<EOF
set long 100000
set head off
set echo off
set pagesize 0
set verify off
set feedback off
spool schema.out

select dbms_metadata.get_ddl(object_type, object_name, owner)
from
(
    --Convert DBA_OBJECTS.OBJECT_TYPE to DBMS_METADATA object type:
    select
        owner,
        --Java object names may need to be converted with DBMS_JAVA.LONGNAME.
        --That code is not included since many database don't have Java installed.
        object_name,
        decode(object_type,
            'DATABASE LINK',      'DB_LINK',
            'JOB',                'PROCOBJ',
            'RULE SET',           'PROCOBJ',
            'RULE',               'PROCOBJ',
            'EVALUATION CONTEXT', 'PROCOBJ',
            'CREDENTIAL',         'PROCOBJ',
            'CHAIN',              'PROCOBJ',
            'PROGRAM',            'PROCOBJ',
            'PACKAGE',            'PACKAGE_SPEC',
            'PACKAGE BODY',       'PACKAGE_BODY',
            'TYPE',               'TYPE_SPEC',
            'TYPE BODY',          'TYPE_BODY',
            'MATERIALIZED VIEW',  'MATERIALIZED_VIEW',
            'QUEUE',              'AQ_QUEUE',
            'JAVA CLASS',         'JAVA_CLASS',
            'JAVA TYPE',          'JAVA_TYPE',
            'JAVA SOURCE',        'JAVA_SOURCE',
            'JAVA RESOURCE',      'JAVA_RESOURCE',
            'XML SCHEMA',         'XMLSCHEMA',
            object_type
        ) object_type
    from dba_objects 
    where owner in ('OWNER1')
        --These objects are included with other object types.
        and object_type not in ('INDEX PARTITION','INDEX SUBPARTITION',
           'LOB','LOB PARTITION','TABLE PARTITION','TABLE SUBPARTITION')
        --Ignore system-generated types that support collection processing.
        and not (object_type = 'TYPE' and object_name like 'SYS_PLSQL_%')
        --Exclude nested tables, their DDL is part of their parent table.
        and (owner, object_name) not in (select owner, table_name from dba_nested_tables)
        --Exclude overflow segments, their DDL is part of their parent table.
        and (owner, object_name) not in (select owner, table_name from dba_tables where iot_type = 'IOT_OVERFLOW')
)
order by owner, object_type, object_name;

spool off
quit
EOF

cat schema.out|sed 's/OWNER1/MYOWNER/g'>schema.out.change.sql

Put everything in a script and run it via cron (scheduler). Exporting objects can be tricky when advanced features are used. Don't be surprised if you need to add some more exceptions to the above code.

How can I add a variable to console.log?

You can use the backslash to include both the story and the players name in one line.

var name=prompt("what is your name?"); console.log("story"\name\"story");

Why can a function modify some arguments as perceived by the caller, but not others?

Some answers contain the word "copy" in a context of a function call. I find it confusing.

Python doesn't copy objects you pass during a function call ever.

Function parameters are names. When you call a function Python binds these parameters to whatever objects you pass (via names in a caller scope).

Objects can be mutable (like lists) or immutable (like integers, strings in Python). Mutable object you can change. You can't change a name, you just can bind it to another object.

Your example is not about scopes or namespaces, it is about naming and binding and mutability of an object in Python.

def f(n, x): # these `n`, `x` have nothing to do with `n` and `x` from main()
    n = 2    # put `n` label on `2` balloon
    x.append(4) # call `append` method of whatever object `x` is referring to.
    print('In f():', n, x)
    x = []   # put `x` label on `[]` ballon
    # x = [] has no effect on the original list that is passed into the function

Here are nice pictures on the difference between variables in other languages and names in Python.

CSS Box Shadow Bottom Only

You can use two elements, one inside the other, and give the outer one overflow: hidden and a width equal to the inner element together with a bottom padding so that the shadow on all the other sides are "cut off"

#outer {
    width: 100px;
    overflow: hidden;
    padding-bottom: 10px;
}

#outer > div {
    width: 100px;
    height: 100px;
    background: orange;

    -moz-box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
    -webkit-box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
    box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
}

Alternatively, float the outer element to cause it to shrink to the size of the inner element. See: http://jsfiddle.net/QJPd5/1/

convert streamed buffers to utf8-string

var fs = require("fs");

function readFileLineByLine(filename, processline) {
    var stream = fs.createReadStream(filename);
    var s = "";
    stream.on("data", function(data) {
        s += data.toString('utf8');
        var lines = s.split("\n");
        for (var i = 0; i < lines.length - 1; i++)
            processline(lines[i]);
        s = lines[lines.length - 1];
    });

    stream.on("end",function() {
        var lines = s.split("\n");
        for (var i = 0; i < lines.length; i++)
            processline(lines[i]);
    });
}

var linenumber = 0;
readFileLineByLine(filename, function(line) {
    console.log(++linenumber + " -- " + line);
});

Disabled form fields not submitting data

We can also use the readonly only with below attributes -

readonly onclick='return false;'

This is because if we will only use the readonly then radio buttons will be editable. To avoid this situation we can use readonly with above combination. It will restrict the editing and element's values will also passed during form submission.

What is the difference between Left, Right, Outer and Inner Joins?

LEFT JOIN and RIGHT JOIN are types of OUTER JOINs.

INNER JOIN is the default -- rows from both tables must match the join condition.

How to resolve "Input string was not in a correct format." error?

If using TextBox2.Text as the source for a numeric value, it must first be checked to see if a value exists, and then converted to integer.

If the text box is blank when Convert.ToInt32 is called, you will receive the System.FormatException. Suggest trying:

protected void SetImageWidth()
{
   try{
      Image1.Width = Convert.ToInt32(TextBox1.Text);
   }
   catch(System.FormatException)
   {
      Image1.Width = 100; // or other default value as appropriate in context.
   }
}

How can I set the default value for an HTML <select> element?

I used this php function to generate the options, and insert it into my HTML

<?php
  # code to output a set of options for a numeric drop down list
  # parameters: (start, end, step, format, default)
  function numericoptions($start, $end, $step, $formatstring, $default)
  {
    $retstring = "";
    for($i = $start; $i <= $end; $i = $i + $step)
    {
      $retstring = $retstring . '<OPTION ';
      $retstring = $retstring . 'value="' . sprintf($formatstring,$i) . '"';
      if($default == $i)
      {
        $retstring = $retstring . ' selected="selected"';
      }
      $retstring = $retstring . '>' . sprintf($formatstring,$i) . '</OPTION> ';
    }

  return $retstring;
  }

?>

And then in my webpage code I use it as below;

<select id="endmin" name="endmin">
  <?php echo numericoptions(0,55,5,'%02d',$endmin); ?>
</select>

If $endmin is created from a _POST variable every time the page is loaded (and this code is inside a form which posts) then the previously selected value is selected by default.

Using psql how do I list extensions installed in a database?

This SQL query gives output similar to \dx:

SELECT e.extname AS "Name", e.extversion AS "Version", n.nspname AS "Schema", c.description AS "Description" 
FROM pg_catalog.pg_extension e 
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace 
LEFT JOIN pg_catalog.pg_description c ON c.objoid = e.oid AND c.classoid = 'pg_catalog.pg_extension'::pg_catalog.regclass 
ORDER BY 1;

Thanks to https://blog.dbi-services.com/listing-the-extensions-available-in-postgresql/

How to find the php.ini file used by the command line?

Do

find / -type f -name "php.ini" 

This will output all files named php.ini.

Find out which one you're using, usually apache2/php.ini

How to resize datagridview control when form resizes

The 'Anchor' property exists for any container: form, panel, group box, etc.

You can choose 1 side, left for example, or up to all four sides.

Anchor means the distance between the side(s) chosen and the edge of the container will stay the same, even upon resizing.

E.g., A datagridview, dgv1, is in the middle of Form1. Your 'Anchor' the left and top sides of dgv1. When the app is run and resizing occurs, either from different screen resolutions or changing the form size, the top and left sides of dgv1 will change accordingly to maintain their distance from the edge of From1. The bottom and right sides will not.

Class constants in python

class Animal:
    HUGE = "Huge"
    BIG = "Big"

class Horse:
    def printSize(self):
        print(Animal.HUGE)

How to resolve Unneccessary Stubbing exception

Looking at a part of your stack trace it looks like you are stubbing the dao.doSearch() elsewhere. More like repeatedly creating the stubs of the same method.

Following stubbings are unnecessary (click to navigate to relevant line of code):
  1. -> at service.Test.testDoSearch(Test.java:72)
Please remove unnecessary stubbings or use 'silent' option. More info: javadoc for UnnecessaryStubbingException class.

Consider the below Test Class for example:

@RunWith(MockitoJUnitRunner.class)
public class SomeTest {
    @Mock
    Service1 svc1Mock1;

    @Mock
    Service2 svc2Mock2;

    @InjectMock
    TestClass class;

    //Assume you have many dependencies and you want to set up all the stubs 
    //in one place assuming that all your tests need these stubs.

    //I know that any initialization code for the test can/should be in a 
    //@Before method. Lets assume there is another method just to create 
    //your stubs.

    public void setUpRequiredStubs() {
        when(svc1Mock1.someMethod(any(), any())).thenReturn(something));
        when(svc2Mock2.someOtherMethod(any())).thenReturn(somethingElse);
    }

    @Test
    public void methodUnderTest_StateUnderTest_ExpectedBehavior() {
        // You forget that you defined the stub for svcMock1.someMethod or 
        //thought you could redefine it. Well you cannot. That's going to be 
        //a problem and would throw your UnnecessaryStubbingException.
       when(svc1Mock1.someMethod(any(),any())).thenReturn(anyThing);//ERROR!
       setUpRequiredStubs();
    }
}

I would rather considering refactoring your tests to stub where necessary.

sklearn: Found arrays with inconsistent numbers of samples when calling LinearRegression.fit()

Seen on the Udacity deep learning foundation course:

df = pd.read_csv('my.csv')
...
regr = LinearRegression()
regr.fit(df[['column x']], df[['column y']])

@AspectJ pointcut for all methods of a class with specific annotation

Using annotations, as described in the question.

Annotation: @Monitor

Annotation on class, app/PagesController.java:

package app;
@Controller
@Monitor
public class PagesController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public @ResponseBody String home() {
        return "w00t!";
    }
}

Annotation on method, app/PagesController.java:

package app;
@Controller
public class PagesController {
    @Monitor
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public @ResponseBody String home() {
        return "w00t!";
    }
}

Custom annotation, app/Monitor.java:

package app;
@Component
@Target(value = {ElementType.METHOD, ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Monitor {
}

Aspect for annotation, app/MonitorAspect.java:

package app;
@Component
@Aspect
public class MonitorAspect {
    @Before(value = "@within(app.Monitor) || @annotation(app.Monitor)")
    public void before(JoinPoint joinPoint) throws Throwable {
        LogFactory.getLog(MonitorAspect.class).info("monitor.before, class: " + joinPoint.getSignature().getDeclaringType().getSimpleName() + ", method: " + joinPoint.getSignature().getName());
    }

    @After(value = "@within(app.Monitor) || @annotation(app.Monitor)")
    public void after(JoinPoint joinPoint) throws Throwable {
        LogFactory.getLog(MonitorAspect.class).info("monitor.after, class: " + joinPoint.getSignature().getDeclaringType().getSimpleName() + ", method: " + joinPoint.getSignature().getName());
    }
}

Enable AspectJ, servlet-context.xml:

<aop:aspectj-autoproxy />

Include AspectJ libraries, pom.xml:

<artifactId>spring-aop</artifactId>
<artifactId>aspectjrt</artifactId>
<artifactId>aspectjweaver</artifactId>
<artifactId>cglib</artifactId>

Applying Comic Sans Ms font style

The font may exist with different names, and not at all on some systems, so you need to use different variations and fallback to get the closest possible look on all systems:

font-family: "Comic Sans MS", "Comic Sans", cursive;

Be careful what you use this font for, though. Many consider it as ugly and overused, so it should not be use for something that should look professional.

SHOW PROCESSLIST in MySQL command: sleep

"Sleep" state connections are most often created by code that maintains persistent connections to the database.

This could include either connection pools created by application frameworks, or client-side database administration tools.

As mentioned above in the comments, there is really no reason to worry about these connections... unless of course you have no idea where the connection is coming from.

(CAVEAT: If you had a long list of these kinds of connections, there might be a danger of running out of simultaneous connections.)

Concat scripts in order with Gulp

if you would like to order third party libraries dependencies, try wiredep. This package basically checks each package dependency in bower.json then wire them up for you.

How to make full screen background in a web page

Make a div 100% wide and 100% high. Then set a background image.

How do I query between two dates using MySQL?

Your query should have date as

select * from table between `lowerdate` and `upperdate`

try

SELECT * FROM `objects` 
WHERE  (date_field BETWEEN '2010-01-30 14:15:55' AND '2010-09-29 10:15:55')

Why I get 411 Length required error?

When you make a POST HttpWebRequest, you must specify the length of the data you are sending, something like:

string data = "something you need to send"
byte[] postBytes = Encoding.ASCII.GetBytes(data);
request.ContentLength = postBytes.Length;

if you are not sending any data, just set it to 0, that means you just have to add to your code this line:

request.ContentLength = 0;

Usually, if you are not sending any data, chosing the GET method instead is wiser, as you can see in the HTTP RFC

Filter element based on .data() key/value

your filter would work, but you need to return true on matching objects in the function passed to the filter for it to grab them.

var $previous = $('.navlink').filter(function() { 
  return $(this).data("selected") == true 
});

.NET / C# - Convert char[] to string

String mystring = new String(mychararray);

__init__ and arguments in Python

Every method needs to accept one argument: The instance itself (or the class if it is a static method).

Read more about classes in Python.

Why do I need an IoC container as opposed to straightforward DI code?

You don't need an IoC container.

But if you're rigorously following a DI pattern, you'll find that having one will remove a ton of redundant, boring code.

That's often the best time to use a library/framework, anyway - when you understand what it's doing and could do it without the library.

Pass a simple string from controller to a view MVC3

Just define your action method like this

public string ThemePath()

and simply return the string itself.

VS 2012: Scroll Solution Explorer to current file

I've found the Sync with Active Document button in the solution explorer to be the the most effective (this may be a vs2013 feature!)

enter image description here

How to loop through a JSON object with typescript (Angular2)

ECMAScript 6 introduced the let statement. You can use it in a for statement.

var ids:string = [];

for(let result of this.results){
   ids.push(result.Id);
}

How to catch integer(0)?

If it's specifically zero length integers, then you want something like

is.integer0 <- function(x)
{
  is.integer(x) && length(x) == 0L
}

Check it with:

is.integer0(integer(0)) #TRUE
is.integer0(0L)         #FALSE
is.integer0(numeric(0)) #FALSE

You can also use assertive for this.

library(assertive)
x <- integer(0)
assert_is_integer(x)
assert_is_empty(x)
x <- 0L
assert_is_integer(x)
assert_is_empty(x)
## Error: is_empty : x has length 1, not 0.
x <- numeric(0)
assert_is_integer(x)
assert_is_empty(x)
## Error: is_integer : x is not of class 'integer'; it has class 'numeric'.

What are XAND and XOR

This is what you are looking for: https://en.wikipedia.org/wiki/XNOR_gate

Here is the logic table:

A B   XOR XNOR
0 0   0   1 
0 1   1   0
1 0   1   0
1 1   0   1

XNOR sometimes is called XAND.

Delete multiple objects in django

You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model

Post.objects.all().delete()

and to delete any Post with a future publication date

Post.objects.filter(pub_date__gt=datetime.now()).delete()

You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.

EDIT:

Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForms and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.

Keylistener in Javascript

A bit more readable comparing is done by casting event.key to upper case (I used onkeyup - needed the event to fire once upon each key tap):

window.onkeyup = function(event) {
    let key = event.key.toUpperCase();
    if ( key == 'W' ) {
        // 'W' key is pressed
    } else if ( key == 'D' ) {
        // 'D' key is pressed
    }
}

Each key has it's own code, get it out by outputting value of "key" variable (eg for arrow up key it will be 'ARROWUP' - (casted to uppercase))

How to set data attributes in HTML elements

Please take note that jQuery .data() is not updated when you change html5 data- attributes with javascript.

If you use jQuery .data() to set data- attributes in HTML elements you better use jQuery .data() to read them. Otherwise there can be inconsistencies if you update the attributes dynamically. For example, see setAttribute(), dataset(), attr() below. Change the value, push the button several times and see the console.

_x000D_
_x000D_
$("#button").on("click", function() {_x000D_
  var field = document.querySelector("#textfield")_x000D_
_x000D_
  switch ($("#method").val()) {_x000D_
    case "setAttribute":_x000D_
      field.setAttribute("data-customval", field.value)_x000D_
      break;_x000D_
    case "dataset":_x000D_
      field.dataset.customval = field.value_x000D_
      break;_x000D_
    case "jQuerydata":_x000D_
      $(field).data("customval", field.value)_x000D_
      break;_x000D_
    case "jQueryattr":_x000D_
      $(field).attr("data-customval", field.value)_x000D_
      break;_x000D_
  }_x000D_
_x000D_
  objValues = {}_x000D_
  objValues['$(field).data("customval")'] = $(field).data("customval")_x000D_
  objValues['$(field).attr("data-customval")'] = $(field).attr("data-customval")_x000D_
  objValues['field.getAttribute("data-customval")'] = field.getAttribute("data-customval")_x000D_
  objValues['field.dataset.customval'] = field.dataset.customval_x000D_
_x000D_
  console.table([objValues])_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<h1>Example</h1>_x000D_
<form>_x000D_
  <input id="textfield" type="text" data-customval="initial">_x000D_
  <br/>_x000D_
  <input type="button" value="Set and show in console.table (F12)" id="button">_x000D_
  <br/>_x000D_
  <select id="method">_x000D_
    <option value="setAttribute">setAttribute</option>_x000D_
    <option value="dataset">dataset</option>_x000D_
    <option value="jQuerydata">jQuery data</option>_x000D_
    <option value="jQueryattr">jQuery attr</option>_x000D_
  </select>_x000D_
  <div id="results"></div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

push() a two-dimensional array

var r = 3; //start from rows 3
var c = 5; //start from col 5

var rows = 8;

var cols = 7;


for (var i = 0; i < rows; i++)

{

 for (var j = 0; j < cols; j++)

 {
    if(j <= c && i <= r) {
      myArray[i][j] = 1;
    } else {
      myArray[i][j] = 0;
    }
}

}

Using :before and :after CSS selector to insert Html

content doesn't support HTML, only text. You should probably use javascript, jQuery or something like that.

Another problem with your code is " inside a " block. You should mix ' and " (class='headingDetail').

If content did support HTML you could end up in an infinite loop where content is added inside content.

How to remove an element from a list by index

Or if multiple indexes should be removed:

print([v for i,v in enumerate(your_list) if i not in list_of_unwanted_indexes])

Of course then could also do:

print([v for i,v in enumerate(your_list) if i != unwanted_index])

How to count TRUE values in a logical vector

which is good alternative, especially when you operate on matrices (check ?which and notice the arr.ind argument). But I suggest that you stick with sum, because of na.rm argument that can handle NA's in logical vector. For instance:

# create dummy variable
set.seed(100)
x <- round(runif(100, 0, 1))
x <- x == 1
# create NA's
x[seq(1, length(x), 7)] <- NA

If you type in sum(x) you'll get NA as a result, but if you pass na.rm = TRUE in sum function, you'll get the result that you want.

> sum(x)
[1] NA
> sum(x, na.rm=TRUE)
[1] 43

Is your question strictly theoretical, or you have some practical problem concerning logical vectors?

Should I add the Visual Studio .suo and .user files to source control?

You don't need to add these -- they contain per-user settings, and other developers won't want your copy.

how to specify new environment location for conda create

like Paul said, use

conda create --prefix=/users/.../yourEnvName python=x.x

if you are located in the folder in which you want to create your virtual environment, just omit the path and use

conda create --prefix=yourEnvName python=x.x

conda only keep track of the environments included in the folder envs inside the anaconda folder. The next time you will need to activate your new env, move to the folder where you created it and activate it with

source activate yourEnvName

How to recover MySQL database from .myd, .myi, .frm files

I found a solution for converting the files to a .sql file (you can then import the .sql file to a server and recover the database), without needing to access the /var directory, therefore you do not need to be a server admin to do this either.

It does require XAMPP or MAMP installed on your computer.

  • After you have installed XAMPP, navigate to the install directory (Usually C:\XAMPP), and the the sub-directory mysql\data. The full path should be C:\XAMPP\mysql\data
  • Inside you will see folders of any other databases you have created. Copy & Paste the folder full of .myd, .myi and .frm files into there. The path to that folder should be

    C:\XAMPP\mysql\data\foldername\.mydfiles

  • Then visit localhost/phpmyadmin in a browser. Select the database you have just pasted into the mysql\data folder, and click on Export in the navigation bar. Chooses the export it as a .sql file. It will then pop up asking where the save the file

And that is it! You (should) now have a .sql file containing the database that was originally .myd, .myi and .frm files. You can then import it to another server through phpMyAdmin by creating a new database and pressing 'Import' in the navigation bar, then following the steps to import it

Get value of a merged cell of an excel from its cell address in vba

Even if it is really discouraged to use merge cells in Excel (use Center Across Selection for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).

Hence, you can get the value of merged cells in range B4:B11 in several ways:

  • Range("B4").Value
  • Range("B4:B11").Cells(1).Value
  • Range("B4:B11").Cells(1,1).Value

You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty.

Also note that Range("B4:B11").Value won't work (raises an execution error number 13 if you try to Debug.Print it) because it returns an array.

ConfigurationManager.AppSettings - How to modify and save?

as the base question is about win forms here is the solution : ( I just changed the code by user1032413 to rflect windowsForms settings ) if it's a new key :

Configuration config = configurationManager.OpenExeConfiguration(Application.ExecutablePath); 
config.AppSettings.Settings.Add("Key","Value");
config.Save(ConfigurationSaveMode.Modified);

if the key already exists :

Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath); 
config.AppSettings.Settings["Key"].Value="Value";
config.Save(ConfigurationSaveMode.Modified);

C# equivalent of C++ map<string,double>

This code is all you need:

   static void Main(string[] args) {
        String xml = @"
            <transactions>
                <transaction name=""Fred"" amount=""5,20"" />
                <transaction name=""John"" amount=""10,00"" />
                <transaction name=""Fred"" amount=""3,00"" />
            </transactions>";

        XDocument xmlDocument = XDocument.Parse(xml);

        var query = from x in xmlDocument.Descendants("transaction")
                    group x by x.Attribute("name").Value into g
                    select new { Name = g.Key, Amount = g.Sum(t => Decimal.Parse(t.Attribute("amount").Value)) };

        foreach (var item in query) {
            Console.WriteLine("Name: {0}; Amount: {1:C};", item.Name, item.Amount);
        }
    }

And the content is:

Name: Fred; Amount: R$ 8,20;
Name: John; Amount: R$ 10,00;

That is the way of doing this in C# - in a declarative way!

I hope this helps,

Ricardo Lacerda Castelo Branco

Use a normal link to submit a form

Two ways. Either create a button and style it so it looks like a link with css, or create a link and use onclick="this.closest('form').submit();return false;".

How do I see which checkbox is checked?

I love short hands so:

$isChecked = isset($_POST['myCheckbox']) ? "yes" : "no";

When would you use the different git merge strategies?

Actually the only two strategies you would want to choose are ours if you want to abandon changes brought by branch, but keep the branch in history, and subtree if you are merging independent project into subdirectory of superproject (like 'git-gui' in 'git' repository).

octopus merge is used automatically when merging more than two branches. resolve is here mainly for historical reasons, and for when you are hit by recursive merge strategy corner cases.

How to semantically add heading to a list

According to w3.org (note that this link is in the long-expired draft HTML 3.0 spec):

An unordered list typically is a bulleted list of items. HTML 3.0 gives you the ability to customise the bullets, to do without bullets and to wrap list items horizontally or vertically for multicolumn lists.

The opening list tag must be <UL>. It is followed by an optional list header (<LH>caption</LH>) and then by the first list item (<LI>). For example:

<UL>
  <LH>Table Fruit</LH>
  <LI>apples
  <LI>oranges
  <LI>bananas
</UL>

which could be rendered as:

Table Fruit

  • apples
  • oranges
  • bananas

Note: Some legacy documents may include headers or plain text before the first LI element. Implementors of HTML 3.0 user agents are advised to cater for this possibility in order to handle badly formed legacy documents.

Get checkbox values using checkbox name using jquery

You should include the brackets as well . . .

<input type="checkbox" name="bla[]" value="1" />

therefore referencing it should be as be name='bla[]'

$(document).ready( function () { 

   $("input[name='bla[]']").each( function () {
       alert( $(this).val() );
   });

});

What and When to use Tuple?

The difference between a tuple and a class is that a tuple has no property names. This is almost never a good thing, and I would only use a tuple when the arguments are fairly meaningless like in an abstract math formula Eg. abstract calculus over 5,6,7 dimensions might take a tuple for the coordinates.

Writing a Python list of lists to a csv file

If you don't want to import csv module for that, you can write a list of lists to a csv file using only Python built-ins

with open("output.csv", "w") as f:
    for row in a:
        f.write("%s\n" % ','.join(str(col) for col in row))

What causes this error? "Runtime error 380: Invalid property value"

Old thread, but here is an answer.

Problematic fonts with voyager

ie. if you install some corel suite, drop some language options away. We dig through this with process monitor and found the reason, with us it was these two font files.

DFKai71.ttf dfmw5.ttf

We had same problem and it was fixed by removing these two font files from windows\fonts folder.

Why do I keep getting Delete 'cr' [prettier/prettier]?

All the answers above are correct, but when I use windows and disable the Prettier ESLint extension rvest.vs-code-prettier-eslint the issue will be fixed.

How can I debug my JavaScript code?

I use WebKit's developer menu/console (Safari 4). It is almost identical to Firebug.

console.log() is the new black -- far better than alert().

How to use a FolderBrowserDialog from a WPF application

The advantage of passing an owner handle is that the FolderBrowserDialog will not be modal to that window. This prevents the user from interacting with your main application window while the dialog is active.

How can I use grep to show just filenames on Linux?

From the grep(1) man page:

  -l, --files-with-matches
          Suppress  normal  output;  instead  print the name of each input
          file from which output would normally have  been  printed.   The
          scanning  will  stop  on  the  first match.  (-l is specified by
          POSIX.)

NULL vs nullptr (Why was it replaced?)

You can find a good explanation of why it was replaced by reading A name for the null pointer: nullptr, to quote the paper:

This problem falls into the following categories:

  • Improve support for library building, by providing a way for users to write less ambiguous code, so that over time library writers will not need to worry about overloading on integral and pointer types.

  • Improve support for generic programming, by making it easier to express both integer 0 and nullptr unambiguously.

  • Make C++ easier to teach and learn.

Should ol/ul be inside <p> or outside?

GO here http://validator.w3.org/ upload your html file and it will tell you what is valid and what is not.

C#: How do you edit items and subitems in a listview?

I use a hidden textbox to edit all the listview items/subitems. The only problem is that the textbox needs to disappear as soon as any event takes place outside the textbox and the listview doesn't trigger the scroll event so if you scroll the listview the textbox will still be visible. To bypass this problem I created the Scroll event with this overrided listview.

Here is my code, I constantly reuse it so it might be help for someone:

ListViewItem.ListViewSubItem SelectedLSI;
private void listView2_MouseUp(object sender, MouseEventArgs e)
{
    ListViewHitTestInfo i = listView2.HitTest(e.X, e.Y);
    SelectedLSI = i.SubItem;
    if (SelectedLSI == null)
        return;

    int border = 0;
    switch (listView2.BorderStyle)
    {
        case BorderStyle.FixedSingle:
            border = 1;
            break;
        case BorderStyle.Fixed3D:
            border = 2;
            break;
    }

    int CellWidth = SelectedLSI.Bounds.Width;
    int CellHeight = SelectedLSI.Bounds.Height;
    int CellLeft = border + listView2.Left + i.SubItem.Bounds.Left;
    int CellTop =listView2.Top + i.SubItem.Bounds.Top;
    // First Column
    if (i.SubItem == i.Item.SubItems[0])
        CellWidth = listView2.Columns[0].Width;

    TxtEdit.Location = new Point(CellLeft, CellTop);
    TxtEdit.Size = new Size(CellWidth, CellHeight);
    TxtEdit.Visible = true;
    TxtEdit.BringToFront();
    TxtEdit.Text = i.SubItem.Text;
    TxtEdit.Select();
    TxtEdit.SelectAll();
}
private void listView2_MouseDown(object sender, MouseEventArgs e)
{
    HideTextEditor();
}
private void listView2_Scroll(object sender, EventArgs e)
{
    HideTextEditor();
}
private void TxtEdit_Leave(object sender, EventArgs e)
{
    HideTextEditor();
}
private void TxtEdit_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Return)
        HideTextEditor();
}
private void HideTextEditor()
{
    TxtEdit.Visible = false;
    if (SelectedLSI != null)
        SelectedLSI.Text = TxtEdit.Text;
    SelectedLSI = null;
    TxtEdit.Text = "";
}

Difference between webdriver.Dispose(), .Close() and .Quit()

Close() - It is used to close the browser or page currently which is having the focus.

Quit() - It is used to shut down the web driver instance or destroy the web driver instance(Close all the windows).

Dispose() - I am not aware of this method.

IFrame: This content cannot be displayed in a frame

use <meta http-equiv="X-Frame-Options" content="allow"> in the one to show in the iframe to allow it.

How do you add multi-line text to a UIButton?

Left align on iOS7 with autolayout:

button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentLeft;
button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;

calling a java servlet from javascript

Sorry, I read jsp not javascript. You need to do something like (note that this is a relative url and may be different depending on the url of the document this javascript is in):

document.location = 'path/to/servlet';

Where your servlet-mapping in web.xml looks something like this:

<servlet-mapping>
    <servlet-name>someServlet</servlet-name>
    <url-pattern>/path/to/servlet*</url-pattern>
</servlet-mapping>

Best way to pass parameters to jQuery's .load()

As Davide Gualano has been told. This one

$("#myDiv").load("myScript.php?var=x&var2=y&var3=z")

use GET method for sending the request, and this one

$("#myDiv").load("myScript.php", {var:x, var2:y, var3:z})

use POST method for sending the request. But any limitation that is applied to each method (post/get) is applied to the alternative usages that has been mentioned in the question.

For example: url length limits the amount of sending data in GET method.

What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?

Simple explanation about what a Index out of bound exception is:

Just think one train is there its compartments are D1,D2,D3. One passenger came to enter the train and he have the ticket for D4. now what will happen. the passenger want to enter a compartment that does not exist so obviously problem will arise.

Same scenario: whenever we try to access an array list, etc. we can only access the existing indexes in the array. array[0] and array[1] are existing. If we try to access array[3], it's not there actually, so an index out of bound exception will arise.

Why is git push gerrit HEAD:refs/for/master used instead of git push origin master

In order to avoid having to fully specify the git push command you could alternatively modify your git config file:

[remote "gerrit"]
    url = https://your.gerrit.repo:44444/repo
    fetch = +refs/heads/master:refs/remotes/origin/master
    push = refs/heads/master:refs/for/master

Now you can simply:

git fetch gerrit
git push gerrit

This is according to Gerrit

Waiting for HOME ('android.process.acore') to be launched

What worked for me was to delete the AVD from the AVD manager and create a new one. Then go to
Run >Run Configurations, select the target tab and choose the new AVD.

Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes

<p:commandXxx process> <p:ajax process> <f:ajax execute>

The process attribute is server side and can only affect UIComponents implementing EditableValueHolder (input fields) or ActionSource (command fields). The process attribute tells JSF, using a space-separated list of client IDs, which components exactly must be processed through the entire JSF lifecycle upon (partial) form submit.

JSF will then apply the request values (finding HTTP request parameter based on component's own client ID and then either setting it as submitted value in case of EditableValueHolder components or queueing a new ActionEvent in case of ActionSource components), perform conversion, validation and updating the model values (EditableValueHolder components only) and finally invoke the queued ActionEvent (ActionSource components only). JSF will skip processing of all other components which are not covered by process attribute. Also, components whose rendered attribute evaluates to false during apply request values phase will also be skipped as part of safeguard against tampered requests.

Note that it's in case of ActionSource components (such as <p:commandButton>) very important that you also include the component itself in the process attribute, particularly if you intend to invoke the action associated with the component. So the below example which intends to process only certain input component(s) when a certain command component is invoked ain't gonna work:

<p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="foo" action="#{bean.action}" />

It would only process the #{bean.foo} and not the #{bean.action}. You'd need to include the command component itself as well:

<p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="@this foo" action="#{bean.action}" />

Or, as you apparently found out, using @parent if they happen to be the only components having a common parent:

<p:panel><!-- Type doesn't matter, as long as it's a common parent. -->
    <p:inputText id="foo" value="#{bean.foo}" />
    <p:commandButton process="@parent" action="#{bean.action}" />
</p:panel>

Or, if they both happen to be the only components of the parent UIForm component, then you can also use @form:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" />
    <p:commandButton process="@form" action="#{bean.action}" />
</h:form>

This is sometimes undesirable if the form contains more input components which you'd like to skip in processing, more than often in cases when you'd like to update another input component(s) or some UI section based on the current input component in an ajax listener method. You namely don't want that validation errors on other input components are preventing the ajax listener method from being executed.

Then there's the @all. This has no special effect in process attribute, but only in update attribute. A process="@all" behaves exactly the same as process="@form". HTML doesn't support submitting multiple forms at once anyway.

There's by the way also a @none which may be useful in case you absolutely don't need to process anything, but only want to update some specific parts via update, particularly those sections whose content doesn't depend on submitted values or action listeners.

Noted should be that the process attribute has no influence on the HTTP request payload (the amount of request parameters). Meaning, the default HTML behavior of sending "everything" contained within the HTML representation of the <h:form> will be not be affected. In case you have a large form, and want to reduce the HTTP request payload to only these absolutely necessary in processing, i.e. only these covered by process attribute, then you can set the partialSubmit attribute in PrimeFaces Ajax components as in <p:commandXxx ... partialSubmit="true"> or <p:ajax ... partialSubmit="true">. You can also configure this 'globally' by editing web.xml and add

<context-param>
    <param-name>primefaces.SUBMIT</param-name>
    <param-value>partial</param-value>
</context-param>

Alternatively, you can also use <o:form> of OmniFaces 3.0+ which defaults to this behavior.

The standard JSF equivalent to the PrimeFaces specific process is execute from <f:ajax execute>. It behaves exactly the same except that it doesn't support a comma-separated string while the PrimeFaces one does (although I personally recommend to just stick to space-separated convention), nor the @parent keyword. Also, it may be useful to know that <p:commandXxx process> defaults to @form while <p:ajax process> and <f:ajax execute> defaults to @this. Finally, it's also useful to know that process supports the so-called "PrimeFaces Selectors", see also How do PrimeFaces Selectors as in update="@(.myClass)" work?


<p:commandXxx update> <p:ajax update> <f:ajax render>

The update attribute is client side and can affect the HTML representation of all UIComponents. The update attribute tells JavaScript (the one responsible for handling the ajax request/response), using a space-separated list of client IDs, which parts in the HTML DOM tree need to be updated as response to the form submit.

JSF will then prepare the right ajax response for that, containing only the requested parts to update. JSF will skip all other components which are not covered by update attribute in the ajax response, hereby keeping the response payload small. Also, components whose rendered attribute evaluates to false during render response phase will be skipped. Note that even though it would return true, JavaScript cannot update it in the HTML DOM tree if it was initially false. You'd need to wrap it or update its parent instead. See also Ajax update/render does not work on a component which has rendered attribute.

Usually, you'd like to update only the components which really need to be "refreshed" in the client side upon (partial) form submit. The example below updates the entire parent form via @form:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" required="true" />
    <p:message id="foo_m" for="foo" />
    <p:inputText id="bar" value="#{bean.bar}" required="true" />
    <p:message id="bar_m" for="bar" />
    <p:commandButton action="#{bean.action}" update="@form" />
</h:form>

(note that process attribute is omitted as that defaults to @form already)

Whilst that may work fine, the update of input and command components is in this particular example unnecessary. Unless you change the model values foo and bar inside action method (which would in turn be unintuitive in UX perspective), there's no point of updating them. The message components are the only which really need to be updated:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" required="true" />
    <p:message id="foo_m" for="foo" />
    <p:inputText id="bar" value="#{bean.bar}" required="true" />
    <p:message id="bar_m" for="bar" />
    <p:commandButton action="#{bean.action}" update="foo_m bar_m" />
</h:form>

However, that gets tedious when you have many of them. That's one of the reasons why PrimeFaces Selectors exist. Those message components have in the generated HTML output a common style class of ui-message, so the following should also do:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" required="true" />
    <p:message id="foo_m" for="foo" />
    <p:inputText id="bar" value="#{bean.bar}" required="true" />
    <p:message id="bar_m" for="bar" />
    <p:commandButton action="#{bean.action}" update="@(.ui-message)" />
</h:form>

(note that you should keep the IDs on message components, otherwise @(...) won't work! Again, see How do PrimeFaces Selectors as in update="@(.myClass)" work? for detail)

The @parent updates only the parent component, which thus covers the current component and all siblings and their children. This is more useful if you have separated the form in sane groups with each its own responsibility. The @this updates, obviously, only the current component. Normally, this is only necessary when you need to change one of the component's own HTML attributes in the action method. E.g.

<p:commandButton action="#{bean.action}" update="@this" 
    oncomplete="doSomething('#{bean.value}')" />

Imagine that the oncomplete needs to work with the value which is changed in action, then this construct wouldn't have worked if the component isn't updated, for the simple reason that oncomplete is part of generated HTML output (and thus all EL expressions in there are evaluated during render response).

The @all updates the entire document, which should be used with care. Normally, you'd like to use a true GET request for this instead by either a plain link (<a> or <h:link>) or a redirect-after-POST by ?faces-redirect=true or ExternalContext#redirect(). In effects, process="@form" update="@all" has exactly the same effect as a non-ajax (non-partial) submit. In my entire JSF career, the only sensible use case I encountered for @all is to display an error page in its entirety in case an exception occurs during an ajax request. See also What is the correct way to deal with JSF 2.0 exceptions for AJAXified components?

The standard JSF equivalent to the PrimeFaces specific update is render from <f:ajax render>. It behaves exactly the same except that it doesn't support a comma-separated string while the PrimeFaces one does (although I personally recommend to just stick to space-separated convention), nor the @parent keyword. Both update and render defaults to @none (which is, "nothing").


See also:

What does the @ symbol before a variable name mean in C#?

The @ symbol serves 2 purposes in C#:

Firstly, it allows you to use a reserved keyword as a variable like this:

int @int = 15;

The second option lets you specify a string without having to escape any characters. For instance the '\' character is an escape character so typically you would need to do this:

var myString = "c:\\myfolder\\myfile.txt"

alternatively you can do this:

var myString = @"c:\myFolder\myfile.txt"

How to use jQuery to get the current value of a file input field

I think it should be

 $('#fileinput').val();

Is it better practice to use String.format over string Concatenation in Java?

String.format() is more than just concatenating strings. For example, you can display numbers in a specific locale using String.format().

However, if you don't care about localisation, there is no functional difference. Maybe the one is faster than the other, but in most cases it will be negligible..

Android eclipse DDMS - Can't access data/data/ on phone to pull files

If it retures "permission denied" on adb shell -> su...

Go to "Developer Options" -> Root access -> "Apps and ADB"

Html helper for <input type="file" />

You can also use:

@using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ 
    <p>
        <input type="file" id="fileUpload" name="fileUpload" size="23" />
    </p>
    <p>
        <input type="submit" value="Upload file" /></p> 
}

Regex Match all characters between two strings

For example

(?<=This is)(.*)(?=sentence)

Regexr

I used lookbehind (?<=) and look ahead (?=) so that "This is" and "sentence" is not included in the match, but this is up to your use case, you can also simply write This is(.*)sentence.

The important thing here is that you activate the "dotall" mode of your regex engine, so that the . is matching the newline. But how you do this depends on your regex engine.

The next thing is if you use .* or .*?. The first one is greedy and will match till the last "sentence" in your string, the second one is lazy and will match till the next "sentence" in your string.

Update

Regexr

This is(?s)(.*)sentence

Where the (?s) turns on the dotall modifier, making the . matching the newline characters.

Update 2:

(?<=is \()(.*?)(?=\s*\))

is matching your example "This is (a simple) sentence". See here on Regexr

Quick Sort Vs Merge Sort

While quicksort is often a better choice than merge sort, there are definitely times when merge sort is thereotically a better choice. The most obvious time is when it's extremely important that your algorithm run faster than O(n^2). Quicksort is usually faster than this, but given the theoretical worst possible input, it could run in O(n^2), which is worse than the worst possible merge sort.

Quicksort is also more complicated than mergesort, especially if you want to write a really solid implementation, and so if you're aiming for simplicity and maintainability, merge sort becomes a promising alternative with very little performance loss.

link button property to open in new tab?

Here is your Tag.

<asp:LinkButton ID="LinkButton1" runat="server">Open Test Page</asp:LinkButton>

Here is your code on the code behind.

LinkButton1.Attributes.Add("href","../Test.aspx")
LinkButton1.Attributes.Add("target","_blank")

Hope this will be helpful for someone.

Edit To do the same with a link button inside a template field, use the following code.

Use GridView_RowDataBound event to find Link button.

Dim LB as LinkButton = e.Row.FindControl("LinkButton1")         
LB.Attributes.Add("href","../Test.aspx")  
LB.Attributes.Add("target","_blank")

How to read response headers in angularjs?

The response headers in case of cors remain hidden. You need to add in response headers to direct the Angular to expose headers to javascript.

// From server response headers :
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, 
Content-Type, Accept, Authorization, X-Custom-header");
header("Access-Control-Expose-Headers: X-Custom-header");
header("X-Custom-header: $some data");

var data = res.headers.get('X-Custom-header');

Source : https://github.com/angular/angular/issues/5237

How to Right-align flex item?

For those using Angular and Flex-Layout, use the following on the flex-item container:

<div fxLayout="row" fxLayoutAlign="flex-end">

See fxLayoutAlign docs here and the full fxLayout docs here.

How do I concatenate two strings in C?

Without GNU extension:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    const char str1[] = "First";
    const char str2[] = "Second";
    char *res;

    res = malloc(strlen(str1) + strlen(str2) + 1);
    if (!res) {
        fprintf(stderr, "malloc() failed: insufficient memory!\n");
        return EXIT_FAILURE;
    }

    strcpy(res, str1);
    strcat(res, str2);

    printf("Result: '%s'\n", res);
    free(res);
    return EXIT_SUCCESS;
}

Alternatively with GNU extension:

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    const char str1[] = "First";
    const char str2[] = "Second";
    char *res;

    if (-1 == asprintf(&res, "%s%s", str1, str2)) {
        fprintf(stderr, "asprintf() failed: insufficient memory!\n");
        return EXIT_FAILURE;
    }

    printf("Result: '%s'\n", res);
    free(res);
    return EXIT_SUCCESS;
}

See malloc, free and asprintf for more details.

How do I detect unsigned integer multiply overflow?

Here is a "non-portable" solution to the question. The Intel x86 and x64 CPUs have the so-called EFLAGS-register, which is filled in by the processor after each integer arithmetic operation. I will skip a detailed description here. The relevant flags are the "Overflow" Flag (mask 0x800) and the "Carry" Flag (mask 0x1). To interpret them correctly, one should consider if the operands are of signed or unsigned type.

Here is a practical way to check the flags from C/C++. The following code will work on Visual Studio 2005 or newer (both 32 and 64 bit), as well as on GNU C/C++ 64 bit.

#include <cstddef>
#if defined( _MSC_VER )
#include <intrin.h>
#endif

inline size_t query_intel_x86_eflags(const size_t query_bit_mask)
{
    #if defined( _MSC_VER )

        return __readeflags() & query_bit_mask;

    #elif defined( __GNUC__ )
        // This code will work only on 64-bit GNU-C machines.
        // Tested and does NOT work with Intel C++ 10.1!
        size_t eflags;
        __asm__ __volatile__(
            "pushfq \n\t"
            "pop %%rax\n\t"
            "movq %%rax, %0\n\t"
            :"=r"(eflags)
            :
            :"%rax"
            );
        return eflags & query_bit_mask;

    #else

        #pragma message("No inline assembly will work with this compiler!")
            return 0;
    #endif
}

int main(int argc, char **argv)
{
    int x = 1000000000;
    int y = 20000;
    int z = x * y;
    int f = query_intel_x86_eflags(0x801);
    printf("%X\n", f);
}

If the operands were multiplied without overflow, you would get a return value of 0 from query_intel_eflags(0x801), i.e. neither the carry nor the overflow flags are set. In the provided example code of main(), an overflow occurs and the both flags are set to 1. This check does not imply any further calculations, so it should be quite fast.

How to get date and time from server

You can use the "system( string $command[, int &$return_var] ) : string" function. For Windows system( "time" );, system( "time > output.txt" ); to put the response in the output.txt file. If you plan on deploying your website on someone else's server, then you may not want to hardcode the server time, as the server may move to an unknown timezone. Then it may be best to set the default time zone in the php.ini file. I use Hostinger and they allow you to configure that php.ini value.

get UTC time in PHP

As previously answered here, since PHP 5.2.0 you can use the DateTime class and specify the UTC timezone with an instance of DateTimeZone.

The DateTime __construct() documentation suggests passing "now" as the first parameter when creating a DateTime instance and specifying a timezone to get the current time.

$date_utc = new \DateTime("now", new \DateTimeZone("UTC"));

echo $date_utc->format(\DateTime::RFC850); # Saturday, 18-Apr-15 03:23:46 UTC

error: function returns address of local variable

a is defined locally in the function, and can't be used outside the function. If you want to return a char array from the function, you'll need to allocate it dynamically:

char *a = malloc(1000);

And at some point call free on the returned pointer.

You should also see a warning at this line: char b = "blah";: you're trying to assign a string literal to a char.

ssh-copy-id no identities found error

The simplest way is to:

ssh-keygen
[enter]
[enter]
[enter]

cd ~/.ssh
ssh-copy-id -i id_rsa.pub USERNAME@SERVERTARGET

Att:

Its very very simple.

In manual of "ss-keygen" explains:

"DESCRIPTION ssh-keygen generates, manages and converts authentication keys for ssh(1). ssh-keygen can create RSA keys for use by SSH protocol version 1 and DSA, ECDSA or RSA keys for use by SSH protocol version 2. The type of key to be generated is specified with the -t option. If invoked without any arguments, ssh-keygen will generate an RSA key for use in SSH protocol 2 connections."

Compare objects in Angular

To compare two objects you can use:

angular.equals(obj1, obj2)

It does a deep comparison and does not depend on the order of the keys See AngularJS DOCS and a little Demo

var obj1 = {
  key1: "value1",
  key2: "value2",
  key3: {a: "aa", b: "bb"}
}

var obj2 = {
  key2: "value2",
  key1: "value1",
  key3: {a: "aa", b: "bb"}
}

angular.equals(obj1, obj2) //<--- would return true

How do you clear the console screen in C?

#include <conio.h>

and use

clrscr()

Convert pyQt UI to python

The question has already been answered, but if you are looking for a shortcut during development, including this at the top of your python script will save you some time but mostly let you forget about actually having to make the conversion.

import os #Used in Testing Script
os.system("pyuic4 -o outputFile.py inpuiFile.ui")

Sorting an IList in C#

The accepted answer by @DavidMills is quite good, but I think it can be improved upon. For one, there is no need to define the ComparisonComparer<T> class when the framework already includes a static method Comparer<T>.Create(Comparison<T>). This method can be used to create an IComparison on the fly.

Also, it casts IList<T> to IList which has the potential to be dangerous. In most cases that I have seen, List<T> which implements IList is used behind the scenes to implement IList<T>, but this is not guaranteed and can lead to brittle code.

Lastly, the overloaded List<T>.Sort() method has 4 signatures and only 2 of them are implemented.

  1. List<T>.Sort()
  2. List<T>.Sort(Comparison<T>)
  3. List<T>.Sort(IComparer<T>)
  4. List<T>.Sort(Int32, Int32, IComparer<T>)

The below class implements all 4 List<T>.Sort() signatures for the IList<T> interface:

using System;
using System.Collections.Generic;

public static class IListExtensions
{
    public static void Sort<T>(this IList<T> list)
    {
        if (list is List<T>)
        {
            ((List<T>)list).Sort();
        }
        else
        {
            List<T> copy = new List<T>(list);
            copy.Sort();
            Copy(copy, 0, list, 0, list.Count);
        }
    }

    public static void Sort<T>(this IList<T> list, Comparison<T> comparison)
    {
        if (list is List<T>)
        {
            ((List<T>)list).Sort(comparison);
        }
        else
        {
            List<T> copy = new List<T>(list);
            copy.Sort(comparison);
            Copy(copy, 0, list, 0, list.Count);
        }
    }

    public static void Sort<T>(this IList<T> list, IComparer<T> comparer)
    {
        if (list is List<T>)
        {
            ((List<T>)list).Sort(comparer);
        }
        else
        {
            List<T> copy = new List<T>(list);
            copy.Sort(comparer);
            Copy(copy, 0, list, 0, list.Count);
        }
    }

    public static void Sort<T>(this IList<T> list, int index, int count,
        IComparer<T> comparer)
    {
        if (list is List<T>)
        {
            ((List<T>)list).Sort(index, count, comparer);
        }
        else
        {
            List<T> range = new List<T>(count);
            for (int i = 0; i < count; i++)
            {
                range.Add(list[index + i]);
            }
            range.Sort(comparer);
            Copy(range, 0, list, index, count);
        }
    }

    private static void Copy<T>(IList<T> sourceList, int sourceIndex,
        IList<T> destinationList, int destinationIndex, int count)
    {
        for (int i = 0; i < count; i++)
        {
            destinationList[destinationIndex + i] = sourceList[sourceIndex + i];
        }
    }
}

Usage:

class Foo
{
    public int Bar;

    public Foo(int bar) { this.Bar = bar; }
}

void TestSort()
{
    IList<int> ints = new List<int>() { 1, 4, 5, 3, 2 };
    IList<Foo> foos = new List<Foo>()
    {
        new Foo(1),
        new Foo(4),
        new Foo(5),
        new Foo(3),
        new Foo(2),
    };

    ints.Sort();
    foos.Sort((x, y) => Comparer<int>.Default.Compare(x.Bar, y.Bar));
}

The idea here is to leverage the functionality of the underlying List<T> to handle sorting whenever possible. Again, most IList<T> implementations that I have seen use this. In the case when the underlying collection is a different type, fallback to creating a new instance of List<T> with elements from the input list, use it to do the sorting, then copy the results back to the input list. This will work even if the input list does not implement the IList interface.

MacOSX homebrew mysql root password

If you run

brew install mariadb
...
brew services start mariadb
==> Successfully started `mariadb` (label: homebrew.mxcl.mariadb)

 $(brew --prefix mariadb)/bin/mysqladmin -u root password newpass
/usr/local/opt/mariadb/bin/mysqladmin: connect to server at 'localhost' failed
error: 'Access denied for user 'root'@'localhost''

also login with root account fails:

mariadb -u root
ERROR 1698 (28000): Access denied for user 'root'@'localhost'

then default admin user is created same name as your MacOS account username, e.g. johnsmit.

To login as root, issue:

mariadb -u johnsmit
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 17
Server version: 10.4.11-MariaDB Homebrew

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> exit
Bye

How to Set Selected value in Multi-Value Select in Jquery-Select2.?

Use multiselect function as below.

$("#drp_Books_Ill_Illustrations").val(["val1", "val2"]).trigger("change");

What techniques can be used to speed up C++ compilation times?

Use

#pragma once

at the top of header files, so if they're included more than once in a translation unit, the text of the header will only get included and parsed once.

How do I list all cron jobs for all users?

getent passwd | cut -d: -f1 | perl -e'while(<>){chomp;$l = `crontab -u $_ -l 2>/dev/null`;print "$_\n$l\n" if $l}'

This avoids messing with passwd directly, skips users that have no cron entries and for those who have them it prints out the username as well as their crontab.

Mostly dropping this here though so i can find it later in case i ever need to search for it again.

How to reload .bash_profile from the command line?

Simply type source ~/.bash_profile

Alternatively, if you like saving keystrokes you can type . ~/.bash_profile

Convert string to decimal number with 2 decimal places in Java

Float.parseFloat() is the problem as it returns a new float.

Returns a new float initialized to the value represented by the specified String, as performed by the valueOf method of class Float.

You are formatting just for the purpose of display . It doesn't mean the float will be represented by the same format internally .

You can use java.lang.BigDecimal.

I am not sure why are you using parseFloat() twice. If you want to display the float in a certain format then just format it and display it.

Float litersOfPetrol=Float.parseFloat(stringLitersOfPetrol);
DecimalFormat df = new DecimalFormat("0.00");
df.setMaximumFractionDigits(2);
System.out.println("liters of petrol before putting in editor"+df.format(litersOfPetrol));

How to fully delete a git repository created with init?

If you want to delete all .git folders in a project use the following command:

find . -type f | grep -i "\.git" | xargs rm

This will also delete all the .git folders and .gitignore files from all subfolders

Executing JavaScript without a browser?

I have installed Node.js on an iMac and

node somefile.js

in bash will work.

Reading file from Workspace in Jenkins with Groovy script

Although this question is only related to finding directory path ($WORKSPACE) however I had a requirement to read the file from workspace and parse it into JSON object to read sonar issues ( ignore minor/notes issues )

Might help someone, this is how I did it- from readFile

jsonParse(readFile('xyz.json')) 

and jsonParse method-

@NonCPS
def jsonParse(text) {
        return new groovy.json.JsonSlurperClassic().parseText(text);
}

This will also require script approval in ManageJenkins-> In-process script approval

What is the role of "Flatten" in Keras?

Flatten make explicit how you serialize a multidimensional tensor (tipically the input one). This allows the mapping between the (flattened) input tensor and the first hidden layer. If the first hidden layer is "dense" each element of the (serialized) input tensor will be connected with each element of the hidden array. If you do not use Flatten, the way the input tensor is mapped onto the first hidden layer would be ambiguous.

How do I perform HTML decoding/encoding using Python/Django?

Given the Django use case, there are two answers to this. Here is its django.utils.html.escape function, for reference:

def escape(html):
    """Returns the given HTML with ampersands, quotes and carets encoded."""
    return mark_safe(force_unicode(html).replace('&', '&amp;').replace('<', '&l
t;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;'))

To reverse this, the Cheetah function described in Jake's answer should work, but is missing the single-quote. This version includes an updated tuple, with the order of replacement reversed to avoid symmetric problems:

def html_decode(s):
    """
    Returns the ASCII decoded version of the given HTML string. This does
    NOT remove normal HTML tags like <p>.
    """
    htmlCodes = (
            ("'", '&#39;'),
            ('"', '&quot;'),
            ('>', '&gt;'),
            ('<', '&lt;'),
            ('&', '&amp;')
        )
    for code in htmlCodes:
        s = s.replace(code[1], code[0])
    return s

unescaped = html_decode(my_string)

This, however, is not a general solution; it is only appropriate for strings encoded with django.utils.html.escape. More generally, it is a good idea to stick with the standard library:

# Python 2.x:
import HTMLParser
html_parser = HTMLParser.HTMLParser()
unescaped = html_parser.unescape(my_string)

# Python 3.x:
import html.parser
html_parser = html.parser.HTMLParser()
unescaped = html_parser.unescape(my_string)

# >= Python 3.5:
from html import unescape
unescaped = unescape(my_string)

As a suggestion: it may make more sense to store the HTML unescaped in your database. It'd be worth looking into getting unescaped results back from BeautifulSoup if possible, and avoiding this process altogether.

With Django, escaping only occurs during template rendering; so to prevent escaping you just tell the templating engine not to escape your string. To do that, use one of these options in your template:

{{ context_var|safe }}
{% autoescape off %}
    {{ context_var }}
{% endautoescape %}

Multi-dimensional arraylist or list in C#?

you just make a list of lists like so:

List<List<string>> results = new List<List<string>>();

and then it's just a matter of using the functionality you want

results.Add(new List<string>()); //adds a new list to your list of lists
results[0].Add("this is a string"); //adds a string to the first list
results[0][0]; //gets the first string in your first list

How can I strip all punctuation from a string in JavaScript using regex?

I ran across the same issue, this solution did the trick and was very readable:

var sentence = "This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation";
var newSen = sentence.match(/[^_\W]+/g).join(' ');
console.log(newSen);

Result:

"This is an example of a string with punctuation"

The trick was to create a negated set. This means that it matches anything that is not within the set i.e. [^abc] - not a, b or c

\W is any non-word, so [^\W]+ will negate anything that is not a word char.

By adding in the _ (underscore) you can negate that as well.

Make it apply globally /g, then you can run any string through it and clear out the punctuation:

/[^_\W]+/g

Nice and clean ;)

How to Upload Image file in Retrofit 2

@Multipart
@POST("user/updateprofile")
Observable<ResponseBody> updateProfile(@Part("user_id") RequestBody id,
                                       @Part("full_name") RequestBody fullName,
                                       @Part MultipartBody.Part image,
                                       @Part("other") RequestBody other);

//pass it like this
File file = new File("/storage/emulated/0/Download/Corrections 6.jpg");
RequestBody requestFile =
        RequestBody.create(MediaType.parse("multipart/form-data"), file);

// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
        MultipartBody.Part.createFormData("image", file.getName(), requestFile);

// add another part within the multipart request
RequestBody fullName = 
        RequestBody.create(MediaType.parse("multipart/form-data"), "Your Name");

service.updateProfile(id, fullName, body, other);

Look at the way I am passing the multipart and string params. Hope this will help you!

Javascript/Jquery Convert string to array

Change

var trainindIdArray = traingIds.split(',');

to

var trainindIdArray = traingIds.replace("[","").replace("]","").split(',');

That will basically remove [ and ] and then split the string

Set padding for UITextField with UITextBorderStyleNone

Swift version:

extension UITextField {
    @IBInspectable var padding_left: CGFloat {
        get {
            LF.log("WARNING no getter for UITextField.padding_left")
            return 0
        }
        set (f) {
            layer.sublayerTransform = CATransform3DMakeTranslation(f, 0, 0)
        }
    }
}

So that you can assign value in IB

IBInspectable setting represented in Interface Builder

Java project in Eclipse: The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files

This happened to me when I imported a Java 1.8 project from Eclipse Luna into Eclipse Kepler.

  1. Right click on project > Build path > configure build path...
  2. Select the Libraries tab, you should see the Java 1.8 jre with an error
  3. Select the java 1.8 jre and click the Remove button
  4. Add Library... > JRE System Library > Next > workspace default > Finish
  5. Click OK to close the properties window
  6. Go to the project menu > Clean... > OK

Et voilà, that worked for me.

How to use radio on change event?

Use onchage function

<input type="radio" name="bedStatus" id="allot" checked="checked" value="allot" onchange="my_function('allot')">Allot
<input type="radio" name="bedStatus" id="transfer" value="transfer" onchange="my_function('transfer')">Transfer

<script>
 function my_function(val){
    alert(val);
 }
</script>

How do you wait for input on the same Console.WriteLine() line?

Use Console.Write instead, so there's no newline written:

Console.Write("What is your name? ");
var name = Console.ReadLine();

Need a good hex editor for Linux

Personally, I use Emacs with hexl-mod.

Emacs is able to work with really huge files. You can use search/replace value easily. Finally, you can use 'ediff' to do some diffs.

Converting a value to 2 decimal places within jQuery

Try to use this

parseFloat().toFixed(2)

Getting a 'source: not found' error when using source in a bash script

In Ubuntu if you execute the script with sh scriptname.sh you get this problem.

Try executing the script with ./scriptname.sh instead.

How to pause in C?

you can put

getchar();

before the return from the main function. That will wait for a character input before exiting the program.

Alternatively you could run your program from a command line and the output would be visible.

Calculate summary statistics of columns in dataframe

To clarify one point in @EdChum's answer, per the documentation, you can include the object columns by using df.describe(include='all'). It won't provide many statistics, but will provide a few pieces of info, including count, number of unique values, top value. This may be a new feature, I don't know as I am a relatively new user.

Difference between AutoPostBack=True and AutoPostBack=False?

The AutoPostBack property is used to set or return whether or not an automatic postback occurs when the user presses "ENTER" or "TAB" in the TextBox control.

If this property is set to TRUE the automatic postback is enabled, otherwise FALSE. The default is FALSE.

How to change background color in the Notepad++ text editor?

Notepad++ changed in the past couple of years, and it requires a few extra steps to set up a dark theme.

The answer by Amit-IO is good, but the example theme that is needed has stopped being maintained. The DraculaTheme is active. Just download the XML and put it in a themes folder. You may need Admin access in Windows.

C:\Users\YOUR_USER\AppData\Roaming\Notepad++\themes

https://draculatheme.com/notepad-plus-plus

Directory.GetFiles of certain extension

I would have done using just single line like

List<string> imageFiles = Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories)
      .Where(file => new string[] { ".jpg", ".gif", ".png" }
      .Contains(Path.GetExtension(file)))
      .ToList();

Grep and Python

You might be interested in pyp. Citing my other answer:

"The Pyed Piper", or pyp, is a linux command line text manipulation tool similar to awk or sed, but which uses standard python string and list methods as well as custom functions evolved to generate fast results in an intense production environment.

How to style a clicked button in CSS

If you just want the button to have different styling while the mouse is pressed you can use the :active pseudo class.

.button:active {
}

If on the other hand you want the style to stay after clicking you will have to use javascript.

Enable/Disable a dropdownbox in jquery

$(document).ready(function() {
 $('#chkdwn2').click(function() {
   if ($('#chkdwn2').prop('checked')) {
      $('#dropdown').prop('disabled', true);
   } else {
      $('#dropdown').prop('disabled', false);  
   }
 });
});

making use of .prop in the if statement.

Scrollable Menu with Bootstrap - Menu expanding its container when it should not

You can use the built-in CSS class pre-scrollable in bootstrap 3 inside the span element of the dropdown and it works immediately without implementing custom css.

 <ul class="dropdown-menu pre-scrollable">
                <li>item 1 </li>
                <li>item 2 </li>

 </ul>

Html5 Placeholders with .NET MVC 3 Razor EditorFor extension?

I actually prefer to use the display name for the placeholder text majority of the time. Here is an example of using the DisplayName:

  @Html.TextBoxFor(x => x.FirstName, true, null, new { @class = "form-control", placeholder = Html.DisplayNameFor(x => x.FirstName) })

Make file echo displaying "$PATH" string

The make uses the $ for its own variable expansions. E.g. single character variable $A or variable with a long name - ${VAR} and $(VAR).

To put the $ into a command, use the $$, for example:

all:
  @echo "Please execute next commands:"
  @echo 'setenv PATH /usr/local/greenhills/mips5/linux86:$$PATH'

Also note that to make the "" and '' (double and single quoting) do not play any role and they are passed verbatim to the shell. (Remove the @ sign to see what make sends to shell.) To prevent the shell from expanding $PATH, second line uses the ''.

Count the Number of Tables in a SQL Server Database

Try this:

SELECT Count(*)
FROM <DATABASE_NAME>.INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'

JavaFX Location is not set error message

mine was strange... IntelliJ specific quirk.

I looked at my output classes and there was a folder:

x.y.z

instead of

x/y/z

but if you have certain options set in IntelliJ, in the navigator they will both look like x.y.z

so check your output folder if you're scratching your head

Simple JavaScript login form validation

You can do two things here either move the onSubmit attribute to the form tag, or change the onSubmit event to an onCLick event.

Option 1

<form name="loginform" onSubmit="return validateForm();">

Option 2

<input type="submit" value="Login" onClick="return validateForm();" />

How to list running screen sessions?

Multiple folks have already pointed that

$ screen -ls

would list the screen sessions.

Here is another trick that may be useful to you.

If you add the following command as a last line in your .bashrc file on server xxx, then it will automatically reconnect to your screen session on login.

screen -d -r

Hope you find it useful.

Convert web page to image

Not sure if this is what you want but this is what I do sometimes in a pinch when certain websites are not saving right.

I just print them to PDF and I get a PDF file of the 'print output'. There's an Microsoft XPS Document writer under my list of printers as well, but I don't use it.

Hope this helps! =)

Input button target="_blank" isn't causing the link to load in a new window/tab

The formtarget attribute is only used for buttons with type="submit".

That is from this reference.

Here is an answer using JavaScript:

<input type="button" onClick="openNewTab()" value="facebook">

<script type="text/javascript">
    function openNewTab() {
        window.open("http://www.facebook.com/");
    }
</script>

How to disable text selection using jQuery?

In jQuery 1.8, this can be done as follows:

(function($){
    $.fn.disableSelection = function() {
        return this
                 .attr('unselectable', 'on')
                 .css('user-select', 'none')
                 .on('selectstart', false);
    };
})(jQuery);

How do I execute a PowerShell script automatically using Windows task scheduler?

None of posted solutions worked for me. Workaround, which worked:

create a run.bat and put inside powershell.exe -file "C:\...\script.ps1"

then set Action to Program/Script: "C:\...\run.bat"

How to generate a QR Code for an Android application?

Maybe this old topic but i found this library is very helpful and easy to use

QRGen

example for using it in android

 Bitmap myBitmap = QRCode.from("www.example.org").bitmap();
ImageView myImage = (ImageView) findViewById(R.id.imageView);
myImage.setImageBitmap(myBitmap);

How can I change column types in Spark SQL's DataFrame?

Generate a simple dataset containing five values and convert int to string type:

val df = spark.range(5).select( col("id").cast("string") )

How to upload and parse a CSV file in php

Although you could easily find a tutorial how to handle file uploads with php, and there are functions (manual) to handle CSVs, I will post some code because just a few days ago I worked on a project, including a bit of code you could use...

HTML:

<table width="600">
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" enctype="multipart/form-data">

<tr>
<td width="20%">Select file</td>
<td width="80%"><input type="file" name="file" id="file" /></td>
</tr>

<tr>
<td>Submit</td>
<td><input type="submit" name="submit" /></td>
</tr>

</form>
</table>

PHP:

if ( isset($_POST["submit"]) ) {

   if ( isset($_FILES["file"])) {

            //if there was an error uploading the file
        if ($_FILES["file"]["error"] > 0) {
            echo "Return Code: " . $_FILES["file"]["error"] . "<br />";

        }
        else {
                 //Print file details
             echo "Upload: " . $_FILES["file"]["name"] . "<br />";
             echo "Type: " . $_FILES["file"]["type"] . "<br />";
             echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
             echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

                 //if file already exists
             if (file_exists("upload/" . $_FILES["file"]["name"])) {
            echo $_FILES["file"]["name"] . " already exists. ";
             }
             else {
                    //Store file in directory "upload" with the name of "uploaded_file.txt"
            $storagename = "uploaded_file.txt";
            move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $storagename);
            echo "Stored in: " . "upload/" . $_FILES["file"]["name"] . "<br />";
            }
        }
     } else {
             echo "No file selected <br />";
     }
}

I know there must be an easier way to do this, but I read the CSV file and store the single cells of every record in an two dimensional array.

if ( isset($storagename) && $file = fopen( "upload/" . $storagename , r ) ) {

    echo "File opened.<br />";

    $firstline = fgets ($file, 4096 );
        //Gets the number of fields, in CSV-files the names of the fields are mostly given in the first line
    $num = strlen($firstline) - strlen(str_replace(";", "", $firstline));

        //save the different fields of the firstline in an array called fields
    $fields = array();
    $fields = explode( ";", $firstline, ($num+1) );

    $line = array();
    $i = 0;

        //CSV: one line is one record and the cells/fields are seperated by ";"
        //so $dsatz is an two dimensional array saving the records like this: $dsatz[number of record][number of cell]
    while ( $line[$i] = fgets ($file, 4096) ) {

        $dsatz[$i] = array();
        $dsatz[$i] = explode( ";", $line[$i], ($num+1) );

        $i++;
    }

        echo "<table>";
        echo "<tr>";
    for ( $k = 0; $k != ($num+1); $k++ ) {
        echo "<td>" . $fields[$k] . "</td>";
    }
        echo "</tr>";

    foreach ($dsatz as $key => $number) {
                //new table row for every record
        echo "<tr>";
        foreach ($number as $k => $content) {
                        //new table cell for every field of the record
            echo "<td>" . $content . "</td>";
        }
    }

    echo "</table>";
}

So I hope this will help, it is just a small snippet of code and I have not tested it, because I used it slightly different. The comments should explain everything.

WooCommerce - get category for product page

I literally striped out this line of code from content-single-popup.php located in woocommerce folder in my theme directory.

global $product; 
echo $product->get_categories( ', ', ' ' . _n( ' ', '  ', $cat_count, 'woocommerce' ) . ' ', ' ' );

Since my theme that I am working on has integrated woocommerce in it, this was my solution.

The view or its master was not found or no view engine supports the searched locations

I had this same issue. I had copied a view "Movie" and renamed it "Customer" accordingly. I also did the same with the models and the controllers.

The resolution was this...I rename the Customer View to Customer1 and just created a new view and called it Customer....I then just copied the Customer1 code into Customer.

This worked.

I would love to know the real cause of the problem.

UPDATE Just for grins....I went back and replicated all the renaming scenario again...and did not get any errors.

How to trigger the window resize event in JavaScript?

Where possible, I prefer to call the function rather than dispatch an event. This works well if you have control over the code you want to run, but see below for cases where you don't own the code.

window.onresize = doALoadOfStuff;

function doALoadOfStuff() {
    //do a load of stuff
}

In this example, you can call the doALoadOfStuff function without dispatching an event.

In your modern browsers, you can trigger the event using:

window.dispatchEvent(new Event('resize'));

This doesn't work in Internet Explorer, where you'll have to do the longhand:

var resizeEvent = window.document.createEvent('UIEvents'); 
resizeEvent.initUIEvent('resize', true, false, window, 0); 
window.dispatchEvent(resizeEvent);

jQuery has the trigger method, which works like this:

$(window).trigger('resize');

And has the caveat:

Although .trigger() simulates an event activation, complete with a synthesized event object, it does not perfectly replicate a naturally-occurring event.

You can also simulate events on a specific element...

function simulateClick(id) {
  var event = new MouseEvent('click', {
    'view': window,
    'bubbles': true,
    'cancelable': true
  });

  var elem = document.getElementById(id); 

  return elem.dispatchEvent(event);
}

Change the color of cells in one column when they don't match cells in another column

you could try this:

I have these two columns (column "A" and column "B"). I want to color them when the values between cells in the same row mismatch.

Follow these steps:

  1. Select the elements in column "A" (excluding A1);

  2. Click on "Conditional formatting -> New Rule -> Use a formula to determine which cells to format";

  3. Insert the following formula: =IF(A2<>B2;1;0);

  4. Select the format options and click "OK";

  5. Select the elements in column "B" (excluding B1) and repeat the steps from 2 to 4.

Differences between dependencyManagement and dependencies in Maven

In the parent POM, the main difference between the <dependencies> and <dependencyManagement> is this:

Artifacts specified in the <dependencies> section will ALWAYS be included as a dependency of the child module(s).

Artifacts specified in the <dependencyManagement> section will only be included in the child module if they were also specified in the section of the child module itself. Why is it good you ask? because you specify the version and/or scope in the parent, and you can leave them out when specifying the dependencies in the child POM. This can help you use unified versions for dependencies for child modules, without specifying the version in each child module.

Exit single-user mode

To switch out of Single User mode, try:

ALTER DATABASE [my_db] SET MULTI_USER

To switch back to Single User mode, you can use:

ALTER DATABASE [my_db] SET SINGLE_USER

How to kill a child process by the parent process?

In the parent process, fork()'s return value is the process ID of the child process. Stuff that value away somewhere for when you need to terminate the child process. fork() returns zero(0) in the child process.

When you need to terminate the child process, use the kill(2) function with the process ID returned by fork(), and the signal you wish to deliver (e.g. SIGTERM).

Remember to call wait() on the child process to prevent any lingering zombies.

Passing multiple values to a single PowerShell script parameter

The easiest way is probably to use two parameters: One for hosts (can be an array), and one for vlan.

param([String[]] $Hosts, [String] $VLAN)

Instead of

foreach ($i in $args)

you can use

foreach ($hostName in $Hosts)

If there is only one host, the foreach loop will iterate only once. To pass multiple hosts to the script, pass it as an array:

myScript.ps1 -Hosts host1,host2,host3 -VLAN 2

...or something similar.

How to subtract/add days from/to a date?

Just subtract a number:

> as.Date("2009-10-01")
[1] "2009-10-01"
> as.Date("2009-10-01")-5
[1] "2009-09-26"

Since the Date class only has days, you can just do basic arithmetic on it.

If you want to use POSIXlt for some reason, then you can use it's slots:

> a <- as.POSIXlt("2009-10-04")
> names(unclass(as.POSIXlt("2009-10-04")))
[1] "sec"   "min"   "hour"  "mday"  "mon"   "year"  "wday"  "yday"  "isdst"
> a$mday <- a$mday - 6
> a
[1] "2009-09-28 EDT"

How to convert a color integer to a hex String in Android?

The mask makes sure you only get RRGGBB, and the %06X gives you zero-padded hex (always 6 chars long):

String hexColor = String.format("#%06X", (0xFFFFFF & intColor));

scp via java

Like some here, I ended up writing a wrapper around the JSch library.

It's called way-secshell and it is hosted on GitHub:

https://github.com/objectos/way-secshell

// scp myfile.txt localhost:/tmp
File file = new File("myfile.txt");
Scp res = WaySSH.scp()
  .file(file)
  .toHost("localhost")
  .at("/tmp")
  .send();

How to read a string one letter at a time in python

A couple of things for ya:

The loading would be "better" like this:

with file('morsecodes.txt', 'rt') as f:
   for line in f:
      line = line.strip()
      if len(line) > 0:
         # do your stuff to parse the file

That way you don't need to close, and you don't need to manually load each line, etc., etc.

for letter in userInput:
   if ValidateLetter(letter):  # you need to define this
      code = GetMorseCode(letter)  # from my other answer
      # do whatever you want

VBA equivalent to Excel's mod function

You want the mod operator.

The expression a Mod b is equivalent to the following formula:

a - (b * (a \ b))

Edited to add:

There are some special cases you may have to consider, because Excel is using floating point math (and returns a float), which the VBA function returns an integer. Because of this, using mod with floating-point numbers may require extra attention:

  • Excel's results may not correspond exactly with what you would predict; this is covered briefly here (see topmost answer) and at great length here.

  • As @André points out in the comments, negative numbers may round in the opposite direction from what you expect. The Fix() function he suggests is explained here (MSDN).

What LaTeX Editor do you suggest for Linux?

I use TeXMaker. If you're using Ubuntu, it should be in the apt-get repository. To install texmaker, run:

sudo apt-get install texmaker

css divide width 100% to 3 column

.selector{width:calc(100% / 3);}

Resize Google Maps marker icon image

As mentionned in comments, this is the updated solution in favor of Icon object with documentation.

Use Icon object

var icon = {
    url: "../res/sit_marron.png", // url
    scaledSize: new google.maps.Size(50, 50), // scaled size
    origin: new google.maps.Point(0,0), // origin
    anchor: new google.maps.Point(0, 0) // anchor
};

 posicion = new google.maps.LatLng(latitud,longitud)
 marker = new google.maps.Marker({
  position: posicion,
  map: map,
  icon: icon
 });

Python FileNotFound

try block should be around open. Not around prompt.

while True:
    prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
    try:
        sudoku = open(prompt, 'r').readlines()
    except FileNotFoundError:
        print("Wrong file or file path")
    else:
        break

Remove useless zero digits from decimals in PHP

Ultimate Solution: The only safe way is to use regex:

echo preg_replace("/\.?0+$/", "", 3.0); // 3
echo preg_replace("/\d+\.?\d*(\.?0+)/", "", 3.0); // 3

it will work for any case

xcode library not found

The problem might be the following: SVN ignores .a files because of its global config, which means someone didn't commit the libGoogleAnalytics.a to SVN, because it didn't show up in SVN. So now you try to check out the project from SVN which now misses the libGoogleAnalytics.a (since it was ignored and was not committed). Of course the build fails.

You might want to change the global ignore config from SVN to stop ignoring *.a files.

Or just add the one missing libGoogleAnalytics.a file manually to your SVN working copy instead of changing SVNs global ignore config.

Then re-add libGoogleAnalytics.a to your XCode project and commit it to SVN.

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties

I would like to add a solution, that have helpt me to solve this problem in entity framework:

var eventsCustom = eventCustomRepository.FindAllEventsCustomByUniqueStudentReference(userDevice.UniqueStudentReference)
                .Where(x =>  x.DateTimeStart.Year == currentDateTime.Year &&
                             x.DateTimeStart.Month== currentDateTime.Month &&
                             x.DateTimeStart.Day == currentDateTime.Day
    );

I hope that it helps.

Selenium WebDriver.get(url) does not open the URL

Since you mentioned you use a proxy, try setting up the firefox driver with a proxy by following the answer given here proxy selenium python firefox

Insert default value when parameter is null

The easiest way to do this is to modify the table declaration to be

CREATE TABLE Demo
(
    MyColumn VARCHAR(10) NOT NULL DEFAULT 'Me'
)

Now, in your stored procedure you can do something like.

CREATE PROCEDURE InsertDemo
    @MyColumn VARCHAR(10) = null
AS
INSERT INTO Demo (MyColumn) VALUES(@MyColumn)

However, this method ONLY works if you can't have a null, otherwise, your stored procedure would have to use a different form of insert to trigger a default.

File path issues in R using Windows ("Hex digits in character string" error)

readClipboard() works directly too. Copy the path into your clipboard

C:\Users\surfcat\Desktop\2006_dissimilarity.csv

Then

readClipboard()

appears as

[1] "C:\\Users\\surfcat\\Desktop\\2006_dissimilarity.csv"

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

Microsoft listed the following methods for getting the a View definition: http://technet.microsoft.com/en-us/library/ms175067.aspx


USE AdventureWorks2012;
GO
SELECT definition, uses_ansi_nulls, uses_quoted_identifier, is_schema_bound
FROM sys.sql_modules
WHERE object_id = OBJECT_ID('HumanResources.vEmployee'); 
GO

USE AdventureWorks2012; 
GO
SELECT OBJECT_DEFINITION (OBJECT_ID('HumanResources.vEmployee')) 
AS ObjectDefinition; 
GO

EXEC sp_helptext 'HumanResources.vEmployee';

Failed to load resource: net::ERR_INSECURE_RESPONSE

I still experienced the problem described above on an Asus T100 Windows 10 test device for both (up to date) Edge and Chrome browser.

Solution was in the date/time settings of the device; somehow the date was not set correctly (date in the past). Restoring this by setting the correct date (and restarting the browsers) solved the issue for me. I hope I save someone a headache debugging this problem.