Programs & Examples On #Jhat

jHat refers to Java Heap Analysis Tool.

How to find a Java Memory Leak

As most of us use Eclipse already for writing code, Why not use the Memory Analyser Tool(MAT) in Eclipse. It works great.

The Eclipse MAT is a set of plug-ins for the Eclipse IDE which provides tools to analyze heap dumps from Java application and to identify memory problems in the application.

This helps the developer to find memory leaks with the following features

  1. Acquiring a memory snapshot (Heap Dump)
  2. Histogram
  3. Retained Heap
  4. Dominator Tree
  5. Exploring Paths to the GC Roots
  6. Inspector
  7. Common Memory Anti-Patterns
  8. Object Query Language

enter image description here

Installed Java 7 on Mac OS X but Terminal is still using version 6

I had run into a similar issue with terminal not updating the java version to match the version installed on the mac.

There was no issue with the JAVA_HOME environmental variable being set

I have come up with a temporary and somewhat painful but working solution.

In you .bash_profile add the line:

export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_11.jdk/Contents/Home"

(This is the path on my machine but may be different on yours, make sure to get yours. The paths should match up to /Library/Java/JavaVirtualMachines/)

the run source ~/.bash_profile

As I mentioned this is a temporary band-aid solution because the java home path is being hard-coded. There is really no way to set the path to get the latest as that is what Apple is supposedly doing for terminal already and the issue is that Apple's java_home environment variable is not getting updated.

XML Parser for C

My personal preference is libxml2. It's very easy to use but I never bothered to benchmark it, as I've only used it for configuration file parsing.

X close button only using css

As a pure CSS solution for the close or 'times' symbol you can use the ISO code with the content property. I often use this for :after or :before pseudo selectors.

The content code is \00d7.

Example

div:after{
  display: inline-block;
  content: "\00d7"; /* This will render the 'X' */
}

You can then style and position the pseudo selector in any way you want. Hope this helps someone :).

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

str.split() without any arguments splits on runs of whitespace characters:

>>> s = 'I am having a very nice day.'
>>> 
>>> len(s.split())
7

From the linked documentation:

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

Detect encoding and make everything UTF-8

A really nice way to implement an isUTF8-function can be found on php.net:

function isUTF8($string) {
    return (utf8_encode(utf8_decode($string)) == $string);
}

What's the difference between Perl's backticks, system, and exec?

Let me quote the manuals first:

perldoc exec():

The exec function executes a system command and never returns-- use system instead of exec if you want it to return

perldoc system():

Does exactly the same thing as exec LIST , except that a fork is done first, and the parent process waits for the child process to complete.

In contrast to exec and system, backticks don't give you the return value but the collected STDOUT.

perldoc `String`:

A string which is (possibly) interpolated and then executed as a system command with /bin/sh or its equivalent. Shell wildcards, pipes, and redirections will be honored. The collected standard output of the command is returned; standard error is unaffected.


Alternatives:

In more complex scenarios, where you want to fetch STDOUT, STDERR or the return code, you can use well known standard modules like IPC::Open2 and IPC::Open3.

Example:

use IPC::Open2;
my $pid = open2(\*CHLD_OUT, \*CHLD_IN, 'some', 'cmd', 'and', 'args');
waitpid( $pid, 0 );
my $child_exit_status = $? >> 8;

Finally, IPC::Run from the CPAN is also worth looking at…

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

Java logical operator short-circuiting

Java provides two interesting Boolean operators not found in most other computer languages. These secondary versions of AND and OR are known as short-circuit logical operators. As you can see from the preceding table, the OR operator results in true when A is true, no matter what B is.

Similarly, the AND operator results in false when A is false, no matter what B is. If you use the || and && forms, rather than the | and & forms of these operators, Java will not bother to evaluate the right-hand operand alone. This is very useful when the right-hand operand depends on the left one being true or false in order to function properly.

For example, the following code fragment shows how you can take advantage of short-circuit logical evaluation to be sure that a division operation will be valid before evaluating it:

if ( denom != 0 && num / denom >10)

Since the short-circuit form of AND (&&) is used, there is no risk of causing a run-time exception from dividing by zero. If this line of code were written using the single & version of AND, both sides would have to be evaluated, causing a run-time exception when denom is zero.

It is standard practice to use the short-circuit forms of AND and OR in cases involving Boolean logic, leaving the single-character versions exclusively for bitwise operations. However, there are exceptions to this rule. For example, consider the following statement:

 if ( c==1 & e++ < 100 ) d = 100;

Here, using a single & ensures that the increment operation will be applied to e whether c is equal to 1 or not.

Find an element in DOM based on an attribute value

Use query selectors, examples:

document.querySelectorAll(' input[name], [id|=view], [class~=button] ')

input[name] Inputs elements with name property.

[id|=view] Elements with id that start with view-.

[class~=button] Elements with the button class.

How do I break a string across more than one line of code in JavaScript?

Break up the string into two pieces 

alert ("Please select file " +
       "to delete");

How do I add a project as a dependency of another project?

Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so

<project>
   ...
   <dependencies>
      <dependency>
         <groupId>yourgroup</groupId>
         <artifactId>myejbproject</artifactId>
         <version>2.0</version>
         <scope>system</scope>
         <systemPath>path/to/myejbproject.jar</systemPath>
      </dependency>
   </dependencies>
   ...
</project>

That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.


If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:

parent
|- pom.xml
|- MyEJBProject
|   `- pom.xml
`- MyWarProject
    `- pom.xml

The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)

<project>
   ...
   <artifactId>myparentproject</artifactId>
   <groupId>...</groupId>
   <version>...</version>

   <packaging>pom</packaging>
   ...
   <modules>
     <module>MyEJBModule</module>
     <module>MyWarModule</module>
   </modules>
   ...
</project>

That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects


Finally, if your projects are not in related directories, you might try to give them as relative modules:

filesystem
 |- mywarproject
 |   `pom.xml
 |- myejbproject
 |   `pom.xml
 `- parent
     `pom.xml

now you could just do this (worked in maven 2, just tried it):

<!--parent-->
<project>
  <modules>
    <module>../mywarproject</module>
    <module>../myejbproject</module>
  </modules>
</project>

How can I access "static" class variables within class methods in Python?

class Foo(object):    
    bar = 1

    def bah(object_reference):
        object_reference.var = Foo.bar
        return object_reference.var


f = Foo() 
print 'var=', f.bah()

What is it exactly a BLOB in a DBMS context

This may seem like a silly question, but what do you actually want to use a RDBMS for ?

If you just want to store files, then the operating system's filesystem is generally adequate. An RDBMS is generally used for structured data and (except for embedded ones like SQLite) handling concurrent manipulation of that data (locking etc). Other useful features are security (handling access to the data) and backup/recovery. In the latter, the primary advantage over a regular filesystem backup is being able to recover to a point in time between backups by applying some form of log files.

BLOBs are, as far as the database concerned, unstructured and opaque. Oracle does have some specific ORDSYS types for multi-media objects (eg images) that also have a bunch of metadata attached, and have associated methods (eg rescaling or recolouring an image).

SyntaxError: missing ; before statement

Looks like you have an extra parenthesis.

The following portion is parsed as an assignment so the interpreter/compiler will look for a semi-colon or attempt to insert one if certain conditions are met.

foob_name = $this.attr('name').replace(/\[(\d+)\]/, function($0, $1) {
   return '[' + (+$1 + 1) + ']';
})

javascript getting my textbox to display a variable

Even if this is already answered (1 year ago) you could also let the fields be calculated automatically.

The HTML

    <tr>
        <td><input type="text" value="" ></td>
        <td><input type="text" class="class_name" placeholder="bla bla"/></td>
    </tr>
    <tr>
        <td><input type="text" value="" ></td>
        <td><input type="text" class="class_name" placeholder="bla bla."/></td>
    </tr>

The script

$(document).ready(function(){
                $(".class_name").each(function(){
                    $(this).keyup(function(){
                        calculateSum()
                        ;})
                    ;})
                ;}
                );
            function calculateSum(){
                var sum=0;
                $(".class_name").each(function(){
                    if(!isNaN(this.value) && this.value.length!=0){
                        sum+=parseFloat(this.value);
                    }
                    else if(isNaN(this.value)) {
                        alert("Maybe an alert if they type , instead of .");
                    }
                }
                );
                $("#sum").html(sum.toFixed(2));
                } 

Remove characters from NSString?

Taken from NSString

stringByReplacingOccurrencesOfString:withString:

Returns a new string in which all occurrences of a target string in the receiver are replaced by another given string.

- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement

Parameters

target

The string to replace.

replacement

The string with which to replace target.

Return Value

A new string in which all occurrences of target in the receiver are replaced by replacement.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Error

NullPointerExceptions are among the easier exceptions to diagnose, frequently. Whenever you get an exception in Java and you see the stack trace ( that's what your second quote-block is called, by the way ), you read from top to bottom. Often, you will see exceptions that start in Java library code or in native implementations methods, for diagnosis you can just skip past those until you see a code file that you wrote.

Then you like at the line indicated and look at each of the objects ( instantiated classes ) on that line -- one of them was not created and you tried to use it. You can start by looking up in your code to see if you called the constructor on that object. If you didn't, then that's your problem, you need to instantiate that object by calling new Classname( arguments ). Another frequent cause of NullPointerExceptions is accidentally declaring an object with local scope when there is an instance variable with the same name.

In your case, the exception occurred in your constructor for Workshop on line 75. <init> means the constructor for a class. If you look on that line in your code, you'll see the line

denimjeansButton.addItemListener(this);

There are fairly clearly two objects on this line: denimjeansButton and this. this is synonymous with the class instance you are currently in and you're in the constructor, so it can't be this. denimjeansButton is your culprit. You never instantiated that object. Either remove the reference to the instance variable denimjeansButton or instantiate it.

fatal: bad default revision 'HEAD'

Make sure branch "master" exists! It's not just a name apparently.

I got this error after creating a blank bare repo, pushing a branch named "dev" to it, and trying to use git log in the bare repo. Interestingly, git branch knows that dev is the only branch existing (so I think this is a git bug).

Solution: I repeated the procedure, this time having renamed "dev" to "master" on the working repo before pushing to the bare repo. Success!

Difference between declaring variables before or in loop?

I tested for JS with Node 4.0.0 if anyone is interested. Declaring outside the loop resulted in a ~.5 ms performance improvement on average over 1000 trials with 100 million loop iterations per trial. So I'm gonna say go ahead and write it in the most readable / maintainable way which is B, imo. I would put my code in a fiddle, but I used the performance-now Node module. Here's the code:

var now = require("../node_modules/performance-now")

// declare vars inside loop
function varInside(){
    for(var i = 0; i < 100000000; i++){
        var temp = i;
        var temp2 = i + 1;
        var temp3 = i + 2;
    }
}

// declare vars outside loop
function varOutside(){
    var temp;
    var temp2;
    var temp3;
    for(var i = 0; i < 100000000; i++){
        temp = i
        temp2 = i + 1
        temp3 = i + 2
    }
}

// for computing average execution times
var insideAvg = 0;
var outsideAvg = 0;

// run varInside a million times and average execution times
for(var i = 0; i < 1000; i++){
    var start = now()
    varInside()
    var end = now()
    insideAvg = (insideAvg + (end-start)) / 2
}

// run varOutside a million times and average execution times
for(var i = 0; i < 1000; i++){
    var start = now()
    varOutside()
    var end = now()
    outsideAvg = (outsideAvg + (end-start)) / 2
}

console.log('declared inside loop', insideAvg)
console.log('declared outside loop', outsideAvg)

Send FormData with other field in AngularJS

You're sending JSON-formatted data to a server which isn't expecting that format. You already provided the format that the server needs, so you'll need to format it yourself which is pretty simple.

var data = '"title='+title+'" "text='+text+'" "file='+file+'"';
$http.post(uploadUrl, data)

Create a file if it doesn't exist

Be warned, each time the file is opened with this method the old data in the file is destroyed regardless of 'w+' or just 'w'.

import os

with open("file.txt", 'w+') as f:
    f.write("file is opened for business")

How do I write the 'cd' command in a makefile?

To change dir

foo: 
    $(MAKE) -C mydir

multi:
    $(MAKE) -C / -C my-custom-dir   ## Equivalent to /my-custom-dir

Declaring and initializing a string array in VB.NET

Array initializer support for type inference were changed in Visual Basic 10 vs Visual Basic 9.

In previous version of VB it was required to put empty parens to signify an array. Also, it would define the array as object array unless otherwise was stated:

' Integer array
Dim i as Integer() = {1, 2, 3, 4} 

' Object array
Dim o() = {1, 2, 3} 

Check more info:

Visual Basic 2010 Breaking Changes

Collection and Array Initializers in Visual Basic 2010

Truncate Decimal number not Round Off

What format are you wanting the output?

If you're happy with a string then consider the following C# code:

double num = 3.12345;
num.ToString("G3");

The result will be "3.12".

This link might be of use if you're using .NET. http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx

I hope that helps....but unless you identify than language you are using and the format in which you want the output it is difficult to suggest an appropriate solution.

Convert a binary NodeJS Buffer to JavaScript ArrayBuffer

Now there is a very useful npm package for this: buffer https://github.com/feross/buffer

It tries to provide an API that is 100% identical to node's Buffer API and allow:

and few more.

Where do I put a single filter that filters methods in two controllers in Rails

Two ways.

i. You can put it in ApplicationController and add the filters in the controller

    class ApplicationController < ActionController::Base       def filter_method       end     end      class FirstController < ApplicationController       before_filter :filter_method     end      class SecondController < ApplicationController       before_filter :filter_method     end 

But the problem here is that this method will be added to all the controllers since all of them extend from application controller

ii. Create a parent controller and define it there

 class ParentController < ApplicationController   def filter_method   end  end  class FirstController < ParentController   before_filter :filter_method end  class SecondController < ParentController   before_filter :filter_method end 

I have named it as parent controller but you can come up with a name that fits your situation properly.

You can also define the filter method in a module and include it in the controllers where you need the filter

Enable SQL Server Broker taking too long

Enabling SQL Server Service Broker requires a database lock. Stop the SQL Server Agent and then execute the following:

USE master ;
GO

ALTER DATABASE [MyDatabase] SET ENABLE_BROKER ;
GO

Change [MyDatabase] with the name of your database in question and then start SQL Server Agent.

If you want to see all the databases that have Service Broker enabled or disabled, then query sys.databases, for instance:

SELECT
    name, database_id, is_broker_enabled
FROM sys.databases

Remove all child elements of a DOM node in JavaScript

with jQuery :

$("#foo").find("*").remove();

How to search for a string in cell array in MATLAB?

I see that everybody missed the most important flaw in your code:

strs = {'HA' 'KU' 'LA' 'MA' 'TATA'}

should be:

strs = {'HA' 'KU' 'NA' 'MA' 'TATA'} 

or

strs = {'HAKUNA' 'MATATA'}

Now if you stick to using

ind=find(ismember(strs,'KU'))

You'll have no worries :).

..The underlying connection was closed: An unexpected error occurred on a receive

The underlying connection was closed: An unexpected error occurred on a receive.

This problem occurs when the server or another network device unexpectedly closes an existing Transmission Control Protocol (TCP) connection. This problem may occur when a time-out value on the server or on the network device is set too low. To resolve this problem, see resolutions A, D, E, F, and O. The problem can also occur if the server resets the connection unexpectedly, such as if an unhandled exception crashes the server process. Analyze the server logs to see if this may be the issue.

Resolution

To resolve this problem, make sure that you are using the most recent version of the .NET Framework.

Add a method to the class to override the GetWebRequest method. This change lets you access the HttpWebRequest object. If you are using Microsoft Visual C#, the new method must be similar to the following.

class MyTestService:TestService.TestService
{
    protected override WebRequest GetWebRequest(Uri uri)
    {
        HttpWebRequest webRequest = (HttpWebRequest) base.GetWebRequest(uri);
        //Setting KeepAlive to false
        webRequest.KeepAlive = false;
        return webRequest;
    }
}

Excerpt from KB915599: You receive one or more error messages when you try to make an HTTP request in an application that is built on the .NET Framework 1.1 Service Pack 1.

Hibernate - Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1

In my case there was an issue with the Database as one of the Stored Procs was consuming all the CPU causing high DB response times. Once this was killed issue got resolved.

ASP.NET MVC3 Razor - Html.ActionLink style

Reviving an old question because it seems to appear at the top of search results.

I wanted to retain transition effects while still being able to style the actionlink so I came up with this solution.

  1. I wrapped the action link with a div that would contain the parent style:
<div class="parent-style-one">
      @Html.ActionLink("Homepage", "Home", "Home")
</div>
  1. Next I create the CSS for the div, this will be the parent css and will be inherited by the child elements such as the action link.
  .parent-style-one {
     /* your styles here */
  }
  1. Because all an action link is, is an element when broken down as html so you just need to target that element in your css selection:
  .parent-style-one a {
     text-decoration: none;
  }
  1. For transition effects I did this:
  .parent-style-one a:hover {
        text-decoration: underline;
        -webkit-transition-duration: 1.1s; /* Safari */
        transition-duration: 1.1s;         
  }

This way I only target the child elements of the div in this case the action link and still be able to apply transition effects.

No Such Element Exception?

Looks like your file.next() line in the while loop is throwing the NoSuchElementException since the scanner reached the end of file. Read the next() java API here

Also you should not call next() in the loop and also in the while condition. In the while condition you should check if next token is available and inside the while loop check if its equal to treasure.

Generics/templates in python?

The other answers are totally fine:

  • One does not need a special syntax to support generics in Python
  • Python uses duck typing as pointed out by André.

However, if you still want a typed variant, there is a built-in solution since Python 3.5.

Generic classes:

from typing import TypeVar, Generic

T = TypeVar('T')

class Stack(Generic[T]):
    def __init__(self) -> None:
        # Create an empty list with items of type T
        self.items: List[T] = []

    def push(self, item: T) -> None:
        self.items.append(item)

    def pop(self) -> T:
        return self.items.pop()

    def empty(self) -> bool:
        return not self.items
# Construct an empty Stack[int] instance
stack = Stack[int]()
stack.push(2)
stack.pop()
stack.push('x')        # Type error

Generic functions:

from typing import TypeVar, Sequence

T = TypeVar('T')      # Declare type variable

def first(seq: Sequence[T]) -> T:
    return seq[0]

def last(seq: Sequence[T]) -> T:
    return seq[-1]


n = first([1, 2, 3])  # n has type int.

Reference: mypy documentation about generics.

How can you test if an object has a specific property?

Real similar to a javascript check:

foreach($member in $members)
{
    if($member.PropertyName)
    {
        Write $member.PropertyName
    }
    else
    {
        Write "Nope!"
    }
}

UICollectionView auto scroll to cell at IndexPath

I would recommend doing it in collectionView: willDisplay: Then you can be sure that the collection view delegate delivers something. Here my example:

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    /// this is done to set the index on start to 1 to have at index 0 the last image to have a infinity loop
    if !didScrollToSecondIndex {
        self.scrollToItem(at: IndexPath(row: 1, section: 0), at: .left, animated: false)
        didScrollToSecondIndex = true
    }
}

Different ways of clearing lists

Clearing a list in place will affect all other references of the same list.

For example, this method doesn't affect other references:

>>> a = [1, 2, 3]
>>> b = a
>>> a = []
>>> print(a)
[]
>>> print(b)
[1, 2, 3]

But this one does:

>>> a = [1, 2, 3]
>>> b = a
>>> del a[:]      # equivalent to   del a[0:len(a)]
>>> print(a)
[]
>>> print(b)
[]
>>> a is b
True

You could also do:

>>> a[:] = []

Link vs compile vs controller

Compile :

This is the phase where Angular actually compiles your directive. This compile function is called just once for each references to the given directive. For example, say you are using the ng-repeat directive. ng-repeat will have to look up the element it is attached to, extract the html fragment that it is attached to and create a template function.

If you have used HandleBars, underscore templates or equivalent, its like compiling their templates to extract out a template function. To this template function you pass data and the return value of that function is the html with the data in the right places.

The compilation phase is that step in Angular which returns the template function. This template function in angular is called the linking function.

Linking phase :

The linking phase is where you attach the data ( $scope ) to the linking function and it should return you the linked html. Since the directive also specifies where this html goes or what it changes, it is already good to go. This is the function where you want to make changes to the linked html, i.e the html that already has the data attached to it. In angular if you write code in the linking function its generally the post-link function (by default). It is kind of a callback that gets called after the linking function has linked the data with the template.

Controller :

The controller is a place where you put in some directive specific logic. This logic can go into the linking function as well, but then you would have to put that logic on the scope to make it "shareable". The problem with that is that you would then be corrupting the scope with your directives stuff which is not really something that is expected. So what is the alternative if two Directives want to talk to each other / co-operate with each other? Ofcourse you could put all that logic into a service and then make both these directives depend on that service but that just brings in one more dependency. The alternative is to provide a Controller for this scope ( usually isolate scope ? ) and then this controller is injected into another directive when that directive "requires" the other one. See tabs and panes on the first page of angularjs.org for an example.

Undefined function mysql_connect()

My guess is your PHP installation wasn't compiled with MySQL support.

Check your configure command (php -i | grep mysql). You should see something like '--with-mysql=shared,/usr'.

You can check for complete instructions at http://php.net/manual/en/mysql.installation.php. Although, I would rather go with the solution proposed by @wanovak.

Still, I think you need MySQL support in order to use PDO.

How to turn a vector into a matrix in R?

A matrix is really just a vector with a dim attribute (for the dimensions). So you can add dimensions to vec using the dim() function and vec will then be a matrix:

vec <- 1:49
dim(vec) <- c(7, 7)  ## (rows, cols)
vec

> vec <- 1:49
> dim(vec) <- c(7, 7)  ## (rows, cols)
> vec
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    1    8   15   22   29   36   43
[2,]    2    9   16   23   30   37   44
[3,]    3   10   17   24   31   38   45
[4,]    4   11   18   25   32   39   46
[5,]    5   12   19   26   33   40   47
[6,]    6   13   20   27   34   41   48
[7,]    7   14   21   28   35   42   49

Testing two JSON objects for equality ignoring child order in Java

I'd take the library at http://json.org/java/, and modify the equals method of JSONObject and JSONArray to do a deep equality test. To make sure that it works regradless of the order of the children, all you need to do is replace the inner map with a TreeMap, or use something like Collections.sort().

Get a list of URLs from a site

I would look into any number of online sitemap generation tools. Personally, I've used this one (java based)in the past, but if you do a google search for "sitemap builder" I'm sure you'll find lots of different options.

Resize font-size according to div size

I found a way of resizing font size according to div size, without any JavaScript. I don't know how much efficient it's, but it nicely gets the job done.

Embed a SVG element inside the required div, and then use a foreignObject tag inside which you can use HTML elements. A sample code snippet that got my job done is given below.

<!-- The SVG element given below should be place inside required div tag -->
<svg viewBox='0 2 108.5 29' xmlns='http://www.w3.org/2000/svg'>
    <!-- The below tag allows adding HTML elements inside SVG tag -->
    <foreignObject x='5' y='0' width='93.5%' height='100%'>
        <!-- The below tag can be styled using CSS classes or style attributes -->
        <div xmlns='http://www.w3.org/1999/xhtml' style='text-overflow: ellipsis; overflow: hidden; white-space: nowrap;'>
            Required text goes here            
        </div>
    </foreignObject>
</svg>

All the viewBox, x, y, width and height values can be changed according to requirement.

Text can be defined inside the SVG element itself, but when the text overflows, ellipsis can't be added to SVG text. So, HTML element(s) are defined inside a foreignObject element, and text-overflow styles are added to that/those element(s).

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

Mac OS apps cannot read bash environment variables. Look at this question Setting environment variables in OS X? to expose M2_HOME to all applications including IntelliJ. You do need to restart after doing this.

How to find list intersection?

a = [1,2,3,4,5]
b = [1,3,5,6]
c = list(set(a).intersection(set(b)))

Should work like a dream. And, if you can, use sets instead of lists to avoid all this type changing!

How to use Bootstrap 4 in ASP.NET Core

As others already mentioned, the package manager Bower, that was usually used for dependencies like this in application that do not rely on heavy client-side scripting, is on the way out and actively recommending to move to other solutions:

..psst! While Bower is maintained, we recommend yarn and webpack for new front-end projects!

So although you can still use it right now, Bootstrap has also announced to drop support for it. As a result, the built-in ASP.NET Core templates are slowly being edited to move away from it too.

Unfortunately, there is no clear path forward. This is mostly due to the fact that web applications are continuously moving further into the client-side, requiring complex client-side build systems and many dependencies. So if you are building something like that, you might already know how to solve this then, and you can expand your existing build process to simply also include Bootstrap and jQuery there.

But there are still many web applications out there that are not that heavy on the client-side, where the application still runs mainly on the server and the server serves static views as a result. Bower previously filled this by making it easy to just publish client-side dependencies without that much of a process.

In the .NET world we also have NuGet and with previous ASP.NET versions, we could use NuGet as well to add dependencies to some client-side dependencies since NuGet would just place the content into our project correctly. Unfortunately, with the new .csproj format and the new NuGet, installed packages are located outside of our project, so we cannot simply reference those.

This leaves us with a few options how to add our dependencies:

One-time installation

This is what the ASP.NET Core templates, that are not single-page applications, are currently doing. When you use those to create a new application, the wwwroot folder simply contains a folder lib that contains the dependencies:

wwwroot folder contains lib folder with static dependencies

If you look closely at the files currently, you can see that they were originally placed there with Bower to create the template, but that is likely to change soon. The basic idea is that the files are copied once to the wwwroot folder so you can depend on them.

To do this, we can simply follow Bootstrap’s introduction and download the compiled files directly. As mentioned on the download site, this does not include jQuery, so we need to download that separately too; it does contain Popper.js though if we choose to use the bootstrap.bundle file later—which we will do. For jQuery, we can simply get a single “compressed, production” file from the download site (right-click the link and select "Save link as..." from the menu).

This leaves us with a few files which will simply extract and copy into the wwwroot folder. We can also make a lib folder to make it clearer that these are external dependencies:

wwwroot folder contains lib folder with our installed dependencies

That’s all we need, so now we just need to adjust our _Layout.cshtml file to include those dependencies. For that, we add the following block to the <head>:

<environment include="Development">
    <link rel="stylesheet" href="~/lib/css/bootstrap.css" />
</environment>
<environment exclude="Development">
    <link rel="stylesheet" href="~/lib/css/bootstrap.min.css" />
</environment>

And the following block at the very end of the <body>:

<environment include="Development">
    <script src="~/lib/js/jquery-3.3.1.js"></script>
    <script src="~/lib/js/bootstrap.bundle.js"></script>
</environment>
<environment exclude="Development">
    <script src="~/lib/js/jquery-3.3.1.min.js"></script>
    <script src="~/lib/js/bootstrap.bundle.min.js"></script>
</environment>

You can also just include the minified versions and skip the <environment> tag helpers here to make it a bit simpler. But that’s all you need to do to keep you starting.

Dependencies from NPM

The more modern way, also if you want to keep your dependencies updated, would be to get the dependencies from the NPM package repository. You can use either NPM or Yarn for this; in my example, I’ll use NPM.

To start off, we need to create a package.json file for our project, so we can specify our dependencies. To do this, we simply do that from the “Add New Item” dialog:

Add New Item: npm Configuration file

Once we have that, we need to edit it to include our dependencies. It should something look like this:

{
  "version": "1.0.0",
  "name": "asp.net",
  "private": true,
  "devDependencies": {
    "bootstrap": "4.0.0",
    "jquery": "3.3.1",
    "popper.js": "1.12.9"
  }
}

By saving, Visual Studio will already run NPM to install the dependencies for us. They will be installed into the node_modules folder. So what is left to do is to get the files from there into our wwwroot folder. There are a few options to do that:

bundleconfig.json for bundling and minification

We can use one of the various ways to consume a bundleconfig.json for bundling and minification, as explained in the documentation. A very easy way is to simply use the BuildBundlerMinifier NuGet package which automatically sets up a build task for this.

After installing that package, we need to create a bundleconfig.json at the root of the project with the following contents:

[
  {
    "outputFileName": "wwwroot/vendor.min.css",
    "inputFiles": [
      "node_modules/bootstrap/dist/css/bootstrap.min.css"
    ],
    "minify": { "enabled": false }
  },
  {
    "outputFileName": "wwwroot/vendor.min.js",
    "inputFiles": [
      "node_modules/jquery/dist/jquery.min.js",
      "node_modules/popper.js/dist/umd/popper.min.js",
      "node_modules/bootstrap/dist/js/bootstrap.min.js"
    ],
    "minify": { "enabled": false }
  }
]

This basically configures which files to combine into what. And when we build, we can see that the vendor.min.css and vendor.js.css are created correctly. So all we need to do is to adjust our _Layouts.html again to include those files:

<!-- inside <head> -->
<link rel="stylesheet" href="~/vendor.min.css" />

<!-- at the end of <body> -->
<script src="~/vendor.min.js"></script>

Using a task manager like Gulp

If we want to move a bit more into client-side development, we can also start to use tools that we would use there. For example Webpack which is a very commonly used build tool for really everything. But we can also start with a simpler task manager like Gulp and do the few necessary steps ourselves.

For that, we add a gulpfile.js into our project root, with the following contents:

const gulp = require('gulp');
const concat = require('gulp-concat');

const vendorStyles = [
    "node_modules/bootstrap/dist/css/bootstrap.min.css"
];
const vendorScripts = [
    "node_modules/jquery/dist/jquery.min.js",
    "node_modules/popper.js/dist/umd/popper.min.js",
    "node_modules/bootstrap/dist/js/bootstrap.min.js",
];

gulp.task('build-vendor-css', () => {
    return gulp.src(vendorStyles)
        .pipe(concat('vendor.min.css'))
        .pipe(gulp.dest('wwwroot'));
});

gulp.task('build-vendor-js', () => {
    return gulp.src(vendorScripts)
        .pipe(concat('vendor.min.js'))
        .pipe(gulp.dest('wwwroot'));
});

gulp.task('build-vendor', gulp.parallel('build-vendor-css', 'build-vendor-js'));

gulp.task('default', gulp.series('build-vendor'));

Now, we also need to adjust our package.json to have dependencies on gulp and gulp-concat:

{
  "version": "1.0.0",
  "name": "asp.net",
  "private": true,
  "devDependencies": {
    "bootstrap": "4.0.0",
    "gulp": "^4.0.2",
    "gulp-concat": "^2.6.1",
    "jquery": "3.3.1",
    "popper.js": "1.12.9"
  }
}

Finally, we edit our .csproj to add the following task which makes sure that our Gulp task runs when we build the project:

<Target Name="RunGulp" BeforeTargets="Build">
  <Exec Command="node_modules\.bin\gulp.cmd" />
</Target>

Now, when we build, the default Gulp task runs, which runs the build-vendor tasks, which then builds our vendor.min.css and vendor.min.js just like we did before. So after adjusting our _Layout.cshtml just like above, we can make use of jQuery and Bootstrap.

While the initial setup of Gulp is a bit more complicated than the bundleconfig.json one above, we have now have entered the Node-world and can start to make use of all the other cool tools there. So it might be worth to start with this.

Conclusion

While this suddenly got a lot more complicated than with just using Bower, we also do gain a lot of control with those new options. For example, we can now decide what files are actually included within the wwwroot folder and how those exactly look like. And we also can use this to make the first moves into the client-side development world with Node which at least should help a bit with the learning curve.

node.js execute system command synchronously

This is the easiest way I found:

exec-Sync: https://github.com/jeremyfa/node-exec-sync
(Not to be confused with execSync.)
Execute shell command synchronously. Use this for migration scripts, cli programs, but not for regular server code.

Example:

var execSync = require('exec-sync');   
var user = execSync('echo $USER');
console.log(user);

psql: FATAL: role "postgres" does not exist

The \du command return:

Role name = postgres@implicit_files

And that command postgres=# \password postgres return error:

ERROR: role "postgres" does not exist.

But that postgres=# \password postgres@implicit_files run fine.

Also after sudo -u postgres createuser -s postgres the first variant also work.

Connect HTML page with SQL server using javascript

Before The execution of following code, I assume you have created a database and a table (with columns Name (varchar), Age(INT) and Address(varchar)) inside that database. Also please update your SQL Server name , UserID, password, DBname and table name in the code below.

In the code. I have used VBScript and embedded it in HTML. Try it out!

<!DOCTYPE html>
<html>
<head>
<script type="text/vbscript">
<!--    

Sub Submit_onclick()
Dim Connection
Dim ConnString
Dim Recordset

Set connection=CreateObject("ADODB.Connection")
Set Recordset=CreateObject("ADODB.Recordset")
ConnString="DRIVER={SQL Server};SERVER=*YourSQLserverNameHere*;UID=*YourUserIdHere*;PWD=*YourpasswordHere*;DATABASE=*YourDBNameHere*"
Connection.Open ConnString

dim form1
Set form1 = document.Register

Name1 = form1.Name.value
Age1 = form1.Age.Value
Add1 = form1.address.value

connection.execute("INSERT INTO [*YourTableName*] VALUES ('"&Name1 &"'," &Age1 &",'"&Add1 &"')")

End Sub

//-->
</script>
</head>
<body>

<h2>Please Fill details</h2><br>
<p>
<form name="Register">
<pre>
<font face="Times New Roman" size="3">Please enter the log in credentials:<br>
Name:   <input type="text" name="Name">
Age:        <input type="text" name="Age">
Address:        <input type="text" name="address">
<input type="button" id ="Submit" value="submit" /><font></form> 
</p>
</pre>
</body>
</html>

How to connect TFS in Visual Studio code

I know I'm a little late to the party, but I did want to throw some interjections. (I would have commented but not enough reputation points yet, so, here's a full answer).

This requires the latest version of VS Code, Azure Repo Extention, and Git to be installed.

Anyone looking to use the new VS Code (or using the preview like myself), when you go to the Settings (Still File -> Preferences -> Settings or CTRL+, ) you'll be looking under User Settings -> Extensions -> Azure Repos.

Azure_Repo_Settings

Then under Tfvc: Location you can paste the location of the executable.

Location_Settings

For 2017 it'll be

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe

Or for 2019 (Preview)

C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe

After adding the location, I closed my VS Code (not sure if this was needed) and went my git repo to copy the git URL.

Git_URL

After that, went back into VS Code went to the Command Palette (View -> Command Palette or CTRL+Shift+P) typed Git: Clone pasted my repo:

Git_Repo

Selected the location for the repo to be stored. Next was an error that popped up. I proceeded to follow this video which walked me through clicking on the Team button with the exclamation mark on the bottom of your VS Code Screen

Team_Button

Then chose the new method of authentication

New_Method

Copy by using CTRL+C and then press enter. Your browser will launch a page where you'll enter the code you copied (CTRL+V).

Enter_Code_Screen

Click Continue

Continue_Button

Log in with your Microsoft Credentials and you should see a change on the bottom bar of VS Code.

Bottom_Bar

Cheers!

How to create PDFs in an Android app?

If you are developing for devices with API level 19 or higher you can use the built in PrintedPdfDocument: http://developer.android.com/reference/android/print/pdf/PrintedPdfDocument.html

// open a new document
PrintedPdfDocument document = new PrintedPdfDocument(context,
     printAttributes);

// start a page
Page page = document.startPage(0);

// draw something on the page
View content = getContentView();
content.draw(page.getCanvas());

// finish the page
document.finishPage(page);
. . .
// add more pages
. . .
// write the document content
document.writeTo(getOutputStream());

//close the document
document.close();

jQuery UI DatePicker to show year only

I had the same problem and, after a day of research, I came up with this solution: http://jsfiddle.net/konstantc/4jkef3a1/

_x000D_
_x000D_
// *** (month and year only) ***_x000D_
$(function() { _x000D_
  $('#datepicker1').datepicker( {_x000D_
    yearRange: "c-100:c",_x000D_
    changeMonth: true,_x000D_
    changeYear: true,_x000D_
    showButtonPanel: true,_x000D_
    closeText:'Select',_x000D_
    currentText: 'This year',_x000D_
    onClose: function(dateText, inst) {_x000D_
      var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();_x000D_
      var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();_x000D_
      $(this).val($.datepicker.formatDate('MM yy (M y) (mm/y)', new Date(year, month, 1)));_x000D_
    }_x000D_
  }).focus(function () {_x000D_
    $(".ui-datepicker-calendar").hide();_x000D_
    $(".ui-datepicker-current").hide();_x000D_
    $("#ui-datepicker-div").position({_x000D_
      my: "left top",_x000D_
      at: "left bottom",_x000D_
      of: $(this)_x000D_
    });_x000D_
  }).attr("readonly", false);_x000D_
});_x000D_
// --------------------------------_x000D_
_x000D_
_x000D_
_x000D_
// *** (year only) ***_x000D_
$(function() { _x000D_
  $('#datepicker2').datepicker( {_x000D_
    yearRange: "c-100:c",_x000D_
    changeMonth: false,_x000D_
    changeYear: true,_x000D_
    showButtonPanel: true,_x000D_
    closeText:'Select',_x000D_
    currentText: 'This year',_x000D_
    onClose: function(dateText, inst) {_x000D_
      var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();_x000D_
      $(this).val($.datepicker.formatDate('yy', new Date(year, 1, 1)));_x000D_
    }_x000D_
  }).focus(function () {_x000D_
    $(".ui-datepicker-month").hide();_x000D_
    $(".ui-datepicker-calendar").hide();_x000D_
    $(".ui-datepicker-current").hide();_x000D_
    $(".ui-datepicker-prev").hide();_x000D_
    $(".ui-datepicker-next").hide();_x000D_
    $("#ui-datepicker-div").position({_x000D_
      my: "left top",_x000D_
      at: "left bottom",_x000D_
      of: $(this)_x000D_
    });_x000D_
  }).attr("readonly", false);_x000D_
});_x000D_
// --------------------------------_x000D_
_x000D_
_x000D_
_x000D_
// *** (year only, no controls) ***_x000D_
$(function() { _x000D_
  $('#datepicker3').datepicker( {_x000D_
    dateFormat: "yy",_x000D_
    yearRange: "c-100:c",_x000D_
    changeMonth: false,_x000D_
    changeYear: true,_x000D_
    showButtonPanel: false,_x000D_
    closeText:'Select',_x000D_
    currentText: 'This year',_x000D_
    onClose: function(dateText, inst) {_x000D_
      var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();_x000D_
      $(this).val($.datepicker.formatDate('yy', new Date(year, 1, 1)));_x000D_
    },_x000D_
    onChangeMonthYear : function () {_x000D_
      $(this).datepicker( "hide" );_x000D_
    }_x000D_
  }).focus(function () {_x000D_
    $(".ui-datepicker-month").hide();_x000D_
    $(".ui-datepicker-calendar").hide();_x000D_
    $(".ui-datepicker-current").hide();_x000D_
    $(".ui-datepicker-prev").hide();_x000D_
    $(".ui-datepicker-next").hide();_x000D_
    $("#ui-datepicker-div").position({_x000D_
      my: "left top",_x000D_
      at: "left bottom",_x000D_
      of: $(this)_x000D_
    });_x000D_
  }).attr("readonly", false);_x000D_
});_x000D_
// --------------------------------
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />_x000D_
_x000D_
<div class="container">_x000D_
_x000D_
  <h2 class="font-weight-light text-lg-left mt-4 mb-0"><b>jQuery UI Datepicker</b> custom select</h2>_x000D_
_x000D_
  <hr class="mt-2 mb-3">_x000D_
  <div class="row text-lg-left">_x000D_
    <div class="col-12">_x000D_
_x000D_
      <form>_x000D_
_x000D_
        <div class="form-label-group">_x000D_
        <label for="datepicker1">(month and year only : <code>id="datepicker1"</code> )</label>_x000D_
          <input type="text" class="form-control" id="datepicker1" _x000D_
                 placeholder="(month and year only)" />_x000D_
        </div>_x000D_
_x000D_
        <hr />_x000D_
_x000D_
        <div class="form-label-group">_x000D_
        <label for="datepicker2">(year only : <code>input id="datepicker2"</code> )</label>_x000D_
          <input type="text" class="form-control" id="datepicker2" _x000D_
                 placeholder="(year only)" />_x000D_
        </div>_x000D_
_x000D_
        <hr />_x000D_
_x000D_
        <div class="form-label-group">_x000D_
        <label for="datepicker3">(year only, no controls : <code>input id="datepicker3"</code> )</label>_x000D_
          <input type="text" class="form-control" id="datepicker3" _x000D_
                 placeholder="(year only, no controls)" />_x000D_
        </div>_x000D_
_x000D_
      </form>_x000D_
_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

I know this question is pretty old but I thought that my solution can be of use to others that encounter this problem. Hope it helps.

How to run a .jar in mac?

You don't need JDK to run Java based programs. JDK is for development which stands for Java Development Kit.

You need JRE which should be there in Mac.

Try: java -jar Myjar_file.jar

EDIT: According to this article, for Mac OS 10

The Java runtime is no longer installed automatically as part of the OS installation.

Then, you need to install JRE to your machine.

Java Regex Replace with Capturing Group

Source: java-implementation-of-rubys-gsub

Usage:

// Rewrite an ancient unit of length in SI units.
String result = new Rewriter("([0-9]+(\\.[0-9]+)?)[- ]?(inch(es)?)") {
    public String replacement() {
        float inches = Float.parseFloat(group(1));
        return Float.toString(2.54f * inches) + " cm";
    }
}.rewrite("a 17 inch display");
System.out.println(result);

// The "Searching and Replacing with Non-Constant Values Using a
// Regular Expression" example from the Java Almanac.
result = new Rewriter("([a-zA-Z]+[0-9]+)") {
    public String replacement() {
        return group(1).toUpperCase();
    }
}.rewrite("ab12 cd efg34");
System.out.println(result);

Implementation (redesigned):

import static java.lang.String.format;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class Rewriter {
    private Pattern pattern;
    private Matcher matcher;

    public Rewriter(String regularExpression) {
        this.pattern = Pattern.compile(regularExpression);
    }

    public String group(int i) {
        return matcher.group(i);
    }

    public abstract String replacement() throws Exception;

    public String rewrite(CharSequence original) {
        return rewrite(original, new StringBuffer(original.length())).toString();
    }

    public StringBuffer rewrite(CharSequence original, StringBuffer destination) {
        try {
            this.matcher = pattern.matcher(original);
            while (matcher.find()) {
                matcher.appendReplacement(destination, "");
                destination.append(replacement());
            }
            matcher.appendTail(destination);
            return destination;
        } catch (Exception e) {
            throw new RuntimeException("Cannot rewrite " + toString(), e);
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(pattern.pattern());
        for (int i = 0; i <= matcher.groupCount(); i++)
            sb.append(format("\n\t(%s) - %s", i, group(i)));
        return sb.toString();
    }
}

How can two strings be concatenated?

As others have pointed out, paste() is the way to go. But it can get annoying to have to type paste(str1, str2, str3, sep='') everytime you want the non-default separator.

You can very easily create wrapper functions that make life much simpler. For instance, if you find yourself concatenating strings with no separator really often, you can do:

p <- function(..., sep='') {
    paste(..., sep=sep, collapse=sep)
}

or if you often want to join strings from a vector (like implode() from PHP):

implode <- function(..., sep='') {
     paste(..., collapse=sep)
}

Allows you do do this:

p('a', 'b', 'c')
#[1] "abc"
vec <- c('a', 'b', 'c')
implode(vec)
#[1] "abc"
implode(vec, sep=', ')
#[1] "a, b, c"

Also, there is the built-in paste0, which does the same thing as my implode, but without allowing custom separators. It's slightly more efficient than paste().

Oracle PL/SQL : remove "space characters" from a string

select regexp_replace('This is a test   ' || chr(9) || ' foo ', '[[:space:]]', '') from dual;

REGEXP_REPLACE
--------------
Thisisatestfoo

How to display a confirmation dialog when clicking an <a> link?

Just for fun, I'm going to use a single event on the whole document instead of adding an event to all the anchor tags:

document.body.onclick = function( e ) {
    // Cross-browser handling
    var evt = e || window.event,
        target = evt.target || evt.srcElement;

    // If the element clicked is an anchor
    if ( target.nodeName === 'A' ) {

        // Add the confirm box
        return confirm( 'Are you sure?' );
    }
};

This method would be more efficient if you had many anchor tags. Of course, it becomes even more efficient when you add this event to the container having all the anchor tags.

"unable to locate adb" using Android Studio

Check your [sdk directory]/platform-tools directory and if it does not exist, then open the SDK manager in the Android Studio (a button somewhere in the top menu, android logo with a down arrow), switch to SDK tools tab and and select/install the Android SDK Platform-tools.

Alternatively, you can try the standalone SDK Manager: Open the SDK manager and you should see a "Launch Standalone SDK manager" link somewhere at the bottom of the settings window. Click and open the standalone SDK manager, then install/update the

"Tools > Android SDK platform tools". If the above does not solve the problem, try reinstalling the tools: open the "Standalone SDK manager" and uninstall the Android SDK platform-tools, delete the [your sdk directory]/platform-tools directory completely and install it again using the SDK manager.

Hope this helps!

Convert Pandas column containing NaNs to dtype `int`

As of Pandas 1.0.0 you can now use pandas.NA values. This does not force integer columns with missing values to be floats.

When reading in your data all you have to do is:

df= pd.read_csv("data.csv", dtype={'id': 'Int64'})  

Notice the 'Int64' is surrounded by quotes and the I is capitalized. This distinguishes Panda's 'Int64' from numpy's int64.

As a side note, this will also work with .astype()

df['id'] = df['id'].astype('Int64')

Documentation here https://pandas.pydata.org/pandas-docs/stable/user_guide/integer_na.html

How to compare 2 files fast using .NET?

A checksum comparison will most likely be slower than a byte-by-byte comparison.

In order to generate a checksum, you'll need to load each byte of the file, and perform processing on it. You'll then have to do this on the second file. The processing will almost definitely be slower than the comparison check.

As for generating a checksum: You can do this easily with the cryptography classes. Here's a short example of generating an MD5 checksum with C#.

However, a checksum may be faster and make more sense if you can pre-compute the checksum of the "test" or "base" case. If you have an existing file, and you're checking to see if a new file is the same as the existing one, pre-computing the checksum on your "existing" file would mean only needing to do the DiskIO one time, on the new file. This would likely be faster than a byte-by-byte comparison.

'Best' practice for restful POST response

Returning the whole object on an update would not seem very relevant, but I can hardly see why returning the whole object when it is created would be a bad practice in a normal use case. This would be useful at least to get the ID easily and to get the timestamps when relevant. This is actually the default behavior got when scaffolding with Rails.

I really do not see any advantage to returning only the ID and doing a GET request after, to get the data you could have got with your initial POST.

Anyway as long as your API is consistent I think that you should choose the pattern that fits your needs the best. There is not any correct way of how to build a REST API, imo.

How to keep a git branch in sync with master

Yeah I agree with your approach. To merge mobiledevicesupport into master you can use

git checkout master
git pull origin master //Get all latest commits of master branch
git merge mobiledevicesupport

Similarly you can also merge master in mobiledevicesupport.

Q. If cross merging is an issue or not.

A. Well it depends upon the commits made in mobile* branch and master branch from the last time they were synced. Take this example: After last sync, following commits happen to these branches

Master branch: A -> B -> C [where A,B,C are commits]
Mobile branch: D -> E

Now, suppose commit B made some changes to file a.txt and commit D also made some changes to a.txt. Let us have a look at the impact of each operation of merging now,

git checkout master //Switches to master branch
git pull // Get the commits you don't have. May be your fellow workers have made them.
git merge mobiledevicesupport // It will try to add D and E in master branch.

Now, there are two types of merging possible

  1. Fast forward merge
  2. True merge (Requires manual effort)

Git will first try to make FF merge and if it finds any conflicts are not resolvable by git. It fails the merge and asks you to merge. In this case, a new commit will occur which is responsible for resolving conflicts in a.txt.

So Bottom line is Cross merging is not an issue and ultimately you have to do it and that is what syncing means. Make sure you dirty your hands in merging branches before doing anything in production.

onKeyPress Vs. onKeyUp and onKeyDown

A few practical facts that might be useful to decide which event to handle (run the script below and focus on the input box):

_x000D_
_x000D_
$('input').on('keyup keydown keypress',e=>console.log(e.type, e.keyCode, e.which, e.key))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input/>
_x000D_
_x000D_
_x000D_

Pressing:

  • non inserting/typing keys (e.g. Shift, Ctrl) will not trigger a keypress. Press Ctrl and release it:

    keydown 17 17 Control

    keyup 17 17 Control

  • keys from keyboards that apply characters transformations to other characters may lead to Dead and duplicate "keys" (e.g. ~, ´) on keydown. Press ´ and release it in order to display a double ´´:

    keydown 192 192 Dead

    keydown 192 192 ´´

    keypress 180 180 ´

    keypress 180 180 ´

    keyup 192 192 Dead

Additionally, non typing inputs (e.g. ranged <input type="range">) will still trigger all keyup, keydown and keypress events according to the pressed keys.

How can I display a list view in an Android Alert Dialog?

As a beginner I would suggest you go through http://www.mkyong.com/android/android-custom-dialog-example/

I'll rundown what it basically does

  1. Creates an XML file for the dialog and main Activity
  2. In the main activity in the required place creates an object of android class Dialog
  3. Adds custom styling and text based on the XML file
  4. Calls the dialog.show() method.

Storing database records into array

$mysearch="Your Search Name";
$query = mysql_query("SELECT * FROM table");
$c=0;
// set array
$array = array();

// look through query
while($row = mysql_fetch_assoc($query)){

  // add each row returned into an array
  $array[] = $row;
  $c++;
}

for($i=0;$i=$c;$i++)
{
if($array[i]['username']==$mysearch)
{
// name found
}
}

Excel VBA Password via Hex Editor

New version, now you also have the GC= try to replace both DPB and GC with those

DPB="DBD9775A4B774B77B4894C77DFE8FE6D2CCEB951E8045C2AB7CA507D8F3AC7E3A7F59012A2" GC="BAB816BBF4BCF4BCF4"

password will be "test"

cpp / c++ get pointer value or depointerize pointer

To get the value of a pointer, just de-reference the pointer.

int *ptr;
int value;
*ptr = 9;

value = *ptr;

value is now 9.

I suggest you read more about pointers, this is their base functionality.

How to simulate a mouse click using JavaScript?

JavaScript Code

   //this function is used to fire click event
    function eventFire(el, etype){
      if (el.fireEvent) {
        el.fireEvent('on' + etype);
      } else {
        var evObj = document.createEvent('Events');
        evObj.initEvent(etype, true, false);
        el.dispatchEvent(evObj);
      }
    }

function showPdf(){
  eventFire(document.getElementById('picToClick'), 'click');
}

HTML Code

<img id="picToClick" data-toggle="modal" data-target="#pdfModal" src="img/Adobe-icon.png" ng-hide="1===1">
  <button onclick="showPdf()">Click me</button>

Android - How to decode and decompile any APK file?

You can try this website http://www.decompileandroid.com Just upload the .apk file and rest of it will be done by this site.

Delete all files in directory (but not directory) - one liner solution

Or to use this in Java 8:

try {
  Files.newDirectoryStream( directory ).forEach( file -> {
    try { Files.delete( file ); }
    catch ( IOException e ) { throw new UncheckedIOException(e); }
  } );
}
catch ( IOException e ) {
  e.printStackTrace();
}

It's a pity the exception handling is so bulky, otherwise it would be a one-liner ...

undefined reference to boost::system::system_category() when compiling

The above error is a linker error... the linker a program that takes one or more objects generated by a compiler and combines them into a single executable program.

You must add -lboost_system to you linker flags which indicates to the linker that it must look for symbols like boost::system::system_category() in the library libboost_system.so.

If you have main.cpp, either:

g++ main.cpp -o main -lboost_system

OR

g++ -c -o main.o main.cpp
g++ main.o -lboost_system

How to use GROUP BY to concatenate strings in MySQL?

SELECT id, GROUP_CONCAT( string SEPARATOR ' ') FROM table GROUP BY id

More details here.

From the link above, GROUP_CONCAT: This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values.

Passing Variable through JavaScript from one html page to another page

There are two pages: Pageone.html :

<script>
var hello = "hi"
location.replace("http://example.com/PageTwo.html?" + hi + "");
</script>

PageTwo.html :

<script>
var link = window.location.href;
link = link.replace("http://example.com/PageTwo.html?","");
document.write("The variable contained this content:" + link + "");
</script>

Hope it helps!

Is having an 'OR' in an INNER JOIN condition a bad idea?

I use following code for get different result from condition That worked for me.


Select A.column, B.column
FROM TABLE1 A
INNER JOIN
TABLE2 B
ON A.Id = (case when (your condition) then b.Id else (something) END)

How to retrieve an element from a set without removing it?

I use a utility function I wrote. Its name is somewhat misleading because it kind of implies it might be a random item or something like that.

def anyitem(iterable):
    try:
        return iter(iterable).next()
    except StopIteration:
        return None

Storing query results into a variable and modifying it inside a Stored Procedure

Yup, this is possible of course. Here are several examples.

-- one way to do this
DECLARE @Cnt int

SELECT @Cnt = COUNT(SomeColumn)
FROM TableName
GROUP BY SomeColumn

-- another way to do the same thing
DECLARE @StreetName nvarchar(100)
SET @StreetName = (SELECT Street_Name from Streets where Street_ID = 123)

-- Assign values to several variables at once
DECLARE @val1 nvarchar(20)
DECLARE @val2 int
DECLARE @val3 datetime
DECLARE @val4 uniqueidentifier
DECLARE @val5 double

SELECT @val1 = TextColumn,
@val2 = IntColumn,
@val3 = DateColumn,
@val4 = GuidColumn,
@val5 = DoubleColumn
FROM SomeTable

How to check if a class inherits another class without instantiating it?

Try this

typeof(IFoo).IsAssignableFrom(typeof(BarClass));

This will tell you whether BarClass(Derived) implements IFoo(SomeType) or not

How to create UILabel programmatically using Swift?

Just to add onto the already great answers, you might want to add multiple labels in your project so doing all of this (setting size, style etc) will be a pain. To solve this, you can create a separate UILabel class.

  import UIKit

  class MyLabel: UILabel {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initializeLabel()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        initializeLabel()
    }

    func initializeLabel() {

        self.textAlignment = .left
        self.font = UIFont(name: "Halvetica", size: 17)
        self.textColor = UIColor.white

    }

}

To use it, do the following

import UIKit

class ViewController: UIViewController {

     var myLabel: MyLabel()

     override func viewDidLoad() {
          super.viewDidLoad()

          myLabel = MyLabel(frame: CGRect(x: self.view.frame.size.width / 2, y: self.view.frame.size.height / 2, width: 100, height: 20))
          self.view.addSubView(myLabel)
     }


}

Android studio Gradle icon error, Manifest Merger

This error also occurs when your app's minSdk is higher than any library's minSdk.

app's minSdk >= libraries minSdk

How do I set proxy for chrome in python webdriver?

For people out there asking how to setup proxy server in chrome which needs authentication should follow these steps.

  1. Create a proxy.py file in your project, use this code and call proxy_chrome from
    proxy.py everytime you need it. You need to pass parameters like proxy server, port and username password for authentication.

Group by with multiple columns using lambda

if your table is like this

rowId     col1    col2    col3    col4
 1          a       e       12       2
 2          b       f       42       5
 3          a       e       32       2
 4          b       f       44       5


var grouped = myTable.AsEnumerable().GroupBy(r=> new {pp1 =  r.Field<int>("col1"), pp2 = r.Field<int>("col2")});

Python send POST with header

To make POST request instead of GET request using urllib2, you need to specify empty data, for example:

import urllib2
req = urllib2.Request("http://am.domain.com:8080/openam/json/realms/root/authenticate?authIndexType=Module&authIndexValue=LDAP")
req.add_header('X-OpenAM-Username', 'demo')
req.add_data('')
r = urllib2.urlopen(req)

How to get the host name of the current machine as defined in the Ansible hosts file?

The necessary variable is inventory_hostname.

- name: Install this only for local dev machine
  pip: name=pyramid
  when: inventory_hostname == "local"

It is somewhat hidden in the documentation at the bottom of this section.

How to get the new value of an HTML input after a keypress has modified it?

To give a modern approach to this question. This works well, including Ctrl+v. GlobalEventHandlers.oninput.

var onChange = function(evt) {
  console.info(this.value);
  // or
  console.info(evt.target.value);
};
var input = document.getElementById('some-id');
input.addEventListener('input', onChange, false);

How do I update Anaconda?

Here's the best practice (in my humble experience). Selecting these four packages will also update all other dependencies to the appropriate versions that will help you keep your environment consistent. The latter is a common problem others have expressed in earlier responses. This solution doesn't need the terminal.

Updating and upgrading Anaconda 3 or Anaconda 2 best practice

How to make Bitmap compress without change the bitmap size?

I have done this way:

Get Compressed Bitmap from Singleton class:

ImageView imageView = (ImageView)findViewById(R.id.imageView);
Bitmap bitmap = ImageUtils.getInstant().getCompressedBitmap("Your_Image_Path_Here");
imageView.setImageBitmap(bitmap);

ImageUtils.java:

public class ImageUtils {

    public static ImageUtils mInstant;

    public static ImageUtils getInstant(){
        if(mInstant==null){
            mInstant = new ImageUtils();
        }
        return mInstant;
    }

    public  Bitmap getCompressedBitmap(String imagePath) {
        float maxHeight = 1920.0f;
        float maxWidth = 1080.0f;
        Bitmap scaledBitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeFile(imagePath, options);

        int actualHeight = options.outHeight;
        int actualWidth = options.outWidth;
        float imgRatio = (float) actualWidth / (float) actualHeight;
        float maxRatio = maxWidth / maxHeight;

        if (actualHeight > maxHeight || actualWidth > maxWidth) {
            if (imgRatio < maxRatio) {
                imgRatio = maxHeight / actualHeight;
                actualWidth = (int) (imgRatio * actualWidth);
                actualHeight = (int) maxHeight;
            } else if (imgRatio > maxRatio) {
                imgRatio = maxWidth / actualWidth;
                actualHeight = (int) (imgRatio * actualHeight);
                actualWidth = (int) maxWidth;
            } else {
                actualHeight = (int) maxHeight;
                actualWidth = (int) maxWidth;

            }
        }

        options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
        options.inJustDecodeBounds = false;
        options.inDither = false;
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inTempStorage = new byte[16 * 1024];

        try {
            bmp = BitmapFactory.decodeFile(imagePath, options);
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();

        }
        try {
            scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.ARGB_8888);
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();
        }

        float ratioX = actualWidth / (float) options.outWidth;
        float ratioY = actualHeight / (float) options.outHeight;
        float middleX = actualWidth / 2.0f;
        float middleY = actualHeight / 2.0f;

        Matrix scaleMatrix = new Matrix();
        scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);

        Canvas canvas = new Canvas(scaledBitmap);
        canvas.setMatrix(scaleMatrix);
        canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));

        ExifInterface exif = null;
        try {
            exif = new ExifInterface(imagePath);
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
            Matrix matrix = new Matrix();
            if (orientation == 6) {
                matrix.postRotate(90);
            } else if (orientation == 3) {
                matrix.postRotate(180);
            } else if (orientation == 8) {
                matrix.postRotate(270);
            }
            scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 85, out);

        byte[] byteArray = out.toByteArray();

        Bitmap updatedBitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);

        return updatedBitmap;
    }

    private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        final float totalPixels = width * height;
        final float totalReqPixelsCap = reqWidth * reqHeight * 2;

        while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
            inSampleSize++;
        }
        return inSampleSize;
    }
}

Dimensions are same after compressing Bitmap.

How did I checked ?

Bitmap beforeBitmap = BitmapFactory.decodeFile("Your_Image_Path_Here");
Log.i("Before Compress Dimension", beforeBitmap.getWidth()+"-"+beforeBitmap.getHeight());

Bitmap afterBitmap = ImageUtils.getInstant().getCompressedBitmap("Your_Image_Path_Here");
Log.i("After Compress Dimension", afterBitmap.getWidth() + "-" + afterBitmap.getHeight());

Output:

Before Compress : Dimension: 1080-1452
After Compress : Dimension: 1080-1452

Hope this will help you.

Python - Module Not Found

You need to make sure the module is installed for all versions of python

You can check to see if a module is installed for python by running:

pip uninstall moduleName

If it is installed, it will ask you if you want to delete it or not. My issue was that it was installed for python, but not for python3. To check to see if a module is installed for python3, run:

python3 -m pip uninstall moduleName

After doing this, if you find that a module is not installed for one or both versions, use these two commands to install the module.

  • pip install moduleName
  • python3 -m pip install moduleName

Show a popup/message box from a Windows batch file

You can invoke dll function from user32.dll i think Something like

Rundll32.exe user32.dll, MessageBox (0, "text", "titleText", {extra flags for like topmost messagebox e.t.c})

Typing it from my Phone, don't judge me... otherwise i would link the extra flags.

What does the following Oracle error mean: invalid column index

I had this problem in one legacy application that create prepared statement dynamically.

String firstName;
StringBuilder query =new StringBuilder("select id, name from employee where country_Code=1");
query.append("and  name like '");
query.append(firstName + "' ");
query.append("and ssn=?");
PreparedStatement preparedStatement =new prepareStatement(query.toString());

when it try to set value for ssn, it was giving invalid column index error, and finally found out that it is caused by firstName having ' within; that disturb the syntax.

How to remove youtube branding after embedding video in web page?

Since August 2018 showinfo and rel parameter doesn't work so answers which recommend to use them no longer works and modestbranding do not remove all logos

here is my tricky solution how to hide EVERYTHING

  1. Before you start you should realize that all youtube's info are sticks to the top and bottom of iframe(not video, that's important)

  2. Make iframe higher than real video height. In iframe parameters set height = width * 1.7 (or other multiplicator)

  3. Hide youtube's info under your header and footer with an absolute position at top and bottom of iframe wrapper element. Height of header and footer could be calculated as: iframeHeight - (iframeWidth * (9 / 16))) / 2. If you want fullscreen than you should hide it outside screen visible zone and set overflow to hidden

  4. In my case I use JS to destroy iframe after video is finished so user couldn't see youtube's offer with another videos

  5. Also important note: since iOS 12.2 is replacing Youtube's player by their own, width and height calculation should be done in constructor(in case of React) because iOS player arrival cause page resize ->possible width&height recalculation-> video rerender -> video pause

code example jsfiddle.net/s6tp2xfm

A disadvantage of this solution is that it stretches image placeholder.

enter image description here

that's how it could look like with custom controls

enter image description here

ClassCastException, casting Integer to Double

This means that your ArrayList has integers in some elements. The casting should work unless there's an integer in one of your elements.

One way to make sure that your arraylist has no integers is by declaring it as a Doubles array.

    ArrayList<Double> marks = new ArrayList<Double>();

Rotation of 3D vector?

I just wanted to mention that if speed is required, wrapping unutbu's code in scipy's weave.inline and passing an already existing matrix as a parameter yields a 20-fold decrease in the running time.

The code (in rotation_matrix_test.py):

import numpy as np
import timeit

from math import cos, sin, sqrt
import numpy.random as nr

from scipy import weave

def rotation_matrix_weave(axis, theta, mat = None):
    if mat == None:
        mat = np.eye(3,3)

    support = "#include <math.h>"
    code = """
        double x = sqrt(axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]);
        double a = cos(theta / 2.0);
        double b = -(axis[0] / x) * sin(theta / 2.0);
        double c = -(axis[1] / x) * sin(theta / 2.0);
        double d = -(axis[2] / x) * sin(theta / 2.0);

        mat[0] = a*a + b*b - c*c - d*d;
        mat[1] = 2 * (b*c - a*d);
        mat[2] = 2 * (b*d + a*c);

        mat[3*1 + 0] = 2*(b*c+a*d);
        mat[3*1 + 1] = a*a+c*c-b*b-d*d;
        mat[3*1 + 2] = 2*(c*d-a*b);

        mat[3*2 + 0] = 2*(b*d-a*c);
        mat[3*2 + 1] = 2*(c*d+a*b);
        mat[3*2 + 2] = a*a+d*d-b*b-c*c;
    """

    weave.inline(code, ['axis', 'theta', 'mat'], support_code = support, libraries = ['m'])

    return mat

def rotation_matrix_numpy(axis, theta):
    mat = np.eye(3,3)
    axis = axis/sqrt(np.dot(axis, axis))
    a = cos(theta/2.)
    b, c, d = -axis*sin(theta/2.)

    return np.array([[a*a+b*b-c*c-d*d, 2*(b*c-a*d), 2*(b*d+a*c)],
                  [2*(b*c+a*d), a*a+c*c-b*b-d*d, 2*(c*d-a*b)],
                  [2*(b*d-a*c), 2*(c*d+a*b), a*a+d*d-b*b-c*c]])

The timing:

>>> import timeit
>>> 
>>> setup = """
... import numpy as np
... import numpy.random as nr
... 
... from rotation_matrix_test import rotation_matrix_weave
... from rotation_matrix_test import rotation_matrix_numpy
... 
... mat1 = np.eye(3,3)
... theta = nr.random()
... axis = nr.random(3)
... """
>>> 
>>> timeit.repeat("rotation_matrix_weave(axis, theta, mat1)", setup=setup, number=100000)
[0.36641597747802734, 0.34883809089660645, 0.3459300994873047]
>>> timeit.repeat("rotation_matrix_numpy(axis, theta)", setup=setup, number=100000)
[7.180983066558838, 7.172032117843628, 7.180462837219238]

using jquery $.ajax to call a PHP function

I would stick with normal approach to call the file directly, but if you really want to call a function, have a look at JSON-RPC (JSON Remote Procedure Call).

You basically send a JSON string in a specific format to the server, e.g.

{ "method": "echo", "params": ["Hello JSON-RPC"], "id": 1}

which includes the function to call and the parameters of that function.

Of course the server has to know how to handle such requests.
Here is jQuery plugin for JSON-RPC and e.g. the Zend JSON Server as server implementation in PHP.


This might be overkill for a small project or less functions. Easiest way would be karim's answer. On the other hand, JSON-RPC is a standard.

Make a URL-encoded POST request using `http.NewRequest(...)`

URL-encoded payload must be provided on the body parameter of the http.NewRequest(method, urlStr string, body io.Reader) method, as a type that implements io.Reader interface.

Based on the sample code:

package main

import (
    "fmt"
    "net/http"
    "net/url"
    "strconv"
    "strings"
)

func main() {
    apiUrl := "https://api.com"
    resource := "/user/"
    data := url.Values{}
    data.Set("name", "foo")
    data.Set("surname", "bar")

    u, _ := url.ParseRequestURI(apiUrl)
    u.Path = resource
    urlStr := u.String() // "https://api.com/user/"

    client := &http.Client{}
    r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
    r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
    r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))

    resp, _ := client.Do(r)
    fmt.Println(resp.Status)
}

resp.Status is 200 OK this way.

How to ping a server only once from within a batch file?

if you want to use the name "ping.bat", a small trick is to use this code:

@echo off
cd\ 
ping google.com -t

Just add that "cd\" and you are fine... ;)

How to format a float in javascript?

There is no way to avoid inconsistent rounding for prices with x.xx5 as actual value using either multiplication or division. If you need to calculate correct prices client-side you should keep all amounts in cents. This is due to the nature of the internal representation of numeric values in JavaScript. Notice that Excel suffers from the same problems so most people wouldn't notice the small errors caused by this phenomen. However errors may accumulate whenever you add up a lot of calculated values, there is a whole theory around this involving the order of calculations and other methods to minimize the error in the final result. To emphasize on the problems with decimal values, please note that 0.1 + 0.2 is not exactly equal to 0.3 in JavaScript, while 1 + 2 is equal to 3.

Creating a URL in the controller .NET MVC

I know this is an old question, but just in case you are trying to do the same thing in ASP.NET Core, here is how you can create the UrlHelper inside an action:

var urlHelper = new UrlHelper(this.ControllerContext);

Or, you could just use the Controller.Url property if you inherit from Controller.

Delete terminal history in Linux

If you use bash, then the terminal history is saved in a file called .bash_history. Delete it, and history will be gone.

However, for MySQL the better approach is not to enter the password in the command line. If you just specify the -p option, without a value, then you will be prompted for the password and it won't be logged.

Another option, if you don't want to enter your password every time, is to store it in a my.cnf file. Create a file named ~/.my.cnf with something like:

[client]
user = <username>
password = <password>

Make sure to change the file permissions so that only you can read the file.

Of course, this way your password is still saved in a plaintext file in your home directory, just like it was previously saved in .bash_history.

Try catch statements in C

In C99, you can use setjmp/longjmp for non-local control flow.

Within a single scope, the generic, structured coding pattern for C in the presence of multiple resource allocations and multiple exits uses goto, like in this example. This is similar to how C++ implements destructor calls of automatic objects under the hood, and if you stick to this diligently, it should allow you for a certain degree of cleanness even in complex functions.

jquery variable syntax

The dollarsign as a prefix in the var name is a usage from the concept of the hungarian notation.

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

Because
$.ajax({type: "POST" - calls OPTIONS
$.post( - Calls POST

Both are different. Postman calls "POST" properly, but when we call it, it will be "OPTIONS".

For C# web services - Web API

Please add the following code in your web.config file under <system.webServer> tag. This will work:

<httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
    </customHeaders>
</httpProtocol>

Please make sure you are not doing any mistake in the Ajax call

jQuery

$.ajax({
    url: 'http://mysite.microsoft.sample.xyz.com/api/mycall',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    type: "POST", /* or type:"GET" or type:"PUT" */
    dataType: "json",
    data: {
    },
    success: function (result) {
        console.log(result);
    },
    error: function () {
        console.log("error");
    }
});

Note: If you are looking for downloading content from a third-party website then this will not help you. You can try the following code, but not JavaScript.

System.Net.WebClient wc = new System.Net.WebClient();
string str = wc.DownloadString("http://mysite.microsoft.sample.xyz.com/api/mycall");

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". in a Maven Project

Remove

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.16</version>
</dependency> 

slf4j-log4j12 is the log4j binding for slf4j you dont need to add another log4j dependency.

Added
Provide the log4j configuration in log4j.properties and add it to your class path. There are sample configurations here

or you can change your binding to

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.6.1</version>
</dependency>

if you are configuring slf4j due to some dependencies requiring it.

Why am I getting a NoClassDefFoundError in Java?

While it's possible that this is due to a classpath mismatch between compile-time and run-time, it's not necessarily true.

It is important to keep two or three different exceptions straight in our head in this case:

  1. java.lang.ClassNotFoundException This exception indicates that the class was not found on the classpath. This indicates that we were trying to load the class definition, and the class did not exist on the classpath.

  2. java.lang.NoClassDefFoundError This exception indicates that the JVM looked in its internal class definition data structure for the definition of a class and did not find it. This is different than saying that it could not be loaded from the classpath. Usually this indicates that we previously attempted to load a class from the classpath, but it failed for some reason - now we're trying to use the class again (and thus need to load it, since it failed last time), but we're not even going to try to load it, because we failed loading it earlier (and reasonably suspect that we would fail again). The earlier failure could be a ClassNotFoundException or an ExceptionInInitializerError (indicating a failure in the static initialization block) or any number of other problems. The point is, a NoClassDefFoundError is not necessarily a classpath problem.

AngularJS + JQuery : How to get dynamic content working in angularjs

Addition to @jwize's answer

Because angular.element(document).injector() was giving error injector is not defined So, I have created function that you can run after AJAX call or when DOM is changed using jQuery.

  function compileAngularElement( elSelector) {

        var elSelector = (typeof elSelector == 'string') ? elSelector : null ;  
            // The new element to be added
        if (elSelector != null ) {
            var $div = $( elSelector );

                // The parent of the new element
                var $target = $("[ng-app]");

              angular.element($target).injector().invoke(['$compile', function ($compile) {
                        var $scope = angular.element($target).scope();
                        $compile($div)($scope);
                        // Finally, refresh the watch expressions in the new element
                        $scope.$apply();
                    }]);
            }

        }

use it by passing just new element's selector. like this

compileAngularElement( '.user' ) ; 

Upload Image using POST form data in Python-requests

In case if you were to pass the image as part of JSON along with other attributes, you can use the below snippet.
client.py

import base64
import json                    

import requests

api = 'http://localhost:8080/test'
image_file = 'sample_image.png'

with open(image_file, "rb") as f:
    im_bytes = f.read()        
im_b64 = base64.b64encode(im_bytes).decode("utf8")

headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
  
payload = json.dumps({"image": im_b64, "other_key": "value"})
response = requests.post(api, data=payload, headers=headers)
try:
    data = response.json()     
    print(data)                
except requests.exceptions.RequestException:
    print(response.text)

server.py

import io
import json                    
import base64                  
import logging             
import numpy as np
from PIL import Image

from flask import Flask, request, jsonify, abort

app = Flask(__name__)          
app.logger.setLevel(logging.DEBUG)
  
  
@app.route("/test", methods=['POST'])
def test_method():         
    # print(request.json)      
    if not request.json or 'image' not in request.json: 
        abort(400)
             
    # get the base64 encoded string
    im_b64 = request.json['image']

    # convert it into bytes  
    img_bytes = base64.b64decode(im_b64.encode('utf-8'))

    # convert bytes data to PIL Image object
    img = Image.open(io.BytesIO(img_bytes))

    # PIL image object to numpy array
    img_arr = np.asarray(img)      
    print('img shape', img_arr.shape)

    # process your img_arr here    
    
    # access other keys of json
    # print(request.json['other_key'])

    result_dict = {'output': 'output_key'}
    return result_dict
  
  
def run_server_api():
    app.run(host='0.0.0.0', port=8080)
  
  
if __name__ == "__main__":     
    run_server_api()

How to delete multiple files at once in Bash on Linux?

A wild card would work nicely for this, although to be safe it would be best to make the use of the wild card as minimal as possible, so something along the lines of this:

rm -rf abc.log.2012-*

Although from the looks of it, are those just single files? The recursive option should not be necessary if none of those items are directories, so best to not use that, just for safety.

How to change the interval time on bootstrap carousel?

       <div class="carousel-inner text-right">
                  <div class="carousel-item active text-center" id="first"  data-interval="1000" >
                    <img src="images/slide-1.gif" alt="slide-1">
                  </div>
                  <div class="carousel-item  text-center" id="second"  data-interval="2000" >
                    <img src="images/slide-2.gif" alt="slide-2">
                  </div>
                  <div class="carousel-item  text-center" id="third"  data-interval="3000" >
                    <img src="images/slide-3.gif" alt="slide-3">
                  </div>
                  <div class="carousel-item text-center" id="four"  data-interval="5000" >
                    <img src="images/slide-4.gif" alt="slide-4">
                  </div>
                </div>

You can also change different slides.

Real differences between "java -server" and "java -client"?

This is really linked to HotSpot and the default option values (Java HotSpot VM Options) which differ between client and server configuration.

From Chapter 2 of the whitepaper (The Java HotSpot Performance Engine Architecture):

The JDK includes two flavors of the VM -- a client-side offering, and a VM tuned for server applications. These two solutions share the Java HotSpot runtime environment code base, but use different compilers that are suited to the distinctly unique performance characteristics of clients and servers. These differences include the compilation inlining policy and heap defaults.

Although the Server and the Client VMs are similar, the Server VM has been specially tuned to maximize peak operating speed. It is intended for executing long-running server applications, which need the fastest possible operating speed more than a fast start-up time or smaller runtime memory footprint.

The Client VM compiler serves as an upgrade for both the Classic VM and the just-in-time (JIT) compilers used by previous versions of the JDK. The Client VM offers improved run time performance for applications and applets. The Java HotSpot Client VM has been specially tuned to reduce application start-up time and memory footprint, making it particularly well suited for client environments. In general, the client system is better for GUIs.

So the real difference is also on the compiler level:

The Client VM compiler does not try to execute many of the more complex optimizations performed by the compiler in the Server VM, but in exchange, it requires less time to analyze and compile a piece of code. This means the Client VM can start up faster and requires a smaller memory footprint.

The Server VM contains an advanced adaptive compiler that supports many of the same types of optimizations performed by optimizing C++ compilers, as well as some optimizations that cannot be done by traditional compilers, such as aggressive inlining across virtual method invocations. This is a competitive and performance advantage over static compilers. Adaptive optimization technology is very flexible in its approach, and typically outperforms even advanced static analysis and compilation techniques.

Note: The release of jdk6 update 10 (see Update Release Notes:Changes in 1.6.0_10) tried to improve startup time, but for a different reason than the hotspot options, being packaged differently with a much smaller kernel.


G. Demecki points out in the comments that in 64-bit versions of JDK, the -client option is ignored for many years.
See Windows java command:

-client

Selects the Java HotSpot Client VM.
A 64-bit capable JDK currently ignores this option and instead uses the Java Hotspot Server VM.

Is it possible to set async:false to $.getJSON call

In my case, Jay D is right. I have to add this before the call.

$.ajaxSetup({
    async: false
});

In my previous code, I have this:

var jsonData= (function() {
    var result;
    $.ajax({
        type:'GET',
        url:'data.txt',
        dataType:'json',
        async:false,
        success:function(data){
            result = data;
        }
    });
    return result;
})();
alert(JSON.stringify(jsonData));

It works find. Then I change to

var jsonData= (function() {
    var result;
    $.getJSON('data.txt', {}, function(data){
      result = data;
    });
    return result;
})();
alert(JSON.stringify(jsonData));

The alert is undefined.

If I add those three lines, the alert shows the data again.

$.ajaxSetup({
    async: false
});
var jsonData= (function() {
    var result;
    $.getJSON('data.txt', {}, function(data){
      result = data;
    });
    return result;
})();
alert(JSON.stringify(jsonData));

Wait until all promises complete even if some rejected

Benjamin's answer offers a great abstraction for solving this issue, but I was hoping for a less abstracted solution. The explicit way to to resolve this issue is to simply call .catch on the internal promises, and return the error from their callback.

let a = new Promise((res, rej) => res('Resolved!')),
    b = new Promise((res, rej) => rej('Rejected!')),
    c = a.catch(e => { console.log('"a" failed.'); return e; }),
    d = b.catch(e => { console.log('"b" failed.'); return e; });

Promise.all([c, d])
  .then(result => console.log('Then', result)) // Then ["Resolved!", "Rejected!"]
  .catch(err => console.log('Catch', err));

Promise.all([a.catch(e => e), b.catch(e => e)])
  .then(result => console.log('Then', result)) // Then ["Resolved!", "Rejected!"]
  .catch(err => console.log('Catch', err));

Taking this one step further, you could write a generic catch handler that looks like this:

const catchHandler = error => ({ payload: error, resolved: false });

then you can do

> Promise.all([a, b].map(promise => promise.catch(catchHandler))
    .then(results => console.log(results))
    .catch(() => console.log('Promise.all failed'))
< [ 'Resolved!',  { payload: Promise, resolved: false } ]

The problem with this is that the caught values will have a different interface than the non-caught values, so to clean this up you might do something like:

const successHandler = result => ({ payload: result, resolved: true });

So now you can do this:

> Promise.all([a, b].map(result => result.then(successHandler).catch(catchHandler))
    .then(results => console.log(results.filter(result => result.resolved))
    .catch(() => console.log('Promise.all failed'))
< [ 'Resolved!' ]

Then to keep it DRY, you get to Benjamin's answer:

const reflect = promise => promise
  .then(successHandler)
  .catch(catchHander)

where it now looks like

> Promise.all([a, b].map(result => result.then(successHandler).catch(catchHandler))
    .then(results => console.log(results.filter(result => result.resolved))
    .catch(() => console.log('Promise.all failed'))
< [ 'Resolved!' ]

The benefits of the second solution are that its abstracted and DRY. The downside is you have more code, and you have to remember to reflect all your promises to make things consistent.

I would characterize my solution as explicit and KISS, but indeed less robust. The interface doesn't guarantee that you know exactly whether the promise succeeded or failed.

For example you might have this:

const a = Promise.resolve(new Error('Not beaking, just bad'));
const b = Promise.reject(new Error('This actually didnt work'));

This won't get caught by a.catch, so

> Promise.all([a, b].map(promise => promise.catch(e => e))
    .then(results => console.log(results))
< [ Error, Error ]

There's no way to tell which one was fatal and which was wasn't. If that's important then you're going to want to enforce and interface that tracks whether it was successful or not (which reflect does).

If you just want to handle errors gracefully, then you can just treat errors as undefined values:

> Promise.all([a.catch(() => undefined), b.catch(() => undefined)])
    .then((results) => console.log('Known values: ', results.filter(x => typeof x !== 'undefined')))
< [ 'Resolved!' ]

In my case, I don't need to know the error or how it failed--I just care whether I have the value or not. I'll let the function that generates the promise worry about logging the specific error.

const apiMethod = () => fetch()
  .catch(error => {
    console.log(error.message);
    throw error;
  });

That way, the rest of the application can ignore its error if it wants, and treat it as an undefined value if it wants.

I want my high level functions to fail safely and not worry about the details on why its dependencies failed, and I also prefer KISS to DRY when I have to make that tradeoff--which is ultimately why I opted to not use reflect.

React Router v4 - How to get current route?

Add

import {withRouter} from 'react-router-dom';

Then change your component export

export default withRouter(ComponentName)

Then you can access the route directly within the component itself (without touching anything else in your project) using:

window.location.pathname

Tested March 2020 with: "version": "5.1.2"

jQuery validate Uncaught TypeError: Cannot read property 'nodeName' of null

I had this problem and it was because the panel was outside of the [data-role="page"] element.

mySQL Error 1040: Too Many Connection

Try this :

open the terminal and type this command : sudo gedit /etc/mysql/my.cnf

Paste the line in my.cnf file: set-variable=max_connections=500

How do I move a file from one location to another in Java?

With Java 7 or newer you can use Files.move(from, to, CopyOption... options).

E.g.

Files.move(Paths.get("/foo.txt"), Paths.get("bar.txt"), StandardCopyOption.REPLACE_EXISTING);

See the Files documentation for more details

Determine when a ViewPager changes pages

Use the ViewPager.onPageChangeListener:

viewPager.addOnPageChangeListener(new OnPageChangeListener() {
    public void onPageScrollStateChanged(int state) {}
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

    public void onPageSelected(int position) {
        // Check if this is the page you want.
    }
});

java.util.zip.ZipException: error in opening zip file

I saw this with a specific Zip-file with Java 6, but it went away when I upgrade to Java 8 (did not test Java 7), so it seems newer versions of ZipFile in Java support more compression algorithms and thus can read files which fail with earlier versions.

Including non-Python files with setup.py

Figured out a workaround: I renamed my lgpl2.1_license.txt to lgpl2.1_license.txt.py, and put some triple quotes around the text. Now I don't need to use the data_files option nor to specify any absolute paths. Making it a Python module is ugly, I know, but I consider it less ugly than specifying absolute paths.

How to revert uncommitted changes including files and folders?

Use "git checkout -- ..." to discard changes in working directory

git checkout -- app/views/posts/index.html.erb

or

git checkout -- *

removes all changes made to unstaged files in git status eg

modified:    app/controllers/posts.rb
modified:    app/views/posts/index.html.erb

Are HTTPS URLs encrypted?

As the other answers have already pointed out, https "URLs" are indeed encrypted. However, your DNS request/response when resolving the domain name is probably not, and of course, if you were using a browser, your URLs might be recorded too.

href="tel:" and mobile numbers

When dialing a number within the country you are in, you still need to dial the national trunk number before the rest of the number. For example, in Australia one would dial:

   0 - trunk prefix
   2 - Area code for New South Wales
6555 - STD code for a specific telephone exchange
1234 - Telephone Exchange specific extension.

For a mobile phone this becomes

   0 -      trunk prefix
   4 -      Area code for a mobile telephone
1234 5678 - Mobile telephone number

Now, when I want to dial via the international trunk, you need to drop the trunk prefix and replace it with the international dialing prefix

   + -      Short hand for the country trunk number
  61 -      Country code for Australia
   4 -      Area code for a mobile telephone
1234 5678 - Mobile telephone number

This is why you often find that the first digit of a telephone number is dropped when dialling internationally, even when using international prefixing to dial within the same country.

So as per the trunk prefix for Germany drop the 0 and add the +49 for Germany's international calling code (for example) giving:

_x000D_
_x000D_
<a href="tel:+496170961709" class="Blondie">_x000D_
    Call me, call me any, anytime_x000D_
      <b>Call me (call me) I'll arrive</b>_x000D_
        When you're ready we can share the wine!_x000D_
</a>
_x000D_
_x000D_
_x000D_

RHEL 6 - how to install 'GLIBC_2.14' or 'GLIBC_2.15'?

This often occurs when you build software in RHEL 7 and try to run on RHEL 6.

To update GLIBC to any version, simply download the package from

https://ftp.gnu.org/gnu/libc/

For example glibc-2.14.tar.gz in your case.

1. tar xvfz glibc-2.14.tar.gz
2. cd glibc-2.14
3. mkdir build
4. cd build
5. ../configure --prefix=/opt/glibc-2.14
6. make
7. sudo make install
8. export LD_LIBRARY_PATH=/opt/glibc-2.14/lib:$LD_LIBRARY_PATH

Then try to run your software, glibc-2.14 should be linked.

How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

This answer, but with storyboard support.

class SwipeNavigationController: UINavigationController {

    // MARK: - Lifecycle

    override init(rootViewController: UIViewController) {
        super.init(rootViewController: rootViewController)
    }

    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)

        self.setup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        self.setup()
    }

    private func setup() {
        delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // This needs to be in here, not in init
        interactivePopGestureRecognizer?.delegate = self
    }

    deinit {
        delegate = nil
        interactivePopGestureRecognizer?.delegate = nil
    }

    // MARK: - Overrides

    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        duringPushAnimation = true

        super.pushViewController(viewController, animated: animated)
    }

    // MARK: - Private Properties

    fileprivate var duringPushAnimation = false
}

Where do I call the BatchNormalization function in Keras?

This thread is misleading. Tried commenting on Lucas Ramadan's answer, but I don't have the right privileges yet, so I'll just put this here.

Batch normalization works best after the activation function, and here or here is why: it was developed to prevent internal covariate shift. Internal covariate shift occurs when the distribution of the activations of a layer shifts significantly throughout training. Batch normalization is used so that the distribution of the inputs (and these inputs are literally the result of an activation function) to a specific layer doesn't change over time due to parameter updates from each batch (or at least, allows it to change in an advantageous way). It uses batch statistics to do the normalizing, and then uses the batch normalization parameters (gamma and beta in the original paper) "to make sure that the transformation inserted in the network can represent the identity transform" (quote from original paper). But the point is that we're trying to normalize the inputs to a layer, so it should always go immediately before the next layer in the network. Whether or not that's after an activation function is dependent on the architecture in question.

ProgressDialog in AsyncTask

This question is already answered and most of the answers here are correct but they don't solve one major issue with config changes. Have a look at this article https://androidresearch.wordpress.com/2013/05/10/dealing-with-asynctask-and-screen-orientation/ if you would like to write a async task in a better way.

How to clear Facebook Sharer cache?

This answer is intended for developers.

Clearing the cache means that new shares of this webpage will show the new content which is provided in the OG tags. But only if the URL that you are working on has less than 50 interactions (likes + shares). It will also not affect old links to this webpage which have already been posted on Facebook. Only when sharing the URL on Facebook again will the way that Facebook shows the link be updated.

catandmouse's answer is correct but you can also make Facebook clear the OG (OpenGraph) cache by sending a post request to graph.facebook.com (works for both http and https as of the writing of this answer). You do not need an access token.

A post request to graph.facebook.com may look as follows:

POST / HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: graph.facebook.com
Content-Length: 63
Accept-Encoding: gzip
User-Agent: Mojolicious (Perl)

id=<url_encoded_url>&scrape=true

In Perl, you can use the following code where the library Mojo::UserAgent is used to send and receive HTTP requests:

sub _clear_og_cache_on_facebook {
    my $fburl     = "http://graph.facebook.com";
    my $ua        = Mojo::UserAgent->new;
    my $clearurl  = <the url you want Facebook to forget>;
    my $post_body = {id => $clearurl, scrape => 'true'};
    my $res       = $ua->post($fburl => form => $post_body)->res;
    my $code      = $res->code;
    unless ($code eq '200') {
        Log->warn("Clearing cached OG data for $clearurl failed with code $code.");
        }
    }
}

Sending this post request through the terminal can be done with the following command:

curl -F id="<URL>" -F scrape=true graph.facebook.com

LINQ: combining join and group by

I met the same problem as you.

I push two tables result into t1 object and group t1.

 from p in Products                         
  join bp in BaseProducts on p.BaseProductId equals bp.Id
  select new {
   p,
   bp
  } into t1
 group t1 by t1.p.SomeId into g
 select new ProductPriceMinMax { 
  SomeId = g.FirstOrDefault().p.SomeId, 
  CountryCode = g.FirstOrDefault().p.CountryCode, 
  MinPrice = g.Min(m => m.bp.Price), 
  MaxPrice = g.Max(m => m.bp.Price),
  BaseProductName = g.FirstOrDefault().bp.Name
};

Plotting dates on the x-axis with Python's matplotlib

I have too low reputation to add comment to @bernie response, with response to @user1506145. I have run in to same issue.

1

The answer to it is a interval parameter which fixes things up

2

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
import datetime as dt

np.random.seed(1)

N = 100
y = np.random.rand(N)

now = dt.datetime.now()
then = now + dt.timedelta(days=100)
days = mdates.drange(now,then,dt.timedelta(days=1))

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=5))
plt.plot(days,y)
plt.gcf().autofmt_xdate()
plt.show()

How do I 'svn add' all unversioned files to SVN?

svn add --force * --auto-props --parents --depth infinity -q

Great tip! One remark: my Eclipse adds new files to the ignore list automatically. It may be a matter of configuration, but anyhow: there is the --no-ignore option that helps.

After this, you can commit:

svn commit -m 'Adding a file'

How to remove listview all items

if you used List object and passed to the adapter you can remove the value from the List object and than call the notifyDataSetChanged() using adapter object.

for e.g.

List<String> list = new ArrayList<String>();
ArrayAdapter adapter;


adapter = new ArrayAdapter<String>(DeleteManyTask.this, 
            android.R.layout.simple_list_item_1,
            (String[])list.toArray(new String[0]));

listview = (ListView) findViewById(R.id.list);
listview.setAdapter(adapter);

listview.setAdapter(listAdapter);

for remove do this way

list.remove(index); //or
list.clear();
adpater.notifyDataSetChanged();

or without list object remove item from list.

adapter.clear();
adpater.notifyDataSetChanged();

How to upgrade OpenSSL in CentOS 6.5 / Linux / Unix from source?

You can also check the local changelog to verify whether or not OpenSSL is patched against the vulnerability with the following command:

rpm -q --changelog openssl | grep CVE-2014-0224

If a result is not returned, then you must patch OpenSSL.

http://www.liquidweb.com/kb/update-and-patch-openssl-for-the-ccs-injection-vulnerability/

Check if textbox has empty value

Use the following to check if text box is empty or have more than 1 white spaces

var name = jQuery.trim($("#ContactUsName").val());

if ((name.length == 0))
{
    Your code 
}
else
{
    Your code
}

How to get image height and width using java?

This is a rewrite of the great post by @Kay, which throws IOException and provides an early exit:

/**
 * Gets image dimensions for given file 
 * @param imgFile image file
 * @return dimensions of image
 * @throws IOException if the file is not a known image
 */
public static Dimension getImageDimension(File imgFile) throws IOException {
  int pos = imgFile.getName().lastIndexOf(".");
  if (pos == -1)
    throw new IOException("No extension for file: " + imgFile.getAbsolutePath());
  String suffix = imgFile.getName().substring(pos + 1);
  Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix);
  while(iter.hasNext()) {
    ImageReader reader = iter.next();
    try {
      ImageInputStream stream = new FileImageInputStream(imgFile);
      reader.setInput(stream);
      int width = reader.getWidth(reader.getMinIndex());
      int height = reader.getHeight(reader.getMinIndex());
      return new Dimension(width, height);
    } catch (IOException e) {
      log.warn("Error reading: " + imgFile.getAbsolutePath(), e);
    } finally {
      reader.dispose();
    }
  }

  throw new IOException("Not a known image file: " + imgFile.getAbsolutePath());
}

I guess my rep is not high enough for my input to be considered worthy as a reply.

Structure of a PDF file?

Here's the raw reference of PDF 1.7, and here's an article describing the structure of a PDF file. If you use Vim, the pdftk plugin is a good way to explore the document in an ever-so-slightly less raw form, and the pdftk utility itself (and its GPL source) is a great way to tease documents apart.

Correct way to remove plugin from Eclipse

I'm using Eclipse Kepler release. There is no Installation Details or About Eclipse menu item under help. For me, it was Help | Eclipse Marketplace...

I had to click on the "Installed" tab. The plug-in I wanted to remove was listed there, with an "Uninstall" option.

Calculate percentage Javascript

To get the percentage of a number, we need to multiply the desired percentage percent by that number. In practice we will have:

function percentage(percent, total) {
    return ((percent/ 100) * total).toFixed(2)
}

Example of usage:

const percentResult = percentage(10, 100);
// print 10.00

.toFixed() is optional for monetary formats.

How can I force component to re-render with hooks in React?

React Hooks FAQ official solution for forceUpdate:

const [_, forceUpdate] = useReducer((x) => x + 1, 0);
// usage
<button onClick={forceUpdate}>Force update</button>

Working example

_x000D_
_x000D_
const App = () => {
  const [_, forceUpdate] = useReducer((x) => x + 1, 0);

  return (
    <div>
      <button onClick={forceUpdate}>Force update</button>
      <p>Forced update {_} times</p>
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.10.1/umd/react.production.min.js" integrity="sha256-vMEjoeSlzpWvres5mDlxmSKxx6jAmDNY4zCt712YCI0=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.10.1/umd/react-dom.production.min.js" integrity="sha256-QQt6MpTdAD0DiPLhqhzVyPs1flIdstR4/R7x4GqCvZ4=" crossorigin="anonymous"></script>
<script>var useReducer = React.useReducer</script>
<div id="root"></div>
_x000D_
_x000D_
_x000D_

How to stretch a table over multiple pages

You should \usepackage{longtable}.

What is the difference between CHARACTER VARYING and VARCHAR in PostgreSQL?

The PostgreSQL documentation on Character Types is a good reference for this. They are two different names for the same type.

How can I stop a running MySQL query?

mysql>show processlist;

mysql> kill "number from first col";

How does autowiring work in Spring?

Standard way:

@RestController
public class Main {
    UserService userService;

    public Main(){
        userService = new UserServiceImpl();
    }

    @GetMapping("/")
    public String index(){
        return userService.print("Example test");
    }
}

User service interface:

public interface UserService {
    String print(String text);
}

UserServiceImpl class:

public class UserServiceImpl implements UserService {
    @Override
    public String print(String text) {
        return text + " UserServiceImpl";
    }
}

Output: Example test UserServiceImpl

That is a great example of tight coupled classes, bad design example and there will be problem with testing (PowerMockito is also bad).

Now let's take a look at SpringBoot dependency injection, nice example of loose coupling:

Interface remains the same,

Main class:

@RestController
public class Main {
    UserService userService;

    @Autowired
    public Main(UserService userService){
        this.userService = userService;
    }

    @GetMapping("/")
    public String index(){
        return userService.print("Example test");
    }
}

ServiceUserImpl class:

@Component
public class UserServiceImpl implements UserService {
    @Override
    public String print(String text) {
        return text + " UserServiceImpl";
    }
}

Output: Example test UserServiceImpl

and now it's easy to write test:

@RunWith(MockitoJUnitRunner.class)
public class MainTest {
    @Mock
    UserService userService;

    @Test
    public void indexTest() {
        when(userService.print("Example test")).thenReturn("Example test UserServiceImpl");

        String result = new Main(userService).index();

        assertEquals(result, "Example test UserServiceImpl");
    }
}

I showed @Autowired annotation on constructor but it can also be used on setter or field.

Writing to a file in a for loop

The main problem was that you were opening/closing files repeatedly inside your loop.

Try this approach:

with open('new.txt') as text_file, open('xyz.txt', 'w') as myfile:  
    for line in text_file:
        var1, var2 = line.split(",");
        myfile.write(var1+'\n')

We open both files at once and because we are using with they will be automatically closed when we are done (or an exception occurs). Previously your output file was repeatedly openend inside your loop.

We are also processing the file line-by-line, rather than reading all of it into memory at once (which can be a problem when you deal with really big files).

Note that write() doesn't append a newline ('\n') so you'll have to do that yourself if you need it (I replaced your writelines() with write() as you are writing a single item, not a list of items).

When opening a file for rread, the 'r' is optional since it's the default mode.

jQuery ajax post file field

This should help. How can I upload files asynchronously?

As the post suggest I recommend a plugin located here http://malsup.com/jquery/form/#code-samples

Warning: mysql_connect(): Access denied for user 'root'@'localhost' (using password: YES)

try $conn = mysql_connect("localhost", "root") or $conn = mysql_connect("localhost", "root", "")

MySQL combine two columns into one column

This is the only solution that would work for me, when I required a space in between the columns being merged.

select concat(concat(column1,' '), column2)

How do you get an iPhone's device name

In Unity, using C#:

SystemInfo.deviceName;

Seeing the underlying SQL in the Spring JdbcTemplate?

I'm not 100% sure what you're getting at since usually you will pass in your SQL queries (parameterized or not) to the JdbcTemplate, in which case you would just log those. If you have PreparedStatements and you don't know which one is being executed, the toString method should work fine. But while we're on the subject, there's a nice Jdbc logger package here which will let you automatically log your queries as well as see the bound parameters each time. Very useful. The output looks something like this:

executing PreparedStatement: 'insert into ECAL_USER_APPT
(appt_id, user_id, accepted, scheduler, id) values (?, ?, ?, ?, null)'
     with bind parameters: {1=25, 2=49, 3=1, 4=1} 

Scroll RecyclerView to show selected item on top

I use the code below to smooth-scroll an item (thisView) to the top.
It works also for GridLayoutManager with views of different heights:

View firstView = mRecyclerView.getChildAt(0);
int toY = firstView.getTop();
int firstPosition = mRecyclerView.getChildAdapterPosition(firstView);
View thisView = mRecyclerView.getChildAt(thisPosition - firstPosition);
int fromY = thisView.getTop();

mRecyclerView.smoothScrollBy(0, fromY - toY);

Seems to work good enough for a quick solution.

How to convert an NSString into an NSNumber

I think NSDecimalNumber will do it:

Example:

NSNumber *theNumber = [NSDecimalNumber decimalNumberWithString:[stringVariable text]]];

NSDecimalNumber is a subclass of NSNumber, so implicit casting allowed.

Leaflet changing Marker color

Write a function which, given a color (or any other characteristics), returns an SVG representation of the desired icon. Then, when creating the marker, reference this function with the appropriate parameter(s).

How to make a input field readonly with JavaScript?

Try This :

document.getElementById(<element_ID>).readOnly=true;

Objective-C: Extract filename from path string

Taken from the NSString reference, you can use :

NSString *theFileName = [[string lastPathComponent] stringByDeletingPathExtension];

The lastPathComponent call will return thefile.ext, and the stringByDeletingPathExtension will remove the extension suffix from the end.

Java better way to delete file if exists

This is my solution:

File f = new File("file.txt");
if(f.exists() && !f.isDirectory()) { 
    f.delete();
}

Create unique constraint with null columns

Create two partial indexes:

CREATE UNIQUE INDEX favo_3col_uni_idx ON favorites (user_id, menu_id, recipe_id)
WHERE menu_id IS NOT NULL;

CREATE UNIQUE INDEX favo_2col_uni_idx ON favorites (user_id, recipe_id)
WHERE menu_id IS NULL;

This way, there can only be one combination of (user_id, recipe_id) where menu_id IS NULL, effectively implementing the desired constraint.

Possible drawbacks: you cannot have a foreign key referencing (user_id, menu_id, recipe_id), you cannot base CLUSTER on a partial index, and queries without a matching WHERE condition cannot use the partial index. (It seems unlikely you'd want a FK reference three columns wide - use the PK column instead).

If you need a complete index, you can alternatively drop the WHERE condition from favo_3col_uni_idx and your requirements are still enforced.
The index, now comprising the whole table, overlaps with the other one and gets bigger. Depending on typical queries and the percentage of NULL values, this may or may not be useful. In extreme situations it might even help to maintain all three indexes (the two partial ones and a total on top).

Aside: I advise not to use mixed case identifiers in PostgreSQL.

Delete files or folder recursively on Windows CMD

Use the Windows rmdir command

That is, rmdir /S /Q C:\Temp

I'm also using the ones below for some years now, flawlessly.

Check out other options with: forfiles /?

Delete SQM/Telemetry in windows folder recursively

forfiles /p %SYSTEMROOT%\system32\LogFiles /s /m *.* /d -1 /c "cmd /c del @file"

Delete windows TMP files recursively

forfiles /p %SYSTEMROOT%\Temp /s /m *.* /d -1 /c "cmd /c del @file"

Delete user TEMP files and folders recursively

forfiles /p %TMP% /s /m *.* /d -1 /c "cmd /c del @file"

java.lang.OutOfMemoryError: GC overhead limit exceeded

Don't store the whole structure in memory while waiting to get to the end.

Write intermediate results to a temporary table in the database instead of hashmaps - functionally, a database table is the equivalent of a hashmap, i.e. both support keyed access to data, but the table is not memory bound, so use an indexed table here rather than the hashmaps.

If done correctly, your algorithm should not even notice the change - correctly here means to use a class to represent the table, even giving it a put(key, value) and a get(key) method just like a hashmap.

When the intermediate table is complete, generate the required sql statement(s) from it instead of from memory.

Setting Camera Parameters in OpenCV/Python

I wasn't able to fix the problem OpenCV either, but a video4linux (V4L2) workaround does work with OpenCV when using Linux. At least, it does on my Raspberry Pi with Rasbian and my cheap webcam. This is not as solid, light and portable as you'd like it to be, but for some situations it might be very useful nevertheless.

Make sure you have the v4l2-ctl application installed, e.g. from the Debian v4l-utils package. Than run (before running the python application, or from within) the command:

v4l2-ctl -d /dev/video1 -c exposure_auto=1 -c exposure_auto_priority=0 -c exposure_absolute=10

It overwrites your camera shutter time to manual settings and changes the shutter time (in ms?) with the last parameter to (in this example) 10. The lower this value, the darker the image.

c++ array assignment of multiple values

You have to replace the values one by one such as in a for-loop or copying another array over another such as using memcpy(..) or std::copy

e.g.

for (int i = 0; i < arrayLength; i++) {
    array[i] = newValue[i];
}

Take care to ensure proper bounds-checking and any other checking that needs to occur to prevent an out of bounds problem.

"The POM for ... is missing, no dependency information available" even though it exists in Maven Repository

If the POM missing warning is of project's self module, the reason is that you are trying to mistakenly build from a sub-module directory. You need to run the build and install command from root directory of the project.

How to post data using HttpClient?

You need to use:

await client.PostAsync(uri, content);

Something like that:

var comment = "hello world";
var questionId = 1;

var formContent = new FormUrlEncodedContent(new[]
{
    new KeyValuePair<string, string>("comment", comment), 
    new KeyValuePair<string, string>("questionId", questionId) 
});

var myHttpClient = new HttpClient();
var response = await myHttpClient.PostAsync(uri.ToString(), formContent);

And if you need to get the response after post, you should use:

var stringContent = await response.Content.ReadAsStringAsync();

Hope it helps ;)

How can I rename a single column in a table at select?

select table1.price, table2.price as other_price .....

How do I create a link using javascript?

<html>
  <head></head>
  <body>
    <script>
      var a = document.createElement('a');
      var linkText = document.createTextNode("my title text");
      a.appendChild(linkText);
      a.title = "my title text";
      a.href = "http://example.com";
      document.body.appendChild(a);
    </script>
  </body>
</html>

How to check if a particular service is running on Ubuntu

For centos, below command worked for me (:

locate postgres | grep service

Output:

/usr/lib/firewalld/services/postgresql.xml

/usr/lib/systemd/system/postgresql-9.3.service

sudo systemctl status postgresql-9.3.service

How to remove rows with any zero value

I prefer a simple adaptation of csgillespie's method, foregoing the need of a function definition:

d[apply(d!=0, 1, all),]

where d is your data frame.

Combining two sorted lists in Python

People seem to be over complicating this.. Just combine the two lists, then sort them:

>>> l1 = [1, 3, 4, 7]
>>> l2 = [0, 2, 5, 6, 8, 9]
>>> l1.extend(l2)
>>> sorted(l1)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

..or shorter (and without modifying l1):

>>> sorted(l1 + l2)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

..easy! Plus, it's using only two built-in functions, so assuming the lists are of a reasonable size, it should be quicker than implementing the sorting/merging in a loop. More importantly, the above is much less code, and very readable.

If your lists are large (over a few hundred thousand, I would guess), it may be quicker to use an alternative/custom sorting method, but there are likely other optimisations to be made first (e.g not storing millions of datetime objects)

Using the timeit.Timer().repeat() (which repeats the functions 1000000 times), I loosely benchmarked it against ghoseb's solution, and sorted(l1+l2) is substantially quicker:

merge_sorted_lists took..

[9.7439379692077637, 9.8844599723815918, 9.552299976348877]

sorted(l1+l2) took..

[2.860386848449707, 2.7589840888977051, 2.7682540416717529]

How to enable bulk permission in SQL Server

Try GRANT ADMINISTER BULK OPERATIONS TO [server_login]. It is a server level permission, not a database level. This has fixed a similar issue for me in that past (using OPENROWSET I believe).

How to set up a squid Proxy with basic username and password authentication?

Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)

Basic squid conf

/etc/squid3/squid.conf instead of the super bloated default config file

auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

# Choose the port you want. Below we set it to default 3128.
http_port 3128

Please note the basic_ncsa_auth program instead of the old ncsa_auth

squid 2.x

For squid 2.x you need to edit /etc/squid/squid.conf file and place:

auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Setting up a user

sudo htpasswd -c /etc/squid3/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid3 restart

squid 2.x

sudo htpasswd -c /etc/squid/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid restart

htdigest vs htpasswd

For the many people that asked me: the 2 tools produce different file formats:

  • htdigest stores the password in plain text.
  • htpasswd stores the password hashed (various hashing algos are available)

Despite this difference in format basic_ncsa_auth will still be able to parse a password file generated with htdigest. Hence you can alternatively use:

sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like

Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.

On Ubuntu 14.04 htdigest and htpasswd are both available in the [apache2-utils][1] package.

MacOS

Similar as above applies, but file paths are different.

Install squid

brew install squid

Start squid service

brew services start squid

Squid config file is stored at /usr/local/etc/squid.conf.

Comment or remove following line:

http_access allow localnet

Then similar to linux config (but with updated paths) add this:

auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Note that path to basic_ncsa_auth may be different since it depends on installed version when using brew, you can verify this with ls /usr/local/Cellar/squid/. Also note that you should add the above just bellow the following section:

#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#

Now generate yourself a user:password basic auth credential (note: htpasswd and htdigest are also both available on MacOS)

htpasswd -c /usr/local/etc/squid_passwords username_you_like

Restart the squid service

brew services restart squid

Artificially create a connection timeout error

There are a couple of tactics I've used in the past to simulate networking issues;

  1. Pull out the network cable
  2. Switch off the switch (ideally with the switch that the computer is plugged into still being powered so the machine maintains it's "network connection") between your machine and the "target" machine
  3. Run firewall software on the target machine that silently drops received data

One of these ideas might give you some means of artifically generating the scenario you need

How to scroll the page when a modal dialog is longer than the screen?

Here is my demo of modal window that auto-resize to its content and starts scrolling when it does not fit the window.

Modal window demo (see comments in the HTML source code)

All done only with HTML and CSS - no JS required to display and resize the modal window (but you still need it to display the window of course - in new version you don't need JS at all).

Update (more demos):

The point is to have outer and inner DIVs where the outer one defines the fixed position and the inner creates the scrolling. (In the demo there are actually more DIVs to make them look like an actual modal window.)

        #modal {
            position: fixed;
            transform: translate(0,0);
            width: auto; left: 0; right: 0;
            height: auto; top: 0; bottom: 0;
            z-index: 990; /* display above everything else */
            padding: 20px; /* create padding for inner window - page under modal window will be still visible */
        }

        #modal .outer {
            box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; -o-box-sizing: border-box;
            width: 100%;
            height: 100%;
            position: relative;
            z-index: 999;
        }

        #modal .inner {
            box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; -o-box-sizing: border-box;
            width: 100%;
            height: auto;       /* allow to fit content (if smaller)... */
            max-height: 100%;   /* ... but make sure it does not overflow browser window */

            /* allow vertical scrolling if required */
            overflow-x: hidden;
            overflow-y: auto;

            /* definition of modal window layout */
            background: #ffffff;
            border: 2px solid #222222;
            border-radius: 16px; /* some nice (modern) round corners */
            padding: 16px;       /* make sure inner elements does not overflow round corners */
        }

What is the question mark for in a Typescript parameter name

parameter?: type is a shorthand for parameter: type | undefined

Plotting two variables as lines using ggplot2 on the same graph

I am also new to R but trying to understand how ggplot works I think I get another way to do it. I just share probably not as a complete perfect solution but to add some different points of view.

I know ggplot is made to work with dataframes better but maybe it can be also sometimes useful to know that you can directly plot two vectors without using a dataframe.

Loading data. Original date vector length is 100 while var0 and var1 have length 50 so I only plot the available data (first 50 dates).

var0 <- 100 + c(0, cumsum(runif(49, -20, 20)))
var1 <- 150 + c(0, cumsum(runif(49, -10, 10)))
date <- seq(as.Date("2002-01-01"), by="1 month", length.out=50)    

Plotting

ggplot() + geom_line(aes(x=date,y=var0),color='red') + 
           geom_line(aes(x=date,y=var1),color='blue') + 
           ylab('Values')+xlab('date')

enter image description here

However I was not able to add a correct legend using this format. Does anyone know how?

Multi-gradient shapes

You CAN do it using only xml shapes - just use layer-list AND negative padding like this:

    <layer-list>

        <item>
            <shape>
                <solid android:color="#ffffff" />

                <padding android:top="20dp" />
            </shape>
        </item>

        <item>
            <shape>
                <gradient android:endColor="#ffffff" android:startColor="#efefef" android:type="linear" android:angle="90" />

                <padding android:top="-20dp" />
            </shape>
        </item>

    </layer-list>

Saving timestamp in mysql table using php

$created_date = date("Y-m-d H:i:s");
$sql = "INSERT INTO $tbl_name(created_date)VALUES('$created_date')";
$result = mysql_query($sql);

What does it mean to bind a multicast (UDP) socket?

To bind a UDP socket when receiving multicast means to specify an address and port from which to receive data (NOT a local interface, as is the case for TCP acceptor bind). The address specified in this case has a filtering role, i.e. the socket will only receive datagrams sent to that multicast address & port, no matter what groups are subsequently joined by the socket. This explains why when binding to INADDR_ANY (0.0.0.0) I received datagrams sent to my multicast group, whereas when binding to any of the local interfaces I did not receive anything, even though the datagrams were being sent on the network to which that interface corresponded.

Quoting from UNIX® Network Programming Volume 1, Third Edition: The Sockets Networking API by W.R Stevens. 21.10. Sending and Receiving

[...] We want the receiving socket to bind the multicast group and port, say 239.255.1.2 port 8888. (Recall that we could just bind the wildcard IP address and port 8888, but binding the multicast address prevents the socket from receiving any other datagrams that might arrive destined for port 8888.) We then want the receiving socket to join the multicast group. The sending socket will send datagrams to this same multicast address and port, say 239.255.1.2 port 8888.

String's Maximum length in Java - calling length() method

I have a 2010 iMac with 8GB of RAM, running Eclipse Neon.2 Release (4.6.2) with Java 1.8.0_25. With the VM argument -Xmx6g, I ran the following code:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < Integer.MAX_VALUE; i++) {
    try {
        sb.append('a');
    } catch (Throwable e) {
        System.out.println(i);
        break;
    }
}
System.out.println(sb.toString().length());

This prints:

Requested array size exceeds VM limit
1207959550

So, it seems that the max array size is ~1,207,959,549. Then I realized that we don't actually care if Java runs out of memory: we're just looking for the maximum array size (which seems to be a constant defined somewhere). So:

for (int i = 0; i < 1_000; i++) {
    try {
        char[] array = new char[Integer.MAX_VALUE - i];
        Arrays.fill(array, 'a');
        String string = new String(array);
        System.out.println(string.length());
    } catch (Throwable e) {
        System.out.println(e.getMessage());
        System.out.println("Last: " + (Integer.MAX_VALUE - i));
        System.out.println("Last: " + i);
    }
}

Which prints:

Requested array size exceeds VM limit
Last: 2147483647
Last: 0
Requested array size exceeds VM limit
Last: 2147483646
Last: 1
Java heap space
Last: 2147483645
Last: 2

So, it seems the max is Integer.MAX_VALUE - 2, or (2^31) - 3

P.S. I'm not sure why my StringBuilder maxed out at 1207959550 while my char[] maxed out at (2^31)-3. It seems that AbstractStringBuilder doubles the size of its internal char[] to grow it, so that probably causes the issue.

How do emulators work and how are they written?

Yes, you have to interpret the whole binary machine code mess "by hand". Not only that, most of the time you also have to simulate some exotic hardware that doesn't have an equivalent on the target machine.

The simple approach is to interpret the instructions one-by-one. That works well, but it's slow. A faster approach is recompilation - translating the source machine code to target machine code. This is more complicated, as most instructions will not map one-to-one. Instead you will have to make elaborate work-arounds that involve additional code. But in the end it's much faster. Most modern emulators do this.

Android: how to create Switch case from this?

switch(position) {
  case 0:
    ...
    break;
  case 1:
    ...
    break;
  default:
    ...

}

Did you mean that?

How can I make content appear beneath a fixed DIV element?

#nav{
    position: -webkit-sticky; /* Safari */
    position: sticky;
    top: 0;
    margin: 0 auto;
    z-index: 9999;
    background-color: white;
}

Java - ignore exception and continue

I've upvoted Amir Afghani's answer, which seems to be the only one as of yet that actually answers the question.

But I would have written it like this instead:

UserInfo ui = new UserInfo();

DirectoryUser du = null;
try {
    du = LDAPService.findUser(username);
} catch (NullPointerException npe) {
    // It's fine if findUser throws a NPE
}
if (du != null) {
   ui.setUserInfo(du.getUserInfo());
}

Of course, it depends on whether or not you want to catch NPEs from the ui.setUserInfo() and du.getUserInfo() calls.

How to simulate a button click using code?

If you do not use the sender argument, why not refactor the button handler implementation to separate function, and call it from wherever you want (from the button handler and from the other place).

Anyway, it is a better and cleaner design - a code that needs to be called on button handler AND from some other places deserves to be refactored to own function. Plus it will help you separate UI handling from application logic code. You will also have a nice name to the function, not just onDateSelectedButtonClick().

Restarting cron after changing crontab file?

try this one for centos 7 : service crond reload

How do I view cookies in Internet Explorer 11 using Developer Tools

I think I found what you are looking for since I was also looking for it.

You have to follow Pawel's steps and then go to the key that is "Cookie". This will open a submenu with all the cookies and it specifies their name, value, domain, etc...

enter image description here

Respectively the values are: Key, Value, Expiration Date, Domain, Path.

This shows all the keys for this domain.

So again to get there:

  1. Go to Network.
  2. Capture Traffic, green triangle.
  3. Go to Details.
  4. Go to the "Cookie" key that has a gibberish value. (_utmc=xxxxx;something=ajksdhfa) etc...

Is it possible to simulate key press events programmatically?

You can dispatch keyboard events on an element like this

element.dispatchEvent(new KeyboardEvent('keydown',{'key':'a'}));

However, dispatchEvent might not update the input field value


Example:

_x000D_
_x000D_
let element = document.querySelector('input');
element.onkeydown = e => alert(e.key);
element.dispatchEvent(new KeyboardEvent('keydown',{'key':'a'}));
  
_x000D_
<input/>
_x000D_
_x000D_
_x000D_


You can add more properties to the event as needed, like this answer

  element.dispatchEvent(new KeyboardEvent("keydown", {
    key: "e",
    keyCode: 69, // example values.
    code: "KeyE", // put everything you need in this object.
    which: 69,
    shiftKey: false, // you don't need to include values
    ctrlKey: false,  // if you aren't going to use them.
    metaKey: false   // these are here for example's sake.
  }));
    

Also, since keypress is deprecated you can use keydown + keyup, for example

element.dispatchEvent(new KeyboardEvent('keydown', {'key':'Shift'} ));
element.dispatchEvent(new KeyboardEvent( 'keyup' , {'key':'Shift'} ));

How to remove duplicate values from an array in PHP

Remove duplicate values from an associative array in PHP.

$arrDup = Array ('0' => 'aaa-aaa' , 'SKU' => 'aaa-aaa' , '1' => '12/1/1' , 'date' => '12/1/1' , '2' => '1.15' , 'cost' => '1.15' );

foreach($arrDup as $k =>  $v){
  if(!( isset ($hold[$v])))
      $hold[$v]=1;
  else
      unset($arrDup[$k]);
}

Array ( [0] => aaa-aaa [1] => 12/1/1 [2] => 1.15 )

JavaScript get window X/Y position for scroll

The method jQuery (v1.10) uses to find this is:

var doc = document.documentElement;
var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
var top = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);

That is:

  • It tests for window.pageXOffset first and uses that if it exists.
  • Otherwise, it uses document.documentElement.scrollLeft.
  • It then subtracts document.documentElement.clientLeft if it exists.

The subtraction of document.documentElement.clientLeft / Top only appears to be required to correct for situations where you have applied a border (not padding or margin, but actual border) to the root element, and at that, possibly only in certain browsers.

How to convert C# nullable int to int

GetValueOrDefault()

retrieves the value of the object. If it is null, it returns the default value of int , which is 0.

Example:

v2= v1.GetValueOrDefault();

How do I replace all line breaks in a string with <br /> elements?

This worked for me when value came from a TextBox:

string.replace(/\n|\r\n|\r/g, '<br/>');

Android Material Design Button Styles

Here is a sample that will help in applying button style consistently across your app.

Here is a sample Theme I used with the specific styles..

<style name="MyTheme" parent="@style/Theme.AppCompat.Light">
   <item name="colorPrimary">@color/primary</item>
    <item name="colorPrimaryDark">@color/primary_dark</item>
    <item name="colorAccent">@color/accent</item>
    <item name="android:buttonStyle">@style/ButtonAppTheme</item>
</style>
<style name="ButtonAppTheme" parent="android:Widget.Material.Button">
<item name="android:background">@drawable/material_button</item>
</style>

This is how I defined the button shape & effects inside res/drawable-v21 folder...

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?attr/colorControlHighlight">
  <item>
    <shape xmlns:android="http://schemas.android.com/apk/res/android">
      <corners android:radius="2dp" /> 
      <solid android:color="@color/primary" />
    </shape>
  </item>
</ripple>

2dp corners are to keep it consistent with Material theme.

Is CSS Turing complete?

This answer is not accurate because it mix description of UTM and UTM itself (Universal Turing Machine).

We have good answer but from different perspective and it do not show directly flaws in current top answer.


First of all we can agree that human can work as UTM. This mean if we do

CSS + Human == UTM

Then CSS part is useless because all work can be done by Human who will do UTM part. Act of clicking can be UTM, because you do not click at random but only in specific places.

Instead of CSS I could use this text (Rule 110):

000 -> 0
001 -> 1
010 -> 1
011 -> 1
100 -> 0
101 -> 1
110 -> 1
111 -> 0

To guide my actions and result will be same. This mean this text UTM? No this is only input (description) that other UTM (human or computer) can read and run. Clicking is enough to run any UTM.


Critical part that CSS lack is ability to change of it own state in arbitrary way, if CSS could generate clicks then it would be UTM. Argument that your clicks are "crank" for CSS is not accurate because real "crank" for CSS is Layout Engine that run it and it should be enough to prove that CSS is UTM.

MySQL Query GROUP BY day / month / year

If you want to filter records for a particular year (e.g. 2000) then optimize the WHERE clause like this:

SELECT MONTH(date_column), COUNT(*)
FROM date_table
WHERE date_column >= '2000-01-01' AND date_column < '2001-01-01'
GROUP BY MONTH(date_column)
-- average 0.016 sec.

Instead of:

WHERE YEAR(date_column) = 2000
-- average 0.132 sec.

The results were generated against a table containing 300k rows and index on date column.

As for the GROUP BY clause, I tested the three variants against the above mentioned table; here are the results:

SELECT YEAR(date_column), MONTH(date_column), COUNT(*)
FROM date_table
GROUP BY YEAR(date_column), MONTH(date_column)
-- codelogic
-- average 0.250 sec.

SELECT YEAR(date_column), MONTH(date_column), COUNT(*)
FROM date_table
GROUP BY DATE_FORMAT(date_column, '%Y%m')
-- Andriy M
-- average 0.468 sec.

SELECT YEAR(date_column), MONTH(date_column), COUNT(*)
FROM date_table
GROUP BY EXTRACT(YEAR_MONTH FROM date_column)
-- fu-chi
-- average 0.203 sec.

The last one is the winner.

Checking if date is weekend PHP

For guys like me, who aren't minimalistic, there is a PECL extension called "intl". I use it for idn conversion since it works way better than the "idn" extension and some other n1 classes like "IntlDateFormatter".

Well, what I want to say is, the "intl" extension has a class called "IntlCalendar" which can handle many international countries (e.g. in Saudi Arabia, sunday is not a weekend day). The IntlCalendar has a method IntlCalendar::isWeekend for that. Maybe you guys give it a shot, I like that "it works for almost every country" fact on these intl-classes.

EDIT: Not quite sure but since PHP 5.5.0, the intl extension is bundled with PHP (--enable-intl).

Center image in div horizontally

Every solution posted here assumes that you know the dimensions of your img, which is not a common scenario. Also, planting the dimensions into the solution is painful.

Simply set:

/* for the img inside your div */
display: block;
margin-left: auto;
margin-right: auto;

or

/* for the img inside your div */
display: block;
margin: 0 auto;

That's all.

Note, that you'll also have to set an initial min-width for your outer div.

Spaces cause split in path with PowerShell

For any file path with space, simply put them in double quotations will work in Windows Powershell. For example, if you want to go to Program Files directory, instead of use

PS C:\> cd Program Files

which will induce error, simply use the following will solve the problem:

PS C:\> cd "Program Files"

Jenkins fails when running "service start jenkins"

Still fighting the same error on both ubuntu, ubuntu derivatives and opensuse. This is a great way to bypass and move forward until you can fix the actual issue.

Just use the docker image for jenkins from dockerhub.

docker pull jenkins/jenkins

docker run -itd -p 8080:8080 --name jenkins_container jenkins

Use the browser to navigate to:

localhost:8080 or my_pc:8080

To get at the token at the path given on the login screen:

docker exec -it jenkins_container /bin/bash

Then navigate to the token file and copy/paste the code into the login screen. You can use the edit/copy/paste menus in the kde/gnome/lxde/xfce terminals to copy the terminal text, then paste it with ctrl-v

War File

Or use the jenkins.war file. For development purposes you can run jenkins as your user (or as jenkins) from the command line or create a short script in /usr/local or /opt to start it.

Download the jenkins.war from the jenkins download page:

https://jenkins.io/download/

Then put it somewhere safe, ~/jenkins would be a good place.

mkdir ~/jenkins; cp ~/Downloads/jenkins.war ~/jenkins

Then run:

nohup java -jar ~/jenkins/jenkins.war > ~/jenkins/jenkins.log 2>&1

To get the initial admin password token, copy the text output of:

cat /home/my_home_dir/.jenkins/secrets/initialAdminPassword

and paste that into the box with ctrl-v as your initial admin password.

Hope this is detailed enough to get you on your way...

How to set date format in HTML date input tag?

I don't know this for sure, but I think this is supposed to be handled by the browser based on the user's date/time settings. Try setting your computer to display dates in that format.

tell pip to install the dependencies of packages listed in a requirement file

simplifily, use:

pip install -r requirement.txt

it can install all listed in requirement file.

How to parse XML to R data frame

Use xpath more directly for both performance and clarity.

time_path <- "//start-valid-time"
temp_path <- "//temperature[@type='hourly']/value"

df <- data.frame(
    latitude=data[["number(//point/@latitude)"]],
    longitude=data[["number(//point/@longitude)"]],
    start_valid_time=sapply(data[time_path], xmlValue),
    hourly_temperature=as.integer(sapply(data[temp_path], as, "integer"))

leading to

> head(df, 2)
  latitude longitude          start_valid_time hourly_temperature
1    29.81    -82.42 2014-02-14T18:00:00-05:00                 60
2    29.81    -82.42 2014-02-14T19:00:00-05:00                 55

CSS animation delay in repeating

I had a similar problem and used

@-webkit-keyframes pan {
   0%, 10%       { -webkit-transform: translate3d( 0%, 0px, 0px); }
   90%, 100%     { -webkit-transform: translate3d(-50%, 0px, 0px); }
}

Bit irritating that you have to fake your duration to account for 'delays' at either end.