Programs & Examples On #Value of

Override valueof() and toString() in Java enum

How about a Java 8 implementation? (null can be replaced by your default Enum)

public static RandomEnum getEnum(String value) {
    return Arrays.stream(RandomEnum.values()).filter(m -> m.value.equals(value)).findAny().orElse(null);
}

Or you could use:

...findAny().orElseThrow(NotFoundException::new);

Postgresql : syntax error at or near "-"

I have reproduced the issue in my system,

postgres=# alter user my-sys with password 'pass11';
ERROR:  syntax error at or near "-"
LINE 1: alter user my-sys with password 'pass11';
                       ^

Here is the issue,

psql is asking for input and you have given again the alter query see postgres-#That's why it's giving error at alter

postgres-# alter user "my-sys" with password 'pass11';
ERROR:  syntax error at or near "alter"
LINE 2: alter user "my-sys" with password 'pass11';
        ^

Solution is as simple as the error,

postgres=# alter user "my-sys" with password 'pass11';
ALTER ROLE

XML Parser for C

How about one written in pure assembler :-) Don't forget to check out the benchmarks.

slideToggle JQuery right to left

I would suggest you use the below css

.showhideoverlay { 
  width: 100%;
  height: 100%;
  right: 0px;
  top: 0px;
  position: fixed;
  background: #000;
  opacity: 0.75;
}

You can then use a simple toggle function:

$('a.open').click(function() {
  $('div.showhideoverlay').toggle("slow");
});

This will display the overlay menu from right to left. Alternatively, you can use the positioning for changing the effect from top or bottom, i.e. use bottom: 0; instead of top: 0; - you will see menu sliding from right-bottom corner.

Node.js ES6 classes with require

Just treat the ES6 class name the same as you would have treated the constructor name in the ES5 way. They are one and the same.

The ES6 syntax is just syntactic sugar and creates exactly the same underlying prototype, constructor function and objects.

So, in your ES6 example with:

// animal.js
class Animal {
    ...
}

var a = new Animal();

module.exports = {Animal: Animal};

You can just treat Animal like the constructor of your object (the same as you would have done in ES5). You can export the constructor. You can call the constructor with new Animal(). Everything is the same for using it. Only the declaration syntax is different. There's even still an Animal.prototype that has all your methods on it. The ES6 way really does create the same coding result, just with fancier/nicer syntax.


On the import side, this would then be used like this:

const Animal = require('./animal.js').Animal;

let a = new Animal();

This scheme exports the Animal constructor as the .Animal property which allows you to export more than one thing from that module.

If you don't need to export more than one thing, you can do this:

// animal.js
class Animal {
    ...
}

module.exports = Animal;

And, then import it with:

const Animal = require('./animal.js');

let a = new Animal();

How can I echo HTML in PHP?

Try it like this (heredoc syntax):

$variable = <<<XYZ
<html>
<body>

</body>
</html>
XYZ;
echo $variable;

String MinLength and MaxLength validation don't work (asp.net mvc)

This can replace the MaxLength and the MinLength

[StringLength(40, MinimumLength = 10 , ErrorMessage = "Password cannot be longer than 40 characters and less than 10 characters")]

Click event doesn't work on dynamically generated elements

I'm working with tables adding new elements dynamically to them, and when using on(), the only way of making it works for me is using a non-dynamic parent as:

<table id="myTable">
    <tr>
        <td></td> // Dynamically created
        <td></td> // Dynamically created
        <td></td> // Dynamically created
    </tr>
</table>

<input id="myButton" type="button" value="Push me!">

<script>
    $('#myButton').click(function() {
        $('#myTable tr').append('<td></td>');
    });

    $('#myTable').on('click', 'td', function() {
        // Your amazing code here!
    });
</script>

This is really useful because, to remove events bound with on(), you can use off(), and to use events once, you can use one().

' << ' operator in verilog

<< is the left-shift operator, as it is in many other languages.

Here RAM_DEPTH will be 1 left-shifted by 8 bits, which is equivalent to 2^8, or 256.

Guid.NewGuid() vs. new Guid()

Guid.NewGuid(), as it creates GUIDs as intended.

Guid.NewGuid() creates an empty Guid object, initializes it by calling CoCreateGuid and returns the object.

new Guid() merely creates an empty GUID (all zeros, I think).

I guess they had to make the constructor public as Guid is a struct.

jQuery: outer html()

No siblings solution:

var x = $('#xxx').parent().html();
alert(x);

Universal solution:

// no cloning necessary    
var x = $('#xxx').wrapAll('<div>').parent().html(); 
alert(x);

Fiddle here: http://jsfiddle.net/ezmilhouse/Mv76a/

Check whether user has a Chrome extension installed

I used the cookie method:

In my manifest.js file I included a content script that only runs on my site:

 "content_scripts": [
        {
        "matches": [
            "*://*.mysite.co/*"
            ],
        "js": ["js/mysite.js"],
        "run_at": "document_idle"
        }
    ], 

in my js/mysite.js I have one line:

document.cookie = "extension_downloaded=True";

and in my index.html page I look for that cookie.

if (document.cookie.indexOf('extension_downloaded') != -1){
    document.getElementById('install-btn').style.display = 'none';
}

How do you determine what SQL Tables have an identity column programmatically

I think this works for SQL 2000:

SELECT 
    CASE WHEN C.autoval IS NOT NULL THEN
        'Identity'
    ELSE
        'Not Identity'
    AND
FROM
    sysobjects O
INNER JOIN
    syscolumns C
ON
    O.id = C.id
WHERE
    O.NAME = @TableName
AND
    C.NAME = @ColumnName

How to set back button text in Swift

The back button belongs to the previous view controller, not the one currently presented on screen. To modify the back button you should update it before pushing, add viewdidload :

Swift 4:

self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: self, action: nil)

How to initialise a string from NSData in Swift

Swift 2.0

It seems that Swift 2.0 has actually introduced the String(data:encoding:) as an String extension when you import Foundation. I haven't found any place where this is documented, weirdly enough.

(pre Swift 2.0) Lightweight extension

Here's a copy-pasteable little extension without using NSString, let's cut the middle-man.

import Foundation

extension NSData
{
    var byteBuffer : UnsafeBufferPointer<UInt8> { get { return UnsafeBufferPointer<UInt8>(start: UnsafeMutablePointer<UInt8>(self.bytes), count: self.length) }}
}

extension String
{
    init?(data : NSData, encoding : NSStringEncoding)
    {
        self.init(bytes: data.byteBuffer, encoding: encoding)
    }
}

// Playground test
let original = "Nymphs blitz quick vex dwarf jog"
let encoding = NSASCIIStringEncoding

if let data = original.dataUsingEncoding(encoding)
{
    String(data: data, encoding: encoding)
}

This also give you access to data.byteBuffer which is a sequence type, so all those cool operations you can do with sequences also work, like doing a reduce { $0 &+ $1 } for a checksum.

Notes

In my previous edit, I used this method:

var buffer = Array<UInt8>(count: data.length, repeatedValue: 0x00)
data.getBytes(&buffer, length: data.length)
self.init(bytes: buffer, encoding: encoding)

The problem with this approach, is that I'm creating a copy of the information into a new array, thus, I'm duplicating the amount of bytes (specifically: encoding size * data.length)

Check if string contains only letters in javascript

The fastest way is to check if there is a non letter:

if (!/[^a-zA-Z]/.test(word))

Module is not available, misspelled or forgot to load (but I didn't)

Using AngularJS 1.6.9+

There is one more incident, it also happen when you declare variable name different of module name.

var indexPageApp = angular.module('indexApp', []);

to get rid of this error,

Error: [$injector:nomod] Module 'indexPageApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

change the module name similar to var declared name or vice versa -

var indexPageApp = angular.module('indexPageApp', []);

What is a good way to handle exceptions when trying to read a file in python?

How about this:

try:
    f = open(fname, 'rb')
except OSError:
    print "Could not open/read file:", fname
    sys.exit()

with f:
    reader = csv.reader(f)
    for row in reader:
        pass #do stuff here

TortoiseSVN Error: "OPTIONS of 'https://...' could not connect to server (...)"

I realize this is an old question, but the same issue happened to me, but for a completely different reason.

It could be that cvs-dude changed certificates, so it no longer matches the certificate you have cached.

You can go to TortoiseSVN->Settings->Saved Data and click the 'Clear' button next to 'Authentication data' and then try again.

how can get index & count in vuejs

The optional SECOND argument is the index, starting at 0. So to output the index and total length of an array called 'some_list':

<div>Total Length: {{some_list.length}}</div>
<div v-for="(each, i) in some_list">
  {{i + 1}} : {{each}}
</div>

If instead of a list, you were looping through an object, then the second argument is key of the key/value pair. So for the object 'my_object':

var an_id = new Vue({
  el: '#an_id',
  data: {
    my_object: {
        one: 'valueA',
        two: 'valueB'
    }
  }
})

The following would print out the key : value pairs. (you can name 'each' and 'i' whatever you want)

<div id="an_id">
  <span v-for="(each, i) in my_object">
    {{i}} : {{each}}<br/>
  </span>
</div>

For more info on Vue list rendering: https://vuejs.org/v2/guide/list.html

Check for false

Like this:

if(borrar())
{
   // Do something
}

If borrar() returns true then do something (if it is not false).

In VBA get rid of the case sensitivity when comparing words?

It is a bit of hack but will do the task.

Function equalsIgnoreCase(str1 As String, str2 As String) As Boolean
    equalsIgnoreCase = LCase(str1) = LCase(str2)
End Function

string.Replace in AngularJs

var oldString = "stackoverflow";
var str=oldString.replace(/stackover/g,"NO");
$scope.newString= str;

It works for me. Use an intermediate variable.

How to determine the current language of a wordpress page when using polylang?

Simple:

if(pll_current_language() == 'en'){
   //do your work here
}

Escaping backslash in string - javascript

I think this is closer to the answer you're looking for:

<input type="file">

$file = $(file);
var filename = fileElement[0].files[0].name;

Python Replace \\ with \

You are missing, that \ is the escape character.

Look here: http://docs.python.org/reference/lexical_analysis.html at 2.4.1 "Escape Sequence"

Most importantly \n is a newline character. And \\ is an escaped escape character :D

>>> a = 'a\\\\nb'
>>> a
'a\\\\nb'
>>> print a
a\\nb
>>> a.replace('\\\\', '\\')
'a\\nb'
>>> print a.replace('\\\\', '\\')
a\nb

Mongoose: Get full list of users

Same can be done with async await and arrow function

server.get('/usersList', async (req, res) => {

const users = await User.find({});

const userMap = {};
users.forEach((user) => {
    userMap[user._id] = user;
});

res.send(userMap);

});

fetch gives an empty response body

This requires changes to the frontend JS and the headers sent from the backend.

Frontend

Remove "mode":"no-cors" in the fetch options.

fetch(
  "http://example.com/api/docs", 
  {
    // mode: "no-cors",
    method: "GET"
  }
)
  .then(response => response.text())
  .then(data => console.log(data))

Backend

When your server responds to the request, include the CORS headers specifying the origin from where the request is coming. If you don't care about the origin, specify the * wildcard.

The raw response should include a header like this.

Access-Control-Allow-Origin: *

Is there a way to check for both `null` and `undefined`?

I think this answer needs an update, check the edit history for the old answer.

Basically, you have three deferent cases null, undefined, and undeclared, see the snippet below.

// bad-file.ts
console.log(message)

You'll get an error says that variable message is undefined (aka undeclared), of course, the Typescript compiler shouldn't let you do that but REALLY nothing can prevent you.

// evil-file.ts
// @ts-gnore
console.log(message)

The compiler will be happy to just compile the code above. So, if you're sure that all variables are declared you can simply do that

if ( message != null ) {
    // do something with the message
}

the code above will check for null and undefined, BUT in case the message variable may be undeclared (for safety), you may consider the following code

if ( typeof(message) !== 'undefined' && message !== null ) {
    // message variable is more than safe to be used.
}

Note: the order here typeof(message) !== 'undefined' && message !== null is very important you have to check for the undefined state first atherwise it will be just the same as message != null, thanks @Jaider.

Stopping a CSS3 Animation on last frame

You're looking for:

animation-fill-mode: forwards;

More info on MDN and browser support list on canIuse.

How to select date without time in SQL

Try this.

SELECT DATEADD(DD, 0, DATEDIFF(DD, 0, GETDATE()))

Uninstall all installed gems, in OSX?

You could also build out a new Gemfile and run bundle clean --force. This will remove all other gems that aren't included in the new Gemfile.

How to find and replace all occurrences of a string recursively in a directory tree?

On macOS, none of the answers worked for me. I discovered that was due to differences in how sed works on macOS and other BSD systems compared to GNU.

In particular BSD sed takes the -i option but requires a suffix for the backup (but an empty suffix is permitted)

grep version from this answer.

grep -rl 'foo' ./ | LC_ALL=C xargs sed -i '' 's/foo/bar/g'

find version from this answer.

find . \( ! -regex '.*/\..*' \) -type f | LC_ALL=C xargs sed -i '' 's/foo/bar/g'

Don't omit the Regex to ignore . folders if you're in a Git repo. I realized that the hard way!

That LC_ALL=C option is to avoid getting sed: RE error: illegal byte sequence if sed finds a byte sequence that is not a valid UTF-8 character. That's another difference between BSD and GNU. Depending on the kind of files you are dealing with, you may not need it.

For some reason that is not clear to me, the grep version found more occurrences than the find one, which is why I recommend to use grep.

How to handle floats and decimal separators with html5 input type number

According to w3.org the value attribute of the number input is defined as a floating-point number. The syntax of the floating-point number seems to only accept dots as decimal separators.

I've listed a few options below that might be helpful to you:

1. Using the pattern attribute

With the pattern attribute you can specify the allowed format with a regular expression in a HTML5 compatible way. Here you could specify that the comma character is allowed and a helpful feedback message if the pattern fails.

<input type="number" pattern="[0-9]+([,\.][0-9]+)?" name="my-num"
           title="The number input must start with a number and use either comma or a dot as a decimal character."/>

Note: Cross-browser support varies a lot. It may be complete, partial or non-existant..

2. JavaScript validation

You could try to bind a simple callback to for example the onchange (and/or blur) event that would either replace the comma or validate all together.

3. Disable browser validation ##

Thirdly you could try to use the formnovalidate attribute on the number inputs with the intention of disabling browser validation for that field all together.

<input type="number" formnovalidate />

4. Combination..?

<input type="number" pattern="[0-9]+([,\.][0-9]+)?" 
           name="my-num" formnovalidate
           title="The number input must start with a number and use either comma or a dot as a decimal character."/>

Is there a naming convention for git repositories?

If you plan to create a PHP package you most likely want to put in on Packagist to make it available for other with composer. Composer has the as naming-convention to use vendorname/package-name-is-lowercase-with-hyphens.

If you plan to create a JS package you probably want to use npm. One of their naming conventions is to not permit upper case letters in the middle of your package name.

Therefore, I would recommend for PHP and JS packages to use lowercase-with-hyphens and name your packages in composer or npm identically to your package on GitHub.

How to switch to new window in Selenium for Python?

On top of the answers already given, to open a new tab the javascript command window.open() can be used.

For example:

# Opens a new tab
self.driver.execute_script("window.open()")

# Switch to the newly opened tab
self.driver.switch_to.window(self.driver.window_handles[1])

# Navigate to new URL in new tab
self.driver.get("https://google.com")
# Run other commands in the new tab here

You're then able to close the original tab as follows

# Switch to original tab
self.driver.switch_to.window(self.driver.window_handles[0])

# Close original tab
self.driver.close()

# Switch back to newly opened tab, which is now in position 0
self.driver.switch_to.window(self.driver.window_handles[0])

Or close the newly opened tab

# Close current tab
self.driver.close()

# Switch back to original tab
self.driver.switch_to.window(self.driver.window_handles[0])

Hope this helps.

How do I extract data from a DataTable?

Please consider using some code like this:

SqlDataReader reader = command.ExecuteReader();
int numRows = 0;
DataTable dt = new DataTable();

dt.Load(reader);
numRows = dt.Rows.Count;

string attended_type = "";

for (int index = 0; index < numRows; index++)
{
    attended_type = dt.Rows[indice2]["columnname"].ToString();
}

reader.Close();

What are WSDL, SOAP and REST?

You're not going to "simply" understand something complex.

WSDL is an XML-based language for describing a web service. It describes the messages, operations, and network transport information used by the service. These web services usually use SOAP, but may use other protocols.

A WSDL is readable by a program, and so may be used to generate all, or part of the client code necessary to call the web service. This is what it means to call SOAP-based web services "self-describing".

REST is not related to WSDL at all.

FAIL - Application at context path /Hello could not be started

Your web.xml ends with <web-app>, but must end with </web-app>

Which by the way is almost literally what the exception tells you.

Using the "start" command with parameters passed to the started program

The spaces are DOSs/CMDs Problems so you should go to the Path via:

cd "c:\program files\Microsoft Virtual PC"

and then simply start VPC via:

start Virtual~1.exe -pc MY-PC -launch

~1 means the first exe with "Virtual" at the beginning. So if there is a "Virtual PC.exe" and a "Virtual PC1.exe" the first would be the Virtual~1.exe and the second Virtual~2.exe and so on.

Or use a VNC-Client like VirtualBox.

Absolute positioning ignoring padding of parent

add padding:inherit in your absolute position

_x000D_
_x000D_
.box{_x000D_
  background: red;_x000D_
  position: relative;_x000D_
  padding: 30px;_x000D_
  width:500px;_x000D_
  height:200px;_x000D_
 box-sizing: border-box;_x000D_
 _x000D_
_x000D_
}
_x000D_
<div  class="box">_x000D_
_x000D_
  <div style="position: absolute;left:0;top:0;padding: inherit">top left</div>_x000D_
  <div style="position: absolute;right:0;top:0;padding: inherit">top right</div>_x000D_
  <div style="text-align: center;padding: inherit">center</div>_x000D_
  <div style="position: absolute;left:0;bottom:0;padding: inherit">bottom left</div>_x000D_
  <div style="position: absolute;right:0;bottom:0;padding: inherit">bottom right</div>_x000D_
_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

ASP.Net MVC - Read File from HttpPostedFileBase without save

This can be done using httpPostedFileBase class returns the HttpInputStreamObject as per specified here

You should convert the stream into byte array and then you can read file content

Please refer following link

http://msdn.microsoft.com/en-us/library/system.web.httprequest.inputstream.aspx]

Hope this helps

UPDATE :

The stream that you get from your HTTP call is read-only sequential (non-seekable) and the FileStream is read/write seekable. You will need first to read the entire stream from the HTTP call into a byte array, then create the FileStream from that array.

Taken from here

// Read bytes from http input stream
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.ContentLength);

string result = System.Text.Encoding.UTF8.GetString(binData);

How add unique key to existing table (with non uniques rows)

Either create an auto-increment id or a UNIQUE id and add it to the natural key you are talking about with the 4 fields. this will make every row in the table unique...

Dynamically creating keys in a JavaScript associative array

JavaScript does not have associative arrays. It has objects.

The following lines of code all do exactly the same thing - set the 'name' field on an object to 'orion'.

var f = new Object(); f.name = 'orion';
var f = new Object(); f['name'] = 'orion';
var f = new Array(); f.name = 'orion';
var f = new Array(); f['name'] = 'orion';
var f = new XMLHttpRequest(); f['name'] = 'orion';

It looks like you have an associative array because an Array is also an Object - however you're not actually adding things into the array at all; you're setting fields on the object.

Now that that is cleared up, here is a working solution to your example:

var text = '{ name = oscar }'
var dict = new Object();

// Remove {} and spaces
var cleaned = text.replace(/[{} ]/g, '');

// Split into key and value
var kvp = cleaned.split('=');

// Put in the object
dict[ kvp[0] ] = kvp[1];
alert( dict.name ); // Prints oscar.

How to install SimpleJson Package for Python

I would recommend EasyInstall, a package management application for Python.

Once you've installed EasyInstall, you should be able to go to a command window and type:

easy_install simplejson

This may require putting easy_install.exe on your PATH first, I don't remember if the EasyInstall setup does this for you (something like C:\Python25\Scripts).

Create XML in Javascript

Only works in IE

 $(function(){

        var xml = '<?xml version="1.0"?><foo><bar>bar</bar></foo>'; 

        var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async="false";
        xmlDoc.loadXML(xml);

        alert(xmlDoc.xml);

    });

Then push xmlDoc.xml to your java code.

Do while loop in SQL Server 2008

You can also use an exit variable if you want your code to be a bit more readable:

DECLARE @Flag int = 0
DECLARE @Done bit = 0

WHILE @Done = 0 BEGIN
    SET @Flag = @Flag + 1
    PRINT @Flag
    IF @Flag >= 5 SET @Done = 1
END

This would probably be more relevant when you have a more complicated loop and are trying to keep track of the logic. As stated loops are expensive so try and use other methods if you can.

Updates were rejected because the tip of your current branch is behind its remote counterpart

To make sure your local branch FixForBug is not ahead of the remote branch FixForBug pull and merge the changes before pushing.

git pull origin FixForBug
git push origin FixForBug

Test if a property is available on a dynamic variable

If you control the type being used as dynamic, couldn't you return a tuple instead of a value for every property access? Something like...

public class DynamicValue<T>
{
    internal DynamicValue(T value, bool exists)
    {
         Value = value;
         Exists = exists;
    }

    T Value { get; private set; }
    bool Exists { get; private set; }
}

Possibly a naive implementation, but if you construct one of these internally each time and return that instead of the actual value, you can check Exists on every property access and then hit Value if it does with value being default(T) (and irrelevant) if it doesn't.

That said, I might be missing some knowledge on how dynamic works and this might not be a workable suggestion.

How to split page into 4 equal parts?

I did not want to add style to <body> tag and <html> tag.

_x000D_
_x000D_
.quodrant{
    width: 100%;
    height: 100vh;
    margin: 0;
    padding: 0;
}

.qtop,
.qbottom{
    width: 100%;
    height: 50vh;
}

.quodrant1,
.quodrant2,
.quodrant3,
.quodrant4{
    display: inline;
    float: left;
    width: 50%;
    height: 100%;
}

.quodrant1{
    top: 0;
    left: 50vh;
    background-color: red;
}

.quodrant2{
    top: 0;
    left: 0;
    background-color: yellow;
}

.quodrant3{
    top: 50vw;
    left: 0;
    background-color: blue;
}

.quodrant4{ 
    top: 50vw;
    left: 50vh;
    background-color: green;
}
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link type="text/css" rel="stylesheet" href="main.css" />
</head>
<body>

<div class='quodrant'>
    <div class='qtop'>
        <div class='quodrant1'></div>
        <div class='quodrant2'></div>
    </div>
    <div class='qbottom'>
        <div class='quodrant3'></div>
        <div class='quodrant4'></div>
    </div>
</div>

<script type="text/javascript" src="main.js"></script>
</body>
</html>
_x000D_
_x000D_
_x000D_

Or making it looks nicer.

_x000D_
_x000D_
.quodrant{
    width: 100%;
    height: 100vh;
    margin: 0;
    padding: 0;
}

.qtop,
.qbottom{
    width: 96%;
    height: 46vh;
}

.quodrant1,
.quodrant2,
.quodrant3,
.quodrant4{
    display: inline;
    float: left;
    width: 46%;
    height: 96%;
    border-radius: 30px;
    margin: 2%;
}

.quodrant1{
    background-color: #948be5;
}

.quodrant2{
    background-color: #22e235;
}

.quodrant3{
    background-color: #086e75;
}

.quodrant4{ 
    background-color: #7cf5f9;
}
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link type="text/css" rel="stylesheet" href="main.css" />
</head>
<body>

<div class='quodrant'>
    <div class='qtop'>
        <div class='quodrant1'></div>
        <div class='quodrant2'></div>
    </div>
    <div class='qbottom'>
        <div class='quodrant3'></div>
        <div class='quodrant4'></div>
    </div>
</div>

<script type="text/javascript" src="main.js"></script>
</body>
</html>
_x000D_
_x000D_
_x000D_

Check if returned value is not null and if so assign it, in one line, with one method call

Java lacks coalesce operator, so your code with an explicit temporary is your best choice for an assignment with a single call.

You can use the result variable as your temporary, like this:

dinner = ((dinner = cage.getChicken()) != null) ? dinner : getFreeRangeChicken();

This, however, is hard to read.

Matching special characters and letters in regex

Try this regex:

/^[\w&.-]+$/

Also you can use test.

if ( pattern.test( qry ) ) {
  // valid
}

How to check if running in Cygwin, Mac or Linux?

Windows Subsystem for Linux did not exist when this question was asked. It gave these results in my test:

uname -s -> Linux
uname -o -> GNU/Linux
uname -r -> 4.4.0-17763-Microsoft

This means that you need uname -r to distinguish it from native Linux.

How many bytes in a JavaScript string?

You can try this:

  var b = str.match(/[^\x00-\xff]/g);
  return (str.length + (!b ? 0: b.length)); 

It worked for me.

“Origin null is not allowed by Access-Control-Allow-Origin” error for request made by application running from a file:// URL

For the record, as far as I can tell, you had two problems:

  1. You weren't passing a "jsonp" type specifier to your $.get, so it was using an ordinary XMLHttpRequest. However, your browser supported CORS (Cross-Origin Resource Sharing) to allow cross-domain XMLHttpRequest if the server OKed it. That's where the Access-Control-Allow-Origin header came in.

  2. I believe you mentioned you were running it from a file:// URL. There are two ways for CORS headers to signal that a cross-domain XHR is OK. One is to send Access-Control-Allow-Origin: * (which, if you were reaching Flickr via $.get, they must have been doing) while the other was to echo back the contents of the Origin header. However, file:// URLs produce a null Origin which can't be authorized via echo-back.

The first was solved in a roundabout way by Darin's suggestion to use $.getJSON. It does a little magic to change the request type from its default of "json" to "jsonp" if it sees the substring callback=? in the URL.

That solved the second by no longer trying to perform a CORS request from a file:// URL.

To clarify for other people, here are the simple troubleshooting instructions:

  1. If you're trying to use JSONP, make sure one of the following is the case:
    • You're using $.get and set dataType to jsonp.
    • You're using $.getJSON and included callback=? in the URL.
  2. If you're trying to do a cross-domain XMLHttpRequest via CORS...
    1. Make sure you're testing via http://. Scripts running via file:// have limited support for CORS.
    2. Make sure the browser actually supports CORS. (Opera and Internet Explorer are late to the party)

Grep and Python

You can use python-textops3 :

from textops import *

print('\n'.join(cat(f) | grep(search_term)))

with python-textops3 you can use unix-like commands with pipes

facebook: permanent Page Access Token?

In addition to the recommended steps in the Vlasec answer, you can use:

  • Graph API explorer to make the queries, e.g. /{pageId}?fields=access_token&access_token=THE_ACCESS_TOKEN_PROVIDED_BY_GRAPH_EXPLORER
  • Access Token Debugger to get information about the access token.

Format Float to n decimal places

Of note, use of DecimalFormat constructor is discouraged. The javadoc for this class states:

In general, do not call the DecimalFormat constructors directly, since the NumberFormat factory methods may return subclasses other than DecimalFormat.

https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html

So what you need to do is (for instance):

NumberFormat formatter = NumberFormat.getInstance(Locale.US);
formatter.setMaximumFractionDigits(2);
formatter.setMinimumFractionDigits(2);
formatter.setRoundingMode(RoundingMode.HALF_UP); 
Float formatedFloat = new Float(formatter.format(floatValue));

How to open a new HTML page using jQuery?

use window.open("file2.html"); to open on new window,

or use window.location.href = "file2.html" to open on same window.

How do I load an HTML page in a <div> using JavaScript?

Fetching HTML the modern Javascript way

This approach makes use of modern Javascript features like async/await and the fetch API. It downloads HTML as text and then feeds it to the innerHTML of your container element.

/**
  * @param {String} url - address for the HTML to fetch
  * @return {String} the resulting HTML string fragment
  */
async function fetchHtmlAsText(url) {
    return await (await fetch(url)).text();
}

// this is your `load_home() function`
async function loadHome() {
    const contentDiv = document.getElementById("content");
    contentDiv.innerHTML = await fetchHtmlAsText("home.html");
}

The await (await fetch(url)).text() may seem a bit tricky, but it's easy to explain. It has two asynchronous steps and you could rewrite that function like this:

async function fetchHtmlAsText(url) {
    const response = await fetch(url);
    return await response.text();
}

See the fetch API documentation for more details.

Storing and Retrieving ArrayList values from hashmap

for (Map.Entry<String, ArrayList<Integer>> entry : map.entrySet()) {
 System.out.println( entry.getKey());     
 System.out.println( entry.getValue());//Returns the list of values
}

What is considered a good response time for a dynamic, personalized web application?

We strive for response times of 20 milliseconds, while some complex pages take up to 100 milliseconds. For the most complex pages, we break the page down into smaller pieces, and use the progressive display pattern to load each section. This way, some portions load quickly, even if the page takes 1 to 2 seconds to load, keeping the user engaged while the rest of the page is loading.

How do I check if a string contains a specific word?

Another option is to use the strstr() function. Something like:

if (strlen(strstr($haystack,$needle))>0) {
// Needle Found
}

Point to note: The strstr() function is case-sensitive. For a case-insensitive search, use the stristr() function.

#1130 - Host ‘localhost’ is not allowed to connect to this MySQL server

Use the IP instead:

DROP USER 'root'@'127.0.0.1'; GRANT ALL PRIVILEGES ON . TO 'root'@'%';

For more possibilities, see this link.

To create the root user, seeing as MySQL is local & all, execute the following from the command line (Start > Run > "cmd" without quotes):

mysqladmin -u root password 'mynewpassword'

Documentation, and Lost root access in MySQL.

How to apply shell command to each line of a command output?

You can use a basic prepend operation on each line:

ls -1 | while read line ; do echo $line ; done

Or you can pipe the output to sed for more complex operations:

ls -1 | sed 's/^\(.*\)$/echo \1/'

How to reset all checkboxes using jQuery or pure JS?

As said in Tatu Ulmanen's answer using the follow script will do the job

$('input:checkbox').removeAttr('checked');

But, as Blakomen's comment said, after version 1.6 it's better to use jQuery.prop() instead

Note that in jQuery v1.6 and higher, you should be using .prop('checked', false) instead for greater cross-browser compatibility

$('input:checkbox').prop('checked', false);

Be careful when using jQuery.each() it may cause performance issues. (also, avoid jQuery.find() in those case. Use each instead)

$('input[type=checkbox]').each(function() 
{ 
    $(this).prop('checked', false); 
});

Why is a div with "display: table-cell;" not affected by margin?

If you have div next each other like this

<div id="1" style="float:left; margin-right:5px">

</div>
<div id="2" style="float:left">

</div>

This should work!

Checking for Undefined In React

I was face same problem ..... And I got solution by using typeof()

if (typeof(value) !== 'undefined' && value != null) {
         console.log('Not Undefined and Not Null')
  } else {
         console.log('Undefined or Null')
}

You must have to use typeof() to identified undefined

jQuery Event : Detect changes to the html/text of a div

There is no inbuilt solution to this problem, this is a problem with your design and coding pattern.

You can use publisher/subscriber pattern. For this you can use jQuery custom events or your own event mechanism.

First,

function changeHtml(selector, html) {
    var elem = $(selector);
    jQuery.event.trigger('htmlchanging', { elements: elem, content: { current: elem.html(), pending: html} });
    elem.html(html);
    jQuery.event.trigger('htmlchanged', { elements: elem, content: html });
}

Now you can subscribe divhtmlchanging/divhtmlchanged events as follow,

$(document).bind('htmlchanging', function (e, data) {
    //your before changing html, logic goes here
});

$(document).bind('htmlchanged', function (e, data) {
    //your after changed html, logic goes here
});

Now, you have to change your div content changes through this changeHtml() function. So, you can monitor or can do necessary changes accordingly because bind callback data argument containing the information.

You have to change your div's html like this;

changeHtml('#mydiv', '<p>test content</p>');

And also, you can use this for any html element(s) except input element. Anyway you can modify this to use with any element(s).

Git Push error: refusing to update checked out branch

As there's already an existing repository, running

git config --bool core.bare true

on the remote repository should suffice

From the core.bare documentation

If true (bare = true), the repository is assumed to be bare with no working directory associated. If this is the case a number of commands that require a working directory will be disabled, such as git-add or git-merge (but you will be able to push to it).

This setting is automatically guessed by git-clone or git-init when the repository is created. By default a repository that ends in "/.git" is assumed to be not bare (bare = false), while all other repositories are assumed to be bare (bare = true).

jQuery attr('onclick')

As @Richard pointed out above, the onClick needs to have a capital 'C'.

$('#stop').click(function() {
     $('next').attr('onClick','stopMoving()');
}

How to use if - else structure in a batch file?

AFAIK you can't do an if else in batch like you can in other languages, it has to be nested if's.

Using nested if's your batch would look like

IF %F%==1 IF %C%==1(
    ::copying the file c to d
    copy "%sourceFile%" "%destinationFile%"
    ) ELSE (
        IF %F%==1 IF %C%==0(
        ::moving the file c to d
        move "%sourceFile%" "%destinationFile%"
        ) ELSE (
            IF %F%==0 IF %C%==1(
            ::copying a directory c from d, /s:  bos olanlar hariç, /e:bos olanlar dahil
            xcopy "%sourceCopyDirectory%" "%destinationCopyDirectory%" /s/e
            ) ELSE (
                IF %F%==0 IF %C%==0(
                ::moving a directory
                xcopy /E "%sourceMoveDirectory%" "%destinationMoveDirectory%"
                rd /s /q "%sourceMoveDirectory%"
                )
            )
        )
    )

or as James suggested, chain your if's, however I think the proper syntax is

IF %F%==1 IF %C%==1(
    ::copying the file c to d
    copy "%sourceFile%" "%destinationFile%"
    )

Where to find "Microsoft.VisualStudio.TestTools.UnitTesting" missing dll?

I got this problem after moving a project and deleting it's packages folder. Nuget was showning that MSTest.TestAdapter and MSTest.TestFramework v 1.3.2 was installed. The fix seemed to be to open VS as administrator and build After that I was able to re-open and build without having admin priviledge.

How to compile a static library in Linux?

Here a full makefile example:

makefile

TARGET = prog

$(TARGET): main.o lib.a
    gcc $^ -o $@

main.o: main.c
    gcc -c $< -o $@

lib.a: lib1.o lib2.o
    ar rcs $@ $^

lib1.o: lib1.c lib1.h
    gcc -c -o $@ $<

lib2.o: lib2.c lib2.h
    gcc -c -o $@ $<

clean:
    rm -f *.o *.a $(TARGET)

explaining the makefile:

  • target: prerequisites - the rule head
  • $@ - means the target
  • $^ - means all prerequisites
  • $< - means just the first prerequisite
  • ar - a Linux tool to create, modify, and extract from archives see the man pages for further information. The options in this case mean:
    • r - replace files existing inside the archive
    • c - create a archive if not already existent
    • s - create an object-file index into the archive

To conclude: The static library under Linux is nothing more than a archive of object files.

main.c using the lib

#include <stdio.h>

#include "lib.h"

int main ( void )
{
    fun1(10);
    fun2(10);
    return 0;
}

lib.h the libs main header

#ifndef LIB_H_INCLUDED
#define LIB_H_INCLUDED

#include "lib1.h"
#include "lib2.h"

#endif

lib1.c first lib source

#include "lib1.h"

#include <stdio.h>

void fun1 ( int x )
{
    printf("%i\n",x);
}

lib1.h the corresponding header

#ifndef LIB1_H_INCLUDED
#define LIB1_H_INCLUDED

#ifdef __cplusplus
   extern “C” {
#endif

void fun1 ( int x );

#ifdef __cplusplus
   }
#endif

#endif /* LIB1_H_INCLUDED */

lib2.c second lib source

#include "lib2.h"

#include <stdio.h>

void fun2 ( int x )
{
    printf("%i\n",2*x);
}

lib2.h the corresponding header

#ifndef LIB2_H_INCLUDED
#define LIB2_H_INCLUDED

#ifdef __cplusplus
   extern “C” {
#endif

void fun2 ( int x );

#ifdef __cplusplus
   }
#endif

#endif /* LIB2_H_INCLUDED */

Check if a path represents a file or a folder

public static boolean isDirectory(String path) {
    return path !=null && new File(path).isDirectory();
}

To answer the question directly.

How do you automatically set the focus to a textbox when a web page loads?

<html>  
<head>  
<script language="javascript" type="text/javascript">  
function SetFocus(InputID)  
{  
   document.getElementById(InputID).focus();  
}  
</script>  
</head>  
<body onload="SetFocus('Box2')">  
<input id="Box1" size="30" /><br/>  
<input id="Box2" size="30" />  
</body>  
</html>  

How to link to a <div> on another page?

You can add hash info in next page url to move browser at specific position(any html element), after page is loaded.

This is can done in this way:

add hash in the url of next_page : example.com#hashkey

$( document ).ready(function() {

  ##get hash code at next page
  var hashcode = window.location.hash;

  ## move page to any specific position of next page(let that is div with id "hashcode")
  $('html,body').animate({scrollTop: $('div#'+hascode).offset().top},'slow');

});

JavaScript adding decimal numbers issue

Use toFixed to convert it to a string with some decimal places shaved off, and then convert it back to a number.

+(0.1 + 0.2).toFixed(12) // 0.3

It looks like IE's toFixed has some weird behavior, so if you need to support IE something like this might be better:

Math.round((0.1 + 0.2) * 1e12) / 1e12

If statement within Where clause

You can't use IF like that. You can do what you want with AND and OR:

SELECT t.first_name,
       t.last_name,
       t.employid,
       t.status
  FROM employeetable t
 WHERE ((status_flag = STATUS_ACTIVE   AND t.status = 'A')
     OR (status_flag = STATUS_INACTIVE AND t.status = 'T')
     OR (source_flag = SOURCE_FUNCTION AND t.business_unit = 'production')
     OR (source_flag = SOURCE_USER     AND t.business_unit = 'users'))
   AND t.first_name LIKE firstname
   AND t.last_name  LIKE lastname
   AND t.employid   LIKE employeeid;

How to get the nth occurrence in a string?

You can also use the string indexOf without creating any arrays.

The second parameter is the index to start looking for the next match.

function nthIndex(str, pat, n){
    var L= str.length, i= -1;
    while(n-- && i++<L){
        i= str.indexOf(pat, i);
        if (i < 0) break;
    }
    return i;
}

var s= "XYZ 123 ABC 456 ABC 789 ABC";

nthIndex(s,'ABC',3)

/*  returned value: (Number)
24
*/

Error 6 (net::ERR_FILE_NOT_FOUND): The files c or directory could not be found

Big one I see that causes this is filename. If you have a SPACE then any number such as 'Site 2' the file path with look like something/Site%202/index.html This is because spaces or rendered as %20, and if another number is immediately following that it will try to read it as %202. Fix is you never use spaces in your filenames.

How to remove all options from a dropdown using jQuery / JavaScript

Other approach for Vanilla JavaScript:

for(var o of document.querySelectorAll('#models > option')) {
  o.remove()
}

Run Command Line & Command From VBS

The problem is on this line:

oShell.run "cmd.exe /C copy "S:Claims\Sound.wav" "C:\WINDOWS\Media\Sound.wav"

Your first quote next to "S:Claims" ends the string; you need to escape the quotes around your files with a second quote, like this:

oShell.run "cmd.exe /C copy ""S:\Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "

You also have a typo in S:Claims\Sound.wav, should be S:\Claims\Sound.wav.

I also assume the apostrophe before Dim oShell and after Set oShell = Nothing are typos as well.

PHP Get URL with Parameter

Here's probably what you are looking for: php-get-url-query-string. You can combine it with other suggested $_SERVER parameters.

jQuery.css() - marginLeft vs. margin-left?

Late to answer, but no-one has specified that css property with dash won't work in object declaration in jquery:

.css({margin-left:'200px'});//won't work
.css({marginLeft:'200px'});//works

So, do not forget to use quotes if you prefer to use dash style property in jquery code.

.css({'margin-left':'200px'});//works

Reading output of a command into an array in Bash

The other answers will break if output of command contains spaces (which is rather frequent) or glob characters like *, ?, [...].

To get the output of a command in an array, with one line per element, there are essentially 3 ways:

  1. With Bash=4 use mapfile—it's the most efficient:

    mapfile -t my_array < <( my_command )
    
  2. Otherwise, a loop reading the output (slower, but safe):

    my_array=()
    while IFS= read -r line; do
        my_array+=( "$line" )
    done < <( my_command )
    
  3. As suggested by Charles Duffy in the comments (thanks!), the following might perform better than the loop method in number 2:

    IFS=$'\n' read -r -d '' -a my_array < <( my_command && printf '\0' )
    

    Please make sure you use exactly this form, i.e., make sure you have the following:

    • IFS=$'\n' on the same line as the read statement: this will only set the environment variable IFS for the read statement only. So it won't affect the rest of your script at all. The purpose of this variable is to tell read to break the stream at the EOL character \n.
    • -r: this is important. It tells read to not interpret the backslashes as escape sequences.
    • -d '': please note the space between the -d option and its argument ''. If you don't leave a space here, the '' will never be seen, as it will disappear in the quote removal step when Bash parses the statement. This tells read to stop reading at the nil byte. Some people write it as -d $'\0', but it is not really necessary. -d '' is better.
    • -a my_array tells read to populate the array my_array while reading the stream.
    • You must use the printf '\0' statement after my_command, so that read returns 0; it's actually not a big deal if you don't (you'll just get an return code 1, which is okay if you don't use set -e – which you shouldn't anyway), but just bear that in mind. It's cleaner and more semantically correct. Note that this is different from printf '', which doesn't output anything. printf '\0' prints a null byte, needed by read to happily stop reading there (remember the -d '' option?).

If you can, i.e., if you're sure your code will run on Bash=4, use the first method. And you can see it's shorter too.

If you want to use read, the loop (method 2) might have an advantage over method 3 if you want to do some processing as the lines are read: you have direct access to it (via the $line variable in the example I gave), and you also have access to the lines already read (via the array ${my_array[@]} in the example I gave).

Note that mapfile provides a way to have a callback eval'd on each line read, and in fact you can even tell it to only call this callback every N lines read; have a look at help mapfile and the options -C and -c therein. (My opinion about this is that it's a little bit clunky, but can be used sometimes if you only have simple things to do — I don't really understand why this was even implemented in the first place!).


Now I'm going to tell you why the following method:

my_array=( $( my_command) )

is broken when there are spaces:

$ # I'm using this command to test:
$ echo "one two"; echo "three four"
one two
three four
$ # Now I'm going to use the broken method:
$ my_array=( $( echo "one two"; echo "three four" ) )
$ declare -p my_array
declare -a my_array='([0]="one" [1]="two" [2]="three" [3]="four")'
$ # As you can see, the fields are not the lines
$
$ # Now look at the correct method:
$ mapfile -t my_array < <(echo "one two"; echo "three four")
$ declare -p my_array
declare -a my_array='([0]="one two" [1]="three four")'
$ # Good!

Then some people will then recommend using IFS=$'\n' to fix it:

$ IFS=$'\n'
$ my_array=( $(echo "one two"; echo "three four") )
$ declare -p my_array
declare -a my_array='([0]="one two" [1]="three four")'
$ # It works!

But now let's use another command, with globs:

$ echo "* one two"; echo "[three four]"
* one two
[three four]
$ IFS=$'\n'
$ my_array=( $(echo "* one two"; echo "[three four]") )
$ declare -p my_array
declare -a my_array='([0]="* one two" [1]="t")'
$ # What?

That's because I have a file called t in the current directory… and this filename is matched by the glob [three four]… at this point some people would recommend using set -f to disable globbing: but look at it: you have to change IFS and use set -f to be able to fix a broken technique (and you're not even fixing it really)! when doing that we're really fighting against the shell, not working with the shell.

$ mapfile -t my_array < <( echo "* one two"; echo "[three four]")
$ declare -p my_array
declare -a my_array='([0]="* one two" [1]="[three four]")'

here we're working with the shell!

How to import functions from different js file in a Vue+webpack+vue-loader project

I was trying to organize my vue app code, and came across this question , since I have a lot of logic in my component and can not use other sub-coponents , it makes sense to use many functions in a separate js file and call them in the vue file, so here is my attempt

1)The Component (.vue file)

//MyComponent.vue file
<template>
  <div>
  <div>Hello {{name}}</div>
  <button @click="function_A">Read Name</button>
  <button @click="function_B">Write Name</button>
  <button @click="function_C">Reset</button>
  <div>{{message}}</div>
  </div>
 </template>


<script>
import Mylib from "./Mylib"; // <-- import
export default {
  name: "MyComponent",
  data() {
    return {
      name: "Bob",
      message: "click on the buttons"
    };
  },
  methods: {
    function_A() {
      Mylib.myfuncA(this); // <---read data
    },
    function_B() {
      Mylib.myfuncB(this); // <---write data
    },
    function_C() {
      Mylib.myfuncC(this); // <---write data
    }
  }
};
</script>

2)The External js file

//Mylib.js
let exports = {};

// this (vue instance) is passed as that , so we
// can read and write data from and to it as we please :)
exports.myfuncA = (that) => {
  that.message =
  "you hit ''myfuncA'' function that is located in Mylib.js  and data.name = " +
    that.name;
};

exports.myfuncB = (that) => {
  that.message =
  "you hit ''myfuncB'' function that is located in Mylib.js and now I will change the name to Nassim";
  that.name = "Nassim"; // <-- change name to Nassim
};

exports.myfuncC = (that) => {
  that.message =
  "you hit ''myfuncC'' function that is located in Mylib.js and now I will change the name back to Bob";
  that.name = "Bob"; // <-- change name to Bob
};

export default exports;

enter image description here 3)see it in action : https://codesandbox.io/s/distracted-pare-vuw7i?file=/src/components/MyComponent.vue


edit

after getting more experience with Vue , I found out that you could use mixins too to split your code into different files and make it easier to code and maintain see https://vuejs.org/v2/guide/mixins.html

Using DISTINCT and COUNT together in a MySQL Query

I would do something like this:

Select count(*), productid
from products
where keyword = '$keyword'
group by productid

that will give you a list like

count(*)    productid  
----------------------
 5           12345   
 3           93884   
 9           93493    

This allows you to see how many of each distinct productid ID is associated with the keyword.

Check whether a string matches a regex in JS

Use regex.test() if all you want is a boolean result:

_x000D_
_x000D_
console.log(/^([a-z0-9]{5,})$/.test('abc1')); // false_x000D_
_x000D_
console.log(/^([a-z0-9]{5,})$/.test('abc12')); // true_x000D_
_x000D_
console.log(/^([a-z0-9]{5,})$/.test('abc123')); // true
_x000D_
_x000D_
_x000D_

...and you could remove the () from your regexp since you've no need for a capture.

Is there a command to undo git init?

remove the .git folder in your project root folder

if you installed submodules and want to remove their git, also remove .git from submodules folders

How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null)

This is similar to some of the other answers, but is compact and avoids the conversion to dictionary if you already have a list.

Given a ComboBox "combobox" on a windows form and a class SomeClass with the string type property Name,

List<SomeClass> list = new List<SomeClass>();

combobox.DisplayMember = "Name";
combobox.DataSource = list;

Which means that combobox.SelectedItem is a SomeClass object from list, and each item in combobox will be displayed using its property Name.

You can read the selected item using

SomeClass someClass = (SomeClass)combobox.SelectedItem;

How to create custom view programmatically in swift having controls text field, button etc

The CGRectZero constant is equal to a rectangle at position (0,0) with zero width and height. This is fine to use, and actually preferred, if you use AutoLayout, since AutoLayout will then properly place the view.

But, I expect you do not use AutoLayout. So the most simple solution is to specify the size of the custom view by providing a frame explicitly:

customView = MyCustomView(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
self.view.addSubview(customView)

Note that you also need to use addSubview otherwise your view is not added to the view hierarchy.

How to install mechanize for Python 2.7?

install dependencies on Debian/Ubuntu:

$ sudo apt-get install python-pip python-matplotlib

install multi-mechanize from PyPI using Pip:

$ sudo pip install -U multi-mechanize

Sublime Text 2: How to delete blank/empty lines

Their is a more easily way to do that without regex. you have just to select the whole text. then go to: Edit--> Permute Lines --> Unique.

That's all. and all blank lines will be deleted.

How do you post to an iframe?

This function creates a temporary form, then send data using jQuery :

function postToIframe(data,url,target){
    $('body').append('<form action="'+url+'" method="post" target="'+target+'" id="postToIframe"></form>');
    $.each(data,function(n,v){
        $('#postToIframe').append('<input type="hidden" name="'+n+'" value="'+v+'" />');
    });
    $('#postToIframe').submit().remove();
}

target is the 'name' attr of the target iFrame, and data is a JS object :

data={last_name:'Smith',first_name:'John'}

"While .. End While" doesn't work in VBA?

VBA is not VB/VB.NET

The correct reference to use is Do..Loop Statement (VBA). Also see the article Excel VBA For, Do While, and Do Until. One way to write this is:

Do While counter < 20
    counter = counter + 1
Loop

(But a For..Next might be more appropriate here.)

Happy coding.

How do I go about adding an image into a java project with eclipse?

If you still have problems with Eclipse finding your files, you might try the following:

  1. Verify that the file exists according to the current execution environment by using the java.io.File class to get a canonical path format and verify that (a) the file exists and (b) what the canonical path is.
  2. Verify the default working directory by printing the following in your main:

        System.out.println("Working dir:  " + System.getProperty("user.dir"));
    

For (1) above, I put the following debugging code around the specific file I was trying to access:

            File imageFile = new File(source);
            System.out.println("Canonical path of target image: " + imageFile.getCanonicalPath());
            if (!imageFile.exists()) {
                System.out.println("file " + imageFile + " does not exist");
            }
            image = ImageIO.read(imageFile);                

For whatever reason, I ended up ignoring most of the other posts telling me to put the image files in "src" or some other variant, as I verified that the system was looking at the root of the Eclipse project directory hierarchy (e.g., $HOME/workspace/myProject).

Having the images in src/ (which is automatically copied to bin/) didn't do the trick on Eclipse Luna.

SQL Server 2008 R2 Express permissions -- cannot create database or modify users

Coming late to the party, but I found this fantastic step-by-step guide on getting control of your SQLExpress instance if you don't have your sa password. I used this process to not only reset my sa password, but I also added my domain account to all the available server roles. I can now create databases, alter logins, do bulk operations, backups/restores, etc using my normal login.

To summarize, you use SQL Server Configuration Manager to put your instance into single-user mode. This elevates you to sysadmin when you connect, allowing you the ability to set everything up.

Edit: I've copied the steps below - kudos to the original author of the link above.

  1. Log on to the computer as an Administrator (or Any user with administrator privileges)
  2. Open "SQL Server Configuration Manager"
  3. Click "SQL Server Services" on the left pane
  4. Stop "SQL Server" and "SQL Server Agent" instance on the right pane if it is running
  5. Run the SQL Express in single-user mode by right clicking on "SQL Server" instance -> Properties (on the right pane of SQL Server Configuration Manager).
  6. Click Advanced Tab, and look for "Startup Parameters". Change the "Startup Parameters" so that the new value will be -m; (without the <>) example: from: -dc:\Program Files\Microsoft SQL.............(til end of string) to: -m;-dc:\Program Files\Microsoft SQL.............(til end of string)
  7. Start the SQL Server
  8. Open your MS SQL Server Management Studio and log on to the SQL server with "Windows Authentication" as the authentication mode. Since we have the SQL Server running on single user mode, and you are logged on to the computer with Administrator privileges, you will have a "sysadmin" access to the database.
  9. Expand the "Security" node on MS SQL Server Management Studio on the left pane
  10. Expand the "Logins" node
  11. Double-click the 'sa' login
  12. Change the password by entering a complex password if "Enforce password policy" is ticked, otherwise, just enter any password.
  13. Make sure that "sa" Account is "enabled" by clicking on Status on the left pane. Set the radio box under "Login" to "Enabled"
  14. Click "OK"
  15. Back on the main window of MS SQL Server Management Studio, verify if SQL Server Authentication is used by right clicking on the top most node in the left pane (usually ".\SQLEXPRESS (SQL Server )") and choosing properties.
  16. Click "Security" in the left pane and ensure that "SQL Server and Windows Authentication mode" is the one selected under "Server authentication"
  17. Click "OK"
  18. Disconnect from MS SQL Server Management Studio
  19. Open "Sql Server Configuration Manager" again and stop the SQL Server instance.
  20. Right-click on SQL Server instance and click on "Advanced" tab. Again look for "Startup Parameters" and remove the "-m;" that you added earlier.
  21. Click "OK" and start the SQL Server Instance again
  22. You should now be able to log on as "sa" using the new password that you have set in step 12.

How to assign pointer address manually in C programming language?

int *p=(int *)0x1234 = 10; //0x1234 is the memory address and value 10 is assigned in that address


unsigned int *ptr=(unsigned int *)0x903jf = 20;//0x903j is memory address and value 20 is assigned 

Basically in Embedded platform we are using directly addresses instead of names

Java Replace Character At Specific Position Of String?

Petar Ivanov's answer to replace a character at a specific index in a string question

String are immutable in Java. You can't change them.

You need to create a new string with the character replaced.

String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);

Or you can use a StringBuilder:

StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');

System.out.println(myName);

How to preserve insertion order in HashMap?

HashMap is unordered per the second line of the documentation:

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

Perhaps you can do as aix suggests and use a LinkedHashMap, or another ordered collection. This link can help you find the most appropriate collection to use.

When to use CouchDB over MongoDB and vice versa

Of C, A & P (Consistency, Availability & Partition tolerance) which 2 are more important to you? Quick reference, the Visual Guide To NoSQL Systems

  • MongodB : Consistency and Partition Tolerance
  • CouchDB : Availability and Partition Tolerance

A blog post, Cassandra vs MongoDB vs CouchDB vs Redis vs Riak vs HBase vs Membase vs Neo4j comparison has 'Best used' scenarios for each NoSQL database compared. Quoting the link,

  • MongoDB: If you need dynamic queries. If you prefer to define indexes, not map/reduce functions. If you need good performance on a big DB. If you wanted CouchDB, but your data changes too much, filling up disks.
  • CouchDB : For accumulating, occasionally changing data, on which pre-defined queries are to be run. Places where versioning is important.

A recent (Feb 2012) and more comprehensive comparison by Riyad Kalla,

  • MongoDB : Master-Slave Replication ONLY
  • CouchDB : Master-Master Replication

A blog post (Oct 2011) by someone who tried both, A MongoDB Guy Learns CouchDB commented on the CouchDB's paging being not as useful.

A dated (Jun 2009) benchmark by Kristina Chodorow (part of team behind MongoDB),

I'd go for MongoDB.

Hope it helps.

How to show Alert Message like "successfully Inserted" after inserting to DB using ASp.net MVC3

Personally I'd go with AJAX.

If you cannot switch to @Ajax... helpers, I suggest you to add a couple of properties in your model

public bool TriggerOnLoad { get; set; }
public string TriggerOnLoadMessage { get; set: }

Change your view to a strongly typed Model via

@using MyModel

Before returning the View, in case of successfull creation do something like

MyModel model = new MyModel();
model.TriggerOnLoad = true;
model.TriggerOnLoadMessage = "Object successfully created!";
return View ("Add", model);

then in your view, add this

@{
   if (model.TriggerOnLoad) {
   <text>
   <script type="text/javascript">
     alert('@Model.TriggerOnLoadMessage');
   </script>
   </text>
   }
}

Of course inside the tag you can choose to do anything you want, event declare a jQuery ready function:

$(document).ready(function () {
   alert('@Model.TriggerOnLoadMessage');
});

Please remember to reset the Model properties upon successfully alert emission.

Another nice thing about MVC is that you can actually define an EditorTemplate for all this, and then use it in your view via:

@Html.EditorFor (m => m.TriggerOnLoadMessage)

But in case you want to build up such a thing, maybe it's better to define your own C# class:

class ClientMessageNotification {
    public bool TriggerOnLoad { get; set; }
    public string TriggerOnLoadMessage { get; set: }
}

and add a ClientMessageNotification property in your model. Then write EditorTemplate / DisplayTemplate for the ClientMessageNotification class and you're done. Nice, clean, and reusable.

Volatile Vs Atomic

There are two important concepts in multithreading environment:

  1. atomicity
  2. visibility

The volatile keyword eradicates visibility problems, but it does not deal with atomicity. volatile will prevent the compiler from reordering instructions which involve a write and a subsequent read of a volatile variable; e.g. k++. Here, k++ is not a single machine instruction, but three:

  1. copy the value to a register;
  2. increment the value;
  3. place it back.

So, even if you declare a variable as volatile, this will not make this operation atomic; this means another thread can see a intermediate result which is a stale or unwanted value for the other thread.

On the other hand, AtomicInteger, AtomicReference are based on the Compare and swap instruction. CAS has three operands: a memory location V on which to operate, the expected old value A, and the new value B. CAS atomically updates V to the new value B, but only if the value in V matches the expected old value A; otherwise, it does nothing. In either case, it returns the value currently in V. The compareAndSet() methods of AtomicInteger and AtomicReference take advantage of this functionality, if it is supported by the underlying processor; if it is not, then the JVM implements it via spin lock.

NUnit Unit tests not showing in Test Explorer with Test Adapter installed

I also found that when I uninstalled nunit v3.2.1, the nunit framework reference for v3.2.1 was still in my project in solution explorer. Solution Explorer > ProjectName > References

If you right click it will show the version. Remove this Then Right click on References > Add Reference.

Search for the version 2.x version and add then rebuild solution.

That worked for me!

Change onClick attribute with javascript

You are not actually changing the function.

onClick is assigned to a function (Which is a reference to something, a function pointer in this case). The values passed to it don't matter and cannot be utilised in any manner.

Another problem is your variable color seems out of nowhere.

Ideally, inside the function you should put this logic and let it figure out what to write. (on/off etc etc)

python xlrd unsupported format, or corrupt file.

Open in google sheets and then download from sheets as CSV and then reupload to drive. Then you can Open CSV file from python.

How do I convert from int to String?

Normal ways would be Integer.toString(i) or String.valueOf(i).

The concatenation will work, but it is unconventional and could be a bad smell as it suggests the author doesn't know about the two methods above (what else might they not know?).

Java has special support for the + operator when used with strings (see the documentation) which translates the code you posted into:

StringBuilder sb = new StringBuilder();
sb.append("");
sb.append(i);
String strI = sb.toString();

at compile-time. It's slightly less efficient (sb.append() ends up calling Integer.getChars(), which is what Integer.toString() would've done anyway), but it works.

To answer Grodriguez's comment: ** No, the compiler doesn't optimise out the empty string in this case - look:

simon@lucifer:~$ cat TestClass.java
public class TestClass {
  public static void main(String[] args) {
    int i = 5;
    String strI = "" + i;
  }
}
simon@lucifer:~$ javac TestClass.java && javap -c TestClass
Compiled from "TestClass.java"
public class TestClass extends java.lang.Object{
public TestClass();
  Code:
   0:    aload_0
   1:    invokespecial    #1; //Method java/lang/Object."<init>":()V
   4:    return

public static void main(java.lang.String[]);
  Code:
   0:    iconst_5
   1:    istore_1

Initialise the StringBuilder:

   2:    new    #2; //class java/lang/StringBuilder
   5:    dup
   6:    invokespecial    #3; //Method java/lang/StringBuilder."<init>":()V

Append the empty string:

   9:    ldc    #4; //String
   11:    invokevirtual    #5; //Method java/lang/StringBuilder.append:
(Ljava/lang/String;)Ljava/lang/StringBuilder;

Append the integer:

   14:    iload_1
   15:    invokevirtual    #6; //Method java/lang/StringBuilder.append:
(I)Ljava/lang/StringBuilder;

Extract the final string:

   18:    invokevirtual    #7; //Method java/lang/StringBuilder.toString:
()Ljava/lang/String;
   21:    astore_2
   22:    return
}

There's a proposal and ongoing work to change this behaviour, targetted for JDK 9.

Reference — What does this symbol mean in PHP?

{} Curly braces

And some words about last post

$x[4] = 'd'; // it works
$x{4} = 'd'; // it works

$echo $x[4]; // it works
$echo $x{4}; // it works

$x[] = 'e'; // it works
$x{} = 'e'; // does not work

$x = [1, 2]; // it works
$x = {1, 2}; // does not work

echo "${x[4]}"; // it works
echo "${x{4}}"; // does not work

echo "{$x[4]}"; // it works
echo "{$x{4}}"; // it works

Updating property value in properties file without deleting other values

Properties prop = new Properties();
prop.load(...); // FileInputStream 
prop.setProperty("key", "value");
prop.store(...); // FileOutputStream 

Adding quotes to a string in VBScript

You have to use double double quotes to escape the double quotes (lol):

g = "abcd """ & a & """"

How can I change an element's class with JavaScript?

You can use node.className like so:

document.getElementById('foo').className = 'bar';

This should work in IE5.5 and up according to PPK.

How do I create a dictionary with keys from a list and values defaulting to (say) zero?

dict((el,0) for el in a) will work well.

Python 2.7 and above also support dict comprehensions. That syntax is {el:0 for el in a}.

Convert command line arguments into an array in Bash

Side-by-side view of how the array and $@ are practically the same.

Code:

#!/bin/bash

echo "Dollar-1 : $1"
echo "Dollar-2 : $2"
echo "Dollar-3 : $3"
echo "Dollar-AT: $@"
echo ""

myArray=( "$@" )

echo "A Val 0: ${myArray[0]}"
echo "A Val 1: ${myArray[1]}"
echo "A Val 2: ${myArray[2]}"
echo "A All Values: ${myArray[@]}"

Input:

./bash-array-practice.sh 1 2 3 4

Output:

Dollar-1 : 1
Dollar-2 : 2
Dollar-3 : 3
Dollar-AT: 1 2 3 4

A Val 0: 1
A Val 1: 2
A Val 2: 3
A All Values: 1 2 3 4

The way to check a HDFS directory's size?

hadoop version 2.3.33:

hadoop fs -dus  /path/to/dir  |   awk '{print $2/1024**3 " G"}' 

enter image description here

Show whitespace characters in Visual Studio Code

All Platforms (Windows/Linux/Mac):

It is under View -> Render Whitespace.

?? Sometimes the menu item shows that it is currently active but you can's see white spaces. You should uncheck and check again to make it work. It is a known bug


A note about the macOS ?

In the mac environment, you can search for any menu option under the Help menu, then it will open the exact menu path you are looking for. For example, searching for whitespace result in this:

Demo

How to enable named/bind/DNS full logging?

I usually expand each log out into it's own channel and then to a separate log file, certainly makes things easier when you are trying to debug specific issues. So my logging section looks like the following:

logging {
    channel default_file {
        file "/var/log/named/default.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel general_file {
        file "/var/log/named/general.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel database_file {
        file "/var/log/named/database.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel security_file {
        file "/var/log/named/security.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel config_file {
        file "/var/log/named/config.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel resolver_file {
        file "/var/log/named/resolver.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel xfer-in_file {
        file "/var/log/named/xfer-in.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel xfer-out_file {
        file "/var/log/named/xfer-out.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel notify_file {
        file "/var/log/named/notify.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel client_file {
        file "/var/log/named/client.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel unmatched_file {
        file "/var/log/named/unmatched.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel queries_file {
        file "/var/log/named/queries.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel network_file {
        file "/var/log/named/network.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel update_file {
        file "/var/log/named/update.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel dispatch_file {
        file "/var/log/named/dispatch.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel dnssec_file {
        file "/var/log/named/dnssec.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel lame-servers_file {
        file "/var/log/named/lame-servers.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };

    category default { default_file; };
    category general { general_file; };
    category database { database_file; };
    category security { security_file; };
    category config { config_file; };
    category resolver { resolver_file; };
    category xfer-in { xfer-in_file; };
    category xfer-out { xfer-out_file; };
    category notify { notify_file; };
    category client { client_file; };
    category unmatched { unmatched_file; };
    category queries { queries_file; };
    category network { network_file; };
    category update { update_file; };
    category dispatch { dispatch_file; };
    category dnssec { dnssec_file; };
    category lame-servers { lame-servers_file; };
};

Hope this helps.

How to make a link open multiple pages when clicked

You can open multiple windows on single click... Try this..

<a href="http://--" 
     onclick=" window.open('http://--','','width=700,height=700'); 
               window.open('http://--','','width=700,height=500'); ..// add more"
               >Click Here</a>`

Python For loop get index

Do you want to iterate over characters or words?

For words, you'll have to split the words first, such as

for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index

This prints the index of the word.

For the absolute character position you'd need something like

chars = 0
for index, word in enumerate(loopme.split(" ")):
    print "CURRENT WORD IS", word, "AT INDEX", index, "AND AT CHARACTER", chars
    chars += len(word) + 1

How to set a hidden value in Razor

How about like this

public static MvcHtmlString HiddenFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, object htmlAttributes)
    {
        return HiddenFor(htmlHelper, expression, value, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
    }

    public static MvcHtmlString HiddenFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, IDictionary<string, object> htmlAttributes)
    {
        return htmlHelper.Hidden(ExpressionHelper.GetExpressionText(expression), value, htmlAttributes);
    }

Use it like this

 @Html.HiddenFor(customerId => reviewModel.CustomerId, Site.LoggedInCustomerId, null)

Sorting Values of Set

Use a SortedSet (TreeSet is the default one):

SortedSet<String> set=new TreeSet<String>();
set.add("12");
set.add("15");
set.add("5");
List<String> list=new ArrayList<String>(set);

No extra sorting code needed.

Oh, I see you want a different sort order. Supply a Comparator to the TreeSet:

new TreeSet<String>(Comparator.comparing(Integer::valueOf));

Now your TreeSet will sort Strings in numeric order (which implies that it will throw exceptions if you supply non-numeric strings)

Reference:

SQL Logic Operator Precedence: And and Or

And has precedence over Or, so, even if a <=> a1 Or a2

Where a And b 

is not the same as

Where a1 Or a2 And b,

because that would be Executed as

Where a1 Or (a2 And b)

and what you want, to make them the same, is the following (using parentheses to override rules of precedence):

 Where (a1 Or a2) And b

Here's an example to illustrate:

Declare @x tinyInt = 1
Declare @y tinyInt = 0
Declare @z tinyInt = 0

Select Case When @x=1 OR @y=1 And @z=1 Then 'T' Else 'F' End -- outputs T
Select Case When (@x=1 OR @y=1) And @z=1 Then 'T' Else 'F' End -- outputs F

For those who like to consult references (in alphabetic order):

Zabbix server is not running: the information displayed may not be current

Edit this file: sudo nano /etc/default/zabbix-server

Adjust the START property to yes:

START=yes

Then try to run Zabbix again: sudo service zabbix-server start

How to change the value of ${user} variable used in Eclipse templates

dovescrywolf gave tip as a comment on article linked by Davide Inglima

It was was very useful for me on MacOS.

  • Close Eclipse if it's opened.
  • Open Termnal (bash console) and do below things:

    $ pwd /Users/You/YourEclipseInstalationDirectory  
    $ cd Eclipse.app/Contents/MacOS/  
    $ echo "-Duser.name=Your Name" >> eclipse.ini  
    $ cat eclipse.ini
    
  • Close Terminal and start/open Eclipse again.

How to download/checkout a project from Google Code in Windows?

If you have a github account and don't want to download software, you can export to github, then download a zip from github.

How to enable CORS in ASP.NET Core

Step 1: We need Microsoft.AspNetCore.Cors package in our project. For installing go to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution. Search for Microsoft.AspNetCore.Cors and install the package.

Step 2: We need to inject CORS into the container so that it can be used by the application. In Startup.cs class, let’s go to the ConfigureServices method and register CORS.

enter image description here

So, in our server app, let’s go to Controllers -> HomeController.cs and add the EnableCors decorator to the Index method (Or your specific controller and action):

enter image description here

For More Detail Click Here

Best way to get user GPS location in background in Android

For Track the location every 10 mins(based on requirement) please follow this link it is working fine without any issues

https://github.com/safetysystemtechnology/location-tracker-background

Unix ls command: show full path when using options

optimized from spacedrop answer ...

ls $(pwd)/*

and you can use ls options

ls -alrt $(pwd)/*

How to decode Unicode escape sequences like "\u00ed" to proper UTF-8 encoded characters?

This is a sledgehammer approach to replacing raw UNICODE with HTML. I haven't seen any other place to put this solution, but I assume others have had this problem.

Apply this str_replace function to the RAW JSON, before doing anything else.

function unicode2html($str){
    $i=65535;
    while($i>0){
        $hex=dechex($i);
        $str=str_replace("\u$hex","&#$i;",$str);
        $i--;
     }
     return $str;
}

This won't take as long as you think, and this will replace ANY unicode with HTML.

Of course this can be reduced if you know the unicode types that are being returned in the JSON.

For example my code was getting lots of arrows and dingbat unicode. These are between 8448 an 11263. So my production code looks like:

$i=11263;
while($i>08448){
    ...etc...

You can look up the blocks of Unicode by type here: http://unicode-table.com/en/ If you know you're translating Arabic or Telegu or whatever, you can just replace those codes, not all 65,000.

You could apply this same sledgehammer to simple encoding:

 $str=str_replace("\u$hex",chr($i),$str);

PHP: Split string into array, like explode with no delimiter

$array = str_split("$string");

will actuall work pretty fine, BUT if you want to preserve the special characters in that string, and you want to do some manipulation with them, THAN I would use

do {
    $array[] = mb_substr( $string, 0, 1, 'utf-8' );
} while ( $string = mb_substr( $string, 1, mb_strlen( $string ), 'utf-8' ) );

because for some of mine personal uses, it has been shown to be more reliable when there is an issue with special characters

How to get correct timestamp in C#

Your mistake is using new DateTime(), which returns January 1, 0001 at 00:00:00.000 instead of current date and time. The correct syntax to get current date and time is DateTime.Now, so change this:

String timeStamp = GetTimestamp(new DateTime());

to this:

String timeStamp = GetTimestamp(DateTime.Now);

What is mod_php?

Just to add on these answers is that, mod_php is the oldest and slowest method available in HTTPD server to use PHP. It is not recommended, unless you are running old versions of Apache HTTPD and PHP. php-fpm and proxy_cgi are the preferred methods.

HTML table: keep the same width for columns

well, why don't you (get rid of sidebar and) squeeze the table so it is without show/hide effect? It looks odd to me now. The table is too robust.
Otherwise I think scunliffe's suggestion should do it. Or if you wish, you can just set the exact width of table and set either percentage or pixel width for table cells.

How to set a cron job to run at a exact time?

check out

http://www.thesitewizard.com/general/set-cron-job.shtml

for the specifics of setting your crontab directives.

 45 10 * * *

will run in the 10th hour, 45th minute of every day.

for midnight... maybe

 0 0 * * *

How to pass a parameter to Vue @click event handler

I had the same issue and here is how I manage to pass through:

In your case you have addToCount() which is called. now to pass down a param when user clicks, you can say @click="addToCount(item.contactID)"

in your function implementation you can receive the params like:

addToCount(paramContactID){
 // the paramContactID contains the value you passed into the function when you called it
 // you can do what you want to do with the paramContactID in here!

}

Maintaining Session through Angular.js

Typically for a use case which involves a sequence of pages and in the final stage or page we post the data to the server. In this scenario we need to maintain the state. In the below snippet we maintain the state on the client side

As mentioned in the above post. The session is created using the factory recipe.

Client side session can be maintained using the value provider recipe as well.

Please refer to my post for the complete details. session-tracking-in-angularjs

Let's take an example of a shopping cart which we need to maintain across various pages / angularjs controller.

In typical shopping cart we buy products on various product / category pages and keep updating the cart. Here are the steps.

Here we create the custom injectable service having a cart inside using the "value provider recipe".

'use strict';
function Cart() {
    return {
        'cartId': '',
        'cartItem': []
    };
}
// custom service maintains the cart along with its behavior to clear itself , create new , delete Item or update cart 

app.value('sessionService', {
    cart: new Cart(),
    clear: function () {
        this.cart = new Cart();
        // mechanism to create the cart id 
        this.cart.cartId = 1;
    },
    save: function (session) {
        this.cart = session.cart;
    },
    updateCart: function (productId, productQty) {
        this.cart.cartItem.push({
            'productId': productId,
            'productQty': productQty
        });
    },
    //deleteItem and other cart operations function goes here...
});

ASP.NET MVC get textbox input value

Another way by using ajax method:

View:

@Html.TextBox("txtValue", null, new { placeholder = "Input value" })
<input type="button" value="Start" id="btnStart"  />

<script>
    $(function () {
        $('#btnStart').unbind('click');
        $('#btnStart').on('click', function () {
            $.ajax({
                url: "/yourControllerName/yourMethod",
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                data: JSON.stringify({
                    txtValue: $("#txtValue").val()
                }),
                async: false
            });
       });
   });
</script>

Controller:

[HttpPost]
public EmptyResult YourMethod(string txtValue)
{
    // do what you want with txtValue
    ...
}

Ignore case in Python strings

The recommended idiom to sort lists of values using expensive-to-compute keys is to the so-called "decorated pattern". It consists simply in building a list of (key, value) tuples from the original list, and sort that list. Then it is trivial to eliminate the keys and get the list of sorted values:

>>> original_list = ['a', 'b', 'A', 'B']
>>> decorated = [(s.lower(), s) for s in original_list]
>>> decorated.sort()
>>> sorted_list = [s[1] for s in decorated]
>>> sorted_list
['A', 'a', 'B', 'b']

Or if you like one-liners:

>>> sorted_list = [s[1] for s in sorted((s.lower(), s) for s in original_list)]
>>> sorted_list
['A', 'a', 'B', 'b']

If you really worry about the cost of calling lower(), you can just store tuples of (lowered string, original string) everywhere. Tuples are the cheapest kind of containers in Python, they are also hashable so they can be used as dictionary keys, set members, etc.

Sending HTTP POST Request In Java

I recomend use http-request built on apache http api.

HttpRequest<String> httpRequest = HttpRequestBuilder.createPost("http://www.example.com/page.php", String.class)
.responseDeserializer(ResponseDeserializer.ignorableDeserializer()).build();

public void send(){
   String response = httpRequest.execute("id", "10").get();
}

How to disable HTML links

You can use this to disabled the Hyperlink of asp.net or link buttons in html.

$("td > a").attr("disabled", "disabled").on("click", function() {
    return false; 
});

How to make a <div> appear in front of regular text/tables

You can use the stacking index of the div to make it appear on top of anything else. Make it a larger value that other elements and it well be on top of others.

use z-index property. See Specifying the stack level: the 'z-index' property and

Elaborate description of Stacking Contexts

Something like

#divOnTop { z-index: 1000; }

<div id="divOnTop">I am on top</div>

What you have to look out for will be IE6. In IE 6 some elements like <select> will be placed on top of an element with z-index value higher than the <select>. You can have a workaround for this by placing an <iframe> behind the div.

See this Internet Explorer z-index bug?

Why does the html input with type "number" allow the letter 'e' to be entered in the field?

To hide both letter e and minus sign - just go for:

onkeydown="return event.keyCode !== 69 && event.keyCode !== 189"

Removing multiple files from a Git repo that have already been deleted from disk

You can use git add -u <filenames> to stage the deleted files only.

For example, if you deleted the files templates/*.tpl, then use git add -u templates/*.tpl.

The -u is required in order to refer to files that exist in the repository but no longer exist in the working directory. Otherwise, the default of git add is to look for the files in the working directory, and if you specify files you've deleted there, it won't find them.

Apache Spark: map vs mapPartitions?

Imp. TIP :

Whenever you have heavyweight initialization that should be done once for many RDD elements rather than once per RDD element, and if this initialization, such as creation of objects from a third-party library, cannot be serialized (so that Spark can transmit it across the cluster to the worker nodes), use mapPartitions() instead of map(). mapPartitions() provides for the initialization to be done once per worker task/thread/partition instead of once per RDD data element for example : see below.

val newRd = myRdd.mapPartitions(partition => {
  val connection = new DbConnection /*creates a db connection per partition*/

  val newPartition = partition.map(record => {
    readMatchingFromDB(record, connection)
  }).toList // consumes the iterator, thus calls readMatchingFromDB 

  connection.close() // close dbconnection here
  newPartition.iterator // create a new iterator
})

Q2. does flatMap behave like map or like mapPartitions?

Yes. please see example 2 of flatmap.. its self explanatory.

Q1. What's the difference between an RDD's map and mapPartitions

map works the function being utilized at a per element level while mapPartitions exercises the function at the partition level.

Example Scenario : if we have 100K elements in a particular RDD partition then we will fire off the function being used by the mapping transformation 100K times when we use map.

Conversely, if we use mapPartitions then we will only call the particular function one time, but we will pass in all 100K records and get back all responses in one function call.

There will be performance gain since map works on a particular function so many times, especially if the function is doing something expensive each time that it wouldn't need to do if we passed in all the elements at once(in case of mappartitions).

map

Applies a transformation function on each item of the RDD and returns the result as a new RDD.

Listing Variants

def map[U: ClassTag](f: T => U): RDD[U]

Example :

val a = sc.parallelize(List("dog", "salmon", "salmon", "rat", "elephant"), 3)
 val b = a.map(_.length)
 val c = a.zip(b)
 c.collect
 res0: Array[(String, Int)] = Array((dog,3), (salmon,6), (salmon,6), (rat,3), (elephant,8)) 

mapPartitions

This is a specialized map that is called only once for each partition. The entire content of the respective partitions is available as a sequential stream of values via the input argument (Iterarator[T]). The custom function must return yet another Iterator[U]. The combined result iterators are automatically converted into a new RDD. Please note, that the tuples (3,4) and (6,7) are missing from the following result due to the partitioning we chose.

preservesPartitioning indicates whether the input function preserves the partitioner, which should be false unless this is a pair RDD and the input function doesn't modify the keys.

Listing Variants

def mapPartitions[U: ClassTag](f: Iterator[T] => Iterator[U], preservesPartitioning: Boolean = false): RDD[U]

Example 1

val a = sc.parallelize(1 to 9, 3)
 def myfunc[T](iter: Iterator[T]) : Iterator[(T, T)] = {
   var res = List[(T, T)]()
   var pre = iter.next
   while (iter.hasNext)
   {
     val cur = iter.next;
     res .::= (pre, cur)
     pre = cur;
   }
   res.iterator
 }
 a.mapPartitions(myfunc).collect
 res0: Array[(Int, Int)] = Array((2,3), (1,2), (5,6), (4,5), (8,9), (7,8)) 

Example 2

val x = sc.parallelize(List(1, 2, 3, 4, 5, 6, 7, 8, 9,10), 3)
 def myfunc(iter: Iterator[Int]) : Iterator[Int] = {
   var res = List[Int]()
   while (iter.hasNext) {
     val cur = iter.next;
     res = res ::: List.fill(scala.util.Random.nextInt(10))(cur)
   }
   res.iterator
 }
 x.mapPartitions(myfunc).collect
 // some of the number are not outputted at all. This is because the random number generated for it is zero.
 res8: Array[Int] = Array(1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 5, 7, 7, 7, 9, 9, 10) 

The above program can also be written using flatMap as follows.

Example 2 using flatmap

val x  = sc.parallelize(1 to 10, 3)
 x.flatMap(List.fill(scala.util.Random.nextInt(10))(_)).collect

 res1: Array[Int] = Array(1, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10) 

Conclusion :

mapPartitions transformation is faster than map since it calls your function once/partition, not once/element..

Further reading : foreach Vs foreachPartitions When to use What?

Composer: how can I install another dependency without updating old ones?

To install a new package and only that, you have two options:

  1. Using the require command, just run:

    composer require new/package
    

    Composer will guess the best version constraint to use, install the package, and add it to composer.lock.

    You can also specify an explicit version constraint by running:

    composer require new/package ~2.5
    

–OR–

  1. Using the update command, add the new package manually to composer.json, then run:

    composer update new/package
    

If Composer complains, stating "Your requirements could not be resolved to an installable set of packages.", you can resolve this by passing the flag --with-dependencies. This will whitelist all dependencies of the package you are trying to install/update (but none of your other dependencies).

Regarding the question asker's issues with Laravel and mcrypt: check that it's properly enabled in your CLI php.ini. If php -m doesn't list mcrypt then it's missing.

Important: Don't forget to specify new/package when using composer update! Omitting that argument will cause all dependencies, as well as composer.lock, to be updated.

Parsing jQuery AJAX response

Use parseJSON. Look at the doc

var obj = $.parseJSON(data);

Something like this:

$.ajax({     
    type: "POST",
    url: '/admin/systemgoalssystemgoalupdate?format=html',
    data: formdata,
    success: function (data) {

        console.log($.parseJSON(data)); //will log Object

    }
});

Monad in plain English? (For the OOP programmer with no FP background)

You have a recent presentation "Monadologie -- professional help on type anxiety" by Christopher League (July 12th, 2010), which is quite interesting on topics of continuation and monad.
The video going with this (slideshare) presentation is actually available at vimeo.
The Monad part start around 37 minutes in, on this one hour video, and starts with slide 42 of its 58 slide presentation.

It is presented as "the leading design pattern for functional programming", but the language used in the examples is Scala, which is both OOP and functional.
You can read more on Monad in Scala in the blog post "Monads - Another way to abstract computations in Scala", from Debasish Ghosh (March 27, 2008).

A type constructor M is a monad if it supports these operations:

# the return function
def unit[A] (x: A): M[A]

# called "bind" in Haskell 
def flatMap[A,B] (m: M[A]) (f: A => M[B]): M[B]

# Other two can be written in term of the first two:

def map[A,B] (m: M[A]) (f: A => B): M[B] =
  flatMap(m){ x => unit(f(x)) }

def andThen[A,B] (ma: M[A]) (mb: M[B]): M[B] =
  flatMap(ma){ x => mb }

So for instance (in Scala):

  • Option is a monad
    def unit[A] (x: A): Option[A] = Some(x)

    def flatMap[A,B](m:Option[A])(f:A =>Option[B]): Option[B] =
      m match {
       case None => None
       case Some(x) => f(x)
      }
  • List is Monad
    def unit[A] (x: A): List[A] = List(x)

    def flatMap[A,B](m:List[A])(f:A =>List[B]): List[B] =
      m match {
        case Nil => Nil
        case x::xs => f(x) ::: flatMap(xs)(f)
      }

Monad are a big deal in Scala because of convenient syntax built to take advantage of Monad structures:

for comprehension in Scala:

for {
  i <- 1 to 4
  j <- 1 to i
  k <- 1 to j
} yield i*j*k

is translated by the compiler to:

(1 to 4).flatMap { i =>
  (1 to i).flatMap { j =>
    (1 to j).map { k =>
      i*j*k }}}

The key abstraction is the flatMap, which binds the computation through chaining.
Each invocation of flatMap returns the same data structure type (but of different value), that serves as the input to the next command in chain.

In the above snippet, flatMap takes as input a closure (SomeType) => List[AnotherType] and returns a List[AnotherType]. The important point to note is that all flatMaps take the same closure type as input and return the same type as output.

This is what "binds" the computation thread - every item of the sequence in the for-comprehension has to honor this same type constraint.


If you take two operations (that may fail) and pass the result to the third, like:

lookupVenue: String => Option[Venue]
getLoggedInUser: SessionID => Option[User]
reserveTable: (Venue, User) => Option[ConfNo]

but without taking advantage of Monad, you get convoluted OOP-code like:

val user = getLoggedInUser(session)
val confirm =
  if(!user.isDefined) None
  else lookupVenue(name) match {
    case None => None
    case Some(venue) =>
      val confno = reserveTable(venue, user.get)
      if(confno.isDefined)
        mailTo(confno.get, user.get)
      confno
  }

whereas with Monad, you can work with the actual types (Venue, User) like all the operations work, and keep the Option verification stuff hidden, all because of the flatmaps of the for syntax:

val confirm = for {
  venue <- lookupVenue(name)
  user <- getLoggedInUser(session)
  confno <- reserveTable(venue, user)
} yield {
  mailTo(confno, user)
  confno
}

The yield part will only be executed if all three functions have Some[X]; any None would directly be returned to confirm.


So:

Monads allow ordered computation within Functional Programing, that allows us to model sequencing of actions in a nice structured form, somewhat like a DSL.

And the greatest power comes with the ability to compose monads that serve different purposes, into extensible abstractions within an application.

This sequencing and threading of actions by a monad is done by the language compiler that does the transformation through the magic of closures.


By the way, Monad is not only model of computation used in FP:

Category theory proposes many models of computation. Among them

  • the Arrow model of computations
  • the Monad model of computations
  • the Applicative model of computations

Eloquent - where not equal to

For where field not empty this worked for me:

->where('table_name.field_name', '<>', '')

MVC Razor view nested foreach's model

Another much simpler possibility is that one of your property names is wrong (probably one you just changed in the class). This is what it was for me in RazorPages .NET Core 3.

How can I get a List from some class properties with Java 8 Stream?

You can use map :

List<String> names = 
    personList.stream()
              .map(Person::getName)
              .collect(Collectors.toList());

EDIT :

In order to combine the Lists of friend names, you need to use flatMap :

List<String> friendNames = 
    personList.stream()
              .flatMap(e->e.getFriends().stream())
              .collect(Collectors.toList());

What is __main__.py?

__main__.py is used for python programs in zip files. The __main__.py file will be executed when the zip file in run. For example, if the zip file was as such:

test.zip
     __main__.py

and the contents of __main__.py was

import sys
print "hello %s" % sys.argv[1]

Then if we were to run python test.zip world we would get hello world out.

So the __main__.py file run when python is called on a zip file.

How to compare two dates in Objective-C

What you really need is to compare two objects of the same kind.

  1. Create an NSDate out of your string date (@"2009-05-11") :
    http://blog.evandavey.com/2008/12/how-to-convert-a-string-to-nsdate.html

  2. If the current date is a string too, make it an NSDate. If its already an NSDate, leave it.

ORA-00918: column ambiguously defined in SELECT *

A query's projection can only have one instance of a given name. As your WHERE clause shows, you have several tables with a column called ID. Because you are selecting * your projection will have several columns called ID. Or it would have were it not for the compiler hurling ORA-00918.

The solution is quite simple: you will have to expand the projection to explicitly select named columns. Then you can either leave out the duplicate columns, retaining just (say) COACHES.ID or use column aliases: coaches.id as COACHES_ID.

Perhaps that strikes you as a lot of typing, but it is the only way. If it is any comfort, SELECT * is regarded as bad practice in production code: explicitly named columns are much safer.

Testing two JSON objects for equality ignoring child order in Java

Try this:

public static boolean jsonsEqual(Object obj1, Object obj2) throws JSONException

    {
        if (!obj1.getClass().equals(obj2.getClass()))
        {
            return false;
        }

        if (obj1 instanceof JSONObject)
        {
            JSONObject jsonObj1 = (JSONObject) obj1;

            JSONObject jsonObj2 = (JSONObject) obj2;

            String[] names = JSONObject.getNames(jsonObj1);
            String[] names2 = JSONObject.getNames(jsonObj1);
            if (names.length != names2.length)
            {
                return false;
            }

            for (String fieldName:names)
            {
                Object obj1FieldValue = jsonObj1.get(fieldName);

                Object obj2FieldValue = jsonObj2.get(fieldName);

                if (!jsonsEqual(obj1FieldValue, obj2FieldValue))
                {
                    return false;
                }
            }
        }
        else if (obj1 instanceof JSONArray)
        {
            JSONArray obj1Array = (JSONArray) obj1;
            JSONArray obj2Array = (JSONArray) obj2;

            if (obj1Array.length() != obj2Array.length())
            {
                return false;
            }

            for (int i = 0; i < obj1Array.length(); i++)
            {
                boolean matchFound = false;

                for (int j = 0; j < obj2Array.length(); j++)
                {
                    if (jsonsEqual(obj1Array.get(i), obj2Array.get(j)))
                    {
                        matchFound = true;
                        break;
                    }
                }

                if (!matchFound)
                {
                    return false;
                }
            }
        }
        else
        {
            if (!obj1.equals(obj2))
            {
                return false;
            }
        }

        return true;
    }

Rotating a point about another point (2D)

First subtract the pivot point (cx,cy), then rotate it, then add the point again.

Untested:

POINT rotate_point(float cx,float cy,float angle,POINT p)
{
  float s = sin(angle);
  float c = cos(angle);

  // translate point back to origin:
  p.x -= cx;
  p.y -= cy;

  // rotate point
  float xnew = p.x * c - p.y * s;
  float ynew = p.x * s + p.y * c;

  // translate point back:
  p.x = xnew + cx;
  p.y = ynew + cy;
  return p;
}

Is nested function a good approach when required by only one function?

It's just a principle about exposure APIs.

Using python, It's a good idea to avoid exposure API in outer space(module or class), function is a good encapsulation place.

It could be a good idea. when you ensure

  1. inner function is ONLY used by outer function.
  2. insider function has a good name to explain its purpose because the code talks.
  3. code cannot directly understand by your colleagues(or other code-reader).

Even though, Abuse this technique may cause problems and implies a design flaw.

Just from my exp, Maybe misunderstand your question.

Where can I find the Java SDK in Linux after installing it?

Use find to located it. It should be under /usr somewhere:

find /usr -name java

When running the command, if there are too many "Permission denied" message obfuscating the actual found results then, simply redirect stderr to /dev/null

find /usr -name java 2> /dev/null

How to silence output in a Bash script?

If it outputs to stderr as well you'll want to silence that. You can do that by redirecting file descriptor 2:

# Send stdout to out.log, stderr to err.log
myprogram > out.log 2> err.log

# Send both stdout and stderr to out.log
myprogram &> out.log      # New bash syntax
myprogram > out.log 2>&1  # Older sh syntax

# Log output, hide errors.
myprogram > out.log 2> /dev/null

Private pages for a private Github repo

You could host password in a repository and then just hide the page behind hidden address, that is derived from that password. This is not a very secure way, but it is simple.

Demonstration

What are .iml files in Android Studio?

What are iml files in Android Studio project?

A Google search on iml file turns up:

IML is a module file created by IntelliJ IDEA, an IDE used to develop Java applications. It stores information about a development module, which may be a Java, Plugin, Android, or Maven component; saves the module paths, dependencies, and other settings.

(from this page)

why not to use gradle scripts to integrate with external modules that you add to your project.

You do "use gradle scripts to integrate with external modules", or your own modules.

However, Gradle is not IntelliJ IDEA's native project model — that is separate, held in .iml files and the metadata in .idea/ directories. In Android Studio, that stuff is largely generated out of the Gradle build scripts, which is why you are sometimes prompted to "sync project with Gradle files" when you change files like build.gradle. This is also why you don't bother putting .iml files or .idea/ in version control, as their contents will be regenerated.

If I have a team that work in different IDE's like Eclipse and AS how to make project IDE agnostic?

To a large extent, you can't.

You are welcome to have an Android project that uses the Eclipse-style directory structure (e.g., resources and manifest in the project root directory). You can teach Gradle, via build.gradle, how to find files in that structure. However, other metadata (compileSdkVersion, dependencies, etc.) will not be nearly as easily replicated.

Other alternatives include:

  • Move everybody over to another build system, like Maven, that is equally integrated (or not, depending upon your perspective) to both Eclipse and Android Studio

  • Hope that Andmore takes off soon, so that perhaps you can have an Eclipse IDE that can build Android projects from Gradle build scripts

  • Have everyone use one IDE

Save Screen (program) output to a file

There is a command line option for logging. The output is saved to screenlog.n file, where n is a number of the screen. From man pages of screen:

‘-L’ Tell screen to turn on automatic output logging for the windows.

FB OpenGraph og:image not pulling images (possibly https?)

In my case, it seems that the crawler is just having a bug. I've tried:

  • Changing links to http only
  • Removing end white space
  • Switching back to http completely
  • Reinstalling the website
  • Installing a bunch of OG plugins (I use WordPress)
  • Suspecting the server has a weird misconfiguration that blocks the bots (because all the OG checkers are unable to fetch tags, and other requests to my sites are unstable)

None of these works. This costed me a week. And suddenly out of nowhere it seems to work again.

Here are my research, if someone meets this problem again:

Also, there are more checkers other than the Facebook's Object Debugger for you to check: OpenGraphCheck.com, Abhinay Rathore's Open Graph Tester, Iframely's Embed Codes, Card Validator | Twitter Developers.

What is the difference between include and require in Ruby?

  • Ruby require is more like "include" in other languages (such as C). It tells Ruby that you want to bring in the contents of another file. Similar mechanisms in other languages are:

  • Ruby include is an object-oriented inheritance mechanism used for mixins.

There is a good explanation here:

[The] simple answer is that require and include are essentially unrelated.

"require" is similar to the C include, which may cause newbie confusion. (One notable difference is that locals inside the required file "evaporate" when the require is done.)

The Ruby include is nothing like the C include. The include statement "mixes in" a module into a class. It's a limited form of multiple inheritance. An included module literally bestows an "is-a" relationship on the thing including it.

Emphasis added.

Rename all files in a folder with a prefix in a single command

Situation:

We have certificate.key certificate.crt inside /user/ssl/

We want to rename anything that starts with certificate to certificate_OLD

We are now located inside /user

First, you do a dry run with -n:

rename -n "s/certificate/certificate_old/" ./ssl/*

Which returns:

rename(./ssl/certificate.crt, ./ssl/certificate_OLD.crt) rename(./ssl/certificate.key, ./ssl/certificate_OLD.key)

Your files will be unchanged this is just a test run.

Solution:

When your happy with the result of the test run it for real:

rename "s/certificate/certificate_OLD/" ./ssl/*

What it means:

`rename "s/ SOMETHING / SOMETING_ELSE " PATH/FILES

Tip:

If you are already on the path run it like this:

rename "s/certificate/certificate_OLD/" *

Or if you want to do this in any sub-directory starting with ss do:

rename -n "s/certificat/certificate_old/" ./ss*/*

You can also do:

rename -n "s/certi*/certificate_old/" ./ss*/*

Which renames anything starting with certi in any sub-directory starting with ss.

The sky is the limit.

Play around with regex and ALWAYS test this BEFORE with -n.

WATCH OUT THIS WILL EVEN RENAME FOLDER NAMES THAT MATCH. Better cd into the directory and do it there. USE AT OWN RISK.

Only allow Numbers in input Tag without Javascript

Though it's probably suggested to get some heavier validation via JS or on the server, HTML5 does support this via the pattern attribute.

<input type= "text" name= "name" pattern= "[0-9]"  title= "Title"/>

How to get the last N records in mongodb?

you can use sort() , limit() ,skip() to get last N record start from any skipped value

db.collections.find().sort(key:value).limit(int value).skip(some int value);

SQL server 2008 backup error - Operating system error 5(failed to retrieve text for this error. Reason: 15105)

I had this error. Nothing worked for me until I opened the SQLServer log file in the "MSSQL10_50" Log folder. That clearly stated which file could not be overwritten. It turned out that the .mdf file was being written into the "MSSQL10" data folder. I made sure that folder had the same SQLServer user permissions as the "MSSQL10_50" equivalent folder. Then it all worked.

The issue here is that the error detail is logged but not reported, so check the logs.

Multiline for WPF TextBox

Contrary to @Andre Luus, setting Height="Auto" will not make the TextBox stretch. The solution I found was to set VerticalAlignment="Stretch"

How do I find files that do not contain a given string pattern?

The following command gives me all the files that do not contain the pattern foo:

find .  -not  -ipath '.*svn*' -exec  grep  -H -E -o -c  "foo"  {} \; | grep 0

IIS 7, HttpHandler and HTTP Error 500.21

Luckily, it’s very easy to resolve. Run the follow command from an elevated command prompt:

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i

If you’re on a 32-bit machine, you may have to use the following:

%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i

Where can I download mysql jdbc jar from?

Go to http://dev.mysql.com/downloads/connector/j and with in the dropdown select "Platform Independent" then it will show you the options to download tar.gz file or zip file.

Download zip file and extract it, with in that you will find mysql-connector-XXX.jar file

If you are using maven then you can add the dependency from the link http://mvnrepository.com/artifact/mysql/mysql-connector-java

Select the version you want to use and add the dependency in your pom.xml file

AWS EFS vs EBS vs S3 (differences & when to use?)

One word answer: MONEY :D

1 GB to store in US-East-1: (Updated at 2016.dec.20)

  • Glacier: $0.004/Month (Note: Major price cut in 2016)
  • S3: $0.023/Month
  • S3-IA (announced in 2015.09): $0.0125/Month (+$0.01/gig retrieval charge)
  • EBS: $0.045-0.1/Month (depends on speed - SSD or not) + IOPS costs
  • EFS: $0.3/Month

Further storage options, which may be used for temporary storing data while/before processing it:

  • SNS
  • SQS
  • Kinesis stream
  • DynamoDB, SimpleDB

The costs above are just samples. There can be differences by region, and it can change at any point. Also there are extra costs for data transfer (out to the internet). However they show a ratio between the prices of the services.

There are a lot more differences between these services:

EFS is:

  • Generally Available (out of preview), but may not yet be available in your region
  • Network filesystem (that means it may have bigger latency but it can be shared across several instances; even between regions)
  • It is expensive compared to EBS (~10x more) but it gives extra features.
  • It's a highly available service.
  • It's a managed service
  • You can attach the EFS storage to an EC2 Instance
  • Can be accessed by multiple EC2 instances simultaneously
  • Since 2016.dec.20 it's possible to attach your EFS storage directly to on-premise servers via Direct Connect. ()

EBS is:

  • A block storage (so you need to format it). This means you are able to choose which type of file system you want.
  • As it's a block storage, you can use Raid 1 (or 0 or 10) with multiple block storages
  • It is really fast
  • It is relatively cheap
  • With the new announcements from Amazon, you can store up to 16TB data per storage on SSD-s.
  • You can snapshot an EBS (while it's still running) for backup reasons
  • But it only exists in a particular region. Although you can migrate it to another region, you cannot just access it across regions (only if you share it via the EC2; but that means you have a file server)
  • You need an EC2 instance to attach it to
  • New feature (2017.Feb.15): You can now increase volume size, adjust performance, or change the volume type while the volume is in use. You can continue to use your application while the change takes effect.

S3 is:

  • An object store (not a file system).
  • You can store files and "folders" but can't have locks, permissions etc like you would with a traditional file system
  • This means, by default you can't just mount S3 and use it as your webserver
  • But it's perfect for storing your images and videos for your website
  • Great for short term archiving (e.g. a few weeks). It's good for long term archiving too, but Glacier is more cost efficient.
  • Great for storing logs
  • You can access the data from every region (extra costs may apply)
  • Highly Available, Redundant. Basically data loss is not possible (99.999999999% durability, 99.9 uptime SLA)
  • Much cheaper than EBS.
  • You can serve the content directly to the internet, you can even have a full (static) website working direct from S3, without an EC2 instance

Glacier is:

  • Long term archive storage
  • Extremely cheap to store
  • Potentially very expensive to retrieve
  • Takes up to 4 hours to "read back" your data (so only store items you know you won't need to retrieve for a long time)

As it got mentioned in JDL's comment, there are several interesting aspects in terms of pricing. For example Glacier, S3, EFS allocates the storage for you based on your usage, while at EBS you need to predefine the allocated storage. Which means, you need to over estimate. ( However it's easy to add more storage to your EBS volumes, it requires some engineering, which means you always "overpay" your EBS storage, which makes it even more expensive.)

Source: AWS Storage Update – New Lower Cost S3 Storage Option & Glacier Price Reduction

How do I get to IIS Manager?

You need to make sure the IIS Management Console is installed.

Position DIV relative to another DIV?

You need to set postion:relative of outer DIV and position:absolute of inner div.
Try this. Here is the Demo

#one
{
    background-color: #EEE;
    margin: 62px 258px;
    padding: 5px;
    width: 200px;
    position: relative;   
}

#two
{
    background-color: #F00;
    display: inline-block;
    height: 30px;
    position: absolute;
    width: 100px;
    top:10px;
}?

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

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

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

create table sample2
(
    id int primary key,
    created_date date,
    data varchar(10)
  )

insert into sample2 values (1,'2012-01-01','testing');

And here is how to select the data

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

Your project contains error(s), please fix it before running it

That usually comes from errors in the build path.

If you're using eclipse, there is a view you can add that lists all the errors called "Problems":

enter image description here

Otherwise, you can try to clean the project, and that usually solves a few problems.

Finally, if you add or alter resources from outside your IDE, you'll want to reload the resources and clean.

EDIT (Comment by anonymous user)

This can also be caused by an out of date "Debug Certificate" fixed as follows:

IF ALL FAILS THEN THIS GOTTA BE THE SOLUTION:

Delete your debug certificate under ~/.android/debug.keystore (on Linux and Mac OS X); the directory is something like %USERPROFILE%/.androidon Windows.

The Eclipse plugin should then generate a new certificate when you next try to build a debug package. You may need to clean and then build to generate the certificate.

This is also another fix for the "setContentView(R.layout.main);" error that says it cannot find R.layout.main when it is actually generated. (R cannot be resolved to a variable).

This is also another fix for the error "Your project has errors..." and you cannot find any. Clean and rebuild are still necessary after generating a new debug certificate.

ASP MVC in IIS 7 results in: HTTP Error 403.14 - Forbidden

I tried everything here; nothing worked. Problem was in my Web.config file, somehow dependent assembly binding got changed from minimum 1 to minimum 0.

<!-- was -->
<runtime>
    <assemblyBinding>
        <dependentAssembly>
            <assemblyIdentity name="System.Web.Mvc" />
                <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />


<!-- should have been -->
                <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />

What is the behavior difference between return-path, reply-to and from?

Another way to think about Return-Path vs Reply-To is to compare it to snail mail.

When you send an envelope in the mail, you specify a return address. If the recipient does not exist or refuses your mail, the postmaster returns the envelope back to the return address. For email, the return address is the Return-Path.

Inside of the envelope might be a letter and inside of the letter it may direct the recipient to "Send correspondence to example address". For email, the example address is the Reply-To.

In essence, a Postage Return Address is comparable to SMTP's Return-Path header and SMTP's Reply-To header is similar to the replying instructions contained in a letter.

Auto line-wrapping in SVG text

Building on @Mike Gledhill's code, I've taken it a step further and added more parameters. If you have a SVG RECT and want text to wrap inside it, this may be handy:

function wraptorect(textnode, boxObject, padding, linePadding) {

    var x_pos = parseInt(boxObject.getAttribute('x')),
    y_pos = parseInt(boxObject.getAttribute('y')),
    boxwidth = parseInt(boxObject.getAttribute('width')),
    fz = parseInt(window.getComputedStyle(textnode)['font-size']);  // We use this to calculate dy for each TSPAN.

    var line_height = fz + linePadding;

// Clone the original text node to store and display the final wrapping text.

   var wrapping = textnode.cloneNode(false);        // False means any TSPANs in the textnode will be discarded
   wrapping.setAttributeNS(null, 'x', x_pos + padding);
   wrapping.setAttributeNS(null, 'y', y_pos + padding);

// Make a copy of this node and hide it to progressively draw, measure and calculate line breaks.

   var testing = wrapping.cloneNode(false);
   testing.setAttributeNS(null, 'visibility', 'hidden');  // Comment this out to debug

   var testingTSPAN = document.createElementNS(null, 'tspan');
   var testingTEXTNODE = document.createTextNode(textnode.textContent);
   testingTSPAN.appendChild(testingTEXTNODE);

   testing.appendChild(testingTSPAN);
   var tester = document.getElementsByTagName('svg')[0].appendChild(testing);

   var words = textnode.textContent.split(" ");
   var line = line2 = "";
   var linecounter = 0;
   var testwidth;

   for (var n = 0; n < words.length; n++) {

      line2 = line + words[n] + " ";
      testing.textContent = line2;
      testwidth = testing.getBBox().width;

      if ((testwidth + 2*padding) > boxwidth) {

        testingTSPAN = document.createElementNS('http://www.w3.org/2000/svg', 'tspan');
        testingTSPAN.setAttributeNS(null, 'x', x_pos + padding);
        testingTSPAN.setAttributeNS(null, 'dy', line_height);

        testingTEXTNODE = document.createTextNode(line);
        testingTSPAN.appendChild(testingTEXTNODE);
        wrapping.appendChild(testingTSPAN);

        line = words[n] + " ";
        linecounter++;
      }
      else {
        line = line2;
      }
    }

    var testingTSPAN = document.createElementNS('http://www.w3.org/2000/svg', 'tspan');
    testingTSPAN.setAttributeNS(null, 'x', x_pos + padding);
    testingTSPAN.setAttributeNS(null, 'dy', line_height);

    var testingTEXTNODE = document.createTextNode(line);
    testingTSPAN.appendChild(testingTEXTNODE);

    wrapping.appendChild(testingTSPAN);

    testing.parentNode.removeChild(testing);
    textnode.parentNode.replaceChild(wrapping,textnode);

    return linecounter;
}

document.getElementById('original').onmouseover = function () {

    var container = document.getElementById('destination');
    var numberoflines = wraptorect(this,container,20,1);
    console.log(numberoflines);  // In case you need it

};

How to check python anaconda version installed on Windows 10 PC?

On the anaconda prompt, do a

  • conda -V or conda --version to get the conda version.
  • python -V or python --version to get the python version.
  • conda list anaconda$ to get the Anaconda version.
  • conda list to get the Name, Version, Build & Channel details of all the packages installed (in the current environment).
  • conda info to get all the current environment details.
  • conda info --envs To see a list of all your environments

Detailed description here, download cheat sheet from here

Android Device Chooser -- device not showing up

And , if your device is a Sony Ericsson Xperia X8 with the original ROM (2.1) or similar, then use:

 

<uses-sdk android:minSdkVersion="7" android:targetSdkVersion="17" />

in AndroidManifest.xml file

ORDER BY date and time BEFORE GROUP BY name in mysql

I had a different variation on this question where I only had a single DATETIME field and needed a limit after a group by or distinct after sorting descending based on the datetime field, but this is what helped me:

select distinct (column) from
(select column from database.table
order by date_column DESC) as hist limit 10

In this instance with the split fields, if you can sort on a concat, then you might be able to get away with something like:

select name,date,time from
(select name from table order by concat(date,' ',time) ASC)
as sorted

Then if you wanted to limit you would simply add your limit statement to the end:

select name,date,time from
(select name from table order by concat(date,' ',time) ASC)
as sorted limit 10

How to read numbers separated by space using scanf

scanf uses any whitespace as a delimiter, so if you just say scanf("%d", &var) it will skip any whitespace and then read an integer (digits up to the next non-digit) and nothing more.

Note that whitespace is any whitespace -- spaces, tabs, newlines, or carriage returns. Any of those are whitespace and any one or more of them will serve to delimit successive integers.

Count Rows in Doctrine QueryBuilder

Here is another way to format the query:

return $repository->createQueryBuilder('u')
            ->select('count(u.id)')
            ->getQuery()
            ->getSingleScalarResult();

Crop image to specified size and picture location

You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace);  CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession);  CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);       

How can I add an item to a IEnumerable<T> collection?

The type IEnumerable<T> does not support such operations. The purpose of the IEnumerable<T> interface is to allow a consumer to view the contents of a collection. Not to modify the values.

When you do operations like .ToList().Add() you are creating a new List<T> and adding a value to that list. It has no connection to the original list.

What you can do is use the Add extension method to create a new IEnumerable<T> with the added value.

items = items.Add("msg2");

Even in this case it won't modify the original IEnumerable<T> object. This can be verified by holding a reference to it. For example

var items = new string[]{"foo"};
var temp = items;
items = items.Add("bar");

After this set of operations the variable temp will still only reference an enumerable with a single element "foo" in the set of values while items will reference a different enumerable with values "foo" and "bar".

EDIT

I contstantly forget that Add is not a typical extension method on IEnumerable<T> because it's one of the first ones that I end up defining. Here it is

public static IEnumerable<T> Add<T>(this IEnumerable<T> e, T value) {
  foreach ( var cur in e) {
    yield return cur;
  }
  yield return value;
}

How to change the font on the TextView?

You might want to create static class which will contain all the fonts. That way, you won't create the font multiple times which might impact badly on performance. Just make sure that you create a sub-folder called "fonts" under "assets" folder.

Do something like:

public class CustomFontsLoader {

public static final int FONT_NAME_1 =   0;
public static final int FONT_NAME_2 =   1;
public static final int FONT_NAME_3 =   2;

private static final int NUM_OF_CUSTOM_FONTS = 3;

private static boolean fontsLoaded = false;

private static Typeface[] fonts = new Typeface[3];

private static String[] fontPath = {
    "fonts/FONT_NAME_1.ttf",
    "fonts/FONT_NAME_2.ttf",
    "fonts/FONT_NAME_3.ttf"
};


/**
 * Returns a loaded custom font based on it's identifier. 
 * 
 * @param context - the current context
 * @param fontIdentifier = the identifier of the requested font
 * 
 * @return Typeface object of the requested font.
 */
public static Typeface getTypeface(Context context, int fontIdentifier) {
    if (!fontsLoaded) {
        loadFonts(context);
    }
    return fonts[fontIdentifier];
}


private static void loadFonts(Context context) {
    for (int i = 0; i < NUM_OF_CUSTOM_FONTS; i++) {
        fonts[i] = Typeface.createFromAsset(context.getAssets(), fontPath[i]);
    }
    fontsLoaded = true;

}
}

This way, you can get the font from everywhere in your application.

Bootstrap dropdown sub menu missing

Updated 2018

The dropdown-submenu has been removed in Bootstrap 3 RC. In the words of Bootstrap author Mark Otto..

"Submenus just don't have much of a place on the web right now, especially the mobile web. They will be removed with 3.0" - https://github.com/twbs/bootstrap/pull/6342

But, with a little extra CSS you can get the same functionality.

Bootstrap 4 (navbar submenu on hover)

.navbar-nav li:hover > ul.dropdown-menu {
    display: block;
}
.dropdown-submenu {
    position:relative;
}
.dropdown-submenu>.dropdown-menu {
    top:0;
    left:100%;
    margin-top:-6px;
}

Navbar submenu dropdown hover
Navbar submenu dropdown hover (right aligned)
Navbar submenu dropdown click (right aligned)
Navbar dropdown hover (no submenu)


Bootstrap 3

Here is an example that uses 3.0 RC 1: http://bootply.com/71520

Here is an example that uses Bootstrap 3.0.0 (final): http://bootply.com/86684

CSS

.dropdown-submenu {
    position:relative;
}
.dropdown-submenu>.dropdown-menu {
    top:0;
    left:100%;
    margin-top:-6px;
    margin-left:-1px;
    -webkit-border-radius:0 6px 6px 6px;
    -moz-border-radius:0 6px 6px 6px;
    border-radius:0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
    display:block;
}
.dropdown-submenu>a:after {
    display:block;
    content:" ";
    float:right;
    width:0;
    height:0;
    border-color:transparent;
    border-style:solid;
    border-width:5px 0 5px 5px;
    border-left-color:#cccccc;
    margin-top:5px;
    margin-right:-10px;
}
.dropdown-submenu:hover>a:after {
    border-left-color:#ffffff;
}
.dropdown-submenu.pull-left {
    float:none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
    left:-100%;
    margin-left:10px;
    -webkit-border-radius:6px 0 6px 6px;
    -moz-border-radius:6px 0 6px 6px;
    border-radius:6px 0 6px 6px;
}

Sample Markup

<div class="navbar navbar-default navbar-fixed-top" role="navigation">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">  
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
        </div>
        <div class="collapse navbar-collapse navbar-ex1-collapse">
            <ul class="nav navbar-nav">
                <li class="menu-item dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">Drop Down<b class="caret"></b></a>
                    <ul class="dropdown-menu">
                        <li class="menu-item dropdown dropdown-submenu">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">Level 1</a>
                            <ul class="dropdown-menu">
                                <li class="menu-item ">
                                    <a href="#">Link 1</a>
                                </li>
                                <li class="menu-item dropdown dropdown-submenu">
                                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">Level 2</a>
                                    <ul class="dropdown-menu">
                                        <li>
                                            <a href="#">Link 3</a>
                                        </li>
                                    </ul>
                                </li>
                            </ul>
                        </li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</div>

P.S. - Example in navbar that adjusts left position: http://bootply.com/92442

How to get the dimensions of a tensor (in TensorFlow) at graph construction time?

The method tf.shape is a TensorFlow static method. However, there is also the method get_shape for the Tensor class. See

https://www.tensorflow.org/api_docs/python/tf/Tensor#get_shape

How to use string.substr() function?

You can get the above output using following code in c

#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
  char *str;
  clrscr();
  printf("\n Enter the string");
  gets(str);
  for(int i=0;i<strlen(str)-1;i++)
  {
    for(int j=i;j<=i+1;j++)
      printf("%c",str[j]);
    printf("\t");
  }
  getch();
  return 0;
}

MVC Return Partial View as JSON

Url.Action("Evil", model)

will generate a get query string but your ajax method is post and it will throw error status of 500(Internal Server Error). – Fereydoon Barikzehy Feb 14 at 9:51

Just Add "JsonRequestBehavior.AllowGet" on your Json object.

How to get today's Date?

Use this code to easy get Date & Time :

package date.time;

import java.text.SimpleDateFormat;    
import java.util.Date;

public class DateTime {

    public static void main(String[] args) {
        SimpleDateFormat dnt = new SimpleDateFormat("dd/MM/yy :: HH:mm:ss");
        Date date = new Date();
        System.out.println("Today Date & Time at Now :"+dnt.format(date));  
    } 
}

Meaning of .Cells(.Rows.Count,"A").End(xlUp).row

The first part:

.Cells(.Rows.Count,"A")

Sends you to the bottom row of column A, which you knew already.

The End function starts at a cell and then, depending on the direction you tell it, goes that direction until it reaches the edge of a group of cells that have text. Meaning, if you have text in cells C4:E4 and you type:

Sheet1.Cells(4,"C").End(xlToRight).Select

The program will select E4, the rightmost cell with text in it.

In your case, the code is spitting out the row of the very last cell with text in it in column A. Does that help?

ORA-12560: TNS:protocol adaptor error

from command console, if you get this error you can avoid it by typing

c:\> sqlplus /nolog

then you can connect

SQL> conn user/pass @host:port/service

How to display table data more clearly in oracle sqlplus

I usually start with something like:

set lines 256
set trimout on
set tab off

Have a look at help set if you have the help information installed. And then select name,address rather than select * if you really only want those two columns.

Populating a database in a Laravel migration file

Another clean way to do it is to define a private method which create instance et persist concerned Model.

public function up()
{
    Schema::create('roles', function (Blueprint $table) {
        $table->increments('id');
        $table->string('label', 256);
        $table->timestamps();
        $table->softDeletes();
    });

    $this->postCreate('admin', 'user');
}

private function postCreate(string ...$roles)  {
    foreach ($roles as $role) {
        $model = new Role();
        $model->setAttribute('label', $role);
        $model->save();
    }
}

With this solution, timestamps fields will be generated by Eloquent.

EDIT: it's better to use seeder system to disctinct database structure generation and database population.

How to provide a file download from a JSF backing bean?

Introduction

You can get everything through ExternalContext. In JSF 1.x, you can get the raw HttpServletResponse object by ExternalContext#getResponse(). In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream() without the need to grab the HttpServletResponse from under the JSF hoods.

On the response, you should set the Content-Type header so that the client knows which application to associate with the provided file. And, you should set the Content-Length header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition header to attachment if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.

Most important part is to call FacesContext#responseComplete() to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException with a message like getoutputstream() has already been called for this response when the JSF implementation calls getWriter() to render HTML.

Turn off ajax / don't use remote command!

You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink> and <h:commandButton>. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.

In case you're using e.g. PrimeFaces <p:commandXxx>, then you need to make sure that you explicitly turn off ajax via ajax="false" attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" /> in the command component.

Generic JSF 2.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();

    ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
    ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = ec.getResponseOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Generic JSF 1.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
    response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = response.getOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Common static file example

In case you need to stream a static file from the local disk file system, substitute the code as below:

File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();

// ...

Files.copy(file.toPath(), output);

Common dynamic file example

In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output there where the API being used expects an OutputStream.

E.g. iText PDF:

String fileName = "dynamic.pdf";
String contentType = "application/pdf";

// ...

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();

E.g. Apache POI HSSF:

String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";

// ...

HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();

Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.

Utility method

If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile() methods taking either a File, or an InputStream, or a byte[], and specifying whether the file should be downloaded as an attachment (true) or inline (false).

public void download() throws IOException {
    Faces.sendFile(file, true);
}

Yes, this code is complete as-is. You don't need to invoke responseComplete() and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.

In HTML I can make a checkmark with &#x2713; . Is there a corresponding X-mark?

Personally, I like to use named entities when they are available, because they make my HTML more readable. Because of that, I like to use &check; for ✓ and &cross; for ✗. If you're not sure whether a named entity exists for the character you want, try the &what search site. It includes the name for each entity, if there is one.

As mentioned in the comments, &check; and &cross; are not supported in HTML4, so you may be better off using the more cryptic &#x2713; and &#x2717; if you want to target the most browsers. The most definitive references I could find were on the W3C site: HTML4 and HTML5.