Programs & Examples On #Google suggest

How do I disable right click on my web page?

Yes, you can disable it using html.
Just add oncontextmenu="return false;" on your body or element.
It is very simple and just uses valid HTML, no jQuery or JS.

Android Design Support Library expandable Floating Action Button(FAB) menu

In case anyone is still looking for this functionality: I made an Android library that has this ability and much more, called ExpandableFab (https://github.com/nambicompany/expandable-fab).

The Material Design spec refers to this functionality as 'Speed Dial' and ExpandableFab implements it along with many additional features.

Nearly everything is customizable (colors, text, size, placement, margins, animations and more) and optional (don't need an Overlay, or FabOptions, or Labels, or icons, etc). Every property can be accessed or set through XML layouts or programmatically - whatever you prefer.

Written 100% in Kotlin but comes with full JavaDoc and KDoc (published API is well documented). Also comes with an example app so you can see different use cases with 0 coding.

Github: https://github.com/nambicompany/expandable-fab

Library website (w/ links to full documentation): https://nambicompany.github.io/expandable-fab/

Regular ExpandableFab implementing Material Design 'Speed Dial' functionality A highly customized ExpandableFab implementing Material Design 'Speed Dial' functionality

How to read attribute value from XmlNode in C#?

you can loop through all attributes like you do with nodes

foreach (XmlNode item in node.ChildNodes)
{ 
    // node stuff...

    foreach (XmlAttribute att in item.Attributes)
    {
        // attribute stuff
    }
}

Can a java file have more than one class?

Yes you can create more than one public class, but it has to be a nested class.

public class first {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
    }

    public class demo1
    {

        public class demo2
        {

        }
    }
}

How do I get a list of all subdomains of a domain?

In Windows nslookup the command is

ls -d somedomain.com > outfile.txt

which stores the subdomain list in outfile.txt

few domains these days allow this

How to call controller from the button click in asp.net MVC 4

You are mixing razor and aspx syntax,if your view engine is razor just do this:

<button class="btn btn-info" type="button" id="addressSearch"   
          onclick="location.href='@Url.Action("List", "Search")'">

Java, looping through result set

List<String> sids = new ArrayList<String>();
List<String> lids = new ArrayList<String>();

String query = "SELECT rlink_id, COUNT(*)"
             + "FROM dbo.Locate  "
             + "GROUP BY rlink_id ";

Statement stmt = yourconnection.createStatement();
try {
    ResultSet rs4 = stmt.executeQuery(query);

    while (rs4.next()) {
        sids.add(rs4.getString(1));
        lids.add(rs4.getString(2));
    }
} finally {
    stmt.close();
}

String show[] = sids.toArray(sids.size());
String actuate[] = lids.toArray(lids.size());

Getting checkbox values on submit

If you want to turn specific values in to new variables if they have been selected:

// Retrieve array color[] and set as variable    
$colors = $_GET['color'];
// Use array_search to find the key for "red"
$key_red = array_search('red', $colors);
// If "red" exists, the key will be an integer (or FALSE)
if (is_int($key_red)) {
    $red_color = 'Red was selected';
}

How to merge lists into a list of tuples?

In python 3.0 zip returns a zip object. You can get a list out of it by calling list(zip(a, b)).

Vertically aligning CSS :before and :after content

You can also use tables to accomplish this, like:

.pdf {
  display: table;
}
.pdf:before {
  display: table-cell;
  vertical-align: middle;
}

Here is an example: https://jsfiddle.net/ar9fadd0/2/

EDIT: You can also use flex to accomplish this:

.pdf {
  display: flex;
}
.pdf:before {
  display: flex;
  align-items: center;
}

Here is an example: https://jsfiddle.net/ctqk0xq1/1/

scp or sftp copy multiple files with single command

Problem: Copying multiple directories from remote server to local machine using a single SCP command and retaining each directory as it is in the remote server.

Solution: SCP can do this easily. This solves the annoying problem of entering password multiple times when using SCP with multiple folders. Consequently, this also saves a lot of time!

e.g.

# copies folders t1, t2, t3 from `test` to your local working directory
# note that there shouldn't be any space in between the folder names;
# we also escape the braces.
# please note the dot at the end of the SCP command

~$ cd ~/working/directory
~$ scp -r [email protected]:/work/datasets/images/test/\{t1,t2,t3\}  .

PS: Motivated by this great answer: scp or sftp copy multiple files with single command


Based on the comments, this also works fine in Git Bash on Windows

Wrap text in <td> tag

I believe you've encountered the catch 22 of tables. Tables are great for wrapping up content in a tabular structure and they do a wonderful job of "stretching" to meet the needs of the content they contain.

By default the table cells will stretch to fit content... thus your text just makes it wider.

There's a few solutions.

1.) You can try setting a max-width on the TD.

<td style="max-width:150px;">

2.) You can try putting your text in a wrapping element (e.g. a span) and set constraints on it.

<td><span style="max-width:150px;">Hello World...</span></td>

Be aware though that older versions of IE don't support min/max-width.

Since IE doesn't support max-width natively you'll need to add a hack if you want to force it to. There's several ways to add a hack, this is just one.

On page load, for IE6 only, get the rendered width of the table (in pixels) then get 15% of that and apply that as the width to the first TD in that column (or TH if you have headers) again, in pixels.

How to disable CSS in Browser for testing purposes

Install Adblock Plus, then add *.css rule in Filters options (custom filters tab). The method affect only on external stylesheets. It doesn't turn off inline styles.

Disable all external CSS

This method does exactly what you asked.

Foreign key constraints: When to use ON UPDATE and ON DELETE

Do not hesitate to put constraints on the database. You'll be sure to have a consistent database, and that's one of the good reasons to use a database. Especially if you have several applications requesting it (or just one application but with a direct mode and a batch mode using different sources).

With MySQL you do not have advanced constraints like you would have in postgreSQL but at least the foreign key constraints are quite advanced.

We'll take an example, a company table with a user table containing people from theses company

CREATE TABLE COMPANY (
     company_id INT NOT NULL,
     company_name VARCHAR(50),
     PRIMARY KEY (company_id)
) ENGINE=INNODB;

CREATE TABLE USER (
     user_id INT, 
     user_name VARCHAR(50), 
     company_id INT,
     INDEX company_id_idx (company_id),
     FOREIGN KEY (company_id) REFERENCES COMPANY (company_id) ON...
) ENGINE=INNODB;

Let's look at the ON UPDATE clause:

  • ON UPDATE RESTRICT : the default : if you try to update a company_id in table COMPANY the engine will reject the operation if one USER at least links on this company.
  • ON UPDATE NO ACTION : same as RESTRICT.
  • ON UPDATE CASCADE : the best one usually : if you update a company_id in a row of table COMPANY the engine will update it accordingly on all USER rows referencing this COMPANY (but no triggers activated on USER table, warning). The engine will track the changes for you, it's good.
  • ON UPDATE SET NULL : if you update a company_id in a row of table COMPANY the engine will set related USERs company_id to NULL (should be available in USER company_id field). I cannot see any interesting thing to do with that on an update, but I may be wrong.

And now on the ON DELETE side:

  • ON DELETE RESTRICT : the default : if you try to delete a company_id Id in table COMPANY the engine will reject the operation if one USER at least links on this company, can save your life.
  • ON DELETE NO ACTION : same as RESTRICT
  • ON DELETE CASCADE : dangerous : if you delete a company row in table COMPANY the engine will delete as well the related USERs. This is dangerous but can be used to make automatic cleanups on secondary tables (so it can be something you want, but quite certainly not for a COMPANY<->USER example)
  • ON DELETE SET NULL : handful : if you delete a COMPANY row the related USERs will automatically have the relationship to NULL. If Null is your value for users with no company this can be a good behavior, for example maybe you need to keep the users in your application, as authors of some content, but removing the company is not a problem for you.

usually my default is: ON DELETE RESTRICT ON UPDATE CASCADE. with some ON DELETE CASCADE for track tables (logs--not all logs--, things like that) and ON DELETE SET NULL when the master table is a 'simple attribute' for the table containing the foreign key, like a JOB table for the USER table.

Edit

It's been a long time since I wrote that. Now I think I should add one important warning. MySQL has one big documented limitation with cascades. Cascades are not firing triggers. So if you were over confident enough in that engine to use triggers you should avoid cascades constraints.

MySQL triggers activate only for changes made to tables by SQL statements. They do not activate for changes in views, nor by changes to tables made by APIs that do not transmit SQL statements to the MySQL Server

==> See below the last edit, things are moving on this domain

Triggers are not activated by foreign key actions.

And I do not think this will get fixed one day. Foreign key constraints are managed by the InnoDb storage and Triggers are managed by the MySQL SQL engine. Both are separated. Innodb is the only storage with constraint management, maybe they'll add triggers directly in the storage engine one day, maybe not.

But I have my own opinion on which element you should choose between the poor trigger implementation and the very useful foreign keys constraints support. And once you'll get used to database consistency you'll love PostgreSQL.

12/2017-Updating this Edit about MySQL:

as stated by @IstiaqueAhmed in the comments, the situation has changed on this subject. So follow the link and check the real up-to-date situation (which may change again in the future).

how to avoid extra blank page at end while printing?

Have you tried this?

@media print {
    html, body {
        height: 99%;    
    }
}

How do I make a MySQL database run completely in memory?

Assuming you understand the consequences of using the MEMORY engine as mentioned in comments, and here, as well as some others you'll find by searching about (no transaction safety, locking issues, etc) - you can proceed as follows:

MEMORY tables are stored differently than InnoDB, so you'll need to use an export/import strategy. First dump each table separately to a file using SELECT * FROM tablename INTO OUTFILE 'table_filename'. Create the MEMORY database and recreate the tables you'll be using with this syntax: CREATE TABLE tablename (...) ENGINE = MEMORY;. You can then import your data using LOAD DATA INFILE 'table_filename' INTO TABLE tablename for each table.

How to get a variable value if variable name is stored as string?

X=foo
Y=X
eval "Z=\$$Y"

sets Z to "foo"

Take care using eval since this may allow accidential excution of code through values in ${Y}. This may cause harm through code injection.

For example

Y="\`touch /tmp/eval-is-evil\`"

would create /tmp/eval-is-evil. This could also be some rm -rf /, of course.

PowerShell The term is not recognized as cmdlet function script file or operable program

You first have to 'dot' source the script, so for you :

. .\Get-NetworkStatistics.ps1

The first 'dot' asks PowerShell to load the script file into your PowerShell environment, not to start it. You should also use set-ExecutionPolicy Unrestricted or set-ExecutionPolicy AllSigned see(the Execution Policy instructions).

Hiding the R code in Rmarkdown/knit and just showing the results

Alternatively, you can also parse a standard markdown document (without code blocks per se) on the fly by the markdownreports package.

How to compile a 32-bit binary on a 64-bit linux machine with gcc/cmake

One way is to setup a chroot environment. Debian has a number of tools for that, for example debootstrap

How to append a date in batch files

You can also access the date via the variable %DATE%

When testing my system %DATE% produces ddd dd/mm/yyyy

you can use substring operators to produce the format you desire

ie. running the following on MON 11/12/2018 with US regional settings

%DATE:~3,3% %DATE:~0,3% %DATE:~7,2%

Will produce an output:

11 Mon 12

the substring arguments are
%*variable*:~*startpos*,*numberofchars*%

How do I remove the top margin in a web page?

I had same problem. It was resolved by following css line;

h1{margin-top:0px}

My main div contained h1 tag in the beginning.

Have bash script answer interactive prompts

I found the best way to send input is to use cat and a text file to pass along whatever input you need.

cat "input.txt" | ./Script.sh

Best PHP IDE for Mac? (Preferably free!)

Komodo is wonderful, and it runs on OS X; they have a free version, Komodo Edit.

UPDATE from 2015: I've switched to PHPStorm from Jetbrains, the same folks that built IntelliJ IDEA and Resharper. It's better. Not just better. It's well worth the money.

How do I create/edit a Manifest file?

In Visual Studio 2010 (until 2019 and possibly future versions) you can add the manifest file to your project.

Right click your project file on the Solution Explorer, select Add, then New item (or CTRL+SHIFT+A). There you can find Application Manifest File.

The file name is app.manifest.

Sum a list of numbers in Python

I use a while loop to get the result:

i = 0
while i < len(a)-1:
   result = (a[i]+a[i+1])/2
   print result
   i +=1

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

The standard library includes the ordered and the unordered map (std::map and std::unordered_map) containers. In an ordered map the elements are sorted by the key, insert and access is in O(log n). Usually the standard library internally uses red black trees for ordered maps. But this is just an implementation detail. In an unordered map insert and access is in O(1). It is just another name for a hashtable.

An example with (ordered) std::map:

#include <map>
#include <iostream>
#include <cassert>

int main(int argc, char **argv)
{
  std::map<std::string, int> m;
  m["hello"] = 23;
  // check if key is present
  if (m.find("world") != m.end())
    std::cout << "map contains key world!\n";
  // retrieve
  std::cout << m["hello"] << '\n';
  std::map<std::string, int>::iterator i = m.find("hello");
  assert(i != m.end());
  std::cout << "Key: " << i->first << " Value: " << i->second << '\n';
  return 0;
}

Output:

23
Key: hello Value: 23

If you need ordering in your container and are fine with the O(log n) runtime then just use std::map.

Otherwise, if you really need a hash-table (O(1) insert/access), check out std::unordered_map, which has a similar to std::map API (e.g. in the above example you just have to search and replace map with unordered_map).

The unordered_map container was introduced with the C++11 standard revision. Thus, depending on your compiler, you have to enable C++11 features (e.g. when using GCC 4.8 you have to add -std=c++11 to the CXXFLAGS).

Even before the C++11 release GCC supported unordered_map - in the namespace std::tr1. Thus, for old GCC compilers you can try to use it like this:

#include <tr1/unordered_map>

std::tr1::unordered_map<std::string, int> m;

It is also part of boost, i.e. you can use the corresponding boost-header for better portability.

SMTP connect() failed PHPmailer - PHP

If you're using VPS and with httpd service, please check if your httpd_can_sendmail is on.

getsebool -a | grep mail

to set on

setsebool -P httpd_can_sendmail on

URL to compose a message in Gmail (with full Gmail interface and specified to, bcc, subject, etc.)

Bookmarking this URL should give you a full-screen compose window, without any distractions:

https://mail.google.com/mail/?view=cm&fs=1&tf=1

Additionally, if you want to be future-proof (see for instance how other URLs in this question stopped working) you can bookmark a link to:

mailto:

It will open your default email client and you probably already have Gmail configured for that purpose.

jQuery check if <input> exists and has a value

if($('#user_inp').length > 0 && $('#user_inp').val() != '')
{

    $('#user_inp').css({"font-size":"18px"});
    $('#user_line').css({"background-color":"#4cae4c","transition":"0.5s","height":"2px"});
    $('#username').css({"color":"#4cae4c","transition":"0.5s","font-size":"18px"});

}

Amazon S3 - HTTPS/SSL - Is it possible?

This is a response I got from their Premium Services

Hello,

This is actually a issue with the way SSL validates names containing a period, '.', > character. We've documented this behavior here:

http://docs.amazonwebservices.com/AmazonS3/latest/dev/BucketRestrictions.html

The only straight-forward fix for this is to use a bucket name that does not contain that character. You might instead use a bucket named 'furniture-retailcatalog-us'. This would allow you use HTTPS with

https://furniture-retailcatalog-us.s3.amazonaws.com/

You could, of course, put a CNAME DNS record to make that more friendly. For example,

images-furniture.retailcatalog.us IN CNAME furniture-retailcatalog-us.s3.amazonaws.com.

Hope that helps. Let us know if you have any other questions.

Amazon Web Services

Unfortunately your "friendly" CNAME will cause host name mismatch when validating the certificate, therefore you cannot really use it for a secure connection. A big missing feature of S3 is accepting custom certificates for your domains.


UPDATE 10/2/2012

From @mpoisot:

The link Amazon provided no longer says anything about https. I poked around in the S3 docs and finally found a small note about it on the Virtual Hosting page: http://docs.amazonwebservices.com/AmazonS3/latest/dev/VirtualHosting.html


UPDATE 6/17/2013

From @Joseph Lust:

Just got it! Check it out and sign up for an invite: http://aws.amazon.com/cloudfront/custom-ssl-domains

Jquery: Find Text and replace

More specific:

$("#id1 p:contains('dog')").text($("#id1 p:contains('dog')").text().replace('dog', 'doll'));

"An attempt was made to load a program with an incorrect format" even when the platforms are the same

If you encounter this error when you click green arrow button to run the application, but still want to run the app in 64 bit. You can do this in VS 2013, 2015, 2017, and 2019

Go to: Tools > Options > Projects and Solutions > Web Projects > Use the 64 bit version of IIS Express

Change all files and folders permissions of a directory to 644/755

One approach could be using find:

for directories

find /desired_location -type d -print0 | xargs -0 chmod 0755

for files

find /desired_location -type f -print0 | xargs -0 chmod 0644

Print content of JavaScript object?

You can also use Prototype's Object.inspect() method, which "Returns the debug-oriented string representation of the object".

http://api.prototypejs.org/language/Object/inspect/

How to run function in AngularJS controller on document ready?

Why not try with what angular docs mention https://docs.angularjs.org/api/ng/function/angular.element.

angular.element(callback)

I've used this inside my $onInit(){...} function.

 var self = this;

 angular.element(function () {
        var target = document.getElementsByClassName('unitSortingModule');
        target[0].addEventListener("touchstart", self.touchHandler, false);
        ...
    });

This worked for me.

How to fix "ImportError: No module named ..." error in Python?

If you have this problem when using an instaled version, when using setup.py, make sure your module is included inside packages

setup(name='Your program',
    version='0.7.0',
    description='Your desccription',
    packages=['foo', 'foo.bar'], # add `foo.bar` here

Sorting objects by property values

Here's a short example, that creates and array of objects, and sorts numerically or alphabetically:

// Create Objects Array

var arrayCarObjects = [
{brand: "Honda",        topSpeed: 45},
{brand: "Ford",         topSpeed: 6},
{brand: "Toyota",       topSpeed: 240},
{brand: "Chevrolet",    topSpeed: 120},
{brand: "Ferrari",      topSpeed: 1000}
];

// Sort Objects Numerically

arrayCarObjects.sort((a, b) => (a.topSpeed - b.topSpeed));

// Sort Objects Alphabetically

arrayCarObjects.sort((a, b) => (a.brand > b.brand) ? 1 : -1);

How do I add a simple onClick event handler to a canvas element?

When you draw to a canvas element, you are simply drawing a bitmap in immediate mode.

The elements (shapes, lines, images) that are drawn have no representation besides the pixels they use and their colour.

Therefore, to get a click event on a canvas element (shape), you need to capture click events on the canvas HTML element and use some math to determine which element was clicked, provided you are storing the elements' width/height and x/y offset.

To add a click event to your canvas element, use...

canvas.addEventListener('click', function() { }, false);

To determine which element was clicked...

var elem = document.getElementById('myCanvas'),
    elemLeft = elem.offsetLeft + elem.clientLeft,
    elemTop = elem.offsetTop + elem.clientTop,
    context = elem.getContext('2d'),
    elements = [];

// Add event listener for `click` events.
elem.addEventListener('click', function(event) {
    var x = event.pageX - elemLeft,
        y = event.pageY - elemTop;

    // Collision detection between clicked offset and element.
    elements.forEach(function(element) {
        if (y > element.top && y < element.top + element.height 
            && x > element.left && x < element.left + element.width) {
            alert('clicked an element');
        }
    });

}, false);

// Add element.
elements.push({
    colour: '#05EFFF',
    width: 150,
    height: 100,
    top: 20,
    left: 15
});

// Render elements.
elements.forEach(function(element) {
    context.fillStyle = element.colour;
    context.fillRect(element.left, element.top, element.width, element.height);
});?

jsFiddle.

This code attaches a click event to the canvas element, and then pushes one shape (called an element in my code) to an elements array. You could add as many as you wish here.

The purpose of creating an array of objects is so we can query their properties later. After all the elements have been pushed onto the array, we loop through and render each one based on their properties.

When the click event is triggered, the code loops through the elements and determines if the click was over any of the elements in the elements array. If so, it fires an alert(), which could easily be modified to do something such as remove the array item, in which case you'd need a separate render function to update the canvas.


For completeness, why your attempts didn't work...

elem.onClick = alert("hello world"); // displays alert without clicking

This is assigning the return value of alert() to the onClick property of elem. It is immediately invoking the alert().

elem.onClick = alert('hello world');  // displays alert without clicking

In JavaScript, the ' and " are semantically identical, the lexer probably uses ['"] for quotes.

elem.onClick = "alert('hello world!')"; // does nothing, even with clicking

You are assigning a string to the onClick property of elem.

elem.onClick = function() { alert('hello world!'); }; // does nothing

JavaScript is case sensitive. The onclick property is the archaic method of attaching event handlers. It only allows one event to be attached with the property and the event can be lost when serialising the HTML.

elem.onClick = function() { alert("hello world!"); }; // does nothing

Again, ' === ".

How to Compare two Arrays are Equal using Javascript?

You could try this simple approach

_x000D_
_x000D_
var array1 = [4,8,9,10];_x000D_
var array2 = [4,8,9,10];_x000D_
_x000D_
console.log(array1.join('|'));_x000D_
console.log(array2.join('|'));_x000D_
_x000D_
if (array1.join('|') === array2.join('|')) {_x000D_
 console.log('The arrays are equal.');_x000D_
} else {_x000D_
 console.log('The arrays are NOT equal.');_x000D_
}_x000D_
_x000D_
array1 = [[1,2],[3,4],[5,6],[7,8]];_x000D_
array2 = [[1,2],[3,4],[5,6],[7,8]];_x000D_
_x000D_
console.log(array1.join('|'));_x000D_
console.log(array2.join('|'));_x000D_
_x000D_
if (array1.join('|') === array2.join('|')) {_x000D_
 console.log('The arrays are equal.');_x000D_
} else {_x000D_
 console.log('The arrays are NOT equal.');_x000D_
}
_x000D_
_x000D_
_x000D_

If the position of the values are not important you could sort the arrays first.

if (array1.sort().join('|') === array2.sort().join('|')) {
    console.log('The arrays are equal.');
} else {
    console.log('The arrays are NOT equal.');
}

How to find file accessed/created just few minutes ago

If you have GNU find you can also say

find . -newermt '1 minute ago'

The t options makes the reference "file" for newer become a reference date string of the sort that you could pass to GNU date -d, which understands complex date specifications like the one given above.

Maven: best way of linking custom external JAR to my project?

If the external jar is created by a Maven project only then you can copy the entire project on your system and run a

mvn install

in the project directory. This will add the jar into .m2 directory which is local maven repository.

Now you can add the

<dependency>
     <groupId>copy-from-the=maven-pom-of-existing-project</groupId>
     <artifactId>copy-from-the=maven-pom-of-existing-project</artifactId>
     <version>copy-from-the=maven-pom-of-existing-project</version>
</dependency>

This will ensure that you

mvn exec:java 

works. If you use suggested here

<scope>system</scope>

Then you will have to add classes individually while using executing through command line.

You can add the external jars by the following command described here

mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> \
-DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging>

How do I execute a MS SQL Server stored procedure in java/jsp, returning table data?

FWIW, sp_test will not be returning anything but an integer (all SQL Server stored procs just return an integer) and no result sets on the wire (since no SELECT statements). To get the output of the PRINT statements, you normally use the InfoMessage event on the connection (not the command) in ADO.NET.

JAVA_HOME directory in Linux

On the Terminal, type:

echo "$JAVA_HOME"

If you are not getting anything, then your environment variable JAVA_HOME has not been set. You can try using "locate java" to try and discover where your installation of Java is located.

How to export plots from matplotlib with transparent background?

Png files can handle transparency. So you could use this question Save plot to image file instead of displaying it using Matplotlib so as to save you graph as a png file.

And if you want to turn all white pixel transparent, there's this other question : Using PIL to make all white pixels transparent?

If you want to turn an entire area to transparent, then there's this question: And then use the PIL library like in this question Python PIL: how to make area transparent in PNG? so as to make your graph transparent.

Using jquery to get all checked checkboxes with a certain class name

You can use something like this:
HTML:

<div><input class="yourClass" type="checkbox" value="1" checked></div>
<div><input class="yourClass" type="checkbox" value="2"></div>
<div><input class="yourClass" type="checkbox" value="3" checked></div>
<div><input class="yourClass" type="checkbox" value="4"></div>


JQuery:

$(".yourClass:checkbox").filter(":checked")


It will choose values of 1 and 3.

Add the loading screen in starting of the android application

use ProgressDialog.

ProgressDialog dialog=new ProgressDialog(context);
dialog.setMessage("message");
dialog.setCancelable(false);
dialog.setInverseBackgroundForced(false);
dialog.show();

hide it whenever your UI is ready with data. call :

dialog.hide();

SQL Error: ORA-00936: missing expression

  1  

     select ename as name,
      2  sal as salary,
      3  dept,deptno,
      4   from (TABLE_NAME or SUBQUERY)
      5   emp, emp2,  dept
      6    where
      7   emp.deptno = dept.deptno and
      8   emp2.deptno = emp.deptno
      9*  order by dept.dname

 from (TABLE_NAME or SUBQUERY)
 *
ERROR at line 4:
ORA-00936: missing expression`  select ename as name,
 sal as salary,
 dept,deptno,
  from (TABLE_NAME or SUBQUERY)
  emp, emp2,  dept
   where
  emp.deptno = dept.deptno and
  emp2.deptno = emp.deptno
  order by dept.dname`

Get the _id of inserted document in Mongo database in NodeJS

A shorter way than using second parameter for the callback of collection.insert would be using objectToInsert._id that returns the _id (inside of the callback function, supposing it was a successful operation).

The Mongo driver for NodeJS appends the _id field to the original object reference, so it's easy to get the inserted id using the original object:

collection.insert(objectToInsert, function(err){
   if (err) return;
   // Object inserted successfully.
   var objectId = objectToInsert._id; // this will return the id of object inserted
});

Removing duplicate rows from table in Oracle

DELETE FROM tableName  WHERE ROWID NOT IN (SELECT   MIN (ROWID) FROM table GROUP BY columnname);

how to use "AND", "OR" for RewriteCond on Apache?

After many struggles and to achive a general, flexible and more readable solution, in my case I ended up saving the ORs results into ENV variables and doing the ANDs of those variables.

# RESULT_ONE = A OR B
RewriteRule ^ - [E=RESULT_ONE:False]
RewriteCond ...A... [OR]
RewriteCond ...B...
RewriteRule ^ - [E=RESULT_ONE:True]

# RESULT_TWO = C OR D
RewriteRule ^ - [E=RESULT_TWO:False]
RewriteCond ...C... [OR]
RewriteCond ...D...
RewriteRule ^ - [E=RESULT_TWO:True]

# if ( RESULT_ONE AND RESULT_TWO ) then ( RewriteRule ...something... )
RewriteCond %{ENV:RESULT_ONE} =True
RewriteCond %{ENV:RESULT_TWO} =True
RewriteRule ...something...

Requirements:

Dropdownlist width in IE

So far there isn't one. Don't know about IE8 but it cannot be done in IE6 & IE7, unless you implement your own dropdown list functionality with javascript. There are examples how to do it on the web, though I don't see much benefit in duplicating existing functionality.

How to import local packages without gopath

Run:

go mod init yellow

Then create a file yellow.go:

package yellow

func Mix(s string) string {
   return s + "Yellow"
}

Then create a file orange/orange.go:

package main
import "yellow"

func main() {
   s := yellow.Mix("Red")
   println(s)
}

Then build:

go build

https://golang.org/doc/code.html

Delete statement in SQL is very slow

After inspecting an SSIS Package(due to a SQL Server executing commands really slow), that was set up in a client of ours about 5-4 years before the time of me writing this, I found out that there were the below tasks: 1) insert data from an XML file into a table called [Importbarcdes].

2) merge command on an another target table, using as source the above mentioned table.

3) "delete from [Importbarcodes]", to clear the table of the row that was inserted after the XML file was read by the task of the SSIS Package.

After a quick inspection all statements(SELECT, UPDATE, DELETE etc.) on the table ImportBarcodes that had only 1 row, took about 2 minutes to execute.

Extended Events showed a whole lot PAGEIOLATCH_EX wait notifications.

No indexes were present of the table and no triggers were registered.

Upon close inspection of the properties of the table, in the Storage Tab and under general section, the Data Space field showed more than 6 GIGABYTES of space allocated in pages.

What happened:

The query ran for a good portion of time each day for the last 4 years, inserting and deleting data in the table, leaving unused pagefiles behind with out freeing them up.

So, that was the main reason of the wait events that were captured by the Extended Events Session and the slowly executed commands upon the table.

Running ALTER TABLE ImportBarcodes REBUILD fixed the issue freeing up all the unused space. TRUNCATE TABLE ImportBarcodes did a similar thing, with the only difference of deleting all pagefiles and data.

What is the use of the init() usage in JavaScript?

JavaScript doesn't have a built-in init() function, that is, it's not a part of the language. But it's not uncommon (in a lot of languages) for individual programmers to create their own init() function for initialisation stuff.

A particular init() function may be used to initialise the whole webpage, in which case it would probably be called from document.ready or onload processing, or it may be to initialise a particular type of object, or...well, you name it.

What any given init() does specifically is really up to whatever the person who wrote it needed it to do. Some types of code don't need any initialisation.

function init() {
  // initialisation stuff here
}

// elsewhere in code
init();

Batch command date and time in file name

So you want to generate date in format YYYYMMDD_hhmmss. As %date% and %time% formats are locale dependant you might need more robust ways to get a formatted date.

Here's one option:

@if (@X)==(@Y) @end /*
    @cscript //E:JScript //nologo "%~f0"
    @exit /b %errorlevel%
@end*/
var todayDate = new Date();
todayDate = "" + 
    todayDate.getFullYear() + 
    ("0" + (todayDate.getMonth() + 1)).slice(-2) +
    ("0" + todayDate.getDate()).slice(-2) + 
    "_" + 
    ("0" + todayDate.getHours()).slice(-2) +
    ("0" + todayDate.getMinutes()).slice(-2) +
    ("0" + todayDate.getSeconds()).slice(-2) ;
WScript.Echo(todayDate);

and if you save the script as jsdate.bat you can assign it as a value :

for /f %%a in ('jsdate.bat') do @set "fdate=%%a"
echo %fdate%

or directly from command prompt:

for /f %a in ('jsdate.bat') do @set "fdate=%a"

Or you can use powershell which probably is the way that requires the less code:

for /f %%# in ('powershell Get-Date -Format "yyyyMMdd_HHmmss"') do set "fdate=%%#"

How do I call an Angular.js filter with multiple arguments?

In this code, jsondata is our array and in function return we are checking the 'version' present in the jsondata.

var as = $filter('filter')(jsondata, function (n,jsondata){
   return n.filter.version==='V.0.3'
});

console.log("name is " + as[0].name+as[0]); 

VHDL - How should I create a clock in a testbench?

My favoured technique:

signal clk : std_logic := '0'; -- make sure you initialise!
...
clk <= not clk after half_period;

I usually extend this with a finished signal to allow me to stop the clock:

clk <= not clk after half_period when finished /= '1' else '0';

Gotcha alert: Care needs to be taken if you calculate half_period from another constant by dividing by 2. The simulator has a "time resolution" setting, which often defaults to nanoseconds... In which case, 5 ns / 2 comes out to be 2 ns so you end up with a period of 4ns! Set the simulator to picoseconds and all will be well (until you need fractions of a picosecond to represent your clock time anyway!)

mysql query result in php variable

There are a couple of mysql functions you need to look into.

  • mysql_query("query string here") : returns a resource
  • mysql_fetch_array(resource obtained above) : fetches a row and return as an array with numerical and associative(with column name as key) indices. Typically, you need to iterate through the results till expression evaluates to false value. Like the below:

    while ($row = mysql_fetch_array($query)){
        print_r $row;
    }

    Consult the manual, the links to which are provided below, they have more options to specify the format in which the array is requested. Like, you could use mysql_fetch_assoc(..) to get the row in an associative array.

Links:

In your case,

$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=mysql_query($query);
if (!$result){
    die("BAD!");
}
if (mysql_num_rows($result)==1){
    $row = mysql_fetch_array($result);
    echo "user Id: " . $row['userid'];
}
else{
    echo "not found!";
}

Get the current user, within an ApiController action, without passing the userID as a parameter

string userName;
string userId;
if (HttpContext.Current != null && HttpContext.Current.User != null 
        && HttpContext.Current.User.Identity.Name != null)
{
    userName = HttpContext.Current.User.Identity.Name;
    userId = HttpContext.Current.User.Identity.GetUserId();
}

Or based on Darrel Miller's comment, maybe use this to retrieve the HttpContext first.

// get httpContext
object httpContext;
actionContext.Request.Properties.TryGetValue("MS_HttpContext", out httpContext);    

See also:

How to access HTTPContext from within your Web API action

Get month name from date in Oracle

If you are trying to pull the value from a field, you could use:

select extract(month from [field_name])
from [table_name]

You can also insert day or year for the "month" extraction value above.

Checkout Jenkins Pipeline Git SCM with credentials?

For what it's worth adding to the discussion... what I did that ended up helping me... Since the pipeline is run within a workspace within a docker image that is cleaned up each time it runs. I grabbed the credentials needed to perform necessary operations on the repo within my pipeline and stored them in a .netrc file. this allowed me to authorize the git repo operations successfully.

withCredentials([usernamePassword(credentialsId: '<credentials-id>', passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
    sh '''
        printf "machine github.com\nlogin $GIT_USERNAME\n password $GIT_PASSWORD" >> ~/.netrc
        // continue script as necessary working with git repo...
    '''
}

Java Returning method which returns arraylist?

Your method can be called and the arraylist can be stored like this

YourClassName class = new YourClassName();
Arraylist<Integer> numbers = class.numbers(); 

This also allows the arraylist to be manipulated further in this class

How to load json into my angular.js ng-model?

I use following code, found somewhere in the internet don't remember the source though.

    var allText;
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function () {
        if (rawFile.readyState === 4) {
            if (rawFile.status === 200 || rawFile.status == 0) {
                allText = rawFile.responseText;
            }
        }
    }
    rawFile.send(null);
    return JSON.parse(allText);

'^M' character at end of lines

The easiest way is to use vi. I know that sounds terrible but its simple and already installed on most UNIX environments. The ^M is a new line from Windows/DOS environment.

from the command prompt: $ vi filename

Then press ":" to get to command mode.

Search and Replace all Globally is :%s/^M//g "Press and hold control then press V then M" which will replace ^M with nothing.

Then to write and quit enter ":wq" Done!

nginx: send all requests to a single html page

This worked for me:

location / {
    alias /path/to/my/indexfile/;
    try_files $uri /index.html;
}

This allowed me to create a catch-all URL for a javascript single-page app. All static files like css, fonts, and javascript built by npm run build will be found if they are in the same directory as index.html.

If the static files were in another directory, for some reason, you'd also need something like:

# Static pages generated by "npm run build"
location ~ ^/css/|^/fonts/|^/semantic/|^/static/ {
    alias /path/to/my/staticfiles/;
}

How to update/modify an XML file in python?

As Edan Maor explained, the quick and dirty way to do it (for [utc-16] encoded .xml files), which you should not do for the resons Edam Maor explained, can done with the following python 2.7 code in case time constraints do not allow you to learn (propper) XML parses.

Assuming you want to:

  1. Delete the last line in the original xml file.
  2. Add a line
  3. substitute a line
  4. Close the root tag.

It worked in python 2.7 modifying an .xml file named "b.xml" located in folder "a", where "a" was located in the "working folder" of python. It outputs the new modified file as "c.xml" in folder "a", without yielding encoding errors (for me) in further use outside of python 2.7.

pattern = '<Author>'
subst = '    <Author>' + domain + '\\' + user_name + '</Author>'
line_index =0 #set line count to 0 before starting
file = io.open('a/b.xml', 'r', encoding='utf-16')
lines = file.readlines()
outFile = open('a/c.xml', 'w')
for line in lines[0:len(lines)]:
    line_index =line_index +1
    if line_index == len(lines):
        #1. & 2. delete last line and adding another line in its place not writing it
        outFile.writelines("Write extra line here" + '\n')
        # 4. Close root tag:
        outFile.writelines("</phonebook>") # as in:
        #http://tizag.com/xmlTutorial/xmldocument.php
    else:
        #3. Substitue a line if it finds the following substring in a line:
        pattern = '<Author>'
        subst = '    <Author>' + domain + '\\' + user_name + '</Author>'
        if pattern in line:
            line = subst
            print line
        outFile.writelines(line)#just writing/copying all the lines from the original xml except for the last.

Specifying a custom DateTime format when serializing with Json.Net

Also available using one of the serializer settings overloads:

var json = JsonConvert.SerializeObject(someObject, new JsonSerializerSettings() { DateFormatString = "yyyy-MM-ddThh:mm:ssZ" });

Or

var json = JsonConvert.SerializeObject(someObject, Formatting.Indented, new JsonSerializerSettings() { DateFormatString = "yyyy-MM-ddThh:mm:ssZ" });

Overloads taking a Type are also available.

Calling a method every x minutes

Example of using a Timer:

using System;
using System.Timers;

static void Main(string[] args)
{
    Timer t = new Timer(TimeSpan.FromMinutes(5).TotalMilliseconds); // Set the time (5 mins in this case)
    t.AutoReset = true;
    t.Elapsed += new System.Timers.ElapsedEventHandler(your_method);
    t.Start();
}

// This method is called every 5 mins
private static void your_method(object sender, ElapsedEventArgs e)
{
    Console.WriteLine("..."); 
}

What is an 'undeclared identifier' error and how do I fix it?

They most often come from forgetting to include the header file that contains the function declaration, for example, this program will give an 'undeclared identifier' error:

Missing header

int main() {
    std::cout << "Hello world!" << std::endl;
    return 0;
}

To fix it, we must include the header:

#include <iostream>
int main() {
    std::cout << "Hello world!" << std::endl;
    return 0;
}

If you wrote the header and included it correctly, the header may contain the wrong include guard.

To read more, see http://msdn.microsoft.com/en-us/library/aa229215(v=vs.60).aspx.

Misspelled variable

Another common source of beginner's error occur when you misspelled a variable:

int main() {
    int aComplicatedName;
    AComplicatedName = 1;  /* mind the uppercase A */
    return 0;
}

Incorrect scope

For example, this code would give an error, because you need to use std::string:

#include <string>

int main() {
    std::string s1 = "Hello"; // Correct.
    string s2 = "world"; // WRONG - would give error.
}

Use before declaration

void f() { g(); }
void g() { }

g has not been declared before its first use. To fix it, either move the definition of g before f:

void g() { }
void f() { g(); }

Or add a declaration of g before f:

void g(); // declaration
void f() { g(); }
void g() { } // definition

stdafx.h not on top (VS-specific)

This is Visual Studio-specific. In VS, you need to add #include "stdafx.h" before any code. Code before it is ignored by the compiler, so if you have this:

#include <iostream>
#include "stdafx.h"

The #include <iostream> would be ignored. You need to move it below:

#include "stdafx.h"
#include <iostream>

Feel free to edit this answer.

Disabling contextual LOB creation as createClob() method threw error

For anyone who is facing this problem with Spring Boot 2

by default spring boot was using hibernate 5.3.x version, I have added following property in my pom.xml

<hibernate.version>5.4.2.Final</hibernate.version>

and error was gone. Reason for error is already explained in posts above

Overlay with spinner

As an update, for Angular 7, a very good example, loading plus http interceptor, here: https://nezhar.com/blog/create-a-loading-screen-for-angular-apps/.

For version 6, you need a small adjustment when you use Subject. You need to add the generic type.

loadingStatus: Subject<boolean> = new Subject();

I'm using angular material, so instead of a loading text, you can use mat-spinner.

<mat-spinner></mat-spinner>

Update: the code from the previous page will not complete work (regarding the interceptor part), but here you have the complete solution: https://github.com/nezhar/snypy-frontend

And as Miranda recommended into comments, here is also the solution:

The loading screen component:

loading-screen.component.ts

    import { Component, ElementRef, ChangeDetectorRef, OnDestroy, AfterViewInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { LoadingScreenService } from '../services/loading-screen.service';

@Component({
  selector: 'app-loading-screen',
  templateUrl: './loading-screen.component.html',
  styleUrls: ['./loading-screen.component.css']
})
export class LoadingScreenComponent implements AfterViewInit, OnDestroy {

  loading: boolean = false;
  loadingSubscription: Subscription;

  constructor(
    private loadingScreenService: LoadingScreenService,
    private _elmRef: ElementRef,
    private _changeDetectorRef: ChangeDetectorRef
  ) { }

  ngAfterViewInit(): void {
    this._elmRef.nativeElement.style.display = 'none';
    this.loadingSubscription = this.loadingScreenService.loadingStatus.pipe().subscribe(
      (status: boolean) => {
        this._elmRef.nativeElement.style.display = status ? 'block' : 'none';
        this._changeDetectorRef.detectChanges();
      }
    );
  }

  ngOnDestroy() {
    console.log("inside destroy loading component");
    this.loadingSubscription.unsubscribe();
  }

}

loading-screen.component.html

<div id="overlay">
  <mat-spinner class="content"></mat-spinner>
</div>

loading-screen.component.css

  #overlay {
      position: fixed; /* Sit on top of the page content */
      display: block; /* Hidden by default */
      width: 100%; /* Full width (cover the whole page) */
      height: 100%; /* Full height (cover the whole page) */
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: rgba(60, 138, 255, 0.1); /* Black background with opacity */
      opacity: 0.5;
      z-index: 2; /* Specify a stack order in case you're using a different order for other elements */
      cursor: progress; /* Add a pointer on hover */
  }

  .content {
      position: absolute;
      top: 50%;
      left: 50%;
      font-size: 50px;
      color: white;
      transform: translate(-50%, -50%);
      -ms-transform: translate(-50%, -50%);
  }

Don't forget to add the component to your root component. In my case, AppComponent

app.component.html

<app-loading-screen></app-loading-screen>

The service that will manage the component: loading-screen.service.ts

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class LoadingScreenService {

  constructor() { }

  private _loading: boolean = false;
  loadingStatus: Subject<boolean> = new Subject();

  get loading(): boolean {
    console.log("get loading: " + this._loading);
    return this._loading;
  }

  set loading(value) {
    console.log("get loading: " + value);
    this._loading = value;
    this.loadingStatus.next(value);
  }

  startLoading() {
    console.log("startLoading");
    this.loading = true;
  }

  stopLoading() {
    console.log("stopLoading");
    this.loading = false;
  }
}

Here is the http interceptor, which will show/hide the component, using the previous service.

loading-screen-interceptor.ts

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { LoadingScreenService } from '../services/loading-screen.service';
import { Observable } from 'rxjs';
import { finalize } from 'rxjs/operators';

@Injectable()
export class LoadingScreenInterceptor implements HttpInterceptor {

    activeRequests: number = 0;

    constructor(
        private loadingScreenService: LoadingScreenService
    ) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        console.log("inside interceptor");

        if (this.activeRequests === 0) {
            this.loadingScreenService.startLoading();
        }

        this.activeRequests++;

        return next.handle(request).pipe(
            finalize(() => {
                this.activeRequests--;
                if (this.activeRequests === 0) {
                    this.loadingScreenService.stopLoading();
                }
            })
        )
    };
}

And in your app.module.ts, don't forget to config the interceptor

providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: LoadingScreenInterceptor,
      multi: true
    }
  ]

Change column type in pandas

Starting pandas 1.0.0, we have pandas.DataFrame.convert_dtypes. You can even control what types to convert!

In [40]: df = pd.DataFrame(
    ...:     {
    ...:         "a": pd.Series([1, 2, 3], dtype=np.dtype("int32")),
    ...:         "b": pd.Series(["x", "y", "z"], dtype=np.dtype("O")),
    ...:         "c": pd.Series([True, False, np.nan], dtype=np.dtype("O")),
    ...:         "d": pd.Series(["h", "i", np.nan], dtype=np.dtype("O")),
    ...:         "e": pd.Series([10, np.nan, 20], dtype=np.dtype("float")),
    ...:         "f": pd.Series([np.nan, 100.5, 200], dtype=np.dtype("float")),
    ...:     }
    ...: )

In [41]: dff = df.copy()

In [42]: df 
Out[42]: 
   a  b      c    d     e      f
0  1  x   True    h  10.0    NaN
1  2  y  False    i   NaN  100.5
2  3  z    NaN  NaN  20.0  200.0

In [43]: df.dtypes
Out[43]: 
a      int32
b     object
c     object
d     object
e    float64
f    float64
dtype: object

In [44]: df = df.convert_dtypes()

In [45]: df.dtypes
Out[45]: 
a      Int32
b     string
c    boolean
d     string
e      Int64
f    float64
dtype: object

In [46]: dff = dff.convert_dtypes(convert_boolean = False)

In [47]: dff.dtypes
Out[47]: 
a      Int32
b     string
c     object
d     string
e      Int64
f    float64
dtype: object

How can I check whether a numpy array is empty or not?

You can always take a look at the .size attribute. It is defined as an integer, and is zero (0) when there are no elements in the array:

import numpy as np
a = np.array([])

if a.size == 0:
    # Do something when `a` is empty

How to scan a folder in Java?

import java.io.File;
public class Test {
    public static void main( String [] args ) {
        File actual = new File(".");
        for( File f : actual.listFiles()){
            System.out.println( f.getName() );
        }
    }
}

It displays indistinctly files and folders.

See the methods in File class to order them or avoid directory print etc.

http://java.sun.com/javase/6/docs/api/java/io/File.html

On delete cascade with doctrine2

Here is simple example. A contact has one to many associated phone numbers. When a contact is deleted, I want all its associated phone numbers to also be deleted, so I use ON DELETE CASCADE. The one-to-many/many-to-one relationship is implemented with by the foreign key in the phone_numbers.

CREATE TABLE contacts
 (contact_id BIGINT AUTO_INCREMENT NOT NULL,
 name VARCHAR(75) NOT NULL,
 PRIMARY KEY(contact_id)) ENGINE = InnoDB;

CREATE TABLE phone_numbers
 (phone_id BIGINT AUTO_INCREMENT NOT NULL,
  phone_number CHAR(10) NOT NULL,
 contact_id BIGINT NOT NULL,
 PRIMARY KEY(phone_id),
 UNIQUE(phone_number)) ENGINE = InnoDB;

ALTER TABLE phone_numbers ADD FOREIGN KEY (contact_id) REFERENCES \
contacts(contact_id) ) ON DELETE CASCADE;

By adding "ON DELETE CASCADE" to the foreign key constraint, phone_numbers will automatically be deleted when their associated contact is deleted.

INSERT INTO table contacts(name) VALUES('Robert Smith');
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8963333333', 1);
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8964444444', 1);

Now when a row in the contacts table is deleted, all its associated phone_numbers rows will automatically be deleted.

DELETE TABLE contacts as c WHERE c.id=1; /* delete cascades to phone_numbers */

To achieve the same thing in Doctrine, to get the same DB-level "ON DELETE CASCADE" behavoir, you configure the @JoinColumn with the onDelete="CASCADE" option.

<?php
namespace Entities;

use Doctrine\Common\Collections\ArrayCollection;

/**
 * @Entity
 * @Table(name="contacts")
 */
class Contact 
{

    /**
     *  @Id
     *  @Column(type="integer", name="contact_id") 
     *  @GeneratedValue
     */
    protected $id;  

    /** 
     * @Column(type="string", length="75", unique="true") 
     */ 
    protected $name; 

    /** 
     * @OneToMany(targetEntity="Phonenumber", mappedBy="contact")
     */ 
    protected $phonenumbers; 

    public function __construct($name=null)
    {
        $this->phonenumbers = new ArrayCollection();

        if (!is_null($name)) {

            $this->name = $name;
        }
    }

    public function getId()
    {
        return $this->id;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function addPhonenumber(Phonenumber $p)
    {
        if (!$this->phonenumbers->contains($p)) {

            $this->phonenumbers[] = $p;
            $p->setContact($this);
        }
    }

    public function removePhonenumber(Phonenumber $p)
    {
        $this->phonenumbers->remove($p);
    }
}

<?php
namespace Entities;

/**
 * @Entity
 * @Table(name="phonenumbers")
 */
class Phonenumber 
{

    /**
    * @Id
    * @Column(type="integer", name="phone_id") 
    * @GeneratedValue
    */
    protected $id; 

    /**
     * @Column(type="string", length="10", unique="true") 
     */  
    protected $number;

    /** 
     * @ManyToOne(targetEntity="Contact", inversedBy="phonenumbers")
     * @JoinColumn(name="contact_id", referencedColumnName="contact_id", onDelete="CASCADE")
     */ 
    protected $contact; 

    public function __construct($number=null)
    {
        if (!is_null($number)) {

            $this->number = $number;
        }
    }

    public function setPhonenumber($number)
    {
        $this->number = $number;
    }

    public function setContact(Contact $c)
    {
        $this->contact = $c;
    }
} 
?>

<?php

$em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);

$contact = new Contact("John Doe"); 

$phone1 = new Phonenumber("8173333333");
$phone2 = new Phonenumber("8174444444");
$em->persist($phone1);
$em->persist($phone2);
$contact->addPhonenumber($phone1); 
$contact->addPhonenumber($phone2); 

$em->persist($contact);
try {

    $em->flush();
} catch(Exception $e) {

    $m = $e->getMessage();
    echo $m . "<br />\n";
}

If you now do

# doctrine orm:schema-tool:create --dump-sql

you will see that the same SQL will be generated as in the first, raw-SQL example

Can I change the name of `nohup.out`?

Above methods will remove your output file data whenever you run above nohup command.

To Append output in user defined file you can use >> in nohup command.

nohup your_command >> filename.out &

This command will append all output in your file without removing old data.

Cannot import the keyfile 'blah.pfx' - error 'The keyfile may be password protected'

VSCommands 2010 (plugin for Visual Studio) can fix this for you automatically - just right-click on error and click Apply Fix from the menu. You can get it from Visual Studio gallery.

Hive query output to file

This command will redirect the output to a text file of your choice:

$hive -e "select * from table where id > 10" > ~/sample_output.txt

How to change colors of a Drawable in Android?

You can solve it using Android support compat libraries. :)

 // mutate to not share its state with any other drawable
 Drawable drawableWrap = DrawableCompat.wrap(drawable).mutate();
 DrawableCompat.setTint(drawableWrap, ContextCompat.getColor(getContext(), R.color.your_color))

APR based Apache Tomcat Native library was not found on the java.library.path?

My case: Seeing the same INFO message.

Centos 6.2 x86_64 Tomcat 6.0.24

This fixed the problem for me:

yum install tomcat-native

boom!

How to install PIP on Python 3.6?

How did you install Python, and are you using a virtual environment?
As you specifically mentioned Python 3.6, and you have not marked this as answered I will make a guess that you might have installed it using sudo add-apt-repository ppa:jonathonf/python-3.6, as this is a common way to install Python 3.6 on a Unix OS that doesn't have a native 3.6 package. If this is the case the correct way to install pip is as follows ....

Step 1) Make a Virtual Environment with Python 3.6 ...

python3.6 -m venv env --without-pip

Step 2) Activate your virtual environemnt ...

source env/bin/activate

Step 3) Install pip into your environemnt ...

curl https://bootstrap.pypa.io/get-pip.py | python3

What's the difference between window.location and document.location in JavaScript?

Despite of most people recommend here, that is how Google Analytics's dynamic protocol snipped looked like for ages (before they moved from ga.js to analytics.js recently):

ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';

More info: https://developers.google.com/analytics/devguides/collection/gajs/

In new version they used '//' so browser can automatically add protocol:

'//www.google-analytics.com/analytics.js'

So if Google prefers document.location to window.location when they need protocol in JS, I guess they have some reasons for that.

OVERALL: I personally believe that document.location and window.location are the same, but if giant with biggest stats about usage of browsers like Google using document.location, I recommend to follow them.

linux find regex

You should have a look on the -regextype argument of find, see manpage:

      -regextype type
          Changes the regular expression syntax understood by -regex and -iregex 
          tests which occur later on the command line.  Currently-implemented  
          types  are  emacs (this is the default), posix-awk, posix-basic, 
          posix-egrep and posix-extended. 

I guess the emacs type doesn't support the [[:digit:]] construct. I tried it with posix-extended and it worked as expected:

find -regextype posix-extended -regex '.*[1234567890]'
find -regextype posix-extended -regex '.*[[:digit:]]'

grunt: command not found when running from terminal

For windows

npm install -g grunt-cli

npm install load-grunt-tasks

Then run

grunt

Simple state machine example in C#?

In my opinion a state machine is not only meant for changing states but also (very important) for handling triggers/events within a specific state. If you want to understand state machine design pattern better, a good description can be found within the book Head First Design Patterns, page 320.

It is not only about the states within variables but also about handling triggers within the different states. Great chapter (and no, there is no fee for me in mentioning this :-) which contains just an easy to understand explanation.

Eclipse projects not showing up after placing project files in workspace/projects

This problems comes while .metadata of current workspace has been corrupted due to shut down Eclipse Unexpectedly. So if you face this problem just do the following steps:

  • Create a new workspace. Import your existing projects to your new workspace.

you made it!

ASP.NET MVC5/IIS Express unable to debug - Code Not Running

In my case the issue was that Virtual directory was not created.

  1. Right click on web project file and go to properties
  2. Navigate to Web
  3. Scroll down to Project Url
  4. Click Create Virtual Directory button to create virtual directory

enter image description here

Reusing output from last command in Bash

The answer is no. Bash doesn't allocate any output to any parameter or any block on its memory. Also, you are only allowed to access Bash by its allowed interface operations. Bash's private data is not accessible unless you hack it.

typedef struct vs struct definitions

The typedef, as it is with other constructs, is used to give a data type a new name. In this case it is mostly done in order to make the code cleaner:

struct myStruct blah;

vs.

myStruct blah;

What are .tpl files? PHP, web design

You have to learn Smarty syntax. That's a template system.

git diff between two different files

Specify the paths explicitly:

git diff HEAD:full/path/to/foo full/path/to/bar

Check out the --find-renames option in the git-diff docs.

Credit: twaggs.

Python vs Cpython

You should know that CPython doesn't really support multithreading (it does, but not optimal) because of the Global Interpreter Lock. It also has no Optimisation mechanisms for recursion, and has many other limitations that other implementations and libraries try to fill.

You should take a look at this page on the python wiki.

Look at the code snippets on this page, it'll give you a good idea of what an interpreter is.

Usage of MySQL's "IF EXISTS"

The accepted answer works well and one can also just use the

If Exists (...) Then ... End If; 

syntax in Mysql procedures (if acceptable for circumstance) and it will behave as desired/expected. Here's a link to a more thorough source/description: https://dba.stackexchange.com/questions/99120/if-exists-then-update-else-insert

One problem with the solution by @SnowyR is that it does not really behave like "If Exists" in that the (Select 1 = 1 ...) subquery could return more than one row in some circumstances and so it gives an error. I don't have permissions to respond to that answer directly so I thought I'd mention it here in case it saves someone else the trouble I experienced and so others might know that it is not an equivalent solution to MSSQLServer "if exists"!

Javascript date.getYear() returns 111 in 2011?

From what I've read on Mozilla's JS pages, getYear is deprecated. As pointed out many times, getFullYear() is the way to go. If you're really wanting to use getYear() add 1900 to it.

var now = new Date(),
    year = now.getYear() + 1900;

Python 3.1.1 string to hex

You've already got some good answers, but I thought you might be interested in a bit of the background too.

Firstly you're missing the quotes. It should be:

"hello".encode("hex")

Secondly this codec hasn't been ported to Python 3.1. See here. It seems that they haven't yet decided whether or not these codecs should be included in Python 3 or implemented in a different way.

If you look at the diff file attached to that bug you can see the proposed method of implementing it:

import binascii
output = binascii.b2a_hex(input)

Jenkins / Hudson environment variables

Michael,

Two things:

When Jenkins connects to a computer, it goes to the sh shell, and not the bash shell (at least this is what I have noticed - I may be wrong). So any changes you make to $PATH in your bashrc file are not considered.

Also, any changes you make to $PATH in your local shell (one that you personally ssh into) will not show up in Jenkins.

To change the path that Jenkins uses, you have two options (AFAIK):

1) Edit your /etc/profile file and add the paths that you want there

2) Go to the configuration page of your slave, and add environment variable PATH, with value: $PATH:/followed-by/paths/you/want/to/add

If you use the second option, your System Information will still not show it, but your builds will see the added paths.

Understanding ibeacon distancing

I'm very thoroughly investigating the matter of accuracy/rssi/proximity with iBeacons and I really really think that all the resources in the Internet (blogs, posts in StackOverflow) get it wrong.

davidgyoung (accepted answer, > 100 upvotes) says:

Note that the term "accuracy" here is iOS speak for distance in meters.

Actually, most people say this but I have no idea why! Documentation makes it very very clear that CLBeacon.proximity:

Indicates the one sigma horizontal accuracy in meters. Use this property to differentiate between beacons with the same proximity value. Do not use it to identify a precise location for the beacon. Accuracy values may fluctuate due to RF interference.

Let me repeat: one sigma accuracy in meters. All 10 top pages in google on the subject has term "one sigma" only in quotation from docs, but none of them analyses the term, which is core to understand this.

Very important is to explain what is actually one sigma accuracy. Following URLs to start with: http://en.wikipedia.org/wiki/Standard_error, http://en.wikipedia.org/wiki/Uncertainty

In physical world, when you make some measurement, you always get different results (because of noise, distortion, etc) and very often results form Gaussian distribution. There are two main parameters describing Gaussian curve:

  1. mean (which is easy to understand, it's value for which peak of the curve occurs).
  2. standard deviation, which says how wide or narrow the curve is. The narrower curve, the better accuracy, because all results are close to each other. If curve is wide and not steep, then it means that measurements of the same phenomenon differ very much from each other, so measurement has a bad quality.

one sigma is another way to describe how narrow/wide is gaussian curve.
It simply says that if mean of measurement is X, and one sigma is s, then 68% of all measurements will be between X - s and X + s.

Example. We measure distance and get a gaussian distribution as a result. The mean is 10m. If s is 4m, then it means that 68% of measurements were between 6m and 14m.

When we measure distance with beacons, we get RSSI and 1-meter calibration value, which allow us to measure distance in meters. But every measurement gives different values, which form gaussian curve. And one sigma (and accuracy) is accuracy of the measurement, not distance!

It may be misleading, because when we move beacon further away, one sigma actually increases because signal is worse. But with different beacon power-levels we can get totally different accuracy values without actually changing distance. The higher power, the less error.

There is a blog post which thoroughly analyses the matter: http://blog.shinetech.com/2014/02/17/the-beacon-experiments-low-energy-bluetooth-devices-in-action/

Author has a hypothesis that accuracy is actually distance. He claims that beacons from Kontakt.io are faulty beacuse when he increased power to the max value, accuracy value was very small for 1, 5 and even 15 meters. Before increasing power, accuracy was quite close to the distance values. I personally think that it's correct, because the higher power level, the less impact of interference. And it's strange why Estimote beacons don't behave this way.

I'm not saying I'm 100% right, but apart from being iOS developer I have degree in wireless electronics and I think that we shouldn't ignore "one sigma" term from docs and I would like to start discussion about it.

It may be possible that Apple's algorithm for accuracy just collects recent measurements and analyses the gaussian distribution of them. And that's how it sets accuracy. I wouldn't exclude possibility that they use info form accelerometer to detect whether user is moving (and how fast) in order to reset the previous distribution distance values because they have certainly changed.

How to use ng-if to test if a variable is defined

You can still use angular.isDefined()

You just need to set

$rootScope.angular = angular;

in the "run" phase.

See update plunkr: http://plnkr.co/edit/h4ET5dJt3e12MUAXy1mS?p=preview

Understanding the Gemfile.lock file

It seems no clear document talking on the Gemfile.lock format. Maybe it's because Gemfile.lock is just used by bundle internally.

However, since Gemfile.lock is a snapshot of Gemfile, which means all its information should come from Gemfile (or from default value if not specified in Gemfile).

For GEM, it lists all the dependencies you introduce directly or indirectly in the Gemfile. remote under GEM tells where to get the gems, which is specified by source in Gemfile.

If a gem is not fetch from remote, PATH tells the location to find it. PATH's info comes from path in Gemfile when you declare a dependency.

And PLATFORM is from here.

For DEPENDENCIES, it's the snapshot of dependencies resolved by bundle.

How does the class_weight parameter in scikit-learn work?

First off, it might not be good to just go by recall alone. You can simply achieve a recall of 100% by classifying everything as the positive class. I usually suggest using AUC for selecting parameters, and then finding a threshold for the operating point (say a given precision level) that you are interested in.

For how class_weight works: It penalizes mistakes in samples of class[i] with class_weight[i] instead of 1. So higher class-weight means you want to put more emphasis on a class. From what you say it seems class 0 is 19 times more frequent than class 1. So you should increase the class_weight of class 1 relative to class 0, say {0:.1, 1:.9}. If the class_weight doesn't sum to 1, it will basically change the regularization parameter.

For how class_weight="auto" works, you can have a look at this discussion. In the dev version you can use class_weight="balanced", which is easier to understand: it basically means replicating the smaller class until you have as many samples as in the larger one, but in an implicit way.

Rails: How do I create a default value for attributes in Rails activerecord's model?

You can do it without writing any code at all :) You just need to set the default value for the column in the database. You can do this in your migrations. For example:

create_table :projects do |t|
  t.string :status, :null => false, :default => 'P'
  ...
  t.timestamps
end

Hope that helps.

How to display a list of images in a ListView in Android?

To get the data from the database, you'd use a SimpleCursorAdapter.

I think you can directly bind the SimpleCursorAdapter to a ListView - if not, you can create a custom adapter class that extends SimpleCursorAdapter with a custom ViewBinder that overrides setViewValue.

Look at the Notepad tutorial to see how to use a SimpleCursorAdapter.

Save Screen (program) output to a file

The following might be useful (tested on: Linux/Ubuntu 12.04 (Precise Pangolin)):

cat /dev/ttyUSB0

Using the above, you can then do all the re-directions that you need. For example, to dump output to your console while saving to your file, you'd do:

cat /dev/ttyUSB0 | tee console.log

php.ini & SMTP= - how do you pass username & password

Use Mail::factory in the Mail PEAR package. Example.

Submit HTML form, perform javascript function (alert then redirect)

You need to prevent the default behaviour. You can either use e.preventDefault() or return false; In this case, the best thing is, you can use return false; here:

<form onsubmit="completeAndRedirect(); return false;">

Print all key/value pairs in a Java ConcurrentHashMap

I tested your code and works properly. I've added a small demo with another way to print all the data in the map:

ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);

for (String key : map.keySet()) {
    System.out.println(key + " " + map.get(key));
}

for (Map.Entry<String, Integer> entry : map.entrySet()) {
    String key = entry.getKey().toString();
    Integer value = entry.getValue();
    System.out.println("key, " + key + " value " + value);
}

How to select rows with NaN in particular column?

@qbzenker provided the most idiomatic method IMO

Here are a few alternatives:

In [28]: df.query('Col2 != Col2') # Using the fact that: np.nan != np.nan
Out[28]:
   Col1  Col2  Col3
1     0   NaN   0.0

In [29]: df[np.isnan(df.Col2)]
Out[29]:
   Col1  Col2  Col3
1     0   NaN   0.0

$(form).ajaxSubmit is not a function

I'm guessing you don't have a jquery form plugin included. ajaxSubmit isn't a core jquery function, I believe.

Something like this : http://jquery.malsup.com/form/

UPD

<script src="http://malsup.github.com/jquery.form.js"></script> 

com.sun.jdi.InvocationException occurred invoking method

This was my case

I had a entity Student which was having many-to-one relation with another entity Classes (the classes which he studied).

I wanted to save the data into another table, which was having foreign keys of both Student and Classes. At some instance of execution, I was bringing a List of Students under some conditions, and each Student will have a reference of Classes class.

Sample code :-

Iterator<Student> itr = studentId.iterator();
while (itr.hasNext()) 
{
    Student student = (Student) itr.next();
    MarksCardSiNoGen bo = new MarksCardSiNoGen();

    bo.setStudentId(student);

    Classes classBo = student.getClasses();

    bo.setClassId(classBo);
}

Here you can see that, I'm setting both Student and Classes reference to the BO I want to save. But while debugging when I inspected student.getClasses() it was showing this exception(com.sun.jdi.InvocationException).

The problem I found was that, after fetching the Student list using HQL query, I was flushing and closing the session. When I removed that session.close(); statement the problem was solved.

The session was closed when I finally saved all the data into table(MarksCardSiNoGen).

Hope this helps.

How do I serialize an object and save it to a file in Android?

Saving (w/o exception handling code):

FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
fos.close();

Loading (w/o exception handling code):

FileInputStream fis = context.openFileInput(fileName);
ObjectInputStream is = new ObjectInputStream(fis);
SimpleClass simpleClass = (SimpleClass) is.readObject();
is.close();
fis.close();

How do I provide a username and password when running "git clone [email protected]"?

Though there are many answers, myself facing the repeated issue when username or password has special characters in it.

URL encode your username and password for git, then use it as part of URL itself (when there is no security concern).

Say, URL encoded value of username

'user+1' is user%2B1

and URL encoded value of password

'Welcome@1234' is Welcome%401234

Then your GIT Clone URL would look like,

git clone https://user%2B1:Welcome%401234@actual-git-url-for-the-repo works perfectly, whereas,

git clone https://user+1:Welcome@1234@actual-git-url-for-the-repo gives you 403 errors

Hope this helps.

Just in case, want to URL encode online: https://www.urlencoder.org/

Rest-assured. Is it possible to extract value from request json?

JsonPath jsonPathEvaluator = response.jsonPath();
return jsonPathEvaluator.get("user_id").toString();

How to use BigInteger?

BigInteger is an immutable class. So whenever you do any arithmetic, you have to reassign the output to a variable.

Xcode - iPhone - profile doesn't match any valid certificate-/private-key pair in the default keychain

My problem was my Target profile didn't have the proper code signing option selected:

Target Menu -> Code Signing -> Code Signing Identity

Choose "iPhone developer" then select the provisional profile you created.

Is there an addHeaderView equivalent for RecyclerView?

you can create addHeaderView and use

adapter.addHeaderView(View).

This code build the addHeaderView for more then one header. the headers should have:

android:layout_height="wrap_content"

public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final int TYPE_ITEM = -1;
    public class MyViewSHolder extends RecyclerView.ViewHolder {
        public MyViewSHolder (View view) {
            super(view);
        }
        // put you code. for example:
        View mView;
        ...
    }

    public class ViewHeader extends RecyclerView.ViewHolder {
        public ViewHeader(View view) {
            super(view);
        }
    }

    private List<View> mHeaderViews = new ArrayList<>();
    public void addHeaderView(View headerView) {
        mHeaderViews.add(headerView);
    }

    @Override
    public int getItemCount() {
       return ... + mHeaderViews.size();
    }

    @Override
    public int getItemViewType(int position) {
        if (mHeaderViews.size() > position) {
            return position;
        }

        return TYPE_ITEM;
    }
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType != TYPE_ITEM) {
            //inflate your layout and pass it to view holder
            return new ViewHeader(mHeaderViews.get(viewType));
        }
        ...
    }
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int basePosition1) {
        if (holder instanceof ViewHeader) {
            return;
        }
        int basePosition = basePosition1 -  mHeaderViews.size();
        ...
    }
}

How to compare strings in C conditional preprocessor-directives

[UPDATE: 2021.01.04]

One thing that has changed since I first posted this in 2014, is the format of #pragma message.

Nowadays, the parens are required!

#pragma message ("USER    IS " USER)
#pragma message ("USER_VS IS " USER_VS)

That said, the 2016 code (using characters, not strings) still works in VS2019.

But, as @Artyer points out, the version involving c_strcmp will NOT work in ANY modern compiler.

[UPDATE: 2018.05.03]

CAVEAT: Not all compilers implement the C++11 specification in the same way. The below code works in the compiler I tested on, while many commenters used a different compiler.

Quoting from Shafik Yaghmour's answer at: Computing length of a C string at compile time. Is this really a constexpr?

Constant expressions are not guaranteed to be evaluated at compile time, we only have a non-normative quote from draft C++ standard section 5.19 Constant expressions that says this though:

[...]>[ Note: Constant expressions can be evaluated during translation.—end note ]

That word can makes all the difference in the world.

So, YMMV on this (or any) answer involving constexpr, depending on the compiler writer's interpretation of the spec.

[UPDATED 2016.01.31]

As some didn't like my earlier answer because it avoided the whole compile time string compare aspect of the OP by accomplishing the goal with no need for string compares, here is a more detailed answer.

You can't! Not in C98 or C99. Not even in C11. No amount of MACRO manipulation will change this.

The definition of const-expression used in the #if does not allow strings.

It does allow characters, so if you limit yourself to characters you might use this:

#define JACK 'J'
#define QUEEN 'Q'

#define CHOICE JACK     // or QUEEN, your choice

#if 'J' == CHOICE
#define USER "jack"
#define USER_VS "queen"
#elif 'Q' == CHOICE
#define USER "queen"
#define USER_VS "jack"
#else
#define USER "anonymous1"
#define USER_VS "anonymous2"
#endif

#pragma message "USER    IS " USER
#pragma message "USER_VS IS " USER_VS

You can! In C++11. If you define a compile time helper function for the comparison.

[2021.01.04: CAVEAT: This does not work in any MODERN compiler. See comment by @Artyer.]

// compares two strings in compile time constant fashion
constexpr int c_strcmp( char const* lhs, char const* rhs )
{
    return (('\0' == lhs[0]) && ('\0' == rhs[0])) ? 0
        :  (lhs[0] != rhs[0]) ? (lhs[0] - rhs[0])
        : c_strcmp( lhs+1, rhs+1 );
}
// some compilers may require ((int)lhs[0] - (int)rhs[0])

#define JACK "jack"
#define QUEEN "queen"

#define USER JACK       // or QUEEN, your choice

#if 0 == c_strcmp( USER, JACK )
#define USER_VS QUEEN
#elif 0 == c_strcmp( USER, QUEEN )
#define USER_VS JACK
#else
#define USER_VS "unknown"
#endif

#pragma message "USER    IS " USER
#pragma message "USER_VS IS " USER_VS

So, ultimately, you will have to change the way you accomlish your goal of choosing final string values for USER and USER_VS.

You can't do compile time string compares in C99, but you can do compile time choosing of strings.

If you really must do compile time sting comparisons, then you need to change to C++11 or newer variants that allow that feature.

[ORIGINAL ANSWER FOLLOWS]

Try:

#define jack_VS queen
#define queen_VS jack

#define USER jack          // jack    or queen, your choice
#define USER_VS USER##_VS  // jack_VS or queen_VS

// stringify usage: S(USER) or S(USER_VS) when you need the string form.
#define S(U) S_(U)
#define S_(U) #U

UPDATE: ANSI token pasting is sometimes less than obvious. ;-D

Putting a single # before a macro causes it to be changed into a string of its value, instead of its bare value.

Putting a double ## between two tokens causes them to be concatenated into a single token.

So, the macro USER_VS has the expansion jack_VS or queen_VS, depending on how you set USER.

The stringify macro S(...) uses macro indirection so the value of the named macro gets converted into a string. instead of the name of the macro.

Thus USER##_VS becomes jack_VS (or queen_VS), depending on how you set USER.

Later, when the stringify macro is used as S(USER_VS) the value of USER_VS (jack_VS in this example) is passed to the indirection step S_(jack_VS) which converts its value (queen) into a string "queen".

If you set USER to queen then the final result is the string "jack".

For token concatenation, see: https://gcc.gnu.org/onlinedocs/cpp/Concatenation.html

For token string conversion, see: https://gcc.gnu.org/onlinedocs/cpp/Stringification.html#Stringification

[UPDATED 2015.02.15 to correct a typo.]

Bootstrap 3 - Responsive mp4-video

Tip for MULTIPLE VIDEOS on a page: I recently solved an issue with no mp4 playback in Chrome or Firefox (played fine in IE) in a page with 16 videos in modals (bootstrap 3) after discovering the frame rates of all the videos must be identical. I had 6 videos at 25fps and 12 at 29.97fps... after rendering all to 25fps versions, everything runs smooth across all browsers.

jQuery: outer html()

If you don't want to add a wrapper, you could just add the code manually, since you know the ID you are targeting:

var myID = "xxx";

var newCode = "<div id='"+myID+"'>"+$("#"+myID).html()+"</div>";

Don't change link color when a link is clicked

I think this suits perfect for any color you have:

a {
    color: inherit;
}

Vagrant error : Failed to mount folders in Linux guest

I experienced the same issue with Centos 7, I assume due to an outdated kernel in combination with an updated version of VirtualBox. Based on Blizz's update, this is what worked for me (vagrant-vbguest plugin already installed):

vagrant ssh
sudo yum -y install kernel-devel
sudo yum -y update
exit
vagrant reload --provision

How do ports work with IPv6?

The protocols used in IPv6 are the same as the protocols in IPv4. The only thing that changed between the two versions is the addressing scheme, DHCP [DHCPv6] and ICMP [ICMPv6]. So basically, anything TCP/UDP related, including the port range (0-65535) remains unchanged.

Edit: Port 0 is a reserved port in TCP but it does exist. See RFC793

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

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.get("http://www.google.com");

OR

import org.openqa.selenium.support.ui.ExpectedConditions;

WebDriverWait wait = new WebDriverWait(driver,30);
driver.get("http://www.google.com");
//hplogo is the id of Google logo on google.com
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("hplogo")));

Java: int[] array vs int array[]

They are both basically same, there is no difference in performance of any sort, the recommended one however is the first case as it is more readable.

int[] array = new int[10];

FROM JLS:

The [] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both.

Working with time DURATION, not time of day

I don't know how to make the chart label the axis in the format "X1 min : X2 sec", but here's another way to get durations, in the format of minutes with decimals representing seconds (.5 = 30 sec, .25 = 15 sec, etc.)

Suppose in column A you have your time data, for example in cell A1 you have 12:03:06, which your 3min 6sec data misinterpreted as 3:06 past midnight, and column B is free.

In cell B1 enter this formula: =MINUTE(A1) + SECOND(A1)/60 and hit enter/return. Grab the lower right corner of cell B2 and drag as far down as the A column goes to apply the formula to all data in col A.

Last step, be sure to highlight all of column B and set it to Number format (the application of the formula may have automatically set format to Time).

How can I commit a single file using SVN over a network?

strange that your command works, i thougth it would need a target directory. but it looks like it assumes current pwd as default.

cd myapp
svn ci page1.html

you can also just do svn ci in or on that folder and it will detect all changes automatically and give you a list of what will be checked in

man svn tells you the rest

Same Navigation Drawer in different Activities

Easiest way to reuse a common Navigation drawer among a group of activities

app_base_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    android:id="@+id/drawer_layout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <FrameLayout
        android:id="@+id/view_stub"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </FrameLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/navigation_view"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:menu="@menu/menu_test"
        />
</android.support.v4.widget.DrawerLayout>

AppBaseActivity.java

/*
* This is a simple and easy approach to reuse the same 
* navigation drawer on your other activities. Just create
* a base layout that conains a DrawerLayout, the 
* navigation drawer and a FrameLayout to hold your
* content view. All you have to do is to extend your 
* activities from this class to set that navigation 
* drawer. Happy hacking :)
* P.S: You don't need to declare this Activity in the 
* AndroidManifest.xml. This is just a base class.
*/
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

public abstract class AppBaseActivity extends AppCompatActivity implements MenuItem.OnMenuItemClickListener {
    private FrameLayout view_stub; //This is the framelayout to keep your content view
    private NavigationView navigation_view; // The new navigation view from Android Design Library. Can inflate menu resources. Easy
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;
    private Menu drawerMenu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.app_base_layout);// The base layout that contains your navigation drawer.
        view_stub = (FrameLayout) findViewById(R.id.view_stub);
        navigation_view = (NavigationView) findViewById(R.id.navigation_view);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, 0, 0);
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        drawerMenu = navigation_view.getMenu();
        for(int i = 0; i < drawerMenu.size(); i++) {
          drawerMenu.getItem(i).setOnMenuItemClickListener(this);
        }
        // and so on...
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    /* Override all setContentView methods to put the content view to the FrameLayout view_stub
     * so that, we can make other activity implementations looks like normal activity subclasses.
     */
    @Override
    public void setContentView(int layoutResID) {
        if (view_stub != null) {
            LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
            ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            View stubView = inflater.inflate(layoutResID, view_stub, false);
            view_stub.addView(stubView, lp);
        }
    }

    @Override
    public void setContentView(View view) {
        if (view_stub != null) {
            ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            view_stub.addView(view, lp);
        }
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        if (view_stub != null) {
            view_stub.addView(view, params);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Pass the event to ActionBarDrawerToggle, if it returns
        // true, then it has handled the app icon touch event
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle your other action bar items...

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.item1:
                // handle it
                break;
            case R.id.item2:
                // do whatever
                break;
            // and so on...
        }
        return false;
    }
}

Python: Adding element to list while iterating

In short: If you'are absolutely sure all new objects fail somecond() check, then your code works fine, it just wastes some time iterating the newly added objects.

Before giving a proper answer, you have to understand why it considers a bad idea to change list/dict while iterating. When using for statement, Python tries to be clever, and returns a dynamically calculated item each time. Take list as example, python remembers a index, and each time it returns l[index] to you. If you are changing l, the result l[index] can be messy.

NOTE: Here is a stackoverflow question to demonstrate this.

The worst case for adding element while iterating is infinite loop, try(or not if you can read a bug) the following in a python REPL:

import random

l = [0]
for item in l:
    l.append(random.randint(1, 1000))
    print item

It will print numbers non-stop until memory is used up, or killed by system/user.

Understand the internal reason, let's discuss the solutions. Here are a few:

1. make a copy of origin list

Iterating the origin list, and modify the copied one.

result = l[:]
for item in l:
    if somecond(item):
        result.append(Obj())

2. control when the loop ends

Instead of handling control to python, you decides how to iterate the list:

length = len(l)
for index in range(length):
    if somecond(l[index]):
        l.append(Obj())

Before iterating, calculate the list length, and only loop length times.

3. store added objects in a new list

Instead of modifying the origin list, store new object in a new list and concatenate them afterward.

added = [Obj() for item in l if somecond(item)]
l.extend(added)

Adding data attribute to DOM

in Jquery "data" doesn't refresh by default :

alert($('#outer').html());
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').data("myval","20"); //setter
alert($('#outer').html());

You'd use "attr" instead for live update:

alert($('#outer').html());
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').attr("data-myval","20"); //setter
alert($('#outer').html());

How to open a Bootstrap modal window using jQuery?

<script type="text/javascript">
    $(function () {
        $("mybtn").click(function () {
            $("#my-modal").modal("show");
        });
    });
</script>

Can I force pip to reinstall the current version?

pip install --upgrade --force-reinstall <package>

When upgrading, reinstall all packages even if they are already up-to-date.

pip install -I <package>
pip install --ignore-installed <package>

Ignore the installed packages (reinstalling instead).

Table fixed header and scrollable body

Fixed table head - CSS-only

Simply position: sticky; top: 0; your th elements. (Chrome, FF, Edge)

_x000D_
_x000D_
.tableFixHead          { overflow-y: auto; height: 100px; }_x000D_
.tableFixHead thead th { position: sticky; top: 0; }_x000D_
_x000D_
/* Just common table stuff. Really. */_x000D_
table  { border-collapse: collapse; width: 100%; }_x000D_
th, td { padding: 8px 16px; }_x000D_
th     { background:#eee; }
_x000D_
<div class="tableFixHead">_x000D_
  <table>_x000D_
    <thead>_x000D_
      <tr><th>TH 1</th><th>TH 2</th></tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
      <tr><td>A1</td><td>A2</td></tr>_x000D_
      <tr><td>B1</td><td>B2</td></tr>_x000D_
      <tr><td>C1</td><td>C2</td></tr>_x000D_
      <tr><td>D1</td><td>D2</td></tr>_x000D_
      <tr><td>E1</td><td>E2</td></tr>_x000D_
    </tbody>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

TH borders problem fix

Since border cannot be painted properly on a translated TH element, to recreate and render "borders" use the box-shadow property:

/* Borders (if you need them) */
.tableFixHead,
.tableFixHead td {
  box-shadow: inset 1px -1px #000;
}
.tableFixHead th {
  box-shadow: inset 1px 1px #000, 0 1px #000;
}

_x000D_
_x000D_
.tableFixHead          { overflow-y: auto; height: 100px; }_x000D_
.tableFixHead thead th { position: sticky; top: 0; }_x000D_
_x000D_
/* Just common table stuff. Really. */_x000D_
table  { border-collapse: collapse; width: 100%; }_x000D_
th, td { padding: 8px 16px; }_x000D_
th     { background:#eee; }_x000D_
_x000D_
/* Borders (if you need them) */_x000D_
.tableFixHead,_x000D_
.tableFixHead td {_x000D_
  box-shadow: inset 1px -1px #000;_x000D_
}_x000D_
.tableFixHead th {_x000D_
  box-shadow: inset 1px 1px #000, 0 1px #000;_x000D_
}
_x000D_
<div class="tableFixHead">_x000D_
  <table>_x000D_
    <thead>_x000D_
      <tr><th>TH 1</th><th>TH 2</th></tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
      <tr><td>A1</td><td>A2</td></tr>_x000D_
      <tr><td>B1</td><td>B2</td></tr>_x000D_
      <tr><td>C1</td><td>C2</td></tr>_x000D_
      <tr><td>D1</td><td>D2</td></tr>_x000D_
      <tr><td>E1</td><td>E2</td></tr>_x000D_
    </tbody>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Fixed table head - using JS. (IE)

You can use a bit of JS and translateY the th elements

jQuery example

_x000D_
_x000D_
var $th = $('.tableFixHead').find('thead th')_x000D_
$('.tableFixHead').on('scroll', function() {_x000D_
  $th.css('transform', 'translateY('+ this.scrollTop +'px)');_x000D_
});
_x000D_
.tableFixHead { overflow-y: auto; height: 100px; }_x000D_
_x000D_
/* Just common table stuff. */_x000D_
table  { border-collapse: collapse; width: 100%; }_x000D_
th, td { padding: 8px 16px; }_x000D_
th     { background:#eee; }
_x000D_
<div class="tableFixHead">_x000D_
  <table>_x000D_
    <thead>_x000D_
      <tr><th>TH 1</th><th>TH 2</th></tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
      <tr><td>A1</td><td>A2</td></tr>_x000D_
      <tr><td>B1</td><td>B2</td></tr>_x000D_
      <tr><td>C1</td><td>C2</td></tr>_x000D_
      <tr><td>D1</td><td>D2</td></tr>_x000D_
      <tr><td>E1</td><td>E2</td></tr>_x000D_
    </tbody>_x000D_
  </table>_x000D_
</div>_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
_x000D_
_x000D_
_x000D_

Or plain ES6 if you prefer (no jQuery required):

// Fix table head
function tableFixHead (e) {
    const el = e.target,
          sT = el.scrollTop;
    el.querySelectorAll("thead th").forEach(th => 
      th.style.transform = `translateY(${sT}px)`
    );
}
document.querySelectorAll(".tableFixHead").forEach(el => 
    el.addEventListener("scroll", tableFixHead)
);

Running CMD command in PowerShell

For those who may need this info:

I figured out that you can pretty much run a command that's in your PATH from a PS script, and it should work.

Sometimes you may have to pre-launch this command with cmd.exe /c

Examples

Calling git from a PS script

I had to repackage a git client wrapped in Chocolatey (for those who may not know, it's a kind of app-store for Windows) which massively uses PS scripts.

I found out that, once git is in the PATH, commands like

$ca_bundle = git config --get http.sslCAInfo

will store the location of git crt file in $ca_bundle variable.

Looking for an App

Another example that is a combination of the present SO post and this SO post is the use of where command

$java_exe = cmd.exe /c where java

will store the location of java.exe file in $java_exe variable.

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

Use BigDecimal.valueOf(double d) instead of new BigDecimal(double d). The last one has precision errors by float and double.

How to initialize an array's length in JavaScript?

With ES2015 .fill() you can now simply do:

// `n` is the size you want to initialize your array
// `0` is what the array will be filled with (can be any other value)
Array(n).fill(0)

Which is a lot more concise than Array.apply(0, new Array(n)).map(i => value)

It is possible to drop the 0 in .fill() and run without arguments, which will fill the array with undefined. (However, this will fail in Typescript)

java, get set methods

your panel class don't have a constructor that accepts a string

try change

RLS_strid_panel p = new RLS_strid_panel(namn1);

to

RLS_strid_panel p = new RLS_strid_panel();
p.setName1(name1);

"NoClassDefFoundError: Could not initialize class" error

I had this:

 class Util {
  static boolean isNeverAsync = System.getenv().get("asyncc_exclude_redundancy").equals("yes");
}

you can probably see the problem, the env var might return null instead of string. So just to test my theory, I changed it to:

 class Util {
  static boolean isNeverAsync = false;
}

and the problem went away. Too bad that Java can't give you the exact stack trace of the error though, kinda weird.

How to get div height to auto-adjust to background size?

Pretty sure this will never been seen all the way down here. But if your problem was the same as mine, this was my solution:

.imaged-container{
  background-image:url('<%= asset_path("landing-page.png") %> ');
  background-repeat: no-repeat;
  background-size: 100%;
  height: 65vw;
}

I wanted to have a div in the center of the image, and this will allow me of that.

Find duplicates and delete all in notepad++

You need the textFX plugin. Then, just follow these instructions:

Paste the text into Notepad++ (CTRL+V). ...
Mark all the text (CTRL+A). ...
Click TextFX ? Click TextFX Tools ? Click Sort lines case insensitive (at column)
Duplicates and blank lines have been removed and the data has been sorted alphabetically.

Personally, I would use sort -i -u source >dest instead of notepad++

The number of method references in a .dex file cannot exceed 64k API 17

Do this, it works:

defaultConfig {
    applicationId "com.example.maps"
    minSdkVersion 15
    targetSdkVersion 24
    versionCode 1
    versionName "1.0"
    multiDexEnabled true
}

How do I escape double quotes in attributes in an XML String in T-SQL?

tSql escapes a double quote with another double quote. So if you wanted it to be part of your sql string literal you would do this:

declare @xml xml 
set @xml = "<transaction><item value=""hi"" /></transaction>"

If you want to include a quote inside a value in the xml itself, you use an entity, which would look like this:

declare @xml xml
set @xml = "<transaction><item value=""hi &quot;mom&quot; lol"" /></transaction>"

How to update specific key's value in an associative array in PHP?

Change your foreach to something like this, You are not assigning data back to your return variable $data after performing operation on that.

foreach($data as $key => $value)
{
  $data[$key]['transaction_date'] = date('d/m/Y',$value['transaction_date']);
}

Codepad DEMO.

jQuery Ajax File Upload

Here was an idea i was thinking of:

Have an iframe on page and have a referencer.

Have a form in which you move the INPUT:File element to.

Form:  A processing page AND a target of the FRAME.

The result will post to the frame, and then you can just send the fetched data up a level to the image tag you want with something like:

data:image/png;base64,asdfasdfasdfasdfa

and the page loads.

I believe it works for me, and depending you might be able to do something like:

.aftersubmit(function(){
    stopPropigation()// or some other code which would prevent a refresh.
});

How to select all the columns of a table except one column?

Create a view. Yes, in the view creation statement, you will have to list each...and...every...field...by...name.

Once.

Then just select * from viewname after that.

Array to String PHP?

$data = array("asdcasdc","35353","asdca353sdc","sadcasdc","sadcasdc","asdcsdcsad");

$string_array = json_encode($data);

now you can insert this $string_array value into Database

Function is not defined - uncaught referenceerror

How about removing the onclick attribute and adding an ID:

<input type="image" src="btn.png" alt="" id="img-clck" />

And your script:

$(document).ready(function(){
    function codeAddress() {
        var address = document.getElementById("formatedAddress").value;
        geocoder.geocode( { 'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
            }
        });
    }
    $("#img-clck").click(codeAddress);
});

This way if you need to change the function name or whatever no need to touch the html.

How to make Twitter Bootstrap tooltips have multiple lines?

In Angular UI Bootstrap 0.13.X, tooltip-html-unsafe has been deprecated. You should now use tooltip-html and $sce.trustAsHtml() to accomplish a tooltip with html.

https://github.com/angular-ui/bootstrap/commit/e31fcf0fcb06580064d1e6375dbedb69f1c95f25

<a href="#" tooltip-html="htmlTooltip">Check me out!</a>

$scope.htmlTooltip = $sce.trustAsHtml('I\'ve been made <b>bold</b>!');

Is it possible to auto-format your code in Dreamweaver?

For the 2017 CC release this has been moved (after many years of habit development). Find it now at:

Edit > Code > Apply Source Formatting.

It may be prudent to set up a keyboard shortcut if this is something you'll need regularly.

Edit > Keyboard Shortcuts

how to stop a running script in Matlab

Since you mentioned Task Manager, I'll guess you're using Windows. Assuming you're running your script within the editor, if you aren't opposed to quitting the editor at the same time as quitting the running program, the keyboard shortcut to end a process is:

Alt + F4

(By which I mean press the 'Alt' and 'F4' keys on your keyboard simultaneously.)

Alternatively, as mentioned in other answers,

Ctrl + C

should also work, but will not quit the editor.

How to use zIndex in react-native

UPDATE: Supposedly, zIndex has been added to the react-native library. I've been trying to get it to work without success. Check here for details of the fix.

How to change owner of PostgreSql database?

Frank Heikens answer will only update database ownership. Often, you also want to update ownership of contained objects (including tables). Starting with Postgres 8.2, REASSIGN OWNED is available to simplify this task.

IMPORTANT EDIT!

Never use REASSIGN OWNED when the original role is postgres, this could damage your entire DB instance. The command will update all objects with a new owner, including system resources (postgres0, postgres1, etc.)


First, connect to admin database and update DB ownership:

psql
postgres=# REASSIGN OWNED BY old_name TO new_name;

This is a global equivalent of ALTER DATABASE command provided in Frank's answer, but instead of updating a particular DB, it change ownership of all DBs owned by 'old_name'.

The next step is to update tables ownership for each database:

psql old_name_db
old_name_db=# REASSIGN OWNED BY old_name TO new_name;

This must be performed on each DB owned by 'old_name'. The command will update ownership of all tables in the DB.

StringIO in Python3

In my case I have used:

from io import StringIO

jQuery posting JSON

'data' should be a stringified JavaScript object:

data: JSON.stringify({ "userName": userName, "password" : password })

To send your formData, pass it to stringify:

data: JSON.stringify(formData)

Some servers also require the application/json content type:

contentType: 'application/json'

There's also a more detailed answer to a similar question here: Jquery Ajax Posting json to webservice

When should I use Memcache instead of Memcached?

When using Windows, the comparison is cut short: memcache appears to be the only client available.

Windows ignores JAVA_HOME: how to set JDK as default?

In my case I had Java 7 and 8 (both x64) installed and I want to redirect to java 7 but everything is set to use Java 8. Java uses the PATH environment variable:

C:\ProgramData\Oracle\Java\javapath

as the first option to look for its folder runtime (is a hidden folder). This path contains 3 symlinks that can't be edited.

In my pc, the PATH environment variable looks like this:

C:\ProgramData\Oracle\Java\javapath;C:\Windows\System32;C:\Program Files\Java\jdk1.7.0_21\bin;

In my case, It should look like this:

C:\Windows\System32;C:\Program Files\Java\jdk1.7.0_21\bin;

I had to cut and paste the symlinks to somewhere else so java can't find them, and I can restore them later.

After setting the JAVA_HOME and JRE_HOME environment variables to the desired java folders' runtimes (in my case it is Java 7), the command java -version should show your desired java runtime. I remark there's no need to mess with the registry.

Tested on Win7 x64.

UML diagram shapes missing on Visio 2013

Please check this KB article : http://support.microsoft.com/kb/2259709 This issue occurs because Visio 2013 uses new UML and database modeling templates that are not used by Visio 2010 or by earlier versions of Visio. And it applies to both :

"Microsoft Visio Professional 2013" and "Microsoft Visio Standard 2013"

So upgrading to Pro might not help as well.

How to get file creation & modification date/times in Python?

os.stat returns a named tuple with st_mtime and st_ctime attributes. The modification time is st_mtime on both platforms; unfortunately, on Windows, ctime means "creation time", whereas on POSIX it means "change time". I'm not aware of any way to get the creation time on POSIX platforms.

How can I format a decimal to always show 2 decimal places?

The OP always wants two decimal places displayed, so explicitly calling a formatting function, as all the other answers have done, is not good enough.

As others have already pointed out, Decimal works well for currency. But Decimal shows all the decimal places. So, override its display formatter:

class D(decimal.Decimal):
    def __str__(self):
        return f'{self:.2f}'  

Usage:

>>> cash = D(300000.991)
>>> print(cash)
300000.99

Simple.

A message body writer for Java type, class myPackage.B, and MIME media type, application/octet-stream, was not found

This can also happen if you've recently upgraded Ant. I was using Ant 1.8.4 on a project, and upgraded Ant to 1.9.4, and started to get this error when building a fat jar using Ant.

The solution for me was to downgrade back to Ant 1.8.4 for the command line and Eclipse using the process detailed here

how to put image in a bundle and pass it to another activity

So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.

 protected void onCreate(Bundle savedInstanceState) {     setContentView(R.layout.my_layout);     Bitmap bitmap = getIntent().getParcelableExtra("image");     ImageView imageView = (ImageView) findViewById(R.id.imageview);     imageView.setImageBitmap(bitmap);  } 

Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style

I found it useful (where I wanted to ignore line feeds and not change any files) to ignore them in the .eslintrc using linebreak-style as per this answer: https://stackoverflow.com/a/43008668/1129108

module.exports = {
  extends: 'google',
  quotes: [2, 'single'],
  globals: {
    SwaggerEditor: false
  },
  env: {
    browser: true
  },
  rules:{
    "linebreak-style": 0
  }
};

What is the difference between =Empty and IsEmpty() in VBA (Excel)?

I believe IsEmpty is just method that takes return value of Cell and checks if its Empty so: IsEmpty(.Cell(i,1)) does ->

return .Cell(i,1) <> Empty

SQLException: No suitable driver found for jdbc:derby://localhost:1527

You can also get the same error if the Java DB server has not been started.

Java SSLHandshakeException "no cipher suites in common"

Server

import java.net.*;
import java.io.*;
import java.util.*;
import javax.net.ssl.*;
import javax.net.*;
class Test{
  public static void main(String[] args){
    try{
      SSLContext context = SSLContext.getInstance("TLSv1.2");
      context.init(null,null,null);
      SSLServerSocketFactory serverSocketFactory = context.getServerSocketFactory();
      SSLServerSocket server = (SSLServerSocket)serverSocketFactory.createServerSocket(1024);
      server.setEnabledCipherSuites(server.getSupportedCipherSuites());
      SSLSocket socket = (SSLSocket)server.accept();
      DataInputStream in = new DataInputStream(socket.getInputStream());
      DataOutputStream out = new DataOutputStream(socket.getOutputStream());
      System.out.println(in.readInt());
    }catch(Exception e){e.printStackTrace();}
  }
}

Client

import java.net.*;
import java.io.*;
import java.util.*;
import javax.net.ssl.*;
import javax.net.*;
class Test2{
  public static void main(String[] args){
    try{
      SSLContext context = SSLContext.getInstance("TLSv1.2");
      context.init(null,null,null);
      SSLSocketFactory socketFactory = context.getSocketFactory();
      SSLSocket socket = (SSLSocket)socketFactory.createSocket("localhost", 1024);
      socket.setEnabledCipherSuites(socket.getSupportedCipherSuites());
      DataInputStream in = new DataInputStream(socket.getInputStream());
      DataOutputStream out = new DataOutputStream(socket.getOutputStream());
      out.writeInt(1337);     
    }catch(Exception e){e.printStackTrace();}
  }
}

server.setEnabledCipherSuites(server.getSupportedCipherSuites()); socket.setEnabledCipherSuites(socket.getSupportedCipherSuites());

Draggable div without jQuery UI

This is mine. http://jsfiddle.net/pd1vojsL/

3 draggable buttons in a div, dragging constrained by div.

<div id="parent" class="parent">
    <button id="button1" class="button">Drag me</button>
    <button id="button2" class="button">Drag me</button>
    <button id="button3" class="button">Drag me</button>
</div>
<div id="log1"></div>
<div id="log2"></div>

Requires JQuery (only):

$(function() {
    $('.button').mousedown(function(e) {
        if(e.which===1) {
            var button = $(this);
            var parent_height = button.parent().innerHeight();
            var top = parseInt(button.css('top')); //current top position
            var original_ypos = button.css('top','').position().top; //original ypos (without top)
            button.css({top:top+'px'}); //restore top pos
            var drag_min_ypos = 0-original_ypos;
            var drag_max_ypos = parent_height-original_ypos-button.outerHeight();
            var drag_start_ypos = e.clientY;
            $('#log1').text('mousedown top: '+top+', original_ypos: '+original_ypos);
            $(window).on('mousemove',function(e) {
                //Drag started
                button.addClass('drag');
                var new_top = top+(e.clientY-drag_start_ypos);
                button.css({top:new_top+'px'});
                if(new_top<drag_min_ypos) { button.css({top:drag_min_ypos+'px'}); }
                if(new_top>drag_max_ypos) { button.css({top:drag_max_ypos+'px'}); }
                $('#log2').text('mousemove min: '+drag_min_ypos+', max: '+drag_max_ypos+', new_top: '+new_top);
                //Outdated code below (reason: drag contrained too early)
                /*if(new_top>=drag_min_ypos&&new_top<=drag_max_ypos) {
                    button.css({top:new_top+'px'});
                }*/
            });
            $(window).on('mouseup',function(e) {
                 if(e.which===1) {
                    //Drag finished
                    $('.button').removeClass('drag');
                    $(window).off('mouseup mousemove');
                    $('#log1').text('mouseup');
                    $('#log2').text('');
                 }
            });
        }
    });
});

jQuery add class .active on menu

This works for me, basically the navigation is same

<div id="main-menu">
  <ul>
    <li><a href="<?php echo base_url();?>shop">SHOP</a>
    <li><a href="<?php echo base_url();?>events">EVENTS</a>
    <li><a href="<?php echo base_url();?>services">SERVICES</a>
  </ul>
</div>

Let's say you're at the URL : http://localhost/project_name/shop/detail_shop/

And you want the "SHOP" li link to get class "active" so you can visually indicate it's the active navigation, even if you're at the sub page of "shop" at "detail_shop".

The javascript :

var path = window.location.pathname;
var str = path.split("/");
var url = document.location.protocol + "//" + document.location.hostname + "/" + str[1] + "/" + str[2];

$('#main-menu a[href="' + url + '"]').parent('li').addClass('active');
  1. str will get ,project_name,shop,detail_shop
  2. document.location.protocol will get http:
  3. document.location.hostname will get localhost
  4. str[1] will get project_name
  5. str[2] will get shop

Essentially that will match links in the nav who's href attribute begins with "shop" (or whatever the secondary directory happens to be).

Submit form using <a> tag

You can use hidden submit button and click it using java script/jquery like this:

  <form id="contactForm" method="post" class="contact-form">

        <button type="submit" id="submitBtn" style="display:none;" data-validate="contact-form">Hidden Button</button>
        <a href="javascript:;" class="myClass" onclick="$('#submitBtn').click();">Submit</a>

  </form>

Simplest way to do grouped barplot

with ggplot2:

library(ggplot2)
Animals <- read.table(
  header=TRUE, text='Category        Reason Species
1   Decline       Genuine      24
2  Improved       Genuine      16
3  Improved Misclassified      85
4   Decline Misclassified      41
5   Decline     Taxonomic       2
6  Improved     Taxonomic       7
7   Decline       Unclear      41
8  Improved       Unclear     117')

ggplot(Animals, aes(factor(Reason), Species, fill = Category)) + 
  geom_bar(stat="identity", position = "dodge") + 
  scale_fill_brewer(palette = "Set1")

Bar Chart

remove table row with specific id

ID attributes cannot start with a number and they should be unique. In any case, you can use :eq() to select a specific row using a 0-based integer:

// Remove the third row
$("#test tr:eq(2)").remove();

Alternatively, rewrite your HTML so that it's valid:

<table id="test">
 <tr id=test1><td>bla</td></tr>
 <tr id=test2><td>bla</td></tr>
 <tr id=test3><td>bla</td></tr>
 <tr id=test4><td>bla</td></tr>
</table>

And remove it referencing just the id:

$("#test3").remove();

Way to run Excel macros from command line or batch file?

you could write a vbscript to create an instance of excel via the createobject() method, then open the workbook and run the macro. You could either call the vbscript directly, or call the vbscript from a batch file.

Here is a resource I just stumbled accross: http://www.codeguru.com/forum/showthread.php?t=376401

How do I find the PublicKeyToken for a particular dll?

Just adding more info, I wasn't able to find sn.exe utility in the mentioned locations, in my case it was in C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin

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

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

sudo apt-get install openjfx

Error in plot.window(...) : need finite 'xlim' values

I had the same problem. I solve it when I convert string to factor. In your case, check the class of variable and check if they are numeric and 'train and test' should be factor.

Is there a numpy builtin to reject outliers from a list

Building on Benjamin's, using pandas.Series, and replacing MAD with IQR:

def reject_outliers(sr, iq_range=0.5):
    pcnt = (1 - iq_range) / 2
    qlow, median, qhigh = sr.dropna().quantile([pcnt, 0.50, 1-pcnt])
    iqr = qhigh - qlow
    return sr[ (sr - median).abs() <= iqr]

For instance, if you set iq_range=0.6, the percentiles of the interquartile-range would become: 0.20 <--> 0.80, so more outliers will be included.

How to make a input field readonly with JavaScript?

The above answers did not work for me. The below does: document.getElementById("input_field_id").setAttribute("readonly", true);

And to remove the readonly attribute: document.getElementById("input_field_id").removeAttribute("readonly");

And for running when the page is loaded, it is worth referring to here.

Routing with Multiple Parameters using ASP.NET MVC

Starting with MVC 5, you can also use Attribute Routing to move the URL parameter configuration to your controllers.

A detailed discussion is available here: http://blogs.msdn.com/b/webdev/archive/2013/10/17/attribute-routing-in-asp-net-mvc-5.aspx

Summary:

First you enable attribute routing

 public class RouteConfig 
 {
     public static void RegisterRoutes(RouteCollection routes)
     {
         routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

         routes.MapMvcAttributeRoutes();
     } 
 }

Then you can use attributes to define parameters and optionally data types

public class BooksController : Controller
{
    // eg: /books
    // eg: /books/1430210079
    [Route("books/{isbn?}")]
    public ActionResult View(string isbn)

array.select() in javascript

Array.filter is not implemented in many browsers,It is better to define this function if it does not exist.

The source code for Array.prototype is posted in MDN

if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp */)
  {
    "use strict";

    if (this == null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun != "function")
      throw new TypeError();

    var res = [];
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in t)
      {
        var val = t[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, t))
          res.push(val);
      }
    }

    return res;
  };
}

see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter for more details

Read and write a text file in typescript

import { readFileSync } from 'fs';

const file = readFileSync('./filename.txt', 'utf-8');

This worked for me. You may need to wrap the second command in any function or you may need to declare inside a class without keyword const.

How to format a phone number with jQuery

Use a library to handle phone number. Libphonenumber by Google is your best bet.

// Require `PhoneNumberFormat`.
var PNF = require('google-libphonenumber').PhoneNumberFormat;

// Get an instance of `PhoneNumberUtil`.
var phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();

// Parse number with country code.
var phoneNumber = phoneUtil.parse('202-456-1414', 'US');

// Print number in the international format.
console.log(phoneUtil.format(phoneNumber, PNF.INTERNATIONAL));
// => +1 202-456-1414

I recommend to use this package by seegno.

How to set min-font-size in CSS

It will work perfectly with 50px. Which will act as a static and thus as min-width.

font-size: calc(50px + 5vw);

Use NSInteger as array index

According to the error message, you declared myLoc as a pointer to an NSInteger (NSInteger *myLoc) rather than an actual NSInteger (NSInteger myLoc). It needs to be the latter.

OSError: [Errno 2] No such file or directory while using python subprocess in Django

Can't upvote so I'll repost @jfs comment cause I think it should be more visible.

@AnneTheAgile: shell=True is not required. Moreover you should not use it unless it is necessary (see @ valid's comment). You should pass each command-line argument as a separate list item instead e.g., use ['command', 'arg 1', 'arg 2'] instead of "command 'arg 1' 'arg 2'". – jfs Mar 3 '15 at 10:02

MySQL DAYOFWEEK() - my week begins with monday

Try to use the WEEKDAY() function.

Returns the weekday index for date (0 = Monday, 1 = Tuesday, … 6 = Sunday).

How to convert Django Model object to dict with its fields and values?

Maybe this help you. May this not covert many to many relantionship, but es pretty handy when you want to send your model in json format.

def serial_model(modelobj):
  opts = modelobj._meta.fields
  modeldict = model_to_dict(modelobj)
  for m in opts:
    if m.is_relation:
        foreignkey = getattr(modelobj, m.name)
        if foreignkey:
            try:
                modeldict[m.name] = serial_model(foreignkey)
            except:
                pass
  return modeldict

In C# check that filename is *possibly* valid (not that it exists)

I've had luck using regular expressions as others have shown.

One thing to keep in mind is that Windows at least prohibits some filenames that otherwise containlegal characters. A few come to mind: com, nul, prn.

I don't have it with me now, but I have a regex that takes these filename into consideration. If you want I can post it, otherwise I'm sure you can find it the same way I did: Google.

-Jay

Using PowerShell credentials without being prompted for a password

The problem with Get-Credential is that it will always prompt for a password. There is a way around this however but it involves storing the password as a secure string on the filesystem.

The following article explains how this works:

Using PSCredentials without a prompt

In summary, you create a file to store your password (as an encrypted string). The following line will prompt for a password then store it in c:\mysecurestring.txt as an encrypted string. You only need to do this once:

read-host -assecurestring | convertfrom-securestring | out-file C:\mysecurestring.txt

Wherever you see a -Credential argument on a PowerShell command then it means you can pass a PSCredential. So in your case:

$username = "domain01\admin01"
$password = Get-Content 'C:\mysecurestring.txt' | ConvertTo-SecureString
$cred = new-object -typename System.Management.Automation.PSCredential `
         -argumentlist $username, $password

$serverNameOrIp = "192.168.1.1"
Restart-Computer -ComputerName $serverNameOrIp `
                 -Authentication default `
                 -Credential $cred
                 <any other parameters relevant to you>

You may need a different -Authentication switch value because I don't know your environment.

How to quietly remove a directory with content in PowerShell

in short, We can use rm -r -fo {folderName} to remove the folder recursively (remove all the files and folders inside) and force

Test or check if sheet exists

Public Function WorkSheetExists(ByVal strName As String) As Boolean
   On Error Resume Next
   WorkSheetExists = Not Worksheets(strName) Is Nothing
End Function

sub test_sheet()

 If Not WorkSheetExists("SheetName") Then
 MsgBox "Not available"
Else MsgBox "Available"
End If

End Sub

Oracle timestamp data type

The number in parentheses specifies the precision of fractional seconds to be stored. So, (0) would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.

So an unspecified value would store a date like:

TIMESTAMP 24-JAN-2012 08.00.05.993847 AM

And specifying (0) stores only:

TIMESTAMP(0) 24-JAN-2012 08.00.05 AM

See Oracle documentation on data types.

Text not wrapping in p tag

EASY

p{
    word-wrap: break-word;
}

Changing background color of text box input not working when empty

You can style it using javascript and css. Add the style to css and using javascript add/remove style using classlist property. Here is a JSFiddle for it.

  <div class="div-image-text">
    <input class="input-image-url" type="text" placeholder="Add text" name="input-image">
    <input type="button" onclick="addRemoteImage(event);" value="Submit">
  </div>
  <div class="no-image-url-error" name="input-image-error">Textbox empty</div>

addRemoteImage = function(event) {
  var textbox = document.querySelector("input[name='input-image']"),
    imageUrl = textbox.value,
    errorDiv = document.querySelector("div[name='input-image-error']");
  if (imageUrl == "") {
    errorDiv.style.display = "block";
    textbox.classList.add('text-error');
    setTimeout(function() {
      errorDiv.style.removeProperty('display');
      textbox.classList.remove('text-error');
    }, 3000);
  } else {
    textbox.classList.remove('text-error');
  }
}

How to change facet labels?

I feel like I should add my answer to this because it took me quite long to make this work:

This answer is for you if:

  • you do not want to edit your original data
  • if you need expressions (bquote) in your labels and
  • if you want the flexibility of a separate labelling name-vector

I basically put the labels in a named vector so labels would not get confused or switched. The labeller expression could probably be simpler, but this at least works (improvements are very welcome). Note the ` (back quotes) to protect the facet-factor.

n <- 10
x <- seq(0, 300, length.out = n)

# I have my data in a "long" format
my_data <- data.frame(
  Type = as.factor(c(rep('dl/l', n), rep('alpha', n))),
  T = c(x, x),
  Value = c(x*0.1, sqrt(x))
)

# the label names as a named vector
type_names <- c(
  `nonsense` = "this is just here because it looks good",
  `dl/l` = Linear~Expansion~~Delta*L/L[Ref]~"="~"[%]", # bquote expression
  `alpha` = Linear~Expansion~Coefficient~~alpha~"="~"[1/K]"
  )


ggplot() + 
  geom_point(data = my_data, mapping = aes(T, Value)) + 
  facet_wrap(. ~ Type, scales="free_y", 
             labeller = label_bquote(.(as.expression(
               eval(parse(text = paste0('type_names', '$`', Type, '`')))
               )))) +
  labs(x="Temperature [K]", y="", colour = "") +
  theme(legend.position = 'none')

enter image description here

Lightweight workflow engine for Java

The question is what you really want to achieve when you asking for a workflow engine.

The general goal which you would like to achieve by using a workflow engine, is to become more flexible in changing your business logic during runtime. The modelling part is surely one of the most important here. BPMN 2.0 is a de-facto standard in this area and all of the discussed engines support this standard.

The second goal is to control the business process in the way of describing the 'what should happen when...' questions. And this part has a lot to do with the business requirements you are confronted within your project.

Some of the workflow engines (Activity, JBPM) can help you to answer this requirement by 'coding' your processes. This means that you model the 'what should happen when..' paradigm in a way, where you decide which part of your code (e.g a task or an event) should be executed by the workflow engine in various situations. A lot of discussion is going about this concept. And developers naturally ask whether this may not even be implemented by themselves. (It is in fact not so easy as it seems at the first glance)

Some other workflow engines (Imixs-Workflow, Bonita) can help you to answer the 'what should happen when...' requirement in a more user-centric way. This is the area of Human-centric business process management, which supports human skills and activities by a task orientated workflow-engine. The focus is more on the distribution of tasks and processes inside an organisation. The workflow engine helps you to distribute a task to a certain user or user group and to secure, log and monitor a long running business process. Maybe these are the things you do not really want to implement by yourself.

So my advice is, not to mix things that need to be considered separately, because workflow covers a very wide area.

Autowiring two beans implementing same interface - how to set default bean to autowire?

The use of @Qualifier will solve the issue.
Explained as below example : 
public interface PersonType {} // MasterInterface

@Component(value="1.2") 
public class Person implements  PersonType { //Bean implementing the interface
@Qualifier("1.2")
    public void setPerson(PersonType person) {
        this.person = person;
    }
}

@Component(value="1.5")
public class NewPerson implements  PersonType { 
@Qualifier("1.5")
    public void setNewPerson(PersonType newPerson) {
        this.newPerson = newPerson;
    }
}

Now get the application context object in any component class :

Object obj= BeanFactoryAnnotationUtils.qualifiedBeanOfType((ctx).getAutowireCapableBeanFactory(), PersonType.class, type);//type is the qualifier id

you can the object of class of which qualifier id is passed.

Ignore 'Security Warning' running script from command line

Did you download the script from internet?

Then remove NTFS stream from the file using sysinternal's streams.exe on command line.

cmd> streams.exe .\my.ps1

Now try to run the script again.