Programs & Examples On #Jri

how to get curl to output only http response body (json) and no other headers etc

I was executing a get request an also want to see just the response and nothing else, seems like magic is done with -silent,-s option.

From the curl man page:

-s, --silent Silent or quiet mode. Don't show progress meter or error messages. Makes Curl mute. It will still output the data you ask for, potentially even to the terminal/stdout unless you redirect it.

Below the examples:

curl -s "http://host:8080/some/resource"
curl -silent "http://host:8080/some/resource"

Using custom headers

curl -s -H "Accept: application/json" "http://host:8080/some/resource")

Using POST method with a header

curl -s -X POST -H "Content-Type: application/json" "http://host:8080/some/resource") -d '{ "myBean": {"property": "value"}}'

You can also customize the output for specific values with -w, below the options I use to get just response codes of the curl:

curl -s -o /dev/null -w "%{http_code}" "http://host:8080/some/resource"

PHPExcel Make first row bold

Try this

    $objPHPExcel = new PHPExcel();
    $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
                                 ->setLastModifiedBy("Maarten Balliauw")
                                 ->setTitle("Office 2007 XLSX Test Document")
                                 ->setSubject("Office 2007 XLSX Test Document")
                                 ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
                                 ->setKeywords("office 2007 openxml php")
                                 ->setCategory("Test result file");
    $objPHPExcel->setActiveSheetIndex(0);
    $sheet = $objPHPExcel->getActiveSheet();
    $sheet->setCellValue('A1', 'No');
    $sheet->setCellValue('B1', 'Job ID');
    $sheet->setCellValue('C1', 'Job completed Date');
    $sheet->setCellValue('D1', 'Job Archived Date');
    $styleArray = array(
        'font' => array(
        'bold' => true
        )
    );
    $sheet->getStyle('A1')->applyFromArray($styleArray);
    $sheet->getStyle('B1')->applyFromArray($styleArray);
    $sheet->getStyle('C1')->applyFromArray($styleArray);
    $sheet->getStyle('D1')->applyFromArray($styleArray);
    $sheet->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 1);
    

This is give me output like below link.(https://www.screencast.com/t/ZkKFHbDq1le)

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

CREATE FUNCTION DBO.ConvertDateToVarchar
(
@DATE DATETIME
)

RETURNS VARCHAR(24) 
BEGIN
RETURN (SELECT CONVERT(VARCHAR(19),@DATE, 121))
END

Python base64 data decode

(I know this is old but I wanted to post this for people like me who stumble upon it in the future) I personally just use this python code to decode base64 strings:

print open("FILE-WITH-STRING", "rb").read().decode("base64")

So you can run it in a bash script like this:

python -c 'print open("FILE-WITH-STRING", "rb").read().decode("base64")' > outputfile
file -i outputfile

twneale has also pointed out an even simpler solution: base64 -d So you can use it like this:

cat "FILE WITH STRING" | base64 -d > OUTPUTFILE
#Or You Can Do This
echo "STRING" | base64 -d > OUTPUTFILE

That will save the decoded string to outputfile and then attempt to identify file-type using either the file tool or you can try TrID. The following command will decode the string into a file and then use TrID to automatically identify the file's type and add the extension.

echo "STRING" | base64 -d > OUTPUTFILE; trid -ce OUTPUTFILE

Finding modified date of a file/folder

To get the modified date on a single file try:

$lastModifiedDate = (Get-Item "C:\foo.tmp").LastWriteTime

To compare with another:

$dateA= $lastModifiedDate 
$dateB= (Get-Item "C:\other.tmp").LastWriteTime

if ($dateA -ge $dateB) {
  Write-Host("C:\foo.tmp was modified at the same time or after C:\other.tmp")
} else {
  Write-Host("C:\foo.tmp was modified before C:\other.tmp")
}

Vagrant stuck connection timeout retrying

Here is how it worked for me:

After "vagrant up" started the virtual machine, turned off the machine and go to the new virtual machine settings in virtualbox. Then go to "Network" -> "Advanced"

Adapter Type: I changed from "Intel PRO XXXXX" to "PCNet-Fast" (or any other adpter other than Intel PRO did work)

How to use a different version of python during NPM install?

For Windows users something like this should work:

PS C:\angular> npm install --python=C:\Python27\python.exe

How do you clear a stringstream variable?

It's a conceptual problem.

Stringstream is a stream, so its iterators are forward, cannot return. In an output stringstream, you need a flush() to reinitialize it, as in any other output stream.

Secure hash and salt for PHP passwords

DISCLAIMER: This answer was written in 2008.

Since then, PHP has given us password_hash and password_verify and, since their introduction, they are the recommended password hashing & checking method.

The theory of the answer is still a good read though.

TL;DR

Don'ts

  • Don't limit what characters users can enter for passwords. Only idiots do this.
  • Don't limit the length of a password. If your users want a sentence with supercalifragilisticexpialidocious in it, don't prevent them from using it.
  • Don't strip or escape HTML and special characters in the password.
  • Never store your user's password in plain-text.
  • Never email a password to your user except when they have lost theirs, and you sent a temporary one.
  • Never, ever log passwords in any manner.
  • Never hash passwords with SHA1 or MD5 or even SHA256! Modern crackers can exceed 60 and 180 billion hashes/second (respectively).
  • Don't mix bcrypt and with the raw output of hash(), either use hex output or base64_encode it. (This applies to any input that may have a rogue \0 in it, which can seriously weaken security.)

Dos

  • Use scrypt when you can; bcrypt if you cannot.
  • Use PBKDF2 if you cannot use either bcrypt or scrypt, with SHA2 hashes.
  • Reset everyone's passwords when the database is compromised.
  • Implement a reasonable 8-10 character minimum length, plus require at least 1 upper case letter, 1 lower case letter, a number, and a symbol. This will improve the entropy of the password, in turn making it harder to crack. (See the "What makes a good password?" section for some debate.)

Why hash passwords anyway?

The objective behind hashing passwords is simple: preventing malicious access to user accounts by compromising the database. So the goal of password hashing is to deter a hacker or cracker by costing them too much time or money to calculate the plain-text passwords. And time/cost are the best deterrents in your arsenal.

Another reason that you want a good, robust hash on a user accounts is to give you enough time to change all the passwords in the system. If your database is compromised you will need enough time to at least lock the system down, if not change every password in the database.

Jeremiah Grossman, CTO of Whitehat Security, stated on White Hat Security blog after a recent password recovery that required brute-force breaking of his password protection:

Interestingly, in living out this nightmare, I learned A LOT I didn’t know about password cracking, storage, and complexity. I’ve come to appreciate why password storage is ever so much more important than password complexity. If you don’t know how your password is stored, then all you really can depend upon is complexity. This might be common knowledge to password and crypto pros, but for the average InfoSec or Web Security expert, I highly doubt it.

(Emphasis mine.)

What makes a good password anyway?

Entropy. (Not that I fully subscribe to Randall's viewpoint.)

In short, entropy is how much variation is within the password. When a password is only lowercase roman letters, that's only 26 characters. That isn't much variation. Alpha-numeric passwords are better, with 36 characters. But allowing upper and lower case, with symbols, is roughly 96 characters. That's a lot better than just letters. One problem is, to make our passwords memorable we insert patterns—which reduces entropy. Oops!

Password entropy is approximated easily. Using the full range of ascii characters (roughly 96 typeable characters) yields an entropy of 6.6 per character, which at 8 characters for a password is still too low (52.679 bits of entropy) for future security. But the good news is: longer passwords, and passwords with unicode characters, really increase the entropy of a password and make it harder to crack.

There's a longer discussion of password entropy on the Crypto StackExchange site. A good Google search will also turn up a lot of results.

In the comments I talked with @popnoodles, who pointed out that enforcing a password policy of X length with X many letters, numbers, symbols, etc, can actually reduce entropy by making the password scheme more predictable. I do agree. Randomess, as truly random as possible, is always the safest but least memorable solution.

So far as I've been able to tell, making the world's best password is a Catch-22. Either its not memorable, too predictable, too short, too many unicode characters (hard to type on a Windows/Mobile device), too long, etc. No password is truly good enough for our purposes, so we must protect them as though they were in Fort Knox.

Best practices

Bcrypt and scrypt are the current best practices. Scrypt will be better than bcrypt in time, but it hasn't seen adoption as a standard by Linux/Unix or by webservers, and hasn't had in-depth reviews of its algorithm posted yet. But still, the future of the algorithm does look promising. If you are working with Ruby there is an scrypt gem that will help you out, and Node.js now has its own scrypt package. You can use Scrypt in PHP either via the Scrypt extension or the Libsodium extension (both are available in PECL).

I highly suggest reading the documentation for the crypt function if you want to understand how to use bcrypt, or finding yourself a good wrapper or use something like PHPASS for a more legacy implementation. I recommend a minimum of 12 rounds of bcrypt, if not 15 to 18.

I changed my mind about using bcrypt when I learned that bcrypt only uses blowfish's key schedule, with a variable cost mechanism. The latter lets you increase the cost to brute-force a password by increasing blowfish's already expensive key schedule.

Average practices

I almost can't imagine this situation anymore. PHPASS supports PHP 3.0.18 through 5.3, so it is usable on almost every installation imaginable—and should be used if you don't know for certain that your environment supports bcrypt.

But suppose that you cannot use bcrypt or PHPASS at all. What then?

Try an implementation of PDKBF2 with the maximum number of rounds that your environment/application/user-perception can tolerate. The lowest number I'd recommend is 2500 rounds. Also, make sure to use hash_hmac() if it is available to make the operation harder to reproduce.

Future Practices

Coming in PHP 5.5 is a full password protection library that abstracts away any pains of working with bcrypt. While most of us are stuck with PHP 5.2 and 5.3 in most common environments, especially shared hosts, @ircmaxell has built a compatibility layer for the coming API that is backward compatible to PHP 5.3.7.

Cryptography Recap & Disclaimer

The computational power required to actually crack a hashed password doesn't exist. The only way for computers to "crack" a password is to recreate it and simulate the hashing algorithm used to secure it. The speed of the hash is linearly related to its ability to be brute-forced. Worse still, most hash algorithms can be easily parallelized to perform even faster. This is why costly schemes like bcrypt and scrypt are so important.

You cannot possibly foresee all threats or avenues of attack, and so you must make your best effort to protect your users up front. If you do not, then you might even miss the fact that you were attacked until it's too late... and you're liable. To avoid that situation, act paranoid to begin with. Attack your own software (internally) and attempt to steal user credentials, or modify other user's accounts or access their data. If you don't test the security of your system, then you cannot blame anyone but yourself.

Lastly: I am not a cryptographer. Whatever I've said is my opinion, but I happen to think it's based on good ol' common sense ... and lots of reading. Remember, be as paranoid as possible, make things as hard to intrude as possible, and then, if you are still worried, contact a white-hat hacker or cryptographer to see what they say about your code/system.

Declare a variable as Decimal

To declare a variable as a Decimal, first declare it as a Variant and then convert to Decimal with CDec. The type would be Variant/Decimal in the watch window:

enter image description here

Considering that programming floating point arithmetic is not what one has studied during Maths classes at school, one should always try to avoid common pitfalls by converting to decimal whenever possible.

In the example below, we see that the expression:

0.1 + 0.11 = 0.21

is either True or False, depending on whether the collectibles (0.1,0.11) are declared as Double or as Decimal:

Public Sub TestMe()

    Dim preciseA As Variant: preciseA = CDec(0.1)
    Dim preciseB As Variant: preciseB = CDec(0.11)

    Dim notPreciseA As Double: notPreciseA = 0.1
    Dim notPreciseB As Double: notPreciseB = 0.11

    Debug.Print preciseA + preciseB
    Debug.Print preciseA + preciseB = 0.21 'True

    Debug.Print notPreciseA + notPreciseB
    Debug.Print notPreciseA + notPreciseB = 0.21 'False

End Sub

enter image description here

How to solve the “failed to lazily initialize a collection of role” Hibernate exception

@Controller
@RequestMapping(value = "/topic")
@Transactional

i solve this problem by adding @Transactional,i think this can make session open

How to split a string between letters and digits (or between digits and letters)?

How about:

private List<String> Parse(String str) {
    List<String> output = new ArrayList<String>();
    Matcher match = Pattern.compile("[0-9]+|[a-z]+|[A-Z]+").matcher(str);
    while (match.find()) {
        output.add(match.group());
    }
    return output;
}

How to tune Tomcat 5.5 JVM Memory settings without using the configuration program

Just to add to the previous comment, the documentation for the command line tool for updating the Tomcat service settings (if Tomcat is running as a service on Windows) is here. This tool updates the registry with the proper settings. So if you wanted to update the max memory setting for the Tomcat service you could run this (from the tomcat/bin directory), assuming the default service name of Tomcat5:

tomcat5 //US//Tomcat5 --JvmMx=512

I keep getting "Uncaught SyntaxError: Unexpected token o"

SyntaxError: Unexpected token o in JSON

This also happens when you forget to use the await keyword for a method that returns JSON data.

For example:

async function returnJSONData()
{
   return "{\"prop\": 2}";
}

var json_str = returnJSONData();
var json_obj = JSON.parse(json_str);

will throw an error because of the missing await. What is actually returned is a Promise [object], not a string.

To fix just add await as you're supposed to:

var json_str = await returnJSONData();

This should be pretty obvious, but the error is called on JSON.parse, so it's easy to miss if there's some distance between your await method call and the JSON.parse call.

How can I inject a property value into a Spring Bean which was configured using annotations?

As mentioned @Value does the job and it is quite flexible as you can have spring EL in it.

Here are some examples, which could be helpful:

//Build and array from comma separated parameters 
//Like currency.codes.list=10,11,12,13
@Value("#{'${currency.codes.list}'.split(',')}") 
private List<String> currencyTypes;

Another to get a set from a list

//If you have a list of some objects like (List<BranchVO>) 
//and the BranchVO has areaCode,cityCode,...
//You can easily make a set or areaCodes as below
@Value("#{BranchList.![areaCode]}") 
private Set<String> areas;

You can also set values for primitive types.

@Value("${amount.limit}")
private int amountLimit;

You can call static methods:

@Value("#{T(foo.bar).isSecurityEnabled()}")
private boolean securityEnabled;

You can have logic

@Value("#{T(foo.bar).isSecurityEnabled() ? '${security.logo.path}' : '${default.logo.path}'}")
private String logoPath;

How to retrieve a recursive directory and file list from PowerShell excluding some files and folders?

I like Keith Hill's answer except it has a bug that prevents it from recursing past two levels. These commands manifest the bug:

New-Item level1/level2/level3/level4/foobar.txt -Force -ItemType file
cd level1
GetFiles . xyz | % { $_.fullname }

With Hill's original code you get this:

...\level1\level2
...\level1\level2\level3

Here is a corrected, and slightly refactored, version:

function GetFiles($path = $pwd, [string[]]$exclude)
{
    foreach ($item in Get-ChildItem $path)
    {
        if ($exclude | Where {$item -like $_}) { continue }

        $item
        if (Test-Path $item.FullName -PathType Container)
        {
            GetFiles $item.FullName $exclude
        }
    }
} 

With that bug fix in place you get this corrected output:

...\level1\level2
...\level1\level2\level3
...\level1\level2\level3\level4
...\level1\level2\level3\level4\foobar.txt

I also like ajk's answer for conciseness though, as he points out, it is less efficient. The reason it is less efficient, by the way, is because Hill's algorithm stops traversing a subtree when it finds a prune target while ajk's continues. But ajk's answer also suffers from a flaw, one I call the ancestor trap. Consider a path such as this that includes the same path component (i.e. subdir2) twice:

\usr\testdir\subdir2\child\grandchild\subdir2\doc

Set your location somewhere in between, e.g. cd \usr\testdir\subdir2\child, then run ajk's algorithm to filter out the lower subdir2 and you will get no output at all, i.e. it filters out everything because of the presence of subdir2 higher in the path. This is a corner case, though, and not likely to be hit often, so I would not rule out ajk's solution due to this one issue.

Nonetheless, I offer here a third alternative, one that does not have either of the above two bugs. Here is the basic algorithm, complete with a convenience definition for the path or paths to prune--you need only modify $excludeList to your own set of targets to use it:

$excludeList = @("stuff","bin","obj*")
Get-ChildItem -Recurse | % {
    $pathParts = $_.FullName.substring($pwd.path.Length + 1).split("\");
    if ( ! ($excludeList | where { $pathParts -like $_ } ) ) { $_ }
}

My algorithm is reasonably concise but, like ajk's, it is less efficient than Hill's (for the same reason: it does not stop traversing subtrees at prune targets). However, my code has an important advantage over Hill's--it can pipeline! It is therefore amenable to fit into a filter chain to make a custom version of Get-ChildItem while Hill's recursive algorithm, through no fault of its own, cannot. ajk's algorithm can be adapted to pipeline use as well, but specifying the item or items to exclude is not as clean, being embedded in a regular expression rather than a simple list of items that I have used.

I have packaged my tree pruning code into an enhanced version of Get-ChildItem. Aside from my rather unimaginative name--Get-EnhancedChildItem--I am excited about it and have included it in my open source Powershell library. It includes several other new capabilities besides tree pruning. Furthermore, the code is designed to be extensible: if you want to add a new filtering capability, it is straightforward to do. Essentially, Get-ChildItem is called first, and pipelined into each successive filter that you activate via command parameters. Thus something like this...

Get-EnhancedChildItem –Recurse –Force –Svn
    –Exclude *.txt –ExcludeTree doc*,man -FullName -Verbose 

... is converted internally into this:

Get-ChildItem | FilterExcludeTree | FilterSvn | FilterFullName

Each filter must conform to certain rules: accepting FileInfo and DirectoryInfo objects as inputs, generating the same as outputs, and using stdin and stdout so it may be inserted in a pipeline. Here is the same code refactored to fit these rules:

filter FilterExcludeTree()
{
  $target = $_
  Coalesce-Args $Path "." | % {
    $canonicalPath = (Get-Item $_).FullName
    if ($target.FullName.StartsWith($canonicalPath)) {
      $pathParts = $target.FullName.substring($canonicalPath.Length + 1).split("\");
      if ( ! ($excludeList | where { $pathParts -like $_ } ) ) { $target }
    }
  }
} 

The only additional piece here is the Coalesce-Args function (found in this post by Keith Dahlby), which merely sends the current directory down the pipe in the event that the invocation did not specify any paths.

Because this answer is getting somewhat lengthy, rather than go into further detail about this filter, I refer the interested reader to my recently published article on Simple-Talk.com entitled Practical PowerShell: Pruning File Trees and Extending Cmdlets where I discuss Get-EnhancedChildItem at even greater length. One last thing I will mention, though, is another function in my open source library, New-FileTree, that lets you generate a dummy file tree for testing purposes so you can exercise any of the above algorithms. And when you are experimenting with any of these, I recommend piping to % { $_.fullname } as I did in the very first code fragment for more useful output to examine.

Combining multiple commits before pushing in Git

If you have lots of commits and you only want to squash the last X commits, find the commit ID of the commit from which you want to start squashing and do

git rebase -i <that_commit_id>

Then proceed as described in leopd's answer, changing all the picks to squashes except the first one.

Example:

871adf OK, feature Z is fully implemented      --- newer commit --+
0c3317 Whoops, not yet...                                         |
87871a I'm ready!                                                 |
643d0e Code cleanup                                               |-- Join these into one
afb581 Fix this and that                                          |
4e9baa Cool implementation                                        |
d94e78 Prepare the workbench for feature Z     -------------------+
6394dc Feature Y                               --- older commit

You can either do this (write the number of commits):

git rebase --interactive HEAD~[7]

Or this (write the hash of the last commit you don't want to squash):

git rebase --interactive 6394dc

How to clear browsing history using JavaScript?

As MDN Window.history() describes :

For top-level pages you can see the list of pages in the session history, accessible via the History object, in the browser's dropdowns next to the back and forward buttons.

For security reasons the History object doesn't allow the non-privileged code to access the URLs of other pages in the session history, but it does allow it to navigate the session history.

There is no way to clear the session history or to disable the back/forward navigation from unprivileged code. The closest available solution is the location.replace() method, which replaces the current item of the session history with the provided URL.

So there is no Javascript method to clear the session history, instead, if you want to block navigating back to a certain page, you can use the location.replace() method, and pass the page link as parameter, which will not push the page to the browser's session history list. For example, there are three pages:

a.html:

<!doctype html>
<html>
    <head>
        <title>a.html page</title>
    <meta charset="utf-8">
    </head>
    <body>
         <p>This is <code style="color:red">a.html</code> page ! Go to <a href="b.html">b.html</a> page !</p>        
    </body>
 </html>

b.html:

<!doctype html>
<html>
    <head>
    <title>b.html page</title>
    <meta charset="utf-8">
</head>
<body>
    <p>This is <code style="color:red">b.html</code> page ! Go to <a id="jumper" href="c.html">c.html</a> page !</p>

    <script type="text/javascript">
        var jumper = document.getElementById("jumper");
        jumper.onclick = function(event) {
            var e = event || window.event ;
            if(e.preventDefault) {
                e.preventDefault();
            } else {
                e.returnValue = true ;
            }
            location.replace(this.href);
            jumper = null;
        }
    </script>
</body>

c.html:

<!doctype html>
<html>
<head>
    <title>c.html page</title>
    <meta charset="utf-8">
</head>
<body>
    <p>This is <code style="color:red">c.html</code> page</p>
</body>
</html>

With href link, we can navigate from a.html to b.html to c.html. In b.html, we use the location.replace(c.html) method to navigate from b.html to c.html. Finally, we go to c.html*, and if we click the back button in the browser, we will jump to **a.html.

So this is it! Hope it helps.

Get variable from PHP to JavaScript

It depends on what type of PHP variable you want to use in Javascript. For example, entire PHP objects with class methods cannot be used in Javascript. You can, however, use the built-in PHP JSON (JavaScript Object Notation) functions to convert simple PHP variables into JSON representations. For more information, please read the following links:

You can generate the JSON representation of your PHP variable and then print it into your Javascript code when the page loads. For example:

<script type="text/javascript">
  var foo = <?php echo json_encode($bar); ?>;
</script>

In Chrome 55, prevent showing Download button for HTML 5 video

As of Chrome58 you can now use controlsList to remove controls you don't want shown. This is available for both <audio> and <video> tags.

If you want to remove the download button in the controls do this:

<audio controls controlsList="nodownload">

PHP Warning: Division by zero

You can try with this. You have this error because we can not divide by 'zero' (0) value. So we want to validate before when we do calculations.

if ($itemCost != 0 && $itemCost != NULL && $itemQty != 0 && $itemQty != NULL) 
{
    $diffPricePercent = (($actual * 100) / $itemCost) / $itemQty;
}

And also we can validate POST data. Refer following

$itemQty = isset($_POST['num1']) ? $_POST['num1'] : 0;

$itemCost = isset($_POST['num2']) ? $_POST['num2'] : 0;

$itemSale = isset($_POST['num3']) ? $_POST['num3'] : 0;

$shipMat = isset($_POST['num4']) ? $_POST['num4'] : 0;

About "*.d.ts" in TypeScript

I could not comment and thus am adding this as an answer.
We had some pain trying to map existing types to a javascript library.

To map a .d.ts file to its javascript file you need to give the .d.ts file the same name as the javascript file, keep them in the same folder, and point the code that needs it to the .d.ts file.

eg: test.js and test.d.ts are in the testdir/ folder, then you import it like this in a react component:

import * as Test from "./testdir/test";

The .d.ts file was exported as a namespace like this:

export as namespace Test;

export interface TestInterface1{}
export class TestClass1{}

Start index for iterating Python list

islice has the advantage that it doesn't need to copy part of the list

from itertools import islice
for day in islice(days, 1, None):
    ...

Split a string into array in Perl

I found this one to be very simple!

my $line = "file1.gz file2.gz file3.gz";

my @abc =  ($line =~ /(\w+[.]\w+)/g);

print $abc[0],"\n";
print $abc[1],"\n";
print $abc[2],"\n";

output:

file1.gz 
file2.gz 
file3.gz

Here take a look at this tutorial to find more on Perl regular expression and scroll down to More matching section.

Background position, margin-top?

#div-name

{

  background-image: url('../images/background-art-main.jpg');
  background-position: top right 50px;
  background-repeat: no-repeat;
}

Writing Unicode text to a text file?

Unicode string handling is already standardized in Python 3.

  1. char's are already stored in Unicode (32-bit) in memory
  2. You only need to open file in utf-8
    (32-bit Unicode to variable-byte-length utf-8 conversion is automatically performed from memory to file.)

    out1 = "(???? ??? ??´ ??` ???` )"
    fobj = open("t1.txt", "w", encoding="utf-8")
    fobj.write(out1)
    fobj.close()
    

Putting GridView data in a DataTable

you can do something like this:

DataTable dt = new DataTable();
for (int i = 0; i < GridView1.Columns.Count; i++)
    {
        dt.Columns.Add("column"+i.ToString());
    }
foreach (GridViewRow row in GridView1.Rows)
    {
        DataRow dr = dt.NewRow();
        for(int j = 0;j<GridView1.Columns.Count;j++)
            {
                dr["column" + j.ToString()] = row.Cells[j].Text;
            }

            dt.Rows.Add(dr);
    }

And that will show that it works.

GridView6.DataSource = dt;
GridView6.DataBind();

What are "named tuples" in Python?

What are named tuples?

A named tuple is a tuple.

It does everything a tuple can.

But it's more than just a tuple.

It's a specific subclass of a tuple that is programmatically created to your specification, with named fields and a fixed length.

This, for example, creates a subclass of tuple, and aside from being of fixed length (in this case, three), it can be used everywhere a tuple is used without breaking. This is known as Liskov substitutability.

New in Python 3.6, we can use a class definition with typing.NamedTuple to create a namedtuple:

from typing import NamedTuple

class ANamedTuple(NamedTuple):
    """a docstring"""
    foo: int
    bar: str
    baz: list

The above is the same as the below, except the above additionally has type annotations and a docstring. The below is available in Python 2+:

>>> from collections import namedtuple
>>> class_name = 'ANamedTuple'
>>> fields = 'foo bar baz'
>>> ANamedTuple = namedtuple(class_name, fields)

This instantiates it:

>>> ant = ANamedTuple(1, 'bar', [])

We can inspect it and use its attributes:

>>> ant
ANamedTuple(foo=1, bar='bar', baz=[])
>>> ant.foo
1
>>> ant.bar
'bar'
>>> ant.baz.append('anything')
>>> ant.baz
['anything']

Deeper explanation

To understand named tuples, you first need to know what a tuple is. A tuple is essentially an immutable (can't be changed in-place in memory) list.

Here's how you might use a regular tuple:

>>> student_tuple = 'Lisa', 'Simpson', 'A'
>>> student_tuple
('Lisa', 'Simpson', 'A')
>>> student_tuple[0]
'Lisa'
>>> student_tuple[1]
'Simpson'
>>> student_tuple[2]
'A'

You can expand a tuple with iterable unpacking:

>>> first, last, grade = student_tuple
>>> first
'Lisa'
>>> last
'Simpson'
>>> grade
'A'

Named tuples are tuples that allow their elements to be accessed by name instead of just index!

You make a namedtuple like this:

>>> from collections import namedtuple
>>> Student = namedtuple('Student', ['first', 'last', 'grade'])

You can also use a single string with the names separated by spaces, a slightly more readable use of the API:

>>> Student = namedtuple('Student', 'first last grade')

How to use them?

You can do everything tuples can do (see above) as well as do the following:

>>> named_student_tuple = Student('Lisa', 'Simpson', 'A')
>>> named_student_tuple.first
'Lisa'
>>> named_student_tuple.last
'Simpson'
>>> named_student_tuple.grade
'A'
>>> named_student_tuple._asdict()
OrderedDict([('first', 'Lisa'), ('last', 'Simpson'), ('grade', 'A')])
>>> vars(named_student_tuple)
OrderedDict([('first', 'Lisa'), ('last', 'Simpson'), ('grade', 'A')])
>>> new_named_student_tuple = named_student_tuple._replace(first='Bart', grade='C')
>>> new_named_student_tuple
Student(first='Bart', last='Simpson', grade='C')

A commenter asked:

In a large script or programme, where does one usually define a named tuple?

The types you create with namedtuple are basically classes you can create with easy shorthand. Treat them like classes. Define them on the module level, so that pickle and other users can find them.

The working example, on the global module level:

>>> from collections import namedtuple
>>> NT = namedtuple('NT', 'foo bar')
>>> nt = NT('foo', 'bar')
>>> import pickle
>>> pickle.loads(pickle.dumps(nt))
NT(foo='foo', bar='bar')

And this demonstrates the failure to lookup the definition:

>>> def foo():
...     LocalNT = namedtuple('LocalNT', 'foo bar')
...     return LocalNT('foo', 'bar')
... 
>>> pickle.loads(pickle.dumps(foo()))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
_pickle.PicklingError: Can't pickle <class '__main__.LocalNT'>: attribute lookup LocalNT on __main__ failed

Why/when should I use named tuples instead of normal tuples?

Use them when it improves your code to have the semantics of tuple elements expressed in your code.

You can use them instead of an object if you would otherwise use an object with unchanging data attributes and no functionality.

You can also subclass them to add functionality, for example:

class Point(namedtuple('Point', 'x y')):
    """adding functionality to a named tuple"""
        __slots__ = ()
        @property
        def hypot(self):
            return (self.x ** 2 + self.y ** 2) ** 0.5
        def __str__(self):
            return 'Point: x=%6.3f  y=%6.3f  hypot=%6.3f' % (self.x, self.y, self.hypot)

Why/when should I use normal tuples instead of named tuples?

It would probably be a regression to switch from using named tuples to tuples. The upfront design decision centers around whether the cost from the extra code involved is worth the improved readability when the tuple is used.

There is no extra memory used by named tuples versus tuples.

Is there any kind of "named list" (a mutable version of the named tuple)?

You're looking for either a slotted object that implements all of the functionality of a statically sized list or a subclassed list that works like a named tuple (and that somehow blocks the list from changing in size.)

A now expanded, and perhaps even Liskov substitutable, example of the first:

from collections import Sequence

class MutableTuple(Sequence): 
    """Abstract Base Class for objects that work like mutable
    namedtuples. Subclass and define your named fields with 
    __slots__ and away you go.
    """
    __slots__ = ()
    def __init__(self, *args):
        for slot, arg in zip(self.__slots__, args):
            setattr(self, slot, arg)
    def __repr__(self):
        return type(self).__name__ + repr(tuple(self))
    # more direct __iter__ than Sequence's
    def __iter__(self): 
        for name in self.__slots__:
            yield getattr(self, name)
    # Sequence requires __getitem__ & __len__:
    def __getitem__(self, index):
        return getattr(self, self.__slots__[index])
    def __len__(self):
        return len(self.__slots__)

And to use, just subclass and define __slots__:

class Student(MutableTuple):
    __slots__ = 'first', 'last', 'grade' # customize 


>>> student = Student('Lisa', 'Simpson', 'A')
>>> student
Student('Lisa', 'Simpson', 'A')
>>> first, last, grade = student
>>> first
'Lisa'
>>> last
'Simpson'
>>> grade
'A'
>>> student[0]
'Lisa'
>>> student[2]
'A'
>>> len(student)
3
>>> 'Lisa' in student
True
>>> 'Bart' in student
False
>>> student.first = 'Bart'
>>> for i in student: print(i)
... 
Bart
Simpson
A

Setting environment variables on OS X

  1. Do:

    vim ~/.bash_profile
    

    The file may not exist (if not, you can just create it).

  2. Type in this and save the file:

    export PATH=$PATH:YOUR_PATH_HERE
    
  3. Run

    source ~/.bash_profile
    

How do I copy the contents of one ArrayList into another?

Copy of one list into second is quite simple , you can do that as below:-

ArrayList<List1> list1= new ArrayList<>();
ArrayList<List1> list2= new ArrayList<>();
//this will your copy your list1 into list2
list2.addAll(list1);

How do I get list of methods in a Python class?

Try print(help(ClassName)) It prints out methods of the class

Is there any way of configuring Eclipse IDE proxy settings via an autoproxy configuration script?

Download proxy script and check last line for return statement Proxy IP and Port.
Add this IP and Port using these step.

   1.  Windows -->Preferences-->General -->Network Connection
   2. Select Active Provider : Manual
   3.  Proxy entries select HTTP--> Click on Edit button
   4.  Then add Host as a proxy IP and port left Required Authentication blank.
   5.  Restart eclipse
   6.  Now Eclipse Marketplace... working.

Select values from XML field in SQL Server 2008

Blimey. This was a really useful thread to discover.

I still found some of these suggestions confusing. Whenever I used value with [1] in the string, it would only retrieved the first value. And some suggestions recommended using cross apply which (in my tests) just brought back far too much data.

So, here's my simple example of how you'd create an xml object, then read out its values into a table.

DECLARE @str nvarchar(2000)

SET @str = ''
SET @str = @str + '<users>'
SET @str = @str + '  <user>'
SET @str = @str + '     <firstName>Mike</firstName>'
SET @str = @str + '     <lastName>Gledhill</lastName>'
SET @str = @str + '     <age>31</age>'
SET @str = @str + '  </user>'
SET @str = @str + '  <user>'
SET @str = @str + '     <firstName>Mark</firstName>'
SET @str = @str + '     <lastName>Stevens</lastName>'
SET @str = @str + '     <age>42</age>'
SET @str = @str + '  </user>'
SET @str = @str + '  <user>'
SET @str = @str + '     <firstName>Sarah</firstName>'
SET @str = @str + '     <lastName>Brown</lastName>'
SET @str = @str + '     <age>23</age>'
SET @str = @str + '  </user>'
SET @str = @str + '</users>'

DECLARE @xml xml
SELECT @xml = CAST(CAST(@str AS VARBINARY(MAX)) AS XML) 

--  Iterate through each of the "users\user" records in our XML
SELECT 
    x.Rec.query('./firstName').value('.', 'nvarchar(2000)') AS 'FirstName',
    x.Rec.query('./lastName').value('.', 'nvarchar(2000)') AS 'LastName',
    x.Rec.query('./age').value('.', 'int') AS 'Age'
FROM @xml.nodes('/users/user') as x(Rec)

And here's the output:

enter image description here

It's bizarre syntax, but with a decent example, it's easy enough to add to your own SQL Server functions.

Speaking of which, here's the correct answer to this question.

Assuming your have your xml data in an @xml variable of type xml (as demonstrated in my example above), here's how you would return the three rows of data from the xml quoted in the question:

SELECT 
    x.Rec.query('./firstName').value('.', 'nvarchar(2000)') AS 'FirstName',
    x.Rec.query('./lastName').value('.', 'nvarchar(2000)') AS 'LastName'
FROM @xml.nodes('/person') as x(Rec)

enter image description here

Storing Python dictionaries

Pickle save:

try:
    import cPickle as pickle
except ImportError:  # Python 3.x
    import pickle

with open('data.p', 'wb') as fp:
    pickle.dump(data, fp, protocol=pickle.HIGHEST_PROTOCOL)

See the pickle module documentation for additional information regarding the protocol argument.

Pickle load:

with open('data.p', 'rb') as fp:
    data = pickle.load(fp)

JSON save:

import json

with open('data.json', 'w') as fp:
    json.dump(data, fp)

Supply extra arguments, like sort_keys or indent, to get a pretty result. The argument sort_keys will sort the keys alphabetically and indent will indent your data structure with indent=N spaces.

json.dump(data, fp, sort_keys=True, indent=4)

JSON load:

with open('data.json', 'r') as fp:
    data = json.load(fp)

How to get the difference between two arrays of objects in JavaScript

I prefer map object when it comes to big arrays.

_x000D_
_x000D_
// create tow arrays_x000D_
array1 = Array.from({length: 400},() => ({value:Math.floor(Math.random() * 4000)}))_x000D_
array2 = Array.from({length: 400},() => ({value:Math.floor(Math.random() * 4000)}))_x000D_
_x000D_
// calc diff with some function_x000D_
console.time('diff with some');_x000D_
results = array2.filter(({ value: id1 }) => array1.some(({ value: id2 }) => id2 === id1));_x000D_
console.log('diff results ',results.length)_x000D_
console.timeEnd('diff with some');_x000D_
_x000D_
// calc diff with map object_x000D_
console.time('diff with map');_x000D_
array1Map = {};_x000D_
for(const item1 of array1){_x000D_
    array1Map[item1.value] = true;_x000D_
}_x000D_
results = array2.filter(({ value: id2 }) => array1Map[id2]);_x000D_
console.log('map results ',results.length)_x000D_
console.timeEnd('diff with map');
_x000D_
_x000D_
_x000D_

SQL Server - Adding a string to a text column (concat equivalent)

UPDATE test SET a = CONCAT(a, "more text")

How to check whether a int is not null or empty?

public class Demo {
    private static int i;
    private static Integer j;
    private static int k = -1;

    public static void main(String[] args) {
        System.out.println(i+" "+j+" "+k);
    }
}

OutPut: 0 null -1

how to get the selected index of a drop down

If you are actually looking for the index number (and not the value) of the selected option then it would be

document.forms[0].elements["CCards"].selectedIndex 
/* You may need to change document.forms[0] to reference the correct form */

or using jQuery

$('select[name="CCards"]')[0].selectedIndex 

Replace all particular values in a data frame

Like this:

> df[df==""]<-NA
> df
     A    B
1 <NA>   12
2  xyz <NA>
3  jkl  100

Check if a string within a list contains a specific string with Linq

I think you want Any:

if (myList.Any(str => str.Contains("Mdd LH")))

It's well worth becoming familiar with the LINQ standard query operators; I would usually use those rather than implementation-specific methods (such as List<T>.ConvertAll) unless I was really bothered by the performance of a specific operator. (The implementation-specific methods can sometimes be more efficient by knowing the size of the result etc.)

How to get child process from parent process

You can get the pids of all child processes of a given parent process <pid> by reading the /proc/<pid>/task/<tid>/children entry.

This file contain the pids of first level child processes.

For more information head over to https://lwn.net/Articles/475688/

CAST DECIMAL to INT

Try cast (columnName as unsigned)

unsigned is positive value only

If you want to include negative value, then cast (columnName as signed),
The difference between sign (negative include) and unsigned (twice the size of sign, but non-negative)

Android Respond To URL in Intent

I did it! Using <intent-filter>. Put the following into your manifest file:

<intent-filter>
  <action android:name="android.intent.action.VIEW" />
  <category android:name="android.intent.category.DEFAULT" />
  <category android:name="android.intent.category.BROWSABLE" />
  <data android:host="www.youtube.com" android:scheme="http" />
</intent-filter>

This works perfectly!

Delete item from array and shrink array

The size of a Java array is fixed when you allocate it, and cannot be changed.

  • If you want to "grow" or "shrink" an existing array, you have to allocate a new array of the appropriate size and copy the array elements; e.g. using System.arraycopy(...) or Arrays.copyOf(...). A copy loop works as well, though it looks a bit clunky ... IMO.

  • If you want to "delete" an item or items from an array (in the true sense ... not just replacing them with null), you need to allocate a new smaller array and copy across the elements you want to retain.

  • Finally, you can "erase" an element in an array of a reference type by assigning null to it. But this introduces new problems:

    • If you were using null elements to mean something, you can't do this.
    • All of the code that uses the array now has to deal with the possibility of a null element in the appropriate fashion. More complexity and potential for bugs1.

There are alternatives in the form of 3rd-party libraries (e.g. Apache Commons ArrayUtils), but you may want to consider whether it is worth adding a library dependency just for the sake of a method that you could implement yourself with 5-10 lines of code.


It is better (i.e. simpler ... and in many cases, more efficient2) to use a List class instead of an array. This will take care of (at least) growing the backing storage. And there are operations that take care of inserting and deleting elements anywhere in the list.

For instance, the ArrayList class uses an array as backing, and automatically grows the array as required. It does not automatically reduce the size of the backing array, but you can tell it to do this using the trimToSize() method; e.g.

ArrayList l = ...
l.remove(21);
l.trimToSize();  // Only do this if you really have to.

1 - But note that the explicit if (a[e] == null) checks themselves are likely to be "free", since they can be combined with the implicit null check that happens when you dereference the value of a[e].

2 - I say it is "more efficient in many cases" because ArrayList uses a simple "double the size" strategy when it needs to grow the backing array. This means that if grow the list by repeatedly appending to it, each element will be copied on average one extra time. By contrast, if you did this with an array you would end up copying each array element close to N/2 times on average.

Determine which MySQL configuration file is being used

Some servers have multiple MySQL versions installed and configured. Make sure you are dealing with the correct version running with a Unix command of:

ps -ax | grep mysql

How can I use optional parameters in a T-SQL stored procedure?

You can do in the following case,

CREATE PROCEDURE spDoSearch
   @FirstName varchar(25) = null,
   @LastName varchar(25) = null,
   @Title varchar(25) = null
AS
  BEGIN
      SELECT ID, FirstName, LastName, Title
      FROM tblUsers
      WHERE
        (@FirstName IS NULL OR FirstName = @FirstName) AND
        (@LastNameName IS NULL OR LastName = @LastName) AND
        (@Title IS NULL OR Title = @Title)
END

however depend on data sometimes better create dynamic query and execute them.

How to populate a dropdownlist with json data in jquery?

//javascript
//teams.Table does not exist

function OnSuccessJSON(data, status) {
    var teams = eval('(' + data.d + ')');
    var listItems = "";
    for (var i = 0; i < teams.length; i++) {
      listItems += "<option value='" + teams[i][0]+ "'>" + teams[i][1] + "</option>";
    }
    $("#<%=ddlTeams.ClientID%>").html(listItems);
} 

Is there a way to represent a directory tree in a Github README.md?

The best way to do this is to surround your tree in the triple backticks to denote a code block. For more info, see the markdown docs: http://daringfireball.net/projects/markdown/syntax#code

Prevent HTML5 video from being downloaded (right-click saved)?

Here's what I did:

_x000D_
_x000D_
function noRightClick() {_x000D_
      alert("You cannot save this video for copyright reasons. Sorry about that.");_x000D_
}
_x000D_
    <body oncontextmenu="noRightClick();">_x000D_
    <video>_x000D_
    <source src="http://calumchilds.com/videos/big_buck_bunny.mp4" type="video/mp4">_x000D_
    </video>_x000D_
    </body>
_x000D_
_x000D_
_x000D_ This also works for images, text and pretty much anything. However, you can still access the "Inspect" and the "View source" tool through keyboard shortcuts. (As the answer at the top says, you can't stop it entirely.) But you can try to put barriers up to stop them.

How to upgrade PostgreSQL from version 9.6 to version 10.1 without losing data?

My solution was to do a combination of these two resources:

https://gist.github.com/tamoyal/2ea1fcdf99c819b4e07d

and

http://www.gab.lc/articles/migration_postgresql_9-3_to_9-4

The second one helped more then the first one. Also to not, don't follow the steps as is as some are not necessary. Also, if you are not being able to backup the data via postgres console, you can use alternative approach, and backup it with pgAdmin 3 or some other program, like I did in my case.

Also, the link: https://help.ubuntu.com/stable/serverguide/postgresql.html Helped to set the encrypted password and set md5 for authenticating the postgres user.

After all is done, to check the postgres server version run in terminal:

sudo -u postgres psql postgres

After entering the password run in postgres terminal:

SHOW SERVER_VERSION;

It will output something like:

 server_version 
----------------
 9.4.5

For setting and starting postgres I have used command:

> sudo bash # root
> su postgres # postgres

> /etc/init.d/postgresql start
> /etc/init.d/postgresql stop

And then for restoring database from a file:

> psql -f /home/ubuntu_username/Backup_93.sql postgres

Or if doesn't work try with this one:

> pg_restore --verbose --clean --no-acl --no-owner -h localhost -U postgres -d name_of_database ~/your_file.dump

And if you are using Rails do a bundle exec rake db:migrate after pulling the code :)

fast way to copy formatting in excel

Does:

Set Sheets("Output").Range("$A$1:$A$500") =  Sheets(sheet_).Range("$A$1:$A$500")

...work? (I don't have Excel in front of me, so can't test.)

Network tools that simulate slow network connection

If you'd like a hardware solution, Netgear has a series of cheap ($50 or so) switches that do bandwidth limiting. Netgear Prosafe GS105E and similar switches are worth investigating.

Is it possible to interactively delete matching search pattern in Vim?

1. In my opinion, the most convenient way is to search for one occurrence first, and then invoke the following :substitute command:

:%s///gc

Since the pattern is empty, this :substitute command will look for the occurrences of the last-used search pattern, and will then replace them with the empty string, each time asking for user confirmation, realizing exactly the desired behavior.

2. If it is a common pattern in one’s editing habits, one can further define a couple of text-object selection mappings to operate specifically on the match of the last search pattern under the cursor. The following two mappings can be used in both Visual and Operator-pending modes to select the text of the preceding match of the last search pattern.

vnoremap <silent> i/ :<c-u>call SelectMatch()<cr>
onoremap <silent> i/ :call SelectMatch()<cr>
function! SelectMatch()
    if search(@/, 'bcW')
        norm! v
        call search(@/, 'ceW')
    else
        norm! gv
    endif
endfunction

Using these mappings one can delete the match under the cursor with di/, or apply any other operator or visually select it with vi/.

CSS Pseudo-classes with inline styles

or you can simply try this in inline css

<textarea style="::placeholder{color:white}"/>

Get Excel sheet name and use as variable in macro

in a Visual Basic Macro you would use

pName = ActiveWorkbook.Path      ' the path of the currently active file
wbName = ActiveWorkbook.Name     ' the file name of the currently active file
shtName = ActiveSheet.Name       ' the name of the currently selected worksheet

The first sheet in a workbook can be referenced by

ActiveWorkbook.Worksheets(1)

so after deleting the [Report] tab you would use

ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name

to "work on that sheet later on" you can create a range object like

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]

and continue working on MySheet(rowNum, colNum) etc. ...

shortcut creation of a range object without defining shtName:

Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]

Accessing Google Spreadsheets with C# using Google Data API

I wrote a simple wrapper around Google's .Net client library, it exposes a simpler database-like interface, with strongly-typed record types. Here's some sample code:

public class Entity {
    public int IntProp { get; set; }
    public string StringProp { get; set; }
}

var e1 = new Entity { IntProp = 2 };
var e2 = new Entity { StringProp = "hello" };
var client = new DatabaseClient("[email protected]", "password");
const string dbName = "IntegrationTests";
Console.WriteLine("Opening or creating database");
db = client.GetDatabase(dbName) ?? client.CreateDatabase(dbName); // databases are spreadsheets
const string tableName = "IntegrationTests";
Console.WriteLine("Opening or creating table");
table = db.GetTable<Entity>(tableName) ?? db.CreateTable<Entity>(tableName); // tables are worksheets
table.DeleteAll();
table.Add(e1);
table.Add(e2);
var r1 = table.Get(1);

There's also a LINQ provider that translates to google's structured query operators:

var q = from r in table.AsQueryable()
        where r.IntProp > -1000 && r.StringProp == "hello"
        orderby r.IntProp
        select r;

Pass multiple values with onClick in HTML link

Solution: Pass multiple arguments with onclick for html generated in JS

For html generated in JS , do as below (we are using single quote as string wrapper). Each argument has to wrapped in a single quote else all of yours argument will be considered as a single argument like functionName('a,b') , now its a single argument with value a,b.

We have to use string escape character backslash() to close first argument with single quote, give a separator comma in between and then start next argument with a single quote. (This is the magic code to use '\',\'')

Example:

$('#ValuationAssignedTable').append('<tr> <td><a href=# onclick="return ReAssign(\'' + valuationId  +'\',\'' + user + '\')">Re-Assign</a> </td>  </tr>');

Disable copy constructor

Make SymbolIndexer( const SymbolIndexer& ) private. If you're assigning to a reference, you're not copying.

What is the best place for storing uploaded images, SQL database or disk file system?

Most implementations are option A.

With option B, you open a whole big can of whoop4ss when you marshall those bits from the database into something that can be displayed on a browser... Also, if the db is down, the images are not available.

I don't think that space is too much of an issue... Terabyte drives are a couple hundred bucks now.

We are implementing with option A because we don't have the time or resources to do option B.

How to run a subprocess with Python, wait for it to exit and get the full stdout as a string?

I am using the following construct, although you might want to avoid shell=True. This gives you the output and error message for any command, and the error code as well:

process = subprocess.Popen(cmd, shell=True,
                           stdout=subprocess.PIPE, 
                           stderr=subprocess.PIPE)

# wait for the process to terminate
out, err = process.communicate()
errcode = process.returncode

Is it possible to add an array or object to SharedPreferences on Android

Easy mode for complex object storage with using Gson google library [1]

public static void setComplexObject(Context ctx, ComplexObject obj){
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
    SharedPreferences.Editor editor = preferences.edit();
    editor.putString("COMPLEX_OBJECT",new Gson().toJson(obj)); 
    editor.commit();
}

public static ComplexObject getComplexObject (Context ctx){
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
    String sobj = preferences.getString("COMPLEX_OBJECT", "");
    if(sobj.equals(""))return null;
    else return new Gson().fromJson(sobj, ComplexObject.class);
}

[1] http://code.google.com/p/google-gson/

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

I had the same issue, for me this fixed the issue:
right click on the project ->maven -> update project

maven -> update project

Insert all values of a table into another table in SQL

From here:

SELECT *
INTO new_table_name [IN externaldatabase] 
FROM old_tablename

How to remove all non-alpha numeric characters from a string in MySQL?

From a performance point of view, (and on the assumption that you read more than you write)

I think the best way would be to pre calculate and store a stripped version of the column, This way you do the transform less.

You can then put an index on the new column and get the database to do the work for you.

Is it possible to get element from HashMap by its position?

If you want to maintain the order in which you added the elements to the map, use LinkedHashMap as opposed to just HashMap.

Here is an approach that will allow you to get a value by its index in the map:

public Object getElementByIndex(LinkedHashMap map,int index){
    return map.get( (map.keySet().toArray())[ index ] );
}

C error: undefined reference to function, but it IS defined

I think the problem is that when you're trying to compile testpoint.c, it includes point.h but it doesn't know about point.c. Since point.c has the definition for create, not having point.c will cause the compilation to fail.

I'm not familiar with MinGW, but you need to tell the compiler to look for point.c. For example with gcc you might do this:

gcc point.c testpoint.c

As others have pointed out, you also need to remove one of your main functions, since you can only have one.

Javascript get object key name

Here is a simple example, it will help you to get object key name.

var obj ={parts:{costPart:1000, salesPart: 2000}}; console.log(Object.keys(obj));

the output would be parts.

How to make method call another one in classes?

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
    public class AllMethods
    {
        public static void Method2()
        {
            // code here
        }
    }
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
    class Caller
    {
        public static void Main(string[] args)
        {
            Method2(); // No need to mention AllMethods here
        }
    }
}

Further Reading

How to inject JPA EntityManager using spring

Is it possible to have spring to inject the JPA entityManager object into my DAO class whitout extending JpaDaoSupport? if yes, does spring manage the transaction in this case?

This is documented black on white in 12.6.3. Implementing DAOs based on plain JPA:

It is possible to write code against the plain JPA without using any Spring dependencies, using an injected EntityManagerFactory or EntityManager. Note that Spring can understand @PersistenceUnit and @PersistenceContext annotations both at field and method level if a PersistenceAnnotationBeanPostProcessor is enabled. A corresponding DAO implementation might look like this (...)

And regarding transaction management, have a look at 12.7. Transaction Management:

Spring JPA allows a configured JpaTransactionManager to expose a JPA transaction to JDBC access code that accesses the same JDBC DataSource, provided that the registered JpaDialect supports retrieval of the underlying JDBC Connection. Out of the box, Spring provides dialects for the Toplink, Hibernate and OpenJPA JPA implementations. See the next section for details on the JpaDialect mechanism.

How to set text color to a text view programmatically

Great answers. Adding one that loads the color from an Android resources xml but still sets it programmatically:

textView.setTextColor(getResources().getColor(R.color.some_color));

Please note that from API 23, getResources().getColor() is deprecated. Use instead:

textView.setTextColor(ContextCompat.getColor(context, R.color.some_color));

where the required color is defined in an xml as:

<resources>
  <color name="some_color">#bdbdbd</color>
</resources>

Update:

This method was deprecated in API level 23. Use getColor(int, Theme) instead.

Check this.

Easiest way to compare arrays in C#

Assuming array equality means both arrays have equal elements at equal indexes, there is the SequenceEqual answer and the IStructuralEquatable answer.

But both have drawbacks, performance wise.

SequenceEqual current implementation will not shortcut when the arrays have different lengths, and so it may enumerate one of them entirely, comparing each of its elements.

IStructuralEquatable is not generic and may cause boxing of each compared value. Moreover it is not very straightforward to use and already calls for coding some helper methods hiding it away.

It may be better, performance wise, to use something like:

bool ArrayEquals<T>(T[] first, T[] second)
{
    if (first == second)
        return true;
    if (first == null || second == null)
        return false;
    if (first.Length != second.Length)
        return false;
    for (var i = 0; i < first.Length; i++)
    {
        if (!first[i].Equals(second[i]))
            return false;
    }
    return true;
}

But of course, that is not either some "magic way" of checking array equality.

So currently, no, there is not really an equivalent to Java Arrays.equals() in .Net.

Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell

C++11, < 20ms for me - Run it here

I understand that you want tips to help improve your language specific knowledge, but since that has been well covered here, I thought I would add some context for people who may have looked at the mathematica comment on your question, etc, and wondered why this code was so much slower.

This answer is mainly to provide context to hopefully help people evaluate the code in your question / other answers more easily.

This code uses only a couple of (uglyish) optimisations, unrelated to the language used, based on:

  1. every traingle number is of the form n(n+1)/2
  2. n and n+1 are coprime
  3. the number of divisors is a multiplicative function

#include <iostream>
#include <cmath>
#include <tuple>
#include <chrono>

using namespace std;

// Calculates the divisors of an integer by determining its prime factorisation.

int get_divisors(long long n)
{
    int divisors_count = 1;

    for(long long i = 2;
        i <= sqrt(n);
        /* empty */)
    {
        int divisions = 0;
        while(n % i == 0)
        {
            n /= i;
            divisions++;
        }

        divisors_count *= (divisions + 1);

        //here, we try to iterate more efficiently by skipping
        //obvious non-primes like 4, 6, etc
        if(i == 2)
            i++;
        else
            i += 2;
    }

    if(n != 1) //n is a prime
        return divisors_count * 2;
    else
        return divisors_count;
}

long long euler12()
{
    //n and n + 1
    long long n, n_p_1;

    n = 1; n_p_1 = 2;

    // divisors_x will store either the divisors of x or x/2
    // (the later iff x is divisible by two)
    long long divisors_n = 1;
    long long divisors_n_p_1 = 2;

    for(;;)
    {
        /* This loop has been unwound, so two iterations are completed at a time
         * n and n + 1 have no prime factors in common and therefore we can
         * calculate their divisors separately
         */

        long long total_divisors;                 //the divisors of the triangle number
                                                  // n(n+1)/2

        //the first (unwound) iteration

        divisors_n_p_1 = get_divisors(n_p_1 / 2); //here n+1 is even and we

        total_divisors =
                  divisors_n
                * divisors_n_p_1;

        if(total_divisors > 1000)
            break;

        //move n and n+1 forward
        n = n_p_1;
        n_p_1 = n + 1;

        //fix the divisors
        divisors_n = divisors_n_p_1;
        divisors_n_p_1 = get_divisors(n_p_1);   //n_p_1 is now odd!

        //now the second (unwound) iteration

        total_divisors =
                  divisors_n
                * divisors_n_p_1;

        if(total_divisors > 1000)
            break;

        //move n and n+1 forward
        n = n_p_1;
        n_p_1 = n + 1;

        //fix the divisors
        divisors_n = divisors_n_p_1;
        divisors_n_p_1 = get_divisors(n_p_1 / 2);   //n_p_1 is now even!
    }

    return (n * n_p_1) / 2;
}

int main()
{
    for(int i = 0; i < 1000; i++)
    {
        using namespace std::chrono;
        auto start = high_resolution_clock::now();
        auto result = euler12();
        auto end = high_resolution_clock::now();

        double time_elapsed = duration_cast<milliseconds>(end - start).count();

        cout << result << " " << time_elapsed << '\n';
    }
    return 0;
}

That takes around 19ms on average for my desktop and 80ms for my laptop, a far cry from most of the other code I've seen here. And there are, no doubt, many optimisations still available.

Read and parse a Json File in C#

How about making everything easier with Json.NET?

    public void LoadJson()
    {
        using (StreamReader r = new StreamReader("file.json"))
        {
            string json = r.ReadToEnd();
            List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);
        }
    }

    public class Item
    {
        public int millis;
        public string stamp;
        public DateTime datetime;
        public string light;
        public float temp;
        public float vcc;
    }

You can even get the values dynamically without declaring Item class.

    dynamic array = JsonConvert.DeserializeObject(json);
    foreach(var item in array)
    {
        Console.WriteLine("{0} {1}", item.temp, item.vcc);
    }

How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

I was facing this issue recently, too. Since you can't change the browser's default behavior of showing the popup in case of a 401 (basic or digest authentication), there are two ways to fix this:

  • Change the server response to not return a 401. Return a 200 code instead and handle this in your jQuery client.
  • Change the method that you're using for authorization to a custom value in your header. Browsers will display the popup for Basic and Digest. You have to change this on both the client and the server.

    headers : {
      "Authorization" : "BasicCustom"
    }
    

Please also take a look at this for an example of using jQuery with Basic Auth.

How to detect the physical connected state of a network cable/connector?

Most modern Linux distributions use NetworkManager for this. You could use D-BUS to listen for the events.

If you want a command-line tool to check the status, you can also use mii-tool, given that you have Ethernet in mind.

How to convert char to int?

You may use the following extension method:

public static class CharExtensions
    {
        public static int CharToInt(this char c)
        {
            if (c < '0' || c > '9')
                throw new ArgumentException("The character should be a number", "c");

            return c - '0';
        }
    }

UIViewController viewDidLoad vs. viewWillAppear: What is the proper division of labor?

Initially used only ViewDidLoad with tableView. On testing with loss of Wifi, by setting device to airplane mode, realized that the table did not refresh with return of Wifi. In fact, there appears to be no way to refresh tableView on the device even by hitting the home button with background mode set to YES in -Info.plist.

My solution:

-(void) viewWillAppear: (BOOL) animated { [self.tableView reloadData];}

Should I use window.navigate or document.location in JavaScript?

There really isn't a difference; there are about 5 different methods of doing it. However, the ones I see most often are document.location and window.location because they're supported by all major browsers. (I've personally never seen window.navigate used in production code, so maybe it doesn't have very good support?)

How to compare type of an object in Python?

Use str instead of string

type ( obj ) == str

Explanation

>>> a = "Hello"
>>> type(a)==str
True
>>> type(a)
<type 'str'>
>>>

@Autowired - No qualifying bean of type found for dependency at least 1 bean

I believe for @Service you have to add qualifier name like below :

@Service("employeeService") should solve your issue

or after @Service you should add @Qualifier annontion like below :

@Service
@Qualifier("employeeService")

How to get the index of an item in a list in a single step?

Here's a copy/paste-able extension method for IEnumerable

public static class EnumerableExtensions
{
    /// <summary>
    /// Searches for an element that matches the conditions defined by the specified predicate,
    /// and returns the zero-based index of the first occurrence within the entire <see cref="IEnumerable{T}"/>.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="list">The list.</param>
    /// <param name="predicate">The predicate.</param>
    /// <returns>
    /// The zero-based index of the first occurrence of an element that matches the conditions defined by <paramref name="predicate"/>, if found; otherwise it'll throw.
    /// </returns>
    public static int FindIndex<T>(this IEnumerable<T> list, Func<T, bool> predicate)
    {
        var idx = list.Select((value, index) => new {value, index}).Where(x => predicate(x.value)).Select(x => x.index).First();
        return idx;
    }
}

Enjoy.

git: can't push (unpacker error) related to permission issues

A simpler way to do this is to add a post-receive script which runs the chmod command after every push to the 'hub' repo on the server. Add the following line to hooks/post-receive inside your git folder on the server:

chmod -Rf u+w /path/to/git/repo/objects

Run a command over SSH with JSch

The example provided by Mykhaylo Adamovych is very thorough and exposes most of the major features of JSch. I packaged this code (with attribution, of course) into an open-source library called Remote Session. I added JavaDoc and custom exceptions, and I also provided a facility to specify custom session parameters (RemoteConfig).

One feature that Mykhaylo's code doesn't demonstrate is how to provide an "identity" for remote system interactions. This is critical if you're going to execute commands that require super-user access (i.e. - sudo). Remote Session adds this capability in its SessionHolder.newSession() implementation:

RemoteConfig remoteConfig = RemoteConfig.getConfig();
Path keyPath = remoteConfig.getKeyPath();

if (keyPath == null) {
    throw new RemoteCredentialsUnspecifiedException();
}

String keyPass = remoteConfig.getString(RemoteSettings.SSH_KEY_PASS.key());
if (keyPass != null) {
    Path pubPath = keyPath.resolveSibling(keyPath.getFileName() + ".pub");
    jsch.addIdentity(keyPath.toString(), pubPath.toString(), keyPass.getBytes());
} else {
    jsch.addIdentity(keyPath.toString());
}

Note that this behavior is bypassed if the remote system URL includes credentials.

Another feature that Remote Session demonstrates is how to provide a known-hosts file:

if ( ! remoteConfig.getBoolean(RemoteSettings.IGNORE_KNOWN_HOSTS.key())) {
    Path knownHosts = keyPath.resolveSibling("known_hosts");
    if (knownHosts.toFile().exists()) {
        jsch.setKnownHosts(knownHosts.toString());
    }
}

Remote Session also adds a ChannelStream class that encapsulates input/output operation for the channel attached to this session. This provides the ability to accumulate the output from the remote session until a specified prompt is received:

private boolean appendAndCheckFor(String prompt, StringBuilder input, Logger logger) throws InterruptedException, IOException {
    String recv = readChannel(false);
    if ( ! ((recv == null) || recv.isEmpty())) {
        input.append(recv);
        if (logger != null) {
            logger.debug(recv);
        }
        if (input.toString().contains(prompt)) {
            return false;
        }
    }
    return !channel.isClosed();
}

Nothing too complicated, but this can greatly simplify the implementation of interactive remote operations.

How to redirect the output of an application in background to /dev/null

These will also redirect both:

yourcommand  &> /dev/null

yourcommand  >& /dev/null

though the bash manual says the first is preferred.

Is it possible to make Font Awesome icons larger than 'fa-5x'?

Easy — just use Font Awesome 5's default fa-[size]x classes. You can scale icons up to 10x of the parent element's font-size Read the docs about icon sizing.

Examples:

<span class="fas fa-info-circle fa-6x"></span>
<span class="fas fa-info-circle fa-7x"></span>
<span class="fas fa-info-circle fa-8x"></span>
<span class="fas fa-info-circle fa-9x"></span>
<span class="fas fa-info-circle fa-10x"></span>

Non-conformable arrays error in code

The problem is that omega in your case is matrix of dimensions 1 * 1. You should convert it to a vector if you wish to multiply t(X) %*% X by a scalar (that is omega)

In particular, you'll have to replace this line:

omega   = rgamma(1,a0,1) / L0

with:

omega   = as.vector(rgamma(1,a0,1) / L0)

everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.) or c(t(.)). Both are equivalent.

Here's the modified code that should work:

gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1, 
                     a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
    m0      = c(m01, m02) 
    C0      = matrix(nrow = 2, ncol = 2) 
    C0[1,1] = 1 / k01 
    C0[1,2] = 0 
    C0[2,1] = 0 
    C0[2,2] = 1 / k02 
    beta    = mvrnorm(1,m0,C0) 
    omega   = as.vector(rgamma(1,a0,1) / L0)
    draws   = matrix(ncol = 3,nrow = ndraw) 
    it      = -nburn 

    while (it < ndraw) {
        it    = it + 1 
        C1    = solve(solve(C0) + omega * t(X) %*% X) 
        m1    = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
        beta  = mvrnorm(1, m1, C1) 
        a1    = a0 + n / 2 
        L1    = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2 
        omega = as.vector(rgamma(1, a1, 1) / L1)
        if (it > 0) { 
            draws[it,1] = beta[1]
            draws[it,2] = beta[2]
            draws[it,3] = omega
        }
    }
    return(draws)
}

Controlling Maven final name of jar artifact

The approach you've been using indeed does jar file with a string 'testing' in its name, as you specified, but the default install command sends it to your ~/.m2/repository directory, as seen in this output line:

/tmp/mvn_test/my-app/target/my-app-testing.jar to /home/maxim/.m2/repository/com/mycompany/app/my-app/1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.jar

It seems to me that you're trying to generate a jar with such name and then copy it to a directory of your choice.

Try using outputDirectory property as described here: http://maven.apache.org/plugins/maven-jar-plugin/jar-mojo.html

Loaded nib but the 'view' outlet was not set

Just had the same error in my project, but different reason. In my case I had an IBOutlet setup with the name "View" in my custom UITableViewController class. I knew "view" was special because that is a member of the base class, but I didn't think View (different case) would also be a problem. I guess some areas of Cocoa are not case-sensitive, and probably loading a xib is one of those areas. So I just renamed it to DefaultView and all is good now.

Python naming conventions for modules

From PEP-8: Package and Module Names:

Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability.

Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.

When an extension module written in C or C++ has an accompanying Python module that provides a higher level (e.g. more object oriented) interface, the C/C++ module has a leading underscore (e.g. _socket).

How to add white spaces in HTML paragraph

This can be done easily and cleanly with float.

Demo: jsfiddle.net/KcdpW

HTML:

<ul>
    <li>Item 1 <span class="right">(1)</span></li>
    <li>Item 2 <span class="right">(2)</span></li>
</ul>?

CSS:

ul {
    width: 10em
}
.right {
    float: right
}?

How do I declare a two dimensional array?

For a simple, "fill as you go" kind of solution:

$foo = array(array());

This will get you a flexible pseudo two dimensional array that can hold $foo[n][n] where n <= 8 (of course your limited by the usual constraints of memory size, but you get the idea I hope). This could, in theory, be extended to create as many sub arrays as you need.

How to use `replace` of directive definition?

Also i got this error if i had the comment in tn top level of template among with the actual root element.

<!-- Just a commented out stuff -->
<div>test of {{value}}</div>

Changing background color of selected cell?

In Swift

let v = UIView()
    v.backgroundColor = self.darkerColor(color)
    cell?.selectedBackgroundView = v;

...

func darkerColor( color: UIColor) -> UIColor {
    var h = CGFloat(0)
    var s = CGFloat(0)
    var b = CGFloat(0)
    var a = CGFloat(0)
    let hueObtained = color.getHue(&h, saturation: &s, brightness: &b, alpha: &a)
    if hueObtained {
        return UIColor(hue: h, saturation: s, brightness: b * 0.75, alpha: a)
    }
    return color
}

How do I explicitly specify a Model's table-name mapping in Rails?

Rails >= 3.2 (including Rails 4+ and 5+):

class Countries < ActiveRecord::Base
  self.table_name = "cc"
end

Rails <= 3.1:

class Countries < ActiveRecord::Base
  self.set_table_name "cc"
  ...
end

Get current domain

The only secure way of doing this

The only guaranteed secure method of retrieving the current domain is to store it in a secure location yourself.

Most frameworks take care of storing the domain for you, so you will want to consult the documentation for your particular framework. If you're not using a framework, consider storing the domain in one of the following places:

Secure methods of storing the domain Used By
A config file Joomla, Drupal/Symfony
The database WordPress
An environmental variable Laravel
A service registry Kubernetes DNS

The following work... but they're not secure

Hackers can make the following variables output whatever domain they want. This can lead to cache poisoning and barely noticeable phishing attacks.

$_SERVER['HTTP_HOST']

This gets the domain from the request headers which are open to manipulation by hackers. Same with:

$_SERVER['SERVER_NAME']

This one can be made better if the Apache setting usecanonicalname is turned off; in which case $_SERVER['SERVER_NAME'] will no longer be allowed to be populated with arbitrary values and will be secure. This is, however, non-default and not as common of a setup.

In popular systems

Below is how you can get the current domain in the following frameworks/systems:

WordPress

$urlparts = parse_url(home_url());
$domain = $urlparts['host'];

If you're constructing a URL in WordPress, just use home_url or site_url, or any of the other URL functions.

Laravel

request()->getHost()

The request()->getHost function is inherited from Symfony, and has been secure since the 2013 CVE-2013-4752 was patched.

Drupal

The installer does not yet take care of making this secure (issue #2404259). But in Drupal 8 there is documentation you can you can follow at Trusted Host Settings to secure your Drupal installation after which the following can be used:

\Drupal::request()->getHost();

Other frameworks

Feel free to edit this answer to include how to get the current domain in your favorite framework. When doing so, please include a link to the relevant source code or to anything else that would help me verify that the framework is doing things securely.


Addendum

Exploitation examples:

  1. Cache poisoning can happen if a botnet continuously requests a page using the wrong hosts header. The resulting HTML will then include links to the attackers website where they can phish your users. At first the malicious links will only be sent back to the hacker, but if the hacker does enough requests, the malicious version of the page will end up in your cache where it will be distributed to other users.

  2. A phishing attack can happen if you store links in the database based on the hosts header. For example, let say you store the absolute URL to a user's profiles on a forum. By using the wrong header, a hacker could get anyone who clicks on their profile link to be sent a phishing site.

  3. Password reset poisoning can happen if a hacker uses a malicious hosts header when filling out the password reset form for a different user. That user will then get an email containing a password reset link that leads to a phishing site. Another more complex form of this skips the user having to do anything by getting the email to bounce and resend to one of the hacker's SMTP servers (for example CVE-2017-8295.)

  4. Here are some more malicious examples

Additional Caveats and Notes:

  • When usecanonicalname is turned off the $_SERVER['SERVER_NAME'] is populated with the same header $_SERVER['HTTP_HOST'] would have used anyways (plus the port). This is Apache's default setup. If you or devops turns this on then you're okay -- ish -- but do you really want to rely on a separate team, or yourself three years in the future, to keep what would appear to be a minor configuration at a non-default value? Even though this makes things secure, I would caution against relying on this setup.
  • Redhat, however, does turn usecanonical on by default [source].
  • If serverAlias is used in the virtual hosts entry, and the aliased domain is requested, $_SERVER['SERVER_NAME'] will not return the current domain, but will return the value of the serverName directive.
  • If the serverName cannot be resolved, the operating system's hostname command is used in its place [source].
  • If the host header is left out, the server will behave as if usecanonical was on [source].
  • Lastly, I just tried exploiting this on my local server, and was unable to spoof the hosts header. I'm not sure if there was an update to Apache that addressed this, or if I was just doing something wrong. Regardless, this header would still be exploitable in environments where virtual hosts are not being used.

Little Rant:

     This question received hundreds of thousands of views without a single mention of the security problems at hand! It shouldn't be this way, but just because a Stack Overflow answer is popular, that doesn't mean it is secure.



What happens to a declared, uninitialized variable in C? Does it have a value?

That depends. If that definition is global (outside any function) then num will be initialized to zero. If it's local (inside a function) then its value is indeterminate. In theory, even attempting to read the value has undefined behavior -- C allows for the possibility of bits that don't contribute to the value, but have to be set in specific ways for you to even get defined results from reading the variable.

Location of ini/config files in linux/unix?

For user configuration I've noticed a tendency towards moving away from individual ~/.myprogramrc to a structure below ~/.config. For example, Qt 4 uses ~/.config/<vendor>/<programname> with the default settings of QSettings. The major desktop environments KDE and Gnome use a file structure below a specific folder too (not sure if KDE 4 uses ~/.config, XFCE does use ~/.config).

On design patterns: When should I use the singleton?

A Singleton candidate must satisfy three requirements:

  • controls concurrent access to a shared resource.
  • access to the resource will be requested from multiple, disparate parts of the system.
  • there can be only one object.

If your proposed Singleton has only one or two of these requirements, a redesign is almost always the correct option.

For example, a printer spooler is unlikely to be called from more than one place (the Print menu), so you can use mutexes to solve the concurrent access problem.

A simple logger is the most obvious example of a possibly-valid Singleton, but this can change with more complex logging schemes.

How to compare two columns in Excel (from different sheets) and copy values from a corresponding column if the first two columns match?

Make a truth table and use SUMPRODUCT to get the values. Copy this into cell B1 on Sheet2 and copy down as far as you need:
=SUMPRODUCT(--($A1 = Sheet1!$A:$A), Sheet1!$B:$B)
the part that creates the truth table is:
--($A1 = Sheet1!$A:$A)
This returns an array of 0's and 1's. 1 when the values match and a 0 when they don't. Then the comma after that will basically do what I call "funny" matrix multiplication and will return the result. I may have misunderstood your question though, are there duplicate values in Column A of Sheet1?

Convert canvas to PDF

You can achieve this by utilizing the jsPDF library and the toDataURL function.

I made a little demonstration:

_x000D_
_x000D_
var canvas = document.getElementById('myCanvas');_x000D_
var context = canvas.getContext('2d');_x000D_
_x000D_
// draw a blue cloud_x000D_
context.beginPath();_x000D_
context.moveTo(170, 80);_x000D_
context.bezierCurveTo(130, 100, 130, 150, 230, 150);_x000D_
context.bezierCurveTo(250, 180, 320, 180, 340, 150);_x000D_
context.bezierCurveTo(420, 150, 420, 120, 390, 100);_x000D_
context.bezierCurveTo(430, 40, 370, 30, 340, 50);_x000D_
context.bezierCurveTo(320, 5, 250, 20, 250, 50);_x000D_
context.bezierCurveTo(200, 5, 150, 20, 170, 80);_x000D_
context.closePath();_x000D_
context.lineWidth = 5;_x000D_
context.fillStyle = '#8ED6FF';_x000D_
context.fill();_x000D_
context.strokeStyle = '#0000ff';_x000D_
context.stroke();_x000D_
_x000D_
download.addEventListener("click", function() {_x000D_
  // only jpeg is supported by jsPDF_x000D_
  var imgData = canvas.toDataURL("image/jpeg", 1.0);_x000D_
  var pdf = new jsPDF();_x000D_
_x000D_
  pdf.addImage(imgData, 'JPEG', 0, 0);_x000D_
  pdf.save("download.pdf");_x000D_
}, false);
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>_x000D_
_x000D_
_x000D_
<canvas id="myCanvas" width="578" height="200"></canvas>_x000D_
<button id="download">download</button>
_x000D_
_x000D_
_x000D_

jquery: get id from class selector

$(".class").click(function(){
    alert($(this).attr('id'));
});

only on jquery button click we can do this class should be written there

List rows after specific date

Simply put:

SELECT * 
FROM TABLE_NAME
WHERE
dob > '1/21/2012'

Where 1/21/2012 is the date and you want all data, including that date.

SELECT * 
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'

Use a between if you're selecting time between two dates

how to initialize a char array?

char * msg = new char[65546]();

It's known as value-initialisation, and was introduced in C++03. If you happen to find yourself trapped in a previous decade, then you'll need to use std::fill() (or memset() if you want to pretend it's C).

Note that this won't work for any value other than zero. I think C++0x will offer a way to do that, but I'm a bit behind the times so I can't comment on that.

UPDATE: it seems my ruminations on the past and future of the language aren't entirely accurate; see the comments for corrections.

Dynamic SQL results into temp table in SQL Stored procedure

CREATE PROCEDURE dbo.pdpd_DynamicCall 
AS
DECLARE @SQLString_2 NVARCHAR(4000)
SET NOCOUNT ON
Begin
    --- Create global temp table
    CREATE TABLE ##T1 ( column_1 varchar(10) , column_2 varchar(100) )

    SELECT @SQLString_2 = 'INSERT INTO ##T1( column_1, column_2) SELECT column_1 = "123", column_2 = "MUHAMMAD IMRON"'
    SELECT @SQLString_2 = REPLACE(@SQLString_2, '"', '''')

    EXEC SP_EXECUTESQL @SQLString_2

    --- Test Display records
    SELECT * FROM ##T1

    --- Drop global temp table 
    IF OBJECT_ID('tempdb..##T1','u') IS NOT NULL
    DROP TABLE ##T1
End

Wildcard string comparison in Javascript

I think you meant something like "*" (star) as a wildcard for example:

  • "a*b" => everything that starts with "a" and ends with "b"
  • "a*" => everything that starts with "a"
  • "*b" => everything that ends with "b"
  • "*a*" => everything that has an "a" in it
  • "*a*b*"=> everything that has an "a" in it, followed by anything, followed by a "b", followed by anything

or in your example: "bird*" => everything that starts with bird

I had a similar problem and wrote a function with RegExp:

_x000D_
_x000D_
//Short code_x000D_
function matchRuleShort(str, rule) {_x000D_
  var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");_x000D_
  return new RegExp("^" + rule.split("*").map(escapeRegex).join(".*") + "$").test(str);_x000D_
}_x000D_
_x000D_
//Explanation code_x000D_
function matchRuleExpl(str, rule) {_x000D_
  // for this solution to work on any string, no matter what characters it has_x000D_
  var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");_x000D_
_x000D_
  // "."  => Find a single character, except newline or line terminator_x000D_
  // ".*" => Matches any string that contains zero or more characters_x000D_
  rule = rule.split("*").map(escapeRegex).join(".*");_x000D_
_x000D_
  // "^"  => Matches any string with the following at the beginning of it_x000D_
  // "$"  => Matches any string with that in front at the end of it_x000D_
  rule = "^" + rule + "$"_x000D_
_x000D_
  //Create a regular expression object for matching string_x000D_
  var regex = new RegExp(rule);_x000D_
_x000D_
  //Returns true if it finds a match, otherwise it returns false_x000D_
  return regex.test(str);_x000D_
}_x000D_
_x000D_
//Examples_x000D_
alert(_x000D_
    "1. " + matchRuleShort("bird123", "bird*") + "\n" +_x000D_
    "2. " + matchRuleShort("123bird", "*bird") + "\n" +_x000D_
    "3. " + matchRuleShort("123bird123", "*bird*") + "\n" +_x000D_
    "4. " + matchRuleShort("bird123bird", "bird*bird") + "\n" +_x000D_
    "5. " + matchRuleShort("123bird123bird123", "*bird*bird*") + "\n" +_x000D_
    "6. " + matchRuleShort("s[pe]c 3 re$ex 6 cha^rs", "s[pe]c*re$ex*cha^rs") + "\n" +_x000D_
    "7. " + matchRuleShort("should not match", "should noo*oot match") + "\n"_x000D_
);
_x000D_
_x000D_
_x000D_


If you want to read more about the used functions:

Remove local git tags that are no longer on the remote repository

If you only want those tags which exist on the remote, simply delete all your local tags:

$ git tag -d $(git tag)

And then fetch all the remote tags:

$ git fetch --tags

Failed to install *.apk on device 'emulator-5554': EOF

Solution:

  1. Start emulator (separately) and wait until it is fully loaded.
  2. Open keylock.
  3. Navigate to Eclipse and run your app.

Cause of the problem: Android emulator hasn't loaded all its libraries which handle the installing of a new application and due to that you run into java.io.IOException: EOF

That was causing me the problem.

How can my iphone app detect its own version number?

You can try using dictionary as:-

NSDictionary *infoDictionary = [[NSBundle mainBundle]infoDictionary];

NSString *buildVersion = infoDictionary[(NSString*)kCFBundleVersionKey];
NSString *bundleName = infoDictionary[(NSString *)kCFBundleNameKey]

malloc for struct and pointer in C

Few points

struct Vector y = (struct Vector*)malloc(sizeof(struct Vector)); is wrong

it should be struct Vector *y = (struct Vector*)malloc(sizeof(struct Vector)); since y holds pointer to struct Vector.

1st malloc() only allocates memory enough to hold Vector structure (which is pointer to double + int)

2nd malloc() actually allocate memory to hold 10 double.

#1227 - Access denied; you need (at least one of) the SUPER privilege(s) for this operation

It means you don't have privileges to create the trigger with root@localhost user..

try removing definer from the trigger command:

CREATE DEFINER = root@localhost FUNCTION fnc_calcWalkedDistance

Declare and assign multiple string variables at the same time

Try with:

 string Camnr, Klantnr, Ordernr, Bonnr, Volgnr, Omschrijving;
 Camnr = Klantnr = Ordernr = Bonnr = Volgnr = Omschrijving = string.Empty;

Form inline inside a form horizontal in twitter bootstrap?

Don't nest <form> tags, that will not work. Just use Bootstrap classes.

Bootstrap 3

<form class="form-horizontal" role="form">
    <div class="form-group">
      <label for="inputType" class="col-md-2 control-label">Type</label>
      <div class="col-md-3">
          <input type="text" class="form-control" id="inputType" placeholder="Type">
      </div>
    </div>
    <div class="form-group">
        <span class="col-md-2 control-label">Metadata</span>
        <div class="col-md-6">
            <div class="form-group row">
                <label for="inputKey" class="col-md-1 control-label">Key</label>
                <div class="col-md-2">
                    <input type="text" class="form-control" id="inputKey" placeholder="Key">
                </div>
                <label for="inputValue" class="col-md-1 control-label">Value</label>
                <div class="col-md-2">
                    <input type="text" class="form-control" id="inputValue" placeholder="Value">
                </div>
            </div>
        </div>
    </div>
</form>

You can achieve that behaviour in many ways, that's just an example. Test it on this bootply

Bootstrap 2

<form class="form-horizontal">
    <div class="control-group">
        <label class="control-label" for="inputType">Type</label>
        <div class="controls">
            <input type="text" id="inputType" placeholder="Type">
        </div>
    </div>
    <div class="control-group">
        <span class="control-label">Metadata</span>
        <div class="controls form-inline">
            <label for="inputKey">Key</label>
            <input type="text" class="input-small" placeholder="Key" id="inputKey">
            <label for="inputValue">Value</label>
            <input type="password" class="input-small" placeholder="Value" id="inputValue">
        </div>
    </div>
</form>

Note that I'm using .form-inline to get the propper styling inside a .controls.
You can test it on this jsfiddle

Git adding files to repo

After adding files to the stage, you need to commit them with git commit -m "comment" after git add .. Finally, to push them to a remote repository, you need to git push <remote_repo> <local_branch>.

Concatenating strings in C, which method is more efficient?

The difference is unlikely to matter:

  • If your strings are small, the malloc will drown out the string concatenations.
  • If your strings are large, the time spent copying the data will drown out the differences between strcat / sprintf.

As other posters have mentioned, this is a premature optimization. Concentrate on algorithm design, and only come back to this if profiling shows it to be a performance problem.

That said... I suspect method 1 will be faster. There is some---admittedly small---overhead to parse the sprintf format-string. And strcat is more likely "inline-able".

When do items in HTML5 local storage expire?

I would suggest to store timestamp in the object you store in the localStorage

var object = {value: "value", timestamp: new Date().getTime()}
localStorage.setItem("key", JSON.stringify(object));

You can parse the object, get the timestamp and compare with the current Date, and if necessary, update the value of the object.

var object = JSON.parse(localStorage.getItem("key")),
    dateString = object.timestamp,
    now = new Date().getTime().toString();

compareTime(dateString, now); //to implement

Height equal to dynamic width (CSS fluid layout)

Using jQuery you can achieve this by doing

var cw = $('.child').width();
$('.child').css({'height':cw+'px'});

Check working example at http://jsfiddle.net/n6DAu/1/

IPython Notebook save location

To add to Victor's answer, I was able to change the save directory on Windows using...

c.NotebookApp.notebook_dir = 'C:\\Users\\User\\Folder'

Check whether IIS is installed or not?

go to Start->Run type inetmgr and press OK. If you get an IIS configuration screen. It is installed, otherwise it isn't.

You can also check ControlPanel->Add Remove Programs, Click Add Remove Windows Components and look for IIS in the list of installed components.

EDIT


To Reinstall IIS.

Control Panel -> Add Remove Programs -> Click Add Remove Windows Components
Uncheck IIS box

Click next and follow prompts to UnInstall IIS. Insert your windows disc into the appropriate drive.

Control Panel -> Add Remove Programs -> Click Add Remove Windows Components
Check IIS box

Click next and follow prompts to Install IIS.

HTML table headers always visible at top of window when viewing a large table

It's frustrating that what works great in one browser doesn't work in others. The following works in Firefox, but not in Chrome or IE:

<table width="80%">

 <thead>

 <tr>
  <th>Column 1</th>
  <th>Column 2</th>
  <th>Column 3</th>
 </tr>

 </thead>

 <tbody style="height:50px; overflow:auto">

  <tr>
    <td>Cell A1</td>
    <td>Cell B1</td>
    <td>Cell C1</td>
  </tr>

  <tr>
    <td>Cell A2</td>
    <td>Cell B2</td>
    <td>Cell C2</td>
  </tr>

  <tr>
    <td>Cell A3</td>
    <td>Cell B3</td>
    <td>Cell C3</td>
  </tr>

 </tbody>

</table>

How to write a multiline command?

The caret character works, however the next line should not start with double quotes. e.g. this will not work:

C:\ ^
"SampleText" ..

Start next line without double quotes (not a valid example, just to illustrate)

Replace deprecated preg_replace /e with preg_replace_callback

You can use an anonymous function to pass the matches to your function:

$result = preg_replace_callback(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
    function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
    $result
);

Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e would convert a double quote " into \".

Using two CSS classes on one element

If you want two classes on one element, do it this way:

<div class="social first"></div>

Reference it in css like so:

.social.first {}

Example:

https://jsfiddle.net/tybro0103/covbtpaq/

Change CSS class properties with jQuery

Didn't find the answer I wanted, so I solved it myself:
modify a container div!

<div class="rotation"> <!-- Set the container div's css -->
  <div class="content" id='content-1'>This div gets scaled on hover</div>
</div>

<!-- Since there is no parent here the transform doesnt have specificity! -->
<div class="rotation content" id='content-2'>This div does not</div>

css you want to persist after executing $target.css()

.content:hover {
    transform: scale(1.5);
}

modify content's containing div with css()

$(".rotation").css("transform", "rotate(" + degrees + "deg)");

Codepen example

Android Studio how to run gradle sync manually?

I think ./gradlew tasks is same with Android studio sync. Why? I will explain it.

I meet a problem when I test jacoco coverage report. When I run ./gradlew clean :Test:testDebugUnitTest in command line directly , error appear.

Error opening zip file or JAR manifest missing : build/tmp/expandedArchives/org.jacoco.agent-0.8.2.jar_5bdiis3s7lm1rcnv0gawjjfxc/jacocoagent.jar

However, if I click android studio sync firstly , it runs OK. Because the build/../jacocoagent.jar appear naturally. I dont know why, maybe there is bug in jacoco plugin. Unit I find running .gradlew tasks makes the jar appear as well. So I can get the same result in gralde script.

Besides, gradle --recompile-scripts does not work for the problem.

How do I find a particular value in an array and return its index?

Here is a very simple way to do it by hand. You could also use the <algorithm>, as Peter suggests.

#include <iostream>
int find(int arr[], int len, int seek)
{
    for (int i = 0; i < len; ++i)
    {
        if (arr[i] == seek) return i;
    }
    return -1;
}
int main()
{
    int arr[ 5 ] = { 4, 1, 3, 2, 6 };
    int x = find(arr,5,3);
    std::cout << x << std::endl;    
}

Cannot Resolve Collation Conflict

The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.

When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.

Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:

http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database

Update Collation of all fields in database on the fly

http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx

If you need to have different collation on two objects or can't change collations - you can still JOIN between them using COLLATE command, and choosing the collation you want for join.

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS 

or using default database collation:

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT

The difference between fork(), vfork(), exec() and clone()

  1. fork() - creates a new child process, which is a complete copy of the parent process. Child and parent processes use different virtual address spaces, which is initially populated by the same memory pages. Then, as both processes are executed, the virtual address spaces begin to differ more and more, because the operating system performs a lazy copying of memory pages that are being written by either of these two processes and assigns an independent copies of the modified pages of memory for each process. This technique is called Copy-On-Write (COW).
  2. vfork() - creates a new child process, which is a "quick" copy of the parent process. In contrast to the system call fork(), child and parent processes share the same virtual address space. NOTE! Using the same virtual address space, both the parent and child use the same stack, the stack pointer and the instruction pointer, as in the case of the classic fork()! To prevent unwanted interference between parent and child, which use the same stack, execution of the parent process is frozen until the child will call either exec() (create a new virtual address space and a transition to a different stack) or _exit() (termination of the process execution). vfork() is the optimization of fork() for "fork-and-exec" model. It can be performed 4-5 times faster than the fork(), because unlike the fork() (even with COW kept in the mind), implementation of vfork() system call does not include the creation of a new address space (the allocation and setting up of new page directories).
  3. clone() - creates a new child process. Various parameters of this system call, specify which parts of the parent process must be copied into the child process and which parts will be shared between them. As a result, this system call can be used to create all kinds of execution entities, starting from threads and finishing by completely independent processes. In fact, clone() system call is the base which is used for the implementation of pthread_create() and all the family of the fork() system calls.
  4. exec() - resets all the memory of the process, loads and parses specified executable binary, sets up new stack and passes control to the entry point of the loaded executable. This system call never return control to the caller and serves for loading of a new program to the already existing process. This system call with fork() system call together form a classical UNIX process management model called "fork-and-exec".

Completely cancel a rebase

Use git rebase --abort. From the official Linux kernel documentation for git rebase:

git rebase --continue | --skip | --abort | --edit-todo

How to create an integer array in Python?

two ways:

x = [0] * 10
x = [0 for i in xrange(10)]

Edit: replaced range by xrange to avoid creating another list.

Also: as many others have noted including Pi and Ben James, this creates a list, not a Python array. While a list is in many cases sufficient and easy enough, for performance critical uses (e.g. when duplicated in thousands of objects) you could look into python arrays. Look up the array module, as explained in the other answers in this thread.

Convert HTML5 into standalone Android App

You can use https://appery.io/ It is the same phonegap but in very convinient wrapper

How to decompile to java files intellij idea

I use JD-GUI for extract all decompiled java classes to java files.

PHP - Merging two arrays into one array (also Remove Duplicates)

As already mentioned, array_unique() could be used, but only when dealing with simple data. The objects are not so simple to handle.

When php tries to merge the arrays, it tries to compare the values of the array members. If a member is an object, it cannot get its value and uses the spl hash instead. Read more about spl_object_hash here.

Simply told if you have two objects, instances of the very same class and if one of them is not a reference to the other one - you will end up having two objects, no matter the value of their properties.

To be sure that you don't have any duplicates within the merged array, Imho you should handle the case on your own.

Also if you are going to merge multidimensional arrays, consider using array_merge_recursive() over array_merge().

Where is HttpContent.ReadAsAsync?

If you are already using Newtonsoft.Json and don't want to install Microsoft.AspNet.WebApi.Client:

 var myInstance = JsonConvert.DeserializeObject<MyClass>(
   await response.Content.ReadAsStringAsync());

Check for column name in a SqlDataReader object

TLDR:

Lots of answers with claims about performance and bad practice, so I clarify that here.

The exception route is faster for higher numbers of returned columns, the loop route is faster for lower number of columns, and the crossover point is around 11 columns. Scroll to the bottom to see a graph and test code.

Full answer:

The code for some of the top answers work, but there is an underlying debate here for the "better" answer based on the acceptance of exception handling in logic and it's related performance.

To clear that away, I do not believe there is much guidance regarding CATCHING exceptions. Microsoft does have some guidance regarding THROWING exceptions. There they do state:

DO NOT use exceptions for the normal flow of control, if possible.

The first note is the leniency of "if possible". More importantly, the description gives this context:

framework designers should design APIs so users can write code that does not throw exceptions

What that means is that if you are writing an API that might be consumed by somebody else, give them the ability to navigate an exception without a try/catch. For example, provide a TryParse with your exception-throwing Parse method. Nowhere does this say though that you shouldn't catch an exception.

Further, as another user points out, catches have always allowed filtering by type and somewhat recently allow further filtering via the when clause. This seems like a waste of language features if we're not supposed to be using them.

It can be said that there is SOME cost for a thrown exception, and that cost MAY impact performance in a heavy loop. However, it can also be said that the cost of an exception is going to be negligible in a "connected application". Actual cost was investigated over a decade ago: https://stackoverflow.com/a/891230/852208 In other words, cost of a connection and query of a database is likely to dwarf that of a thrown exception.

All that aside, I wanted to determine which method truly is faster. As expected there is no concrete answer.

Any code that loops over the columns becomes slower as the number of columns exist. It can also be said that any code that relies on exceptions will slow depending on the rate in which the query fails to be found.

Taking the answers of both Chad Grant and Matt Hamilton, I ran both methods with up to 20 columns and up to a 50% error rate (the OP indicated he was using this two test between different procs, so I assumed as few as two).

Here are the results, plotted with LinqPad: Results - Series 1 is Loop, 2 is Exception

The zigzags here are fault rates (column not found) within each column count.

Over narrower result sets, looping is a good choice. However, the GetOrdinal/Exception method is not nearly as sensitive to number of columns and begins to outperform the looping method right around 11 columns.

That said I don't really have a preference performance wise as 11 columns sounds reasonable as an average number of columns returned over an entire application. In either case we're talking about fractions of a millisecond here.

However, from a code simplicity aspect, and alias support, i'd probably go with the GetOrdinal route.

Here is the test in linqpad form. Feel free to repost with your own method:

void Main()
{
    var loopResults = new List<Results>();
    var exceptionResults = new List<Results>();
    var totalRuns = 10000;
    for (var colCount = 1; colCount < 20; colCount++)
    {
        using (var conn = new SqlConnection(@"Data Source=(localdb)\MSSQLLocalDb;Initial Catalog=master;Integrated Security=True;"))
        {
            conn.Open();

            //create a dummy table where we can control the total columns
            var columns = String.Join(",",
                (new int[colCount]).Select((item, i) => $"'{i}' as col{i}")
            );
            var sql = $"select {columns} into #dummyTable";
            var cmd = new SqlCommand(sql,conn);
            cmd.ExecuteNonQuery();

            var cmd2 = new SqlCommand("select * from #dummyTable", conn);

            var reader = cmd2.ExecuteReader();
            reader.Read();

            Func<Func<IDataRecord, String, Boolean>, List<Results>> test = funcToTest =>
            {
                var results = new List<Results>();
                Random r = new Random();
                for (var faultRate = 0.1; faultRate <= 0.5; faultRate += 0.1)
                {
                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Start();
                    var faultCount=0;
                    for (var testRun = 0; testRun < totalRuns; testRun++)
                    {
                        if (r.NextDouble() <= faultRate)
                        {
                            faultCount++;
                            if(funcToTest(reader, "colDNE"))
                                throw new ApplicationException("Should have thrown false");
                        }
                        else
                        {
                            for (var col = 0; col < colCount; col++)
                            {
                                if(!funcToTest(reader, $"col{col}"))
                                    throw new ApplicationException("Should have thrown true");
                            }
                        }
                    }
                    stopwatch.Stop();
                    results.Add(new UserQuery.Results{
                        ColumnCount = colCount, 
                        TargetNotFoundRate = faultRate,
                        NotFoundRate = faultCount * 1.0f / totalRuns, 
                        TotalTime=stopwatch.Elapsed
                    });
                }
                return results;
            };
            loopResults.AddRange(test(HasColumnLoop));

            exceptionResults.AddRange(test(HasColumnException));

        }

    }
    "Loop".Dump();
    loopResults.Dump();

    "Exception".Dump();
    exceptionResults.Dump();

    var combinedResults = loopResults.Join(exceptionResults,l => l.ResultKey, e=> e.ResultKey, (l, e) => new{ResultKey = l.ResultKey, LoopResult=l.TotalTime, ExceptionResult=e.TotalTime});
    combinedResults.Dump();
    combinedResults
        .Chart(r => r.ResultKey, r => r.LoopResult.Milliseconds * 1.0 / totalRuns, LINQPad.Util.SeriesType.Line)
        .AddYSeries(r => r.ExceptionResult.Milliseconds * 1.0 / totalRuns, LINQPad.Util.SeriesType.Line)
        .Dump();
}
public static bool HasColumnLoop(IDataRecord dr, string columnName)
{
    for (int i = 0; i < dr.FieldCount; i++)
    {
        if (dr.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase))
            return true;
    }
    return false;
}

public static bool HasColumnException(IDataRecord r, string columnName)
{
    try
    {
        return r.GetOrdinal(columnName) >= 0;
    }
    catch (IndexOutOfRangeException)
    {
        return false;
    }
}

public class Results
{
    public double NotFoundRate { get; set; }
    public double TargetNotFoundRate { get; set; }
    public int ColumnCount { get; set; }
    public double ResultKey {get => ColumnCount + TargetNotFoundRate;}
    public TimeSpan TotalTime { get; set; }


}

How to connect to MySQL Database?

you can use Package Manager to add it as package and it is the easiest way to do. You don't need anything else to work with mysql database.

Or you can run below command in Package Manager Console

PM> Install-Package MySql.Data

NUGET Mysql.Data

PHP shell_exec() vs exec()

shell_exec - Execute command via shell and return the complete output as a string

exec - Execute an external program.

The difference is that with shell_exec you get output as a return value.

Why doesn't height: 100% work to expand divs to the screen height?

This may not be ideal but you can allways do it with javascript. Or in my case jQuery

<script>
var newheight = $('.innerdiv').css('height');
$('.mainwrapper').css('height', newheight);
</script>

What does the Visual Studio "Any CPU" target mean?

Here's a quick overview that explains the different build targets.

From my own experience, if you're looking to build a project that will run on both x86 and x64 platforms, and you don't have any specific x64 optimizations, I'd change the build to specifically say "x86."

The reason for this is sometimes you can get some DLL files that collide or some code that winds up crashing WoW in the x64 environment. By specifically specifying x86, the x64 OS will treat the application as a pure x86 application and make sure everything runs smoothly.

Iterate through every file in one directory

Dir.foreach("/home/mydir") do |fname|
  puts fname
end

PLS-00428: an INTO clause is expected in this SELECT statement

In PLSQL block, columns of select statements must be assigned to variables, which is not the case in SQL statements.

The second BEGIN's SQL statement doesn't have INTO clause and that caused the error.

DECLARE
   PROD_ROW_ID   VARCHAR (10) := NULL;
   VIS_ROW_ID    NUMBER;
   DSC           VARCHAR (512);
BEGIN
   SELECT ROW_ID
     INTO VIS_ROW_ID
     FROM SIEBEL.S_PROD_INT
    WHERE PART_NUM = 'S0146404';

   BEGIN
      SELECT    RTRIM (VIS.SERIAL_NUM)
             || ','
             || RTRIM (PLANID.DESC_TEXT)
             || ','
             || CASE
                   WHEN PLANID.HIGH = 'TEST123'
                   THEN
                      CASE
                         WHEN TO_DATE (PROD.START_DATE) + 30 > SYSDATE
                         THEN
                            'Y'
                         ELSE
                            'N'
                      END
                   ELSE
                      'N'
                END
             || ','
             || 'GB'
             || ','
             || RTRIM (TO_CHAR (PROD.START_DATE, 'YYYY-MM-DD'))
        INTO DSC
        FROM SIEBEL.S_LST_OF_VAL PLANID
             INNER JOIN SIEBEL.S_PROD_INT PROD
                ON PROD.PART_NUM = PLANID.VAL
             INNER JOIN SIEBEL.S_ASSET NETFLIX
                ON PROD.PROD_ID = PROD.ROW_ID
             INNER JOIN SIEBEL.S_ASSET VIS
                ON VIS.PROM_INTEG_ID = PROD.PROM_INTEG_ID
             INNER JOIN SIEBEL.S_PROD_INT VISPROD
                ON VIS.PROD_ID = VISPROD.ROW_ID
       WHERE     PLANID.TYPE = 'Test Plan'
             AND PLANID.ACTIVE_FLG = 'Y'
             AND VISPROD.PART_NUM = VIS_ROW_ID
             AND PROD.STATUS_CD = 'Active'
             AND VIS.SERIAL_NUM IS NOT NULL;
   END;
END;
/

References

http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/static.htm#LNPLS00601 http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/selectinto_statement.htm#CJAJAAIG http://pls-00428.ora-code.com/

How to verify if $_GET exists?

You are use PHP isset

Example

if (isset($_GET["id"])) {
    echo $_GET["id"];
}

How to pass a callback as a parameter into another function

If you google for javascript callback function example you will get Getting a better understanding of callback functions in JavaScript

This is how to do a callback function:

function f() {
    alert('f was called!');
}

function callFunction(func) {
    func();
}

callFunction(f);

How can I run multiple curl requests processed sequentially?

You can specify any amount of URLs on the command line. They will be fetched in a sequential manner in the specified order.

Getting a POST variable

In addition to using Request.Form and Request.QueryString and depending on your specific scenario, it may also be useful to check the Page's IsPostBack property.

if (Page.IsPostBack)
{
  // HTTP Post
}
else
{
  // HTTP Get
}

Override standard close (X) button in a Windows Form

You can override OnFormClosing to do this. Just be careful you don't do anything too unexpected, as clicking the 'X' to close is a well understood behavior.

protected override void OnFormClosing(FormClosingEventArgs e)
{
    base.OnFormClosing(e);

    if (e.CloseReason == CloseReason.WindowsShutDown) return;

    // Confirm user wants to close
    switch (MessageBox.Show(this, "Are you sure you want to close?", "Closing", MessageBoxButtons.YesNo))
    {
    case DialogResult.No:
        e.Cancel = true;
        break;
    default:
        break;
    }        
}

What is the equivalent of "none" in django templates?

None, False and True all are available within template tags and filters. None, False, the empty string ('', "", """""") and empty lists/tuples all evaluate to False when evaluated by if, so you can easily do

{% if profile.user.first_name == None %}
{% if not profile.user.first_name %}

A hint: @fabiocerqueira is right, leave logic to models, limit templates to be the only presentation layer and calculate stuff like that in you model. An example:

# someapp/models.py
class UserProfile(models.Model):
    user = models.OneToOneField('auth.User')
    # other fields

    def get_full_name(self):
        if not self.user.first_name:
            return
        return ' '.join([self.user.first_name, self.user.last_name])

# template
{{ user.get_profile.get_full_name }}

Hope this helps :)

XPath contains(text(),'some string') doesn't work when used with node with more than one Text subnode

It took me a little while but finally figured out. Custom xpath that contains some text below worked perfectly for me.

//a[contains(text(),'JB-')]

How do I get the latest version of my code?

I understand you want to trash your local changes and pull down what's on your remote?

If all else fails, and if you're (quite understandably) scared of "reset", the simplest thing is just to clone origin into a new directory and trash your old one.

Running a command in a new Mac OS X Terminal window

I call this script trun. I suggest putting it in a directory in your executable path. Make sure it is executable like this:

chmod +x ~/bin/trun

Then you can run commands in a new window by just adding trun before them, like this:

trun tail -f /var/log/system.log

Here's the script. It does some fancy things like pass your arguments, change the title bar, clear the screen to remove shell startup clutter, remove its file when its done. By using a unique file for each new window it can be used to create many windows at the same time.

#!/bin/bash
# make this file executable with chmod +x trun
# create a unique file in /tmp
trun_cmd=`mktemp`
# make it cd back to where we are now
echo "cd `pwd`" >$trun_cmd
# make the title bar contain the command being run
echo 'echo -n -e "\033]0;'$*'\007"' >>$trun_cmd
# clear window
echo clear >>$trun_cmd
# the shell command to execute
echo $* >>$trun_cmd
# make the command remove itself
echo rm $trun_cmd >>$trun_cmd
# make the file executable
chmod +x $trun_cmd

# open it in Terminal to run it in a new Terminal window
open -b com.apple.terminal $trun_cmd

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema

Just change from "loaders" to "rules" in "webpack.config.js"

Because loaders is used in Webpack 1, and rules in Webpack2. You can see there have differences.

adb command not found

nano /home/user/.bashrc  
export ANDROID_HOME=/psth/to/android/sdk  
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools  

However, this will not work for su/ sudo. If you need to set system-wide variables, you may want to think about adding them to /etc/profile, /etc/bash.bashrc, or /etc/environment.

ie:

nano /etc/bash.bashrc  
export ANDROID_HOME=/psth/to/android/sdk  
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools  

How to check radio button is checked using JQuery?

This is best practice

$("input[name='radioGroup']:checked").val()

REST URI convention - Singular or plural name of resource while creating it

Plural

  • Simple - all urls start with the same prefix
  • Logical - orders/ gets an index list of orders.
  • Standard - Most widely adopted standard followed by the overwhelming majority of public and private APIs.

For example:

GET /resources - returns a list of resource items

POST /resources - creates one or many resource items

PUT /resources - updates one or many resource items

PATCH /resources - partially updates one or many resource items

DELETE /resources - deletes all resource items

And for single resource items:

GET /resources/:id - returns a specific resource item based on :id parameter

POST /resources/:id - creates one resource item with specified id (requires validation)

PUT /resources/:id - updates a specific resource item

PATCH /resources/:id - partially updates a specific resource item

DELETE /resources/:id - deletes a specific resource item

To the advocates of singular, think of it this way: Would you ask a someone for an order and expect one thing, or a list of things? So why would you expect a service to return a list of things when you type /order?

jQuery ajax request being block because Cross-Origin

Try to use JSONP in your Ajax call. It will bypass the Same Origin Policy.

http://learn.jquery.com/ajax/working-with-jsonp/

Try example

$.ajax({
    url: "https://api.dailymotion.com/video/x28j5hv?fields=title",

    dataType: "jsonp",
    success: function( response ) {
        console.log( response ); // server response
    }

});

Dynamically fill in form values with jQuery

Assuming this example HTML:

<input type="text" name="email" id="email" />
<input type="text" name="first_name" id="first_name" />
<input type="text" name="last_name" id="last_name" />

You could have this javascript:

$("#email").bind("change", function(e){
  $.getJSON("http://yourwebsite.com/lokup.php?email=" + $("#email").val(),
        function(data){
          $.each(data, function(i,item){
            if (item.field == "first_name") {
              $("#first_name").val(item.value);
            } else if (item.field == "last_name") {
              $("#last_name").val(item.value);
            }
          });
        });
});

Then just you have a PHP script (in this case lookup.php) that takes an email in the query string and returns a JSON formatted array back with the values you want to access. This is the part that actually hits the database to look up the values:

<?php
//look up the record based on email and get the firstname and lastname
...

//build the JSON array for return
$json = array(array('field' => 'first_name', 
                    'value' => $firstName), 
              array('field' => 'last_name', 
                    'value' => $last_name));
echo json_encode($json );
?>

You'll want to do other things like sanitize the email input, etc, but should get you going in the right direction.

Android EditText view Floating Hint in Material Design

@andruboy's suggestion of https://gist.github.com/chrisbanes/11247418 is probably your best bet.

https://github.com/thebnich/FloatingHintEditText kind of works with appcompat-v7 v21.0.0, but since v21.0.0 does not support accent colors with subclasses of EditText, the underline of the FloatingHintEditText will be the default solid black or white. Also the padding is not optimized for the Material style EditText, so you may need to adjust it.

How to send an email using PHP?

You could also use PHPMailer class at https://github.com/PHPMailer/PHPMailer .

It allows you to use the mail function or use an smtp server transparently. It also handles HTML based emails and attachments so you don't have to write your own implementation.

The class is stable and it is used by many other projects like Drupal, SugarCRM, Yii, and Joomla!

Here is an example from the page above:

<?php
require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = '[email protected]';                 // SMTP username
$mail->Password = 'secret';                           // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable encryption, 'ssl' also accepted

$mail->From = '[email protected]';
$mail->FromName = 'Mailer';
$mail->addAddress('[email protected]', 'Joe User');     // Add a recipient
$mail->addAddress('[email protected]');               // Name is optional
$mail->addReplyTo('[email protected]', 'Information');
$mail->addCC('[email protected]');
$mail->addBCC('[email protected]');

$mail->WordWrap = 50;                                 // Set word wrap to 50 characters
$mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
$mail->isHTML(true);                                  // Set email format to HTML

$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

Start an Activity with a parameter

Kotlin code:

Start the SecondActivity:

startActivity(Intent(context, SecondActivity::class.java)
    .putExtra(SecondActivity.PARAM_GAME_ID, gameId))

Get the Id in SecondActivity:

class CaptureActivity : AppCompatActivity() {

    companion object {
        const val PARAM_GAME_ID = "PARAM_GAME_ID"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val gameId = intent.getStringExtra(PARAM_GAME_ID)
        // TODO use gameId
    }
}

where gameId is String? (can be null)

How to get exception message in Python properly

I had the same problem. I think the best solution is to use log.exception, which will automatically print out stack trace and error message, such as:

try:
    pass
    log.info('Success')
except:
    log.exception('Failed')

Init array of structs in Go

You can have it this way:

It is important to mind the commas after each struct item or set of items.

earnings := []LineItemsType{

        LineItemsType{

            TypeName: "Earnings",

            Totals: 0.0,

            HasTotal: true,

            items: []LineItems{

                LineItems{

                    name: "Basic Pay",

                    amount: 100.0,
                },

                LineItems{

                    name: "Commuter Allowance",

                    amount: 100.0,
                },
            },
        },
        LineItemsType{

            TypeName: "Earnings",

            Totals: 0.0,

            HasTotal: true,

            items: []LineItems{

                LineItems{

                    name: "Basic Pay",

                    amount: 100.0,
                },

                LineItems{

                    name: "Commuter Allowance",

                    amount: 100.0,
                },
            },
        },
    }

Which is the default location for keystore/truststore of Java applications?

In Java, according to the JSSE Reference Guide, there is no default for the keystore, the default for the truststore is "jssecacerts, if it exists. Otherwise, cacerts".

A few applications use ~/.keystore as a default keystore, but this is not without problems (mainly because you might not want all the application run by the user to use that trust store).

I'd suggest using application-specific values that you bundle with your application instead, it would tend to be more applicable in general.

Add inline style using Javascript

Using jQuery :

$(nFilter).attr("style","whatever");

Otherwise :

nFilter.setAttribute("style", "whatever");

should work

TextFX menu is missing in Notepad++

For 32 bit Notepad++ only

Plugins -> Plugin Manager -> Show Plugin Manager -> Available tab -> TextFX Characters -> Install.

It was removed from the default installation as it caused issues with certain configurations, and there's no maintainer.

Validating IPv4 addresses with regexp

ip address can be from 0.0.0.0 to 255.255.255.255

(((0|1)?[0-9][0-9]?|2[0-4][0-9]|25[0-5])[.]){3}((0|1)?[0-9][0-9]?|2[0-4][0-9]|25[0-5])$

(0|1)?[0-9][0-9]? - checking value from 0 to 199
2[0-4][0-9]- checking value from 200 to 249
25[0-5]- checking value from 250 to 255
[.] --> represent verify . character 
{3} --> will match exactly 3
$ --> end of string

Arduino Tools > Serial Port greyed out

In my case I solved this issue by uninstalling the version of Arduino that I installed via apt-get and instead installed via the official website.

With the latest version of Arduino I didn't have the problem described on Ubuntu 18.04.

How do I correctly clone a JavaScript object?

Structured Cloning

The HTML standard includes an internal structured cloning/serialization algorithm that can create deep clones of objects. It is still limited to certain built-in types, but in addition to the few types supported by JSON it also supports Dates, RegExps, Maps, Sets, Blobs, FileLists, ImageDatas, sparse Arrays, Typed Arrays, and probably more in the future. It also preserves references within the cloned data, allowing it to support cyclical and recursive structures that would cause errors for JSON.

Support in Node.js: Experimental

The v8 module in Node.js currently (as of Node 11) exposes the structured serialization API directly, but this functionality is still marked as "experimental", and subject to change or removal in future versions. If you're using a compatible version, cloning an object is as simple as:

const v8 = require('v8');

const structuredClone = obj => {
  return v8.deserialize(v8.serialize(obj));
};

Direct Support in Browsers: Maybe Eventually?

Browsers do not currently provide a direct interface for the structured cloning algorithm, but a global structuredClone() function has been discussed in whatwg/html#793 on GitHub. As currently proposed, using it for most purposes would be as simple as:

const clone = structuredClone(original);

Unless this is shipped, browsers' structured clone implementations are only exposed indirectly.

Asynchronous Workaround: Usable.

The lower-overhead way to create a structured clone with existing APIs is to post the data through one port of a MessageChannels. The other port will emit a message event with a structured clone of the attached .data. Unfortunately, listening for these events is necessarily asynchronous, and the synchronous alternatives are less practical.

class StructuredCloner {
  constructor() {
    this.pendingClones_ = new Map();
    this.nextKey_ = 0;

    const channel = new MessageChannel();
    this.inPort_ = channel.port1;
    this.outPort_ = channel.port2;

    this.outPort_.onmessage = ({data: {key, value}}) => {
      const resolve = this.pendingClones_.get(key);
      resolve(value);
      this.pendingClones_.delete(key);
    };
    this.outPort_.start();
  }

  cloneAsync(value) {
    return new Promise(resolve => {
      const key = this.nextKey_++;
      this.pendingClones_.set(key, resolve);
      this.inPort_.postMessage({key, value});
    });
  }
}

const structuredCloneAsync = window.structuredCloneAsync =
    StructuredCloner.prototype.cloneAsync.bind(new StructuredCloner);

Example Use:

const main = async () => {
  const original = { date: new Date(), number: Math.random() };
  original.self = original;

  const clone = await structuredCloneAsync(original);

  // They're different objects:
  console.assert(original !== clone);
  console.assert(original.date !== clone.date);

  // They're cyclical:
  console.assert(original.self === original);
  console.assert(clone.self === clone);

  // They contain equivalent values:
  console.assert(original.number === clone.number);
  console.assert(Number(original.date) === Number(clone.date));

  console.log("Assertions complete.");
};

main();

Synchronous Workarounds: Awful!

There are no good options for creating structured clones synchronously. Here are a couple of impractical hacks instead.

history.pushState() and history.replaceState() both create a structured clone of their first argument, and assign that value to history.state. You can use this to create a structured clone of any object like this:

const structuredClone = obj => {
  const oldState = history.state;
  history.replaceState(obj, null);
  const clonedObj = history.state;
  history.replaceState(oldState, null);
  return clonedObj;
};

Example Use:

_x000D_
_x000D_
'use strict';_x000D_
_x000D_
const main = () => {_x000D_
  const original = { date: new Date(), number: Math.random() };_x000D_
  original.self = original;_x000D_
_x000D_
  const clone = structuredClone(original);_x000D_
  _x000D_
  // They're different objects:_x000D_
  console.assert(original !== clone);_x000D_
  console.assert(original.date !== clone.date);_x000D_
_x000D_
  // They're cyclical:_x000D_
  console.assert(original.self === original);_x000D_
  console.assert(clone.self === clone);_x000D_
_x000D_
  // They contain equivalent values:_x000D_
  console.assert(original.number === clone.number);_x000D_
  console.assert(Number(original.date) === Number(clone.date));_x000D_
  _x000D_
  console.log("Assertions complete.");_x000D_
};_x000D_
_x000D_
const structuredClone = obj => {_x000D_
  const oldState = history.state;_x000D_
  history.replaceState(obj, null);_x000D_
  const clonedObj = history.state;_x000D_
  history.replaceState(oldState, null);_x000D_
  return clonedObj;_x000D_
};_x000D_
_x000D_
main();
_x000D_
_x000D_
_x000D_

Though synchronous, this can be extremely slow. It incurs all of the overhead associated with manipulating the browser history. Calling this method repeatedly can cause Chrome to become temporarily unresponsive.

The Notification constructor creates a structured clone of its associated data. It also attempts to display a browser notification to the user, but this will silently fail unless you have requested notification permission. In case you have the permission for other purposes, we'll immediately close the notification we've created.

const structuredClone = obj => {
  const n = new Notification('', {data: obj, silent: true});
  n.onshow = n.close.bind(n);
  return n.data;
};

Example Use:

_x000D_
_x000D_
'use strict';_x000D_
_x000D_
const main = () => {_x000D_
  const original = { date: new Date(), number: Math.random() };_x000D_
  original.self = original;_x000D_
_x000D_
  const clone = structuredClone(original);_x000D_
  _x000D_
  // They're different objects:_x000D_
  console.assert(original !== clone);_x000D_
  console.assert(original.date !== clone.date);_x000D_
_x000D_
  // They're cyclical:_x000D_
  console.assert(original.self === original);_x000D_
  console.assert(clone.self === clone);_x000D_
_x000D_
  // They contain equivalent values:_x000D_
  console.assert(original.number === clone.number);_x000D_
  console.assert(Number(original.date) === Number(clone.date));_x000D_
  _x000D_
  console.log("Assertions complete.");_x000D_
};_x000D_
_x000D_
const structuredClone = obj => {_x000D_
  const n = new Notification('', {data: obj, silent: true});_x000D_
  n.close();_x000D_
  return n.data;_x000D_
};_x000D_
_x000D_
main();
_x000D_
_x000D_
_x000D_

integrating barcode scanner into php application?

If you have Bluetooth, Use twedge on windows and getblue app on android, they also have a few videos of it. It's made by TEC-IT. I've got it to work by setting the interface option to bluetooth server in TWedge and setting the output setting in getblue to Bluetooth client and selecting my computer from the Bluetooth devices list. Make sure your computer and phone is paired. Also to get the barcode as input set the action setting in TWedge to Keyboard Wedge. This will allow for you to first click the input text box on said form, then scan said product with your phone and wait a sec for the barcode number to be put into the text box. Using this method requires no php that doesn't already exist in your current form processing, just process the text box as usual and viola your phone scans bar codes, sends them to your pc via Bluetooth wirelessly, your computer inserts the barcode into whatever text field is selected in any application or website. Hope this helps.

Does C# have an equivalent to JavaScript's encodeURIComponent()?

HttpUtility.HtmlEncode / Decode
HttpUtility.UrlEncode / Decode

You can add a reference to the System.Web assembly if it's not available in your project

Is there a way to automatically generate getters and setters in Eclipse?

Use Project Lombok or better Kotlin for your Pojos.

(Also, to add Kotlin to your resume ;) )

This :

public class BaseVO {
    protected Long id;

    @Override
    public boolean equals(Object obj) {
        if (obj == null || id == null)
            return false;

        if (obj instanceof BaseVO)
            return ((BaseVO) obj).getId().equals(id);

        return false; 
    }

    @Override
    public int hashCode() {
        return id == null ? null : id.hashCode();
    }
    // getter setter here
}

public class Subclass extends BaseVO {
    protected String name;
    protected String category;
    // getter setter here
}

would become this :

open class BaseVO(var id: Long? = null) {

    override fun hashCode(): Int {
        if (id != null)
            return id.hashCode()

        return super.hashCode()
    }

    override fun equals(other: Any?): Boolean {
        if (id == null || other == null || other !is BaseVO)
            return false

        return id.hashCode() == other.id?.hashCode()
    }
}

@Suppress("unused")
class Subclass(
        var name: String? = null,
        var category: String? = null
) : BaseVO()

Or use Kotlin's "data" classes. You end up writing even fewer lines of code.

What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?

    protected String toCamelCase(CaseFormat caseFormat, String... words){
        if (words.length  == 0){
          throw new IllegalArgumentException("Word list is empty!");
        }

        String firstWord = words[0];
        String [] restOfWords = Arrays.copyOfRange(words, 1, words.length);

        StringBuffer buffer = new StringBuffer();
        buffer.append(firstWord);
        Arrays.asList(restOfWords).stream().forEach(w->buffer.append("_"+ w.toUpperCase()));

        return CaseFormat.UPPER_UNDERSCORE.to(caseFormat, buffer.toString());

    }

How to create Temp table with SELECT * INTO tempTable FROM CTE Query

The SELECT ... INTO needs to be in the select from the CTE.

;WITH Calendar
     AS (SELECT /*... Rest of CTE definition removed for clarity*/)
SELECT EventID,
       EventStartDate,
       EventEndDate,
       PlannedDate                   AS [EventDates],
       Cast(PlannedDate AS DATETIME) AS DT,
       Cast(EventStartTime AS TIME)  AS ST,
       Cast(EventEndTime AS TIME)    AS ET,
       EventTitle,
       EventType
INTO TEMPBLOCKEDDATES /* <---- INTO goes here*/        
FROM   Calendar
WHERE  ( PlannedDate >= Getdate() )
       AND ',' + EventEnumDays + ',' LIKE '%,' + Cast(Datepart(dw, PlannedDate) AS CHAR(1)) + ',%'
        OR EventEnumDays IS NULL
ORDER  BY EventID,
          PlannedDate
OPTION (maxrecursion 0) 

Adding line break in C# Code behind page

If I am understanding this correctly, you should be able to break the string into substrings to accomplish this.

i.e.:

string s = "this is a really long string" +
"and this is the rest of it";

List of all users that can connect via SSH

Any user with a valid shell in /etc/passwd can potentially login. If you want to improve security, set up SSH with public-key authentication (there is lots of info on the web on doing this), install a public key in one user's ~/.ssh/authorized_keys file, and disable password-based authentication. This will prevent anybody except that one user from logging in, and will require that the user have in their possession the matching private key. Make sure the private key has a decent passphrase.

To prevent bots from trying to get in, run SSH on a port other than 22 (i.e. 3456). This doesn't improve security but prevents script-kiddies and bots from cluttering up your logs with failed attempts.

Recommended way to get hostname in Java

As others have noted, getting the hostname based on DNS resolution is unreliable.

Since this question is unfortunately still relevant in 2018, I'd like to share with you my network-independent solution, with some test runs on different systems.

The following code tries to do the following:

  • On Windows

    1. Read the COMPUTERNAME environment variable through System.getenv().

    2. Execute hostname.exe and read the response

  • On Linux

    1. Read the HOSTNAME environment variable through System.getenv()

    2. Execute hostname and read the response

    3. Read /etc/hostname (to do this I'm executing cat since the snippet already contains code to execute and read. Simply reading the file would be better, though).

The code:

public static void main(String[] args) throws IOException {
    String os = System.getProperty("os.name").toLowerCase();

    if (os.contains("win")) {
        System.out.println("Windows computer name through env:\"" + System.getenv("COMPUTERNAME") + "\"");
        System.out.println("Windows computer name through exec:\"" + execReadToString("hostname") + "\"");
    } else if (os.contains("nix") || os.contains("nux") || os.contains("mac os x")) {
        System.out.println("Unix-like computer name through env:\"" + System.getenv("HOSTNAME") + "\"");
        System.out.println("Unix-like computer name through exec:\"" + execReadToString("hostname") + "\"");
        System.out.println("Unix-like computer name through /etc/hostname:\"" + execReadToString("cat /etc/hostname") + "\"");
    }
}

public static String execReadToString(String execCommand) throws IOException {
    try (Scanner s = new Scanner(Runtime.getRuntime().exec(execCommand).getInputStream()).useDelimiter("\\A")) {
        return s.hasNext() ? s.next() : "";
    }
}

Results for different operating systems:

macOS 10.13.2

Unix-like computer name through env:"null"
Unix-like computer name through exec:"machinename
"
Unix-like computer name through /etc/hostname:""

OpenSuse 13.1

Unix-like computer name through env:"machinename"
Unix-like computer name through exec:"machinename
"
Unix-like computer name through /etc/hostname:""

Ubuntu 14.04 LTS This one is kinda strange since echo $HOSTNAME returns the correct hostname, but System.getenv("HOSTNAME") does not:

Unix-like computer name through env:"null"
Unix-like computer name through exec:"machinename
"
Unix-like computer name through /etc/hostname:"machinename
"

EDIT: According to legolas108, System.getenv("HOSTNAME") works on Ubuntu 14.04 if you run export HOSTNAME before executing the Java code.

Windows 7

Windows computer name through env:"MACHINENAME"
Windows computer name through exec:"machinename
"

Windows 10

Windows computer name through env:"MACHINENAME"
Windows computer name through exec:"machinename
"

The machine names have been replaced but I kept the capitalization and structure. Note the extra newline when executing hostname, you might have to take it into account in some cases.

get string value from HashMap depending on key name

You can use the get(Object key) method from the HashMap. Be aware that i many cases your Key Class should override the equals method, to be a useful class for a Map key.

What use is find_package() if you need to specify CMAKE_MODULE_PATH anyway?

If you are running cmake to generate SomeLib yourself (say as part of a superbuild), consider using the User Package Registry. This requires no hard-coded paths and is cross-platform. On Windows (including mingw64) it works via the registry. If you examine how the list of installation prefixes is constructed by the CONFIG mode of the find_packages() command, you'll see that the User Package Registry is one of elements.

Brief how-to

Associate the targets of SomeLib that you need outside of that external project by adding them to an export set in the CMakeLists.txt files where they are created:

add_library(thingInSomeLib ...)
install(TARGETS thingInSomeLib Export SomeLib-export DESTINATION lib)

Create a XXXConfig.cmake file for SomeLib in its ${CMAKE_CURRENT_BUILD_DIR} and store this location in the User Package Registry by adding two calls to export() to the CMakeLists.txt associated with SomeLib:

export(EXPORT SomeLib-export NAMESPACE SomeLib:: FILE SomeLibConfig.cmake) # Create SomeLibConfig.cmake
export(PACKAGE SomeLib)                                                    # Store location of SomeLibConfig.cmake

Issue your find_package(SomeLib REQUIRED) commmand in the CMakeLists.txt file of the project that depends on SomeLib without the "non-cross-platform hard coded paths" tinkering with the CMAKE_MODULE_PATH.

When it might be the right approach

This approach is probably best suited for situations where you'll never use your software downstream of the build directory (e.g., you're cross-compiling and never install anything on your machine, or you're building the software just to run tests in the build directory), since it creates a link to a .cmake file in your "build" output, which may be temporary.

But if you're never actually installing SomeLib in your workflow, calling EXPORT(PACKAGE <name>) allows you to avoid the hard-coded path. And, of course, if you are installing SomeLib, you probably know your platform, CMAKE_MODULE_PATH, etc, so @user2288008's excellent answer will have you covered.

How to submit a form on enter when the textarea has focus?

Why do you want a textarea to submit when you hit enter?

A "text" input will submit by default when you press enter. It is a single line input.

<input type="text" value="...">

A "textarea" will not, as it benefits from multi-line capabilities. Submitting on enter takes away some of this benefit.

<textarea name="area"></textarea>

You can add JavaScript code to detect the enter keypress and auto-submit, but you may be better off using a text input.

Get the last three chars from any string - Java

Here is a method I use to get the last xx of a string:

public static String takeLast(String value, int count) {
    if (value == null || value.trim().length() == 0 || count < 1) {
        return "";
    }

    if (value.length() > count) {
        return value.substring(value.length() - count);
    } else {
        return value;
    }
}

Then use it like so:

String testStr = "this is a test string";
String last1 = takeLast(testStr, 1); //Output: g
String last4 = takeLast(testStr, 4); //Output: ring

Is there a way to create key-value pairs in Bash script?

For persistent key/value storage, you can use kv-bash, a pure bash implementation of key/value database available at https://github.com/damphat/kv-bash

Usage

git clone https://github.com/damphat/kv-bash
source kv-bash/kv-bash

Try create some permanent variables

kvset myName  xyz
kvset myEmail [email protected]

#read the varible
kvget myEmail

#you can also use in another script with $(kvget keyname)
echo $(kvget myEmail)

The page cannot be displayed because an internal server error has occurred on server

it seems it works after I commented this line in web.config

<compilation debug="true" targetFramework="4.5.2" />

how to kill hadoop jobs

An unhandled exception will (assuming it's repeatable like bad data as opposed to read errors from a particular data node) eventually fail the job anyway.

You can configure the maximum number of times a particular map or reduce task can fail before the entire job fails through the following properties:

  • mapred.map.max.attempts - The maximum number of attempts per map task. In other words, framework will try to execute a map task these many number of times before giving up on it.
  • mapred.reduce.max.attempts - Same as above, but for reduce tasks

If you want to fail the job out at the first failure, set this value from its default of 4 to 1.

Java ByteBuffer to String

Convert a String to ByteBuffer, then from ByteBuffer back to String using Java:

import java.nio.charset.Charset;
import java.nio.*;

String babel = "obufscate thdé alphebat and yolo!!";
System.out.println(babel);
//Convert string to ByteBuffer:
ByteBuffer babb = Charset.forName("UTF-8").encode(babel);
try{
    //Convert ByteBuffer to String
    System.out.println(new String(babb.array(), "UTF-8"));
}
catch(Exception e){
    e.printStackTrace();
}

Which prints the printed bare string first, and then the ByteBuffer casted to array():

obufscate thdé alphebat and yolo!!
obufscate thdé alphebat and yolo!!

Also this was helpful for me, reducing the string to primitive bytes can help inspect what's going on:

String text = "?????";
//convert utf8 text to a byte array
byte[] array = text.getBytes("UTF-8");
//convert the byte array back to a string as UTF-8
String s = new String(array, Charset.forName("UTF-8"));
System.out.println(s);
//forcing strings encoded as UTF-8 as an incorrect encoding like
//say ISO-8859-1 causes strange and undefined behavior
String sISO = new String(array, Charset.forName("ISO-8859-1"));
System.out.println(sISO);

Prints your string interpreted as UTF-8, and then again as ISO-8859-1:

?????
ããã«ã¡ã¯

Disable activity slide-in animation when launching new activity?

The FLAG_ACTIVITY_NO_ANIMATION flag works fine for disabling the animation when starting activities.

To disable the similar animation that is triggered when calling finish() on an Activity, i.e the animation slides from right to left instead, you can call overridePendingTransition(0, 0) after calling finish() and the next animation will be excluded.

This also works on the in-animation if you call overridePendingTransition(0, 0) after calling startActivity(...).

Is it possible to change the speed of HTML's <marquee> tag?

we can control the scrolling speed by using the scrollamount attribute,

Example:

<marquee scrollamount="30">scrolling fast</marquee>
<marquee scrollamount="2">scrolling slow</marquee>

note:if you specify the minimum number, the scrolling speed will be reduce vice versa

How to return PDF to browser in MVC?

You would normally do a Response.Flush followed by a Response.Close, but for some reason the iTextSharp library doesn't seem to like this. The data doesn't make it through and Adobe thinks the PDF is corrupt. Leave out the Response.Close function and see if your results are better:

Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-disposition", "attachment; filename=file.pdf"); // open in a new window
Response.OutputStream.Write(outStream.GetBuffer(), 0, outStream.GetBuffer().Length);
Response.Flush();

// For some reason, if we close the Response stream, the PDF doesn't make it through
//Response.Close();

Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.dev.khamsat"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "2.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }

Remove non-utf8 characters from string

I have made a function that deletes invalid UTF-8 characters from a string. I'm using it to clear description of 27000 products before it generates the XML export file.

public function stripInvalidXml($value) {
    $ret = "";
    $current;
    if (empty($value)) {
        return $ret;
    }
    $length = strlen($value);
    for ($i=0; $i < $length; $i++) {
        $current = ord($value{$i});
        if (($current == 0x9) || ($current == 0xA) || ($current == 0xD) || (($current >= 0x20) && ($current <= 0xD7FF)) || (($current >= 0xE000) && ($current <= 0xFFFD)) || (($current >= 0x10000) && ($current <= 0x10FFFF))) {
                $ret .= chr($current);
        }
        else {
            $ret .= "";
        }
    }
    return $ret;
}

file_put_contents: Failed to open stream, no such file or directory

I was also stuck on the same kind of problem and I followed the simple steps below.

Just get the exact url of the file to which you want to copy, for example:

http://www.test.com/test.txt (file to copy)

Then pass the exact absolute folder path with filename where you do want to write that file.

  1. If you are on a Windows machine then d:/xampp/htdocs/upload/test.txt

  2. If you are on a Linux machine then /var/www/html/upload/test.txt

You can get the document root with the PHP function $_SERVER['DOCUMENT_ROOT'].

How to undo last commit

Warning: Don't do this if you've already pushed

You want to do:

git reset HEAD~

If you don't want the changes and blow everything away:

git reset --hard HEAD~

Center image horizontally within a div

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">


      <style>
      body{
  /*-------------------important for fluid images---\/--*/
  overflow-x: hidden; /* some browsers shows it for mysterious reasons to me*/
  overflow-y: scroll;
  margin-left:0px;
  margin-top:0px;
  /*-------------------important for fluid images---/\--*/
      }
      .thirddiv{
      float:left;
      width:100vw;
      height:100vh;
      margin:0px;
      background:olive;
      }
      .thirdclassclassone{
      float:left;   /*important*/
      background:grey;
      width:80vw;
      height:80vh; /*match with img height bellow*/
      margin-left:10vw; /* 100vw minus "width"/2    */
      margin-right:10vw; /* 100vw minus "width"/2   */
      margin-top:10vh;
      }
      .thirdclassclassone img{
      position:relative; /*important*/
     display: block;  /*important*/
    margin-left: auto;  /*very important*/
    margin-right: auto;  /*very important*/
    height:80vh; /*match with parent div above*/

    /*--------------------------------
    margin-top:5vh;
    margin-bottom:5vh;
    ---------------------------------*/
    /*---------------------set margins to match total  height of parent di----------------------------------------*/
      }
    </style>           
</head>  
<body>
    <div class="thirddiv">
       <div class="thirdclassclassone">
       <img src="ireland.png">
    </div>      
</body>
</html>

make an html svg object also a clickable link

i tried this clean easy method and seems to work in all browsers. Inside the svg file:

_x000D_
_x000D_
<svg>_x000D_
<a id="anchor" xlink:href="http://www.google.com" target="_top">_x000D_
  _x000D_
<!--your graphic-->_x000D_
  _x000D_
</a>_x000D_
</svg>_x000D_
  
_x000D_
_x000D_
_x000D_

How to construct a set out of list items in python?

Simply put the line:

new_list = set(your_list)

else & elif statements not working in Python

 if guess == number:
     print ("Good")
 elif guess == 2:
     print ("Bad")
 else:
     print ("Also bad")

Make sure you have your identation right. The syntax is ok.

CMake unable to determine linker language with C++

In my case, implementing a member function of a class in a header file cause this error. Separating interface (in x.h file) and implementation (in x.cpp file) solves the problem.

VBScript How can I Format Date?

The output of FormatDateTime depends on configuration in Regional Settings in Control Panel. So in other countries FormatDateTime(d, 2) may for example return yyyy-MM-dd.

If you want your output to be "culture invariant", use myDateFormat() from stian.net's solution. If you just don't like slashes in dates and you don't care about date format in other countries, you can just use

Replace(FormatDateTime(d,2),"/","-")

Print debugging info from stored procedure in MySQL

This is the way how I will debug:

CREATE PROCEDURE procedure_name() 
BEGIN
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
        SHOW ERRORS;  --this is the only one which you need
        ROLLBACK;   
    END; 
    START TRANSACTION;
        --query 1
        --query 2
        --query 3
    COMMIT;
END 

If query 1, 2 or 3 will throw an error, HANDLER will catch the SQLEXCEPTION and SHOW ERRORS will show errors for us. Note: SHOW ERRORS should be the first statement in the HANDLER.

File Upload with Angular Material

I've join some informations posted here and the possibility of personalize components with Angular Material and this is my contribution without external libs and feedback with the name of the chosen file into field:

enter image description here

enter image description here

HTML

<mat-form-field class="columns">
    <mat-label *ngIf="selectedFiles; else newFile">{{selectedFiles.item(0).name}}</mat-label>
    <ng-template #newFile>
        <mat-label>Choose file</mat-label>
    </ng-template>
    <input matInput disabled>
    <button mat-icon-button matSuffix (click)="fileInput.click()">
        <mat-icon>attach_file</mat-icon>
    </button>
    <input hidden (change)="selectFile($event)" #fileInput type="file" id="file">
</mat-form-field>

TS

selectFile(event) {
    this.selectedFiles = event.target.files;
}

How to convert a Hibernate proxy to a real entity object

I've written following code which cleans object from proxies (if they are not already initialized)

public class PersistenceUtils {

    private static void cleanFromProxies(Object value, List<Object> handledObjects) {
        if ((value != null) && (!isProxy(value)) && !containsTotallyEqual(handledObjects, value)) {
            handledObjects.add(value);
            if (value instanceof Iterable) {
                for (Object item : (Iterable<?>) value) {
                    cleanFromProxies(item, handledObjects);
                }
            } else if (value.getClass().isArray()) {
                for (Object item : (Object[]) value) {
                    cleanFromProxies(item, handledObjects);
                }
            }
            BeanInfo beanInfo = null;
            try {
                beanInfo = Introspector.getBeanInfo(value.getClass());
            } catch (IntrospectionException e) {
                // LOGGER.warn(e.getMessage(), e);
            }
            if (beanInfo != null) {
                for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
                    try {
                        if ((property.getWriteMethod() != null) && (property.getReadMethod() != null)) {
                            Object fieldValue = property.getReadMethod().invoke(value);
                            if (isProxy(fieldValue)) {
                                fieldValue = unproxyObject(fieldValue);
                                property.getWriteMethod().invoke(value, fieldValue);
                            }
                            cleanFromProxies(fieldValue, handledObjects);
                        }
                    } catch (Exception e) {
                        // LOGGER.warn(e.getMessage(), e);
                    }
                }
            }
        }
    }

    public static <T> T cleanFromProxies(T value) {
        T result = unproxyObject(value);
        cleanFromProxies(result, new ArrayList<Object>());
        return result;
    }

    private static boolean containsTotallyEqual(Collection<?> collection, Object value) {
        if (CollectionUtils.isEmpty(collection)) {
            return false;
        }
        for (Object object : collection) {
            if (object == value) {
                return true;
            }
        }
        return false;
    }

    public static boolean isProxy(Object value) {
        if (value == null) {
            return false;
        }
        if ((value instanceof HibernateProxy) || (value instanceof PersistentCollection)) {
            return true;
        }
        return false;
    }

    private static Object unproxyHibernateProxy(HibernateProxy hibernateProxy) {
        Object result = hibernateProxy.writeReplace();
        if (!(result instanceof SerializableProxy)) {
            return result;
        }
        return null;
    }

    @SuppressWarnings("unchecked")
    private static <T> T unproxyObject(T object) {
        if (isProxy(object)) {
            if (object instanceof PersistentCollection) {
                PersistentCollection persistentCollection = (PersistentCollection) object;
                return (T) unproxyPersistentCollection(persistentCollection);
            } else if (object instanceof HibernateProxy) {
                HibernateProxy hibernateProxy = (HibernateProxy) object;
                return (T) unproxyHibernateProxy(hibernateProxy);
            } else {
                return null;
            }
        }
        return object;
    }

    private static Object unproxyPersistentCollection(PersistentCollection persistentCollection) {
        if (persistentCollection instanceof PersistentSet) {
            return unproxyPersistentSet((Map<?, ?>) persistentCollection.getStoredSnapshot());
        }
        return persistentCollection.getStoredSnapshot();
    }

    private static <T> Set<T> unproxyPersistentSet(Map<T, ?> persistenceSet) {
        return new LinkedHashSet<T>(persistenceSet.keySet());
    }

}

I use this function over result of my RPC services (via aspects) and it cleans recursively all result objects from proxies (if they are not initialized).

Real time face detection OpenCV, Python

Your line:

img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.

Try

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

Set iframe content height to auto resize dynamically

In the iframe: So that means you have to add some code in the iframe page. Simply add this script to your code IN THE IFRAME:

<body onload="parent.alertsize(document.body.scrollHeight);">

In the holding page: In the page holding the iframe (in my case with ID="myiframe") add a small javascript:

<script>
function alertsize(pixels){
    pixels+=32;
    document.getElementById('myiframe').style.height=pixels+"px";
}
</script>

What happens now is that when the iframe is loaded it triggers a javascript in the parent window, which in this case is the page holding the iframe.

To that JavaScript function it sends how many pixels its (iframe) height is.

The parent window takes the number, adds 32 to it to avoid scrollbars, and sets the iframe height to the new number.

That's it, nothing else is needed.


But if you like to know some more small tricks keep on reading...

DYNAMIC HEIGHT IN THE IFRAME? If you like me like to toggle content the iframe height will change (without the page reloading and triggering the onload). I usually add a very simple toggle script I found online:

<script>
function toggle(obj) {
    var el = document.getElementById(obj);
    if ( el.style.display != 'block' ) el.style.display = 'block';
    else el.style.display = 'none';
}
</script>

to that script just add:

<script>
function toggle(obj) {
    var el = document.getElementById(obj);
    if ( el.style.display != 'block' ) el.style.display = 'block';
    else el.style.display = 'none';
    parent.alertsize(document.body.scrollHeight); // ADD THIS LINE!
}
</script>

How you use the above script is easy:

<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>

For those that like to just cut and paste and go from there here is the two pages. In my case I had them in the same folder, but it should work cross domain too (I think...)

Complete holding page code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>THE IFRAME HOLDER</title>
<script>
function alertsize(pixels){
    pixels+=32;
    document.getElementById('myiframe').style.height=pixels+"px";
}
</script>
</head>

<body style="background:silver;">
<iframe src='theiframe.htm' style='width:458px;background:white;' frameborder='0' id="myiframe" scrolling="auto"></iframe>
</body>
</html>

Complete iframe code: (this iframe named "theiframe.htm")

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>IFRAME CONTENT</title>
<script>
function toggle(obj) {
    var el = document.getElementById(obj);
    if ( el.style.display != 'block' ) el.style.display = 'block';
    else el.style.display = 'none';
    parent.alertsize(document.body.scrollHeight);
}
</script>
</head>

<body onload="parent.alertsize(document.body.scrollHeight);">
<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
THE END

</body>
</html>

Demo

text-overflow: ellipsis not working

word-wrap: break-word;

this and only this did the job for me for a

<pre> </pre> 

tag

everthing else failed to do the ellipsis....