Programs & Examples On #Fragmentation

Internal and external fragmentation

First of all the term fragmentation cues there's an entity divided into parts — fragments.

  • Internal fragmentation: Typical paper book is a collection of pages (text divided into pages). When a chapter's end isn't located at the end of page and new chapter starts from new page, there's a gap between those chapters and it's a waste of space — a chunk (page for a book) has unused space inside (internally) — "white space"

  • External fragmentation: Say you have a paper diary and you didn't write your thoughts sequentially page after page, but, rather randomly. You might end up with a situation when you'd want to write 3 pages in row, but you can't since there're no 3 clean pages one-by-one, you might have 15 clean pages in the diary totally, but they're not contiguous

Script for rebuilding and reindexing the fragmented index?

Query for REBUILD/REORGANIZE Indexes

  • 30%<= Rebuild
  • 5%<= Reorganize
  • 5%> do nothing

Query:

SELECT OBJECT_NAME(ind.OBJECT_ID) AS TableName, 
ind.name AS IndexName, indexstats.index_type_desc AS IndexType, 
indexstats.avg_fragmentation_in_percent,
'ALTER INDEX ' + QUOTENAME(ind.name)  + ' ON ' +QUOTENAME(object_name(ind.object_id)) + 
CASE    WHEN indexstats.avg_fragmentation_in_percent>30 THEN ' REBUILD ' 
        WHEN indexstats.avg_fragmentation_in_percent>=5 THEN 'REORGANIZE'
        ELSE NULL END as [SQLQuery]  -- if <5 not required, so no query needed
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, NULL) indexstats 
INNER JOIN sys.indexes ind ON ind.object_id = indexstats.object_id 
    AND ind.index_id = indexstats.index_id 
WHERE 
--indexstats.avg_fragmentation_in_percent , e.g. >10, you can specify any number in percent 
ind.Name is not null 
ORDER BY indexstats.avg_fragmentation_in_percent DESC

Output

TableName      IndexName            IndexType              avg_fragmentation_in_percent SQLQuery
--------------------------------------------------------------------------------------- ------------------------------------------------------
Table1         PK_Table1            CLUSTERED INDEX        75                           ALTER INDEX [PK_Table1] ON [Table1] REBUILD 
Table1         IX_Table1_col1_col2  NONCLUSTERED INDEX     66,6666666666667             ALTER INDEX [IX_Table1_col1_col2] ON [Table1] REBUILD 
Table2         IX_Table2_           NONCLUSTERED INDEX     10                           ALTER INDEX [IX_Table2_] ON [Table2] REORGANIZE
Table2         IX_Table2_           NONCLUSTERED INDEX     3                            NULL

Getting Cannot bind argument to parameter 'Path' because it is null error in powershell

$_ is the active object in the current pipeline. You've started a new pipeline with $FOLDLIST | ... so $_ represents the objects in that array that are passed down the pipeline. You should stash the FileInfo object from the first pipeline in a variable and then reference that variable later e.g.:

write-host $NEWN.Length
$file = $_
...
Move-Item $file.Name $DPATH

How to rotate x-axis tick labels in Pandas barplot

Try this -

plt.xticks(rotation=90)

enter image description here

Creating a class object in c++

I can use the same in c++ like this [...] Where constructor is compulsory. From this tutorial I got that we can create object like this [...] Which do not require an constructor.

This is wrong. A constructor must exist in order to create an object. The constructor could be defined implicitly by the compiler under some conditions if you do not provide any, but eventually the constructor must be there if you want an object to be instantiated. In fact, the lifetime of an object is defined to begin when the constructor routine returns.

From Paragraph 3.8/1 of the C++11 Standard:

[...] The lifetime of an object of type T begins when:

— storage with the proper alignment and size for type T is obtained, and

— if the object has non-trivial initialization, its initialization is complete.

Therefore, a constructor must be present.

1) What is the difference between both the way of creating class objects.

When you instantiate object with automatic storage duration, like this (where X is some class):

X x;

You are creating an object which will be automatically destroyed when it goes out of scope. On the other hand, when you do:

X* x = new X();

You are creating an object dynamically and you are binding its address to a pointer. This way, the object you created will not be destroyed when your x pointer goes out of scope.

In Modern C++, this is regarded as a dubious programming practice: although pointers are important because they allow realizing reference semantics, raw pointers are bad because they could result in memory leaks (objects outliving all of their pointers and never getting destroyed) or in dangling pointers (pointers outliving the object they point to, potentially causing Undefined Behavior when dereferenced).

In fact, when creating an object with new, you always have to remember destroying it with delete:

delete x;

If you need reference semantics and are forced to use pointers, in C++11 you should consider using smart pointers instead:

std::shared_ptr<X> x = std::make_shared<X>();

Smart pointers take care of memory management issues, which is what gives you headache with raw pointers. Smart pointers are, in fact, almost the same as Java or C# object references. The "almost" is necessary because the programmer must take care of not introducing cyclic dependencies through owning smart pointers.

2) If i am creating object like Example example; how to use that in an singleton class.

You could do something like this (simplified code):

struct Example
{
    static Example& instance()
    {
        static Example example;
        return example;
    }

 private:

    Example() { }
    Example(Example const&) = delete;
    Example(Example&&) = delete;
    Example& operator = (Example const&) = delete;
    Example& operator = (Example&&) = delete;

};

Why Java Calendar set(int year, int month, int date) not returning correct date?

Selected date at the example is interesting. Example code block is:

Calendar c1 = GregorianCalendar.getInstance();
c1.set(2000, 1, 30);  //January 30th 2000
Date sDate = c1.getTime();

System.out.println(sDate);

and output Wed Mar 01 19:32:21 JST 2000.

When I first read the example i think that output is wrong but it is true:)

  • Calendar.Month is starting from 0 so 1 means February.
  • February last day is 28 so output should be 2 March.
  • But selected year is important, it is 2000 which means February 29 so result should be 1 March.

Package Manager Console Enable-Migrations CommandNotFoundException only in a specific VS project

First "Install-Package EntityFramework -IncludePrerelease" and then Restarting Visual Studio as a Administrator worked for me together.

web.xml is missing and <failOnMissingWebXml> is set to true

Do this:

Go and right click on Deployment Descriptor and click Generate Deployment Descriptor Stub.

how to disable DIV element and everything inside

pure javascript no jQuery

_x000D_
_x000D_
function sah() {_x000D_
  $("#div2").attr("disabled", "disabled").off('click');_x000D_
  var x1=$("#div2").hasClass("disabledDiv");_x000D_
  _x000D_
  (x1==true)?$("#div2").removeClass("disabledDiv"):$("#div2").addClass("disabledDiv");_x000D_
  sah1(document.getElementById("div1"));_x000D_
_x000D_
}_x000D_
_x000D_
    function sah1(el) {_x000D_
        try {_x000D_
            el.disabled = el.disabled ? false : true;_x000D_
        } catch (E) {}_x000D_
        if (el.childNodes && el.childNodes.length > 0) {_x000D_
            for (var x = 0; x < el.childNodes.length; x++) {_x000D_
                sah1(el.childNodes[x]);_x000D_
            }_x000D_
        }_x000D_
    }
_x000D_
#div2{_x000D_
  padding:5px 10px;_x000D_
  background-color:#777;_x000D_
  width:150px;_x000D_
  margin-bottom:20px;_x000D_
}_x000D_
.disabledDiv {_x000D_
    pointer-events: none;_x000D_
    opacity: 0.4;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>_x000D_
<div id="div1">_x000D_
        <div id="div2" onclick="alert('Hello')">Click me</div>_x000D_
        <input type="text" value="SAH Computer" />_x000D_
        <br />_x000D_
        <input type="button" value="SAH Computer" />_x000D_
        <br />_x000D_
        <input type="radio" name="sex" value="Male" />Male_x000D_
        <Br />_x000D_
        <input type="radio" name="sex" value="Female" />Female_x000D_
        <Br />_x000D_
    </div>_x000D_
    <Br />_x000D_
    <Br />_x000D_
    <input type="button" value="Click" onclick="sah()" />
_x000D_
_x000D_
_x000D_

How to install latest version of Node using Brew

After installation/upgrading node via brew I ran into this issue exactly: the node command worked but not the npm command.

I used these commands to fix it.

brew uninstall node
brew update
brew upgrade
brew cleanup
brew install node
sudo chown -R $(whoami) /usr/local
brew link --overwrite node
brew postinstall node

I pieced together this solution after trial and error using...

Python append() vs. + operator on lists, why do these give different results?

The concatenation operator + is a binary infix operator which, when applied to lists, returns a new list containing all the elements of each of its two operands. The list.append() method is a mutator on list which appends its single object argument (in your specific example the list c) to the subject list. In your example this results in c appending a reference to itself (hence the infinite recursion).

An alternative to '+' concatenation

The list.extend() method is also a mutator method which concatenates its sequence argument with the subject list. Specifically, it appends each of the elements of sequence in iteration order.

An aside

Being an operator, + returns the result of the expression as a new value. Being a non-chaining mutator method, list.extend() modifies the subject list in-place and returns nothing.

Arrays

I've added this due to the potential confusion which the Abel's answer above may cause by mixing the discussion of lists, sequences and arrays. Arrays were added to Python after sequences and lists, as a more efficient way of storing arrays of integral data types. Do not confuse arrays with lists. They are not the same.

From the array docs:

Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained. The type is specified at object creation time by using a type code, which is a single character.

How to pass argument to Makefile from command line?

You probably shouldn't do this; you're breaking the basic pattern of how Make works. But here it is:

action:
        @echo action $(filter-out $@,$(MAKECMDGOALS))

%:      # thanks to chakrit
    @:    # thanks to William Pursell

EDIT:
To explain the first command,

$(MAKECMDGOALS) is the list of "targets" spelled out on the command line, e.g. "action value1 value2".

$@ is an automatic variable for the name of the target of the rule, in this case "action".

filter-out is a function that removes some elements from a list. So $(filter-out bar, foo bar baz) returns foo baz (it can be more subtle, but we don't need subtlety here).

Put these together and $(filter-out $@,$(MAKECMDGOALS)) returns the list of targets specified on the command line other than "action", which might be "value1 value2".

Generating UNIQUE Random Numbers within a range

Simply use this function and pass the count of number you want to generate

Code:

function randomFix($length)
{
    $random= "";

srand((double)microtime()*1000000);

$data = "AbcDE123IJKLMN67QRSTUVWXYZ";
$data .= "aBCdefghijklmn123opq45rs67tuv89wxyz";
$data .= "0FGH45OP89";

for($i = 0; $i < $length; $i++)
{
    $random .= substr($data, (rand()%(strlen($data))), 1);
}
return $random;}

@selector() in Swift?

selector is a word from Objective-C world and you are able to use it from Swift to have a possibility to call Objective-C from Swift It allows you to execute some code at runtime

Before Swift 2.2 the syntax is:

Selector("foo:")

Since a function name is passed into Selector as a String parameter("foo") it is not possible to check a name in compile time. As a result you can get a runtime error:

unrecognized selector sent to instance

After Swift 2.2+ the syntax is:

#selector(foo(_:))

Xcode's autocomplete help you to call a right method

jquery .on() method with load event

To run function onLoad

jQuery(window).on("load", function(){
    ..code..
});

To run code onDOMContentLoaded (also called onready)

jQuery(document).ready(function(){
    ..code..
});

or the recommended shorthand for onready

jQuery(function($){
    ..code.. ($ is the jQuery object)
});

onready fires when the document has loaded

onload fires when the document and all the associated content, like the images on the page have loaded.

Why does Boolean.ToString output "True" and not "true"

It's simple code to convert that to all lower case.

Not so simple to convert "true" back to "True", however.

true.ToString().ToLower() 

is what I use for xml output.

Install Windows Service created in Visual Studio

Yet another catch I ran into: ensure your Installer derived class (typically ProjectInstaller) is at the top of the namespace hierarchy, I tried to use a public class within another public class, but this results in the same old error:

No public installers with the RunInstallerAttribute.Yes attribute could be found

How can I match multiple occurrences with a regex in JavaScript similar to PHP's preg_match_all()?

Well... I had a similar problem... I want an incremental / step search with RegExp (eg: start search... do some processing... continue search until last match)

After lots of internet search... like always (this is turning an habit now) I end up in StackOverflow and found the answer...

Whats is not referred and matters to mention is "lastIndex" I now understand why the RegExp object implements the "lastIndex" property

CSS media queries: max-width OR max-height

yes, using and, like:

@media screen and (max-width: 800px), 
       screen and (max-height: 600px) {
  ...
}

How to add hyperlink in JLabel?

You can use this under an

actionListener ->  Runtime.getRuntime().exec("cmd.exe /c start chrome www.google.com")`

or if you want to use Internet Explorer or Firefox replace chrome with iexplore or firefox

Why is my Button text forced to ALL CAPS on Lollipop?

add this line in style

    <item name="android:textAllCaps">false</item>

CSS to make HTML page footer stay at bottom of the page with a minimum height, but not overlap the page

ONE line solution using Bootstrap

Apart from all the CSS and jQuery solutions provided,
I have listed a solution using Bootstrap with a single class declaration on body tag: d-flex flex-column justify-content-between

  • This DOES NOT require knowing the height of the footer ahead of time.
  • This DOES NOT require setting position absolute.
  • This WORKS with dynamic divs that overflow on smaller screens.

_x000D_
_x000D_
html, body {
  height: 100%;
}
_x000D_
<html>

    <head>
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
    </head>

    <body class="d-flex flex-column justify-content-between text-white text-center">

        <header class="p-5 bg-dark">
          <h1>Header</h1>
        </header>
        <main class="p-5 bg-primary">
          <h1>Main</h1>
        </main>
        <footer class="p-5 bg-warning">
          <h1>Footer</h1>
        </footer>

        <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
    </body>

</html>
_x000D_
_x000D_
_x000D_

git - Your branch is ahead of 'origin/master' by 1 commit

I resolved this by just running a simple:

git pull

Nothing more. Now it's showing:

# On branch master
nothing to commit, working directory clean

How do I drop a MongoDB database from the command line?

Using Javascript, you can easily create a drop_bad.js script to drop your database:

create drop_bad.js:

use bad;
db.dropDatabase();

Than run 1 command in terminal to exectue the script using mongo shell:

mongo < drop_bad.js

How can I use Python to get the system hostname?

To get fully qualified hostname use socket.getfqdn()

import socket

print socket.getfqdn()

Printf long long int in C with GCC?

Try to update your compiler, I'm using GCC 4.7 on Windows 7 Starter x86 with MinGW and it compiles fine with the same options both in C99 and C11.

Environment variables in Eclipse

You can also define an environment variable that is visible only within Eclipse.

Go to Run -> Run Configurations... and Select tab "Environment".

enter image description here

There you can add several environment variables that will be specific to your application.

Boolean Field in Oracle

A working example to implement the accepted answer by adding a "Boolean" column to an existing table in an oracle database (using number type):

ALTER TABLE my_table_name ADD (
my_new_boolean_column number(1) DEFAULT 0 NOT NULL
CONSTRAINT my_new_boolean_column CHECK (my_new_boolean_column in (1,0))
);

This creates a new column in my_table_name called my_new_boolean_column with default values of 0. The column will not accept NULL values and restricts the accepted values to either 0 or 1.

How to get current route in react-router 2.0.0-rc5

For any users having the same issue in 2017, I solved it the following way:

NavBar.contextTypes = {
    router: React.PropTypes.object,
    location: React.PropTypes.object
}

and use it like this:

componentDidMount () {
    console.log(this.context.location.pathname);
}

Rename multiple files in cmd

The below command would do the job.

forfiles /M *.txt /C "cmd /c rename @file \"@fname 1.1.txt\""

source: Rename file extensions in bulk

Connection to SQL Server Works Sometimes

I had the same problem, trying to connect to a server in a local network (through VPN) from Visual Studio, while setting up an Entity Data Model.
Managed to solve only by setting TransparentNetworkIPResolution=false in the connection string. In VS Add Connection Wizard, you can find it in the Advanced tab.

Convert string with comma to integer

I would do using String#tr :

"1,112".tr(',','').to_i # => 1112

How do I clone a range of array elements to a new array?

Cloning elements in an array is not something that can be done in a universal way. Do you want deep cloning or a simple copy of all members?

Let's go for the "best effort" approach: cloning objects using the ICloneable interface or binary serialization:

public static class ArrayExtensions
{
  public static T[] SubArray<T>(this T[] array, int index, int length)
  {
    T[] result = new T[length];

    for (int i=index;i<length+index && i<array.Length;i++)
    {
       if (array[i] is ICloneable)
          result[i-index] = (T) ((ICloneable)array[i]).Clone();
       else
          result[i-index] = (T) CloneObject(array[i]);
    }

    return result;
  }

  private static object CloneObject(object obj)
  {
    BinaryFormatter formatter = new BinaryFormatter();

    using (MemoryStream stream = new MemoryStream())
    {
      formatter.Serialize(stream, obj);

      stream.Seek(0,SeekOrigin.Begin);

      return formatter.Deserialize(stream);
    }
  }
}

This is not a perfect solution, because there simply is none that will work for any type of object.

"Invalid JSON primitive" in Ajax processing

Using

data : JSON.stringify(obj)

in the above situation would have worked I believe.

Note: You should add json2.js library all browsers don't support that JSON object (IE7-) Difference between json.js and json2.js

How to subtract 30 days from the current datetime in mysql?

You can also use

select CURDATE()-INTERVAL 30 DAY

PHP fopen() Error: failed to open stream: Permission denied

You may need to change the permissions as an administrator. Open up terminal on your Mac and then open the directory that markers.xml is located in. Then type:

sudo chmod 777 markers.xml

You may be prompted for a password. Also, it could be the directories that don't allow full access. I'm not familiar with WordPress, so you may have to change the permission of each directory moving upward to the mysite directory.

What is the best way to ensure only one instance of a Bash script is running?

i found this in procmail package dependencies:

apt install liblockfile-bin

To run: dotlockfile -l file.lock

file.lock will be created.

To unlock: dotlockfile -u file.lock

Use this to list this package files / command: dpkg-query -L liblockfile-bin

The response content cannot be parsed because the Internet Explorer engine is not available, or

In your invoke web request just use the parameter -UseBasicParsing

e.g. in your script (line 2) you should use:

$rss = Invoke-WebRequest -UseBasicParsing

According to the documentation, this parameter is necessary on systems where IE isn't installed or configured.

Uses the response object for HTML content without Document Object Model (DOM) parsing. This parameter is required when Internet Explorer is not installed on the computers, such as on a Server Core installation of a Windows Server operating system.

lodash multi-column sortBy descending

As of lodash 3.5.0 you can use sortByOrder (renamed orderBy in v4.3.0):

var data = _.sortByOrder(array_of_objects, ['type','name'], [true, false]);

Since version 3.10.0 you can even use standard semantics for ordering (asc, desc):

var data = _.sortByOrder(array_of_objects, ['type','name'], ['asc', 'desc']);

In version 4 of lodash this method has been renamed orderBy:

var data = _.orderBy(array_of_objects, ['type','name'], ['asc', 'desc']);

adding to window.onload event?

This might not be a popular option, but sometimes the scripts end up being distributed in various chunks, in that case I've found this to be a quick fix

if(window.onload != null){var f1 = window.onload;}
window.onload=function(){
    //do something

    if(f1!=null){f1();}
}

then somewhere else...

if(window.onload != null){var f2 = window.onload;}
window.onload=function(){
    //do something else

    if(f2!=null){f2();}
}

this will update the onload function and chain as needed

How do I store data in local storage using Angularjs?

If you use $window.localStorage.setItem(key,value) to store,$window.localStorage.getItem(key) to retrieve and $window.localStorage.removeItem(key) to remove, then you can access the values in any page.

You have to pass the $window service to the controller. Though in JavaScript, window object is available globally.

By using $window.localStorage.xxXX() the user has control over the localStorage value. The size of the data depends upon the browser. If you only use $localStorage then value remains as long as you use window.location.href to navigate to other page and if you use <a href="location"></a> to navigate to other page then your $localStorage value is lost in the next page.

java.io.StreamCorruptedException: invalid stream header: 54657374

You can't expect ObjectInputStream to automagically convert text into objects. The hexadecimal 54657374 is "Test" as text. You must be sending it directly as bytes.

How to upload image in CodeIgniter?

check $this->upload->initialize($config); this works fine for me

    $new_image_name = "imgName".time() . str_replace(str_split(' ()\\/,:*?"<>|'), '', 
    $_FILES['userfile']['name']);
    $config = array();
    $config['upload_path'] = './uploads/'; 
    $config['allowed_types'] = 'gif|jpg|png|bmp|jpeg';
    $config['file_name'] = $new_image_name;
    $config['max_size']  = '0';
    $config['upload_path'] = './uploads/';
    $config['allowed_types'] = 'gif|jpg|png|mp4|jpeg';
    $config['file_name'] = url_title("imgsclogo");
    $config['max_size']      = '0';
    $config['overwrite']     = FALSE; 
    $this->upload->initialize($config);
    $this->upload->do_upload();
    $data = $this->upload->data();
}

How do I do a Date comparison in Javascript?

if (date1.getTime() > date2.getTime()) {
    alert("The first date is after the second date!");
}

Reference to Date object

In PowerShell, how do I test whether or not a specific variable exists in global scope?

So far, it looks like the answer that works is this one.

To break it out further, what worked for me was this:

Get-Variable -Name foo -Scope Global -ea SilentlyContinue | out-null

$? returns either true or false.

Android Studio Gradle DSL method not found: 'android()' -- Error(17,0)

Just delete these lines from the root build.gradle

android {
compileSdkVersion 19
buildToolsVersion '19.1' }

Now trying and compile again. It should work.

Make function wait until element exists

Maybe I'm a little bit late :), but here is a nice and brief solution by chrisjhoughton, which allows to perform a callback function when the wait is over.

https://gist.github.com/chrisjhoughton/7890303

var waitForEl = function(selector, callback) {
  if (jQuery(selector).length) {
    callback();
  } else {
    setTimeout(function() {
      waitForEl(selector, callback);
    }, 100);
  }
};

waitForEl(selector, function() {
  // work the magic
});

If you need to pass parameters to a callback function, you can use it this way:

waitForEl("#" + elDomId, () => callbackFunction(param1, param2));

But be careful! This solution by default can fall into a trap of an infinite loop.

Several improvements of the topicstarter's suggestion are also provided in The GitHub thread.

Enjoy!

Java equivalent to C# extension methods

Extension methods are not just static method and not just convenience syntax sugar, in fact they are quite powerful tool. The main thing there is ability to override different methods based on different generic’s parameters instantiation. This is similar to Haskell’s type classes, and in fact, it looks like they are in C# to support C#’s Monads (i.e. LINQ). Even dropping LINQ syntax, I still don’t know any way to implement similar interfaces in Java.

And I don’t think it is possible to implement them in Java, because of Java’s type erasure semantics of generics parameters.

How to view an HTML file in the browser with Visual Studio Code

Here is a 2.0.0 version for the current document in Chrome w/ keyboard shortcut:

tasks.json

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Chrome",
            "type": "process",
            "command": "chrome.exe",
            "windows": {
                "command": "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
            },
            "args": [
                "${file}"
            ],
            "problemMatcher": []
        }
    ]
}

keybindings.json :

{
    "key": "ctrl+g",
    "command": "workbench.action.tasks.runTask",
    "args": "Chrome"
}

For running on a webserver:

https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer

Items in JSON object are out of order using "json.dumps"?

json.dump() will preserve the ordder of your dictionary. Open the file in a text editor and you will see. It will preserve the order regardless of whether you send it an OrderedDict.

But json.load() will lose the order of the saved object unless you tell it to load into an OrderedDict(), which is done with the object_pairs_hook parameter as J.F.Sebastian instructed above.

It would otherwise lose the order because under usual operation, it loads the saved dictionary object into a regular dict and a regular dict does not preserve the oder of the items it is given.

how to convert an RGB image to numpy array?

OpenCV image format supports the numpy array interface. A helper function can be made to support either grayscale or color images. This means the BGR -> RGB conversion can be conveniently done with a numpy slice, not a full copy of image data.

Note: this is a stride trick, so modifying the output array will also change the OpenCV image data. If you want a copy, use .copy() method on the array!

import numpy as np

def img_as_array(im):
    """OpenCV's native format to a numpy array view"""
    w, h, n = im.width, im.height, im.channels
    modes = {1: "L", 3: "RGB", 4: "RGBA"}
    if n not in modes:
        raise Exception('unsupported number of channels: {0}'.format(n))
    out = np.asarray(im)
    if n != 1:
        out = out[:, :, ::-1]  # BGR -> RGB conversion
    return out

LISTAGG in Oracle to return distinct values

you can use undocumented wm_concat function.

select col1, wm_concat(distinct col2) col2_list 
from tab1
group by col1;

this function returns clob column, if you want you can use dbms_lob.substr to convert clob to varchar2.

R - argument is of length zero in if statement

I spent an entire day bashing my head against this, the solution turned out to be simple..

R isn't zero-index.

Every programming language that I've used before has it's data start at 0, R starts at 1. The result is an off-by-one error but in the opposite direction of the usual. going out of bounds on a data structure returns null and comparing null in an if statement gives the argument is of length zero error. The confusion started because the dataset doesn't contain any null, and starting at position [0] like any other pgramming language turned out to be out of bounds.

Perhaps starting at 1 makes more sense to people with no programming experience (the target market for R?) but for a programmer is a real head scratcher if you're unaware of this.

Listing files in a specific "folder" of a AWS S3 bucket

S3 does not have directories, while you can list files in a pseudo directory manner like you demonstrated, there is no directory "file" per-se.
You may of inadvertently created a data file called users/<user-id>/contacts/<contact-id>/.

Accessing nested JavaScript objects and arrays by string path

Starting from @Alnitak answer I built this source, which downloads an actual .JSON file and processes it, printing to console explanatory strings for each step, and more details in case of wrong key passed:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <script>
function retrieveURL(url) {
        var client = new XMLHttpRequest();
        prefix = "https://cors-anywhere.herokuapp.com/"
        client.open('GET', prefix + url);
        client.responseType = 'text';
        client.onload = function() {
            response = client.response; // Load remote response.
            console.log("Response received.");
            parsedJSON  = JSON.parse(response);
            console.log(parsedJSON);
            console.log(JSONitemByPath(parsedJSON,"geometry[6].obs[3].latituade"));
            return response;
        };
        try {
            client.send();
        } catch(e) {
            console.log("NETWORK ERROR!");
            console.log(e);
        }
}



function JSONitemByPath(o, s) {
    structure = "";
    originalString = s;
    console.log("Received string: ", s);
    s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
    console.log("Converted to   : ", s);
    s = s.replace(/^\./, '');           // strip a leading dot
    var a = s.split('.');

    console.log("Single keys to parse: ",a);

    for (var i = 0, n = a.length; i < n; ++i) {
        var k = a[i];
        if (k in o) {
            o = o[k];
            console.log("object." + structure +  a[i], o);
            structure +=  a[i] + ".";
        } else {
            console.log("ERROR: wrong path passed: ", originalString);
            console.log("       Last working level: ", structure.substr(0,structure.length-1));
            console.log("       Contents: ", o);
            console.log("       Available/passed key: ");
            Object.keys(o).forEach((prop)=> console.log("       "+prop +"/" + k));
            return;
        }
    }
    return o;
}


function main() {
    rawJSON = retrieveURL("http://haya2now.jp/data/data.json");
}

</script>
  </head>
  <body onload="main()">
  </body>
</html>

Output example:

Response received.
json-querier.html:17 {geometry: Array(7), error: Array(0), status: {…}}
json-querier.html:34 Received string:  geometry[6].obs[3].latituade
json-querier.html:36 Converted to   :  geometry.6.obs.3.latituade
json-querier.html:40 Single keys to parse:  (5) ["geometry", "6", "obs", "3", "latituade"]
json-querier.html:46 object.geometry (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]
json-querier.html:46 object.geometry.6 {hayabusa2: {…}, earth: {…}, obs: Array(6), TT: 2458816.04973593, ryugu: {…}, …}
json-querier.html:46 object.geometry.6.obs (6) [{…}, {…}, {…}, {…}, {…}, {…}]
json-querier.html:46 object.geometry.6.obs.3 {longitude: 148.98, hayabusa2: {…}, sun: {…}, name: "DSS-43", latitude: -35.4, …}
json-querier.html:49 ERROR: wrong path passed:  geometry[6].obs[3].latituade
json-querier.html:50        Last working level:  geometry.6.obs.3
json-querier.html:51        Contents:  {longitude: 148.98, hayabusa2: {…}, sun: {…}, name: "DSS-43", latitude: -35.4, …}
json-querier.html:52        Available/passed key: 
json-querier.html:53        longitude/latituade
json-querier.html:53        hayabusa2/latituade
json-querier.html:53        sun/latituade
json-querier.html:53        name/latituade
json-querier.html:53        latitude/latituade
json-querier.html:53        altitude/latituade
json-querier.html:18 undefined

Reading local text file into a JavaScript array

Using Node.js

sync mode:

var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")

async mode:

var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
    var textByLine = text.split("\n")
});

UPDATE

As of at least Node 6, readFileSync returns a Buffer, so it must first be converted to a string in order for split to work:

var text = fs.readFileSync("./mytext.txt").toString('utf-8');

Or

var text = fs.readFileSync("./mytext.txt", "utf-8");

Catch KeyError in Python

I am using Python 3.6 and using a comma between Exception and e does not work. I need to use the following syntax (just for anyone wondering)

try:
    connection = manager.connect("I2Cx")
except KeyError as e:
    print(e.message)

Deleting a local branch with Git

You probably have Test_Branch checked out, and you may not delete it while it is your current branch. Check out a different branch, and then try deleting Test_Branch.

Is the practice of returning a C++ reference variable evil?

About horrible code:

int& getTheValue()
{
   return *new int;
}

So, indeed, memory pointer lost after return. But if you use shared_ptr like that:

int& getTheValue()
{
   std::shared_ptr<int> p(new int);
   return *p->get();
}

Memory not lost after return and will be freed after assignment.

How can I resize an image dynamically with CSS as the browser width/height changes?

window.onresize = function(){
    var img = document.getElementById('fullsize');
    img.style.width = "100%";
};

In IE onresize event gets fired on every pixel change (width or height) so there could be performance issue. Delay image resizing for few milliseconds by using javascript's window.setTimeout().

http://mbccs.blogspot.com/2007/11/fixing-window-resize-event-in-ie.html

Unable to get provider com.google.firebase.provider.FirebaseInitProvider

Don't include the whole play services library but use the one that you need.Replace the line in your build.gradle:

compile 'com.google.android.gms:play-services:9.6.1'

with the appropriate one from Google Play Services APIs,like for example:

compile 'com.google.android.gms:play-services-gcm:9.6.1'

tap gesture recognizer - which object was tapped?

Use this code in Swift

func tappGeastureAction(sender: AnyObject) {
    if let tap = sender as? UITapGestureRecognizer {
        let point = tap.locationInView(locatedView)
        if filterView.pointInside(point, withEvent: nil) == true {
            // write your stuff here                
        }
    }
}

Passing dynamic javascript values using Url.action()

In my case it worked great just by doing the following:

The Controller:

[HttpPost]
public ActionResult DoSomething(int custNum)
{
    // Some magic code here...
}

Create the form with no action:

<form id="frmSomething" method="post">
    <div>
        <!-- Some magic html here... -->
    </div>
    <button id="btnSubmit" type="submit">Submit</button>
</form>

Set button click event to trigger submit after adding the action to the form:

var frmSomething= $("#frmSomething");
var btnSubmit= $("#btnSubmit");
var custNum = 100;

btnSubmit.click(function()
    {
        frmSomething.attr("action", "/Home/DoSomething?custNum=" + custNum);

        btnSubmit.submit();
    });

Hope this helps vatos!

Get and set position with jQuery .offset()

var redBox = $(".post");

var greenBox = $(".post1");

var offset = redBox.offset();

$(".post1").css({'left': +offset.left});
$(".post1").html("Left :" +offset.left);

http://jsfiddle.net/va836/159/

java.io.IOException: Server returned HTTP response code: 500

Change the content-type to "application/x-www-form-urlencoded", i solved the problem.

Set icon for Android application

I found this tool most useful.

  1. Upload a image.
  2. Download a zip.
  3. Extract into your project.

Done

http://romannurik.github.io/AndroidAssetStudio/

how to check the version of jar file?

You can filter version from the MANIFEST file using

unzip -p my.jar META-INF/MANIFEST.MF | grep 'Bundle-Version'

How can I disable ReSharper in Visual Studio and enable it again?

I always forget how to do this and this is the top result on Google. IMO, none of the answers here are satisfactory.
So the next time I search this and to help others, here's how to do it and what the button looks like to toggle it:

Toggle Resharper Toolbar Button

  • Make sure Resharper is currently enabled or the commands may fail.
  • Open package manager console via the Quick Launch bar near the caption buttons to launch a PowerShell instance.
  • Enter the code below into the Package Manager Console Powershell instance:

If you want to add it to the standard toolbar:

$cmdBar = $dte.CommandBars.Item("Standard") 
$cmd = $dte.Commands.Item("ReSharper_ToggleSuspended")
$ctrl = $cmd.AddControl($cmdBar, $cmdBar.Controls.Count+1)
$ctrl.Caption = "R#"

If you want to add it to a new custom toolbar:

$toolbarType = [EnvDTE.vsCommandBarType]::vsCommandBarTypeToolbar
$cmdBar = $dte.Commands.AddCommandBar("Resharper", $toolbarType)
$cmd = $dte.Commands.Item("ReSharper_ToggleSuspended")
$ctrl = $cmd.AddControl($cmdBar, $cmdBar.Controls.Count+1)
$ctrl.Caption = "R#"

If you mess up and need to start over, remove it with:

$ctrl.Delete($cmdBar)
$dte.Commands.RemoveCommandBar($cmdBar)

In addition to adding the button, you may wish to add the keyboard shortcut
ctrl+shift+Num -, ctrl+shift+Num - that is: ctrl+shift+-+-

EDIT: Looks like StingyJack found the original post I found long ago. It never shows up when I do a google search for this
https://stackoverflow.com/a/41792417/16391

Android Facebook 4.0 SDK How to get Email, Date of Birth and gender of User

Use FB static method getCurrentProfile() of Profile class to retrieve those info.

 Profile profile = Profile.getCurrentProfile();
 String firstName = profile.getFirstName());
 System.out.println(profile.getProfilePictureUri(20,20));
 System.out.println(profile.getLinkUri());

String delimiter in string.split method

String[] strArray= str.split(Pattern.quote("||"));

where

  1. str = "1||1||Abdul-Jabbar||Karim||1996||1974";
  2. Pattern.quote("||") will ignore the special character.
  3. .split function will split the string for every occurrence of ||.
  4. strArray will have the array of string that is delimited by ||.

How to calculate percentage with a SQL statement

You have to calculate the total of grades If it is SQL 2005 you can use CTE

    WITH Tot(Total) (
    SELECT COUNT(*) FROM table
    )
    SELECT Grade, COUNT(*) / Total * 100
--, CONVERT(VARCHAR, COUNT(*) / Total * 100) + '%'  -- With percentage sign
--, CONVERT(VARCHAR, ROUND(COUNT(*) / Total * 100, -2)) + '%'  -- With Round
    FROM table
    GROUP BY Grade

How to install npm peer dependencies automatically?

Install yarn an then run

yarn global add install-peerdeps

Create a mocked list by mockito

OK, this is a bad thing to be doing. Don't mock a list; instead, mock the individual objects inside the list. See Mockito: mocking an arraylist that will be looped in a for loop for how to do this.

Also, why are you using PowerMock? You don't seem to be doing anything that requires PowerMock.

But the real cause of your problem is that you are using when on two different objects, before you complete the stubbing. When you call when, and provide the method call that you are trying to stub, then the very next thing you do in either Mockito OR PowerMock is to specify what happens when that method is called - that is, to do the thenReturn part. Each call to when must be followed by one and only one call to thenReturn, before you do any more calls to when. You made two calls to when without calling thenReturn - that's your error.

makefiles - compile all c files at once

LIBS  = -lkernel32 -luser32 -lgdi32 -lopengl32
CFLAGS = -Wall

# Should be equivalent to your list of C files, if you don't build selectively
SRC=$(wildcard *.c)

test: $(SRC)
    gcc -o $@ $^ $(CFLAGS) $(LIBS)

NoSql vs Relational database

Not all data is relational. For those situations, NoSQL can be helpful.

With that said, NoSQL stands for "Not Only SQL". It's not intended to knock SQL or supplant it.

SQL has several very big advantages:

  1. Strong mathematical basis.
  2. Declarative syntax.
  3. A well-known language in Structured Query Language (SQL).

Those haven't gone away.

It's a mistake to think about this as an either/or argument. NoSQL is an alternative that people need to consider when it fits, that's all.

Documents can be stored in non-relational databases, like CouchDB.

Maybe reading this will help.

replace String with another in java

     String s1 = "HelloSuresh";
     String m = s1.replace("Hello","");
     System.out.println(m);

Checking version of angular-cli that's installed?

angular cli can report its version when you run it with the version flag

ng --version

Two's Complement in Python

Unfortunately there is no built-in function to cast an unsigned integer to a two's complement signed value, but we can define a function to do so using bitwise operations:

def s12(value):
    return -(value & 0b100000000000) | (value & 0b011111111111)

The first bitwise-and operation is used to sign-extend negative numbers (most significant bit is set), while the second is used to grab the remaining 11 bits. This works since integers in Python are treated as arbitrary precision two's complement values.

You can then combine this with the int function to convert a string of binary digits into the unsigned integer form, then interpret it as a 12-bit signed value.

>>> s12(int('111111111111', 2))
-1
>>> s12(int('011111111111', 2))
2047
>>> s12(int('100000000000', 2))
-2048

One nice property of this function is that it's idempotent, thus the value of an already signed value will not change.

>>> s12(-1)
-1

@Transactional(propagation=Propagation.REQUIRED)

If you need a laymans explanation of the use beyond that provided in the Spring Docs

Consider this code...

class Service {
    @Transactional(propagation=Propagation.REQUIRED)
    public void doSomething() {
        // access a database using a DAO
    }
}

When doSomething() is called it knows it has to start a Transaction on the database before executing. If the caller of this method has already started a Transaction then this method will use that same physical Transaction on the current database connection.

This @Transactional annotation provides a means of telling your code when it executes that it must have a Transaction. It will not run without one, so you can make this assumption in your code that you wont be left with incomplete data in your database, or have to clean something up if an exception occurs.

Transaction management is a fairly complicated subject so hopefully this simplified answer is helpful

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

I share with you a code that can be useful, it is to create an annotation that can be used either in a class or a method.

@Target({TYPE, METHOD})
@Retention(RUNTIME)
@Documented
public @interface AnnotationLogger {
    /**
     * It is the parameter is to show arguments in the method or the class.
     */
    boolean showArguments() default false;
}


@Aspect
@Component
public class AnnotationLoggerAspect {
    
    @Autowired 
    private Logger logger;  
    
    private static final String METHOD_NAME   = "METHOD NAME: {} ";
    private static final String ARGUMENTS     = "ARGS: {} ";
    
    @Before(value = "@within(com.org.example.annotations.AnnotationLogger) || @annotation(com.org.example.annotations.AnnotationLogger)")
    public void logAdviceExecutionBefore(JoinPoint joinPoint){  
        CodeSignature codeSignature = (CodeSignature) joinPoint.getSignature();
        AnnotationLogger annotationLogger = getAnnotationLogger(joinPoint);
        if(annotationLogger!= null) {
            StringBuilder annotationLoggerFormat = new StringBuilder();
            List<Object> annotationLoggerArguments = new ArrayList<>();
            annotationLoggerFormat.append(METHOD_NAME);
            annotationLoggerArguments.add(codeSignature.getName());
            
            if (annotationLogger.showArguments()) {
                annotationLoggerFormat.append(ARGUMENTS);
                List<?> argumentList = Arrays.asList(joinPoint.getArgs());
                annotationLoggerArguments.add(argumentList.toString());
            }
            logger.error(annotationLoggerFormat.toString(), annotationLoggerArguments.toArray());
        }
    }
    
    private AnnotationLogger getAnnotationLogger(JoinPoint joinPoint) {
        AnnotationLogger annotationLogger = null;
        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = joinPoint.getTarget().getClass().
                    getMethod(signature.getMethod().getName(), signature.getMethod().getParameterTypes());
            
            if (method.isAnnotationPresent(AnnotationLogger.class)){
                annotationLogger = method.getAnnotation(AnnotationLoggerAspect.class);
            }else if (joinPoint.getTarget().getClass().isAnnotationPresent(AnnotationLoggerAspect.class)){
                annotationLogger = joinPoint.getTarget().getClass().getAnnotation(AnnotationLoggerAspect.class);
            }
            return annotationLogger;
        }catch(Exception e) {
            return annotationLogger;
        }
    }
}

How to install a Python module via its setup.py in Windows?

setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").

From the command line, you can type

python setup.py --help

...to get a list of commands. What you are looking to do is...

python setup.py install

Why am I getting an Exception with the message "Invalid setup on a non-virtual (overridable in VB) member..."?

Please see Why does the property I want to mock need to be virtual?

You may have to write a wrapper interface or mark the property as virtual/abstract as Moq creates a proxy class that it uses to intercept calls and return your custom values that you put in the .Returns(x) call.

How to play ringtone/alarm sound in Android

For the future googlers: use RingtoneManager.getActualDefaultRingtoneUri() instead of RingtoneManager.getDefaultUri(). According to its name, it would return the actual uri, so you can freely use it. From documentation of getActualDefaultRingtoneUri():

Gets the current default sound's Uri. This will give the actual sound Uri, instead of using this, most clients can use DEFAULT_RINGTONE_URI.

Meanwhile getDefaultUri() says this:

Returns the Uri for the default ringtone of a particular type. Rather than returning the actual ringtone's sound Uri, this will return the symbolic Uri which will resolved to the actual sound when played.

How to force a line break in a long word in a DIV?

Do this:

<div id="sampleDiv">aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</div>

#sampleDiv{
   overflow-wrap: break-word;
}

force Maven to copy dependencies into target/lib

It's a heavy solution for embedding heavy dependencies, but Maven's Assembly Plugin does the trick for me.

@Rich Seller's answer should work, although for simpler cases you should only need this excerpt from the usage guide:

<project>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.2.2</version>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

How to use tick / checkmark symbol (?) instead of bullets in unordered list?

As an addition to the solution:

ul li:before {
 content: '?'; 
}

You can use any SVG icon as the content, such as the Font Aswesome.

enter image description here

_x000D_
_x000D_
ul {_x000D_
  list-style: none;_x000D_
  padding-left: 0;_x000D_
}_x000D_
li {_x000D_
  position: relative;_x000D_
  padding-left: 1.5em;  /* space to preserve indentation on wrap */_x000D_
}_x000D_
li:before {_x000D_
  content: '';  /* placeholder for the SVG */_x000D_
  position: absolute;_x000D_
  left: 0;  /* place the SVG at the start of the padding */_x000D_
  width: 1em;_x000D_
  height: 1em;_x000D_
  background: url("data:image/svg+xml;utf8,<?xml version='1.0' encoding='utf-8'?><svg width='18' height='18' viewBox='0 0 1792 1792' xmlns='http://www.w3.org/2000/svg'><path d='M1671 566q0 40-28 68l-724 724-136 136q-28 28-68 28t-68-28l-136-136-362-362q-28-28-28-68t28-68l136-136q28-28 68-28t68 28l294 295 656-657q28-28 68-28t68 28l136 136q28 28 28 68z'/></svg>") no-repeat;_x000D_
}
_x000D_
<ul>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>This is my text, it's pretty long so it needs to wrap. Note that wrapping preserves the indentation that bullets had!</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Note: To solve the wrapping problem that other answers had:

  • we reserve 1.5m ems of space at the left of each <li>
  • then position the SVG at the start of that space (position: absolute; left: 0)

Here are more Font Awesome black icons.

Check this CODEPEN to see how you can add colors and change their size.

Differences between Oracle JDK and OpenJDK

  1. Oracle will deliver releases every three years, while OpenJDK will be released every six months.
  2. Oracle provides long term support for its releases. On the other hand, OpenJDK supports the changes to a release only until the next version is released.
  3. Oracle JDK was licensed under Oracle Binary Code License Agreement, whereas OpenJDK has the GNU General Public License (GNU GPL) version 2 with a linking exception.
  4. Oracle product has Flight Recorder, Java Mission Control, and Application Class-Data Sharing features, while OpenJDK has the Font Renderer feature.Also, Oracle has more Garbage Collection options and better renderers,
  5. Oracle JDK is fully developed by Oracle Corporation whereas the OpenJDK is developed by Oracle, OpenJDK, and the Java Community. However, the top-notch companies like Red Hat, Azul Systems, IBM, Apple Inc., SAP AG also take an active part in its development.

From Java 11 turn to a big change

Oracle will change its historical “BCL” license with a combination of an open source and commercial license

  • Oracle’s kit for Java 11 emits a warning when using the -XX:+UnlockCommercialFeatures option, whereas in OpenJDK builds, this option results in an error
  • Oracle JDK offers a configuration to provide usage log data to the “Advanced Management Console” tool
  • Oracle has always required third party cryptographic providers to be signed by a known certificate, while cryptography framework in OpenJDK has an open cryptographic interface, which means there is no restriction as to which providers can be used
  • Oracle JDK 11 will continue to include installers, branding, and JRE packaging, whereas OpenJDK builds are currently available as zip and tar.gz files
  • The javac –release command behaves differently for the Java 9 and Java 10 targets due to the presence of some additional modules in Oracle’s release
  • The output of the java –version and java -fullversion commands will distinguish Oracle’s builds from OpenJDK builds


Update : 25-Aug-2019



enter image description here

for more details oracle-vs-openjdk

Copy or rsync command

It's not really a question of what's more efficient.

The commands 'rsync', and 'cp' are not equivalent and achieve different goals.

1- rsync can preserve the time of creation of existing files. (using -a option)
2- rsync will run multiprocess and transfer using either local sockets or network sockets. (i.e. fork itself into multiple processes)
3- The multiprocessing, and threading will increase your throughput when copying large number of small files, and even with multiple larger files.

So bottom line is rsync is for large data, and cp is for smaller local copying. (MB to small GB range). When you start getting into multiple GB or in the TB range, go with rsync. And of course network copies, rsync all the way.

What is NODE_ENV and how to use it in Express?

NODE_ENV is an environmental variable that stands for node environment in express server.

It's how we set and detect which environment we are in.

It's very common using production and development.

Set:

export NODE_ENV=production

Get:

You can get it using app.get('env')

How to VueJS router-link active style

Let's make things simple, you don't need to read the document about a "custom tag" (as a 16 years web developer, I have enough this kind of tags, such as in struts, webwork, jsp, rails and now it's vuejs)

just press F12, and you will see the source code like:

    <div>
        <a href="#/topologies" class="luelue">page1</a> 
        <a href="#/" aria-current="page" class="router-link-exact-active router-link-active">page2</a> 
        <a href="#/databases" class="">page3</a>
    </div>

so just add styles for the .router-link-active or router-link-exact-active

if you want more details, check the router-link api:

https://router.vuejs.org/en/api/#router-link

How to add Drop-Down list (<select>) programmatically?

I have quickly made a function that can achieve this, it may not be the best way to do this but it simply works and should be cross browser, please also know that i am NOT a expert in JavaScript so any tips are great :)

Pure Javascript Create Element Solution

function createElement(){
    var element  = document.createElement(arguments[0]),
        text     = arguments[1],
        attr     = arguments[2],
        append   = arguments[3],
        appendTo = arguments[4];

    for(var key = 0; key < Object.keys(attr).length ; key++){
        var name = Object.keys(attr)[key],
             value = attr[name],
             tempAttr = document.createAttribute(name);
             tempAttr.value = value;
        element.setAttributeNode(tempAttr)
    }
    
    if(append){
        for(var _key = 0; _key < append.length; _key++) {
            element.appendChild(append[_key]);
        }
    }

    if(text) element.appendChild(document.createTextNode(text));

    if(appendTo){
        var target = appendTo === 'body' ? document.body : document.getElementById(appendTo);
        target.appendChild(element)
    }       

    return element;
}

lets see how we make this

<select name="drop1" id="Select1">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

here's how it works

    var options = [
        createElement('option', 'Volvo', {value: 'volvo'}),
        createElement('option', 'Saab', {value: 'saab'}),
        createElement('option', 'Mercedes', {value: 'mercedes'}),
        createElement('option', 'Audi', {value: 'audi'})
    ];


    createElement('select', null, // 'select' = name of element to create, null = no text to insert
        {id: 'Select1', name: 'drop1'}, // Attributes to attach
        [options[0], options[1], options[2], options[3]], // append all 4 elements
        'body' // append final element to body - this also takes a element by id without the #
    );

this is the params

createElement('tagName', 'Text to Insert', {any: 'attribute', here: 'like', id: 'mainContainer'}, [elements, to, append, to, this, element], 'body || container = where to append this element');

This function would suit if you have to append many element, if there is any way to improve this answer please let me know.

edit:

Here is a working demo

JSFiddle Demo

This can be highly customized to suit your project!

What Scala web-frameworks are available?

Prikrutil, I think we're on the same boat. I also come to Scala from Erlang. I like Nitrogen a lot so I decided to created a Scala web framework inspired by it.

Take a look at Xitrum. Its doc is quite extensive. From README:

Xitrum is an async and clustered Scala web framework and web server on top of Netty and Hazelcast:

  • It fills the gap between Scalatra and Lift: more powerful than Scalatra and easier to use than Lift. You can easily create both RESTful APIs and postbacks. Xitrum is controller-first like Scalatra, not view-first like Lift.
  • Annotation is used for URL routes, in the spirit of JAX-RS. You don't have to declare all routes in a single place.
  • Typesafe, in the spirit of Scala.
  • Async, in the spirit of Netty.
  • Sessions can be stored in cookies or clustered Hazelcast.
  • jQuery Validation is integrated for browser side and server side validation. i18n using GNU gettext, which means unlike most other solutions, both singular and plural forms are supported.
  • Conditional GET using ETag.

Hazelcast also gives:

  • In-process and clustered cache, you don't need separate cache servers.
  • In-process and clustered Comet, you can scale Comet to multiple web servers.

Follow the tutorial for a quick start.

Variables not showing while debugging in Eclipse

I found I needed to remove static declarations if I wanted to see the variables, but this works better...

Modify/view static variables while debugging in Eclipse

no overload for matches delegate 'system.eventhandler'

Yes there is a problem with Click event handler (klik) - First argument must be an object type and second must be EventArgs.

public void klik(object sender, EventArgs e) {
  //
}

If you want to paint on a form or control then use CreateGraphics method.

public void klik(object sender, EventArgs e) {
    Bitmap c = this.DrawMandel();
    Graphics gr = CreateGraphics();  // Graphics gr=(sender as Button).CreateGraphics();
    gr.DrawImage(b, 150, 200);
}

Python: Pandas Dataframe how to multiply entire column with a scalar

You can use the index of the column you want to apply the multiplication for

df.loc[:,6] *= -1

This will multiply the column with index 6 with -1.

bootstrap initially collapsed element

If removing the in class doesn't work for you, such was my case, you can force the collapsed initial state using the CSS display property:

...
<div id="collapseOne" class="accordion-body collapse" style="display: none;">
...

Turn off deprecated errors in PHP 5.3

All the previous answers are correct. Since no one have hinted out how to turn off all errors in PHP, I would like to mention it here:

error_reporting(0); // Turn off warning, deprecated,
                    // notice everything except error

Somebody might find it useful...

Reference an Element in a List of Tuples

You can get a list of the first element in each tuple using a list comprehension:

>>> my_tuples = [(1, 2, 3), ('a', 'b', 'c', 'd', 'e'), (True, False), 'qwerty']
>>> first_elts = [x[0] for x in my_tuples]
>>> first_elts
[1, 'a', True, 'q']

What does "collect2: error: ld returned 1 exit status" mean?

Include: #include<stdlib.h>

and use System("cls") instead of clrscr()

Get current value when change select option - Angular2

Template:

<select class="randomClass" id="randomId" (change) = 
"filterSelected($event.target.value)">

<option *ngFor = 'let type of filterTypes' [value]='type.value'>{{type.display}} 
</option>

</select>

Component:

public filterTypes = [{
  value : 'New', display : 'Open'
},
{
  value : 'Closed', display : 'Closed'
}]


filterSelected(selectedValue:string){
  console.log('selected value= '+selectedValue)

}

Check if TextBox is empty and return MessageBox?

Adding on to what @tjg184 said, you could do something like...

if (String.IsNullOrEmpty(MaterialTextBox.Text.Trim())) 

...

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

For MySQL:

ALTER TABLE MyTable ADD MyId INT AUTO_INCREMENT PRIMARY KEY;

Selecting non-blank cells in Excel with VBA

The following VBA code should get you started. It will copy all of the data in the original workbook to a new workbook, but it will have added 1 to each value, and all blank cells will have been ignored.

Option Explicit

Public Sub exportDataToNewBook()
    Dim rowIndex As Integer
    Dim colIndex As Integer
    Dim dataRange As Range
    Dim thisBook As Workbook
    Dim newBook As Workbook
    Dim newRow As Integer
    Dim temp

    '// set your data range here
    Set dataRange = Sheet1.Range("A1:B100")

    '// create a new workbook
    Set newBook = Excel.Workbooks.Add

    '// loop through the data in book1, one column at a time
    For colIndex = 1 To dataRange.Columns.Count
        newRow = 0
        For rowIndex = 1 To dataRange.Rows.Count
            With dataRange.Cells(rowIndex, colIndex)

            '// ignore empty cells
            If .value <> "" Then
                newRow = newRow + 1
                temp = doSomethingWith(.value)
                newBook.ActiveSheet.Cells(newRow, colIndex).value = temp
                End If

            End With
        Next rowIndex
    Next colIndex
End Sub


Private Function doSomethingWith(aValue)

    '// This is where you would compute a different value
    '// for use in the new workbook
    '// In this example, I simply add one to it.
    aValue = aValue + 1

    doSomethingWith = aValue
End Function

View a specific Git commit

git show <revhash>

Documentation here. Or if that doesn't work, try Google Code's GIT Documentation

onCreateOptionsMenu inside Fragments

I tried the @Alexander Farber and @Sino Raj answers. Both answers are nice, but I couldn't use the onCreateOptionsMenu inside my fragment, until I discover what was missing:

Add setSupportActionBar(toolbar) in my Activity, like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.id.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
}

I hope this answer can be helpful for someone with the same problem.

SQLite Reset Primary Key Field

Try this:

delete from your_table;    
delete from sqlite_sequence where name='your_table';

SQLite Autoincrement

SQLite keeps track of the largest ROWID that a table has ever held using the special SQLITE_SEQUENCE table. The SQLITE_SEQUENCE table is created and initialized automatically whenever a normal table that contains an AUTOINCREMENT column is created. The content of the SQLITE_SEQUENCE table can be modified using ordinary UPDATE, INSERT, and DELETE statements. But making modifications to this table will likely perturb the AUTOINCREMENT key generation algorithm. Make sure you know what you are doing before you undertake such changes.

Unable to read repository at http://download.eclipse.org/releases/indigo

My issue was the Eclipse Marketplace client needed updating.

After trying Fredriks solution of

Go to Window -> Preferences -> Install/update: Available Software sites. Then remove and add the indigo site. Just remember to copy the adress so you can add it again.

The Marketplace client wouldn't load. But I could access it via a browser. So, I went to the Help -> Eclipse Marketplace it loaded fine

Clicked on Installed and found the Eclipse Marketplace Client and it had so i clicked it it updated and then when I did the standard update everything worked.

The type must be a reference type in order to use it as parameter 'T' in the generic type or method

I can't repro, but I suspect that in your actual code there is a constraint somewhere that T : class - you need to propagate that to make the compiler happy, for example (hard to say for sure without a repro example):

public class Derived<SomeModel> : Base<SomeModel> where SomeModel : class, IModel
                                                                    ^^^^^
                                                                 see this bit

Uncaught TypeError: Cannot assign to read only property

I tried changing year to a different term, and it worked.

public_methods : {
    get: function() {
        return this._year;
    },

    set: function(newValue) {
        if(newValue > this.originYear) {
            this._year = newValue;
            this.edition += newValue - this.originYear;
        }
    }
}

How to unload a package without restarting R

I would like to add an alternative solution. This solution does not directly answer your question on unloading a package but, IMHO, provides a cleaner alternative to achieve your desired goal, which I understand, is broadly concerned with avoiding name conflicts and trying different functions, as stated:

mostly because restarting R as I try out different, conflicting packages is getting frustrating, but conceivably this could be used in a program to use one function and then another--although namespace referencing is probably a better idea for that use

Solution

Function with_package offered via the withr package offers the possibility to:

attache a package to the search path, executes the code, then removes the package from the search path. The package namespace is not unloaded, however.

Example

library(withr)
with_package("ggplot2", {
  ggplot(mtcars) + geom_point(aes(wt, hp))
})
# Calling geom_point outside withr context 
exists("geom_point")
# [1] FALSE

geom_point used in the example is not accessible from the global namespace. I reckon it may be a cleaner way of handling conflicts than loading and unloading packages.

IIS_IUSRS and IUSR permissions in IIS8

I hate to post my own answer, but some answers recently have ignored the solution I posted in my own question, suggesting approaches that are nothing short of foolhardy.

In short - you do not need to edit any Windows user account privileges at all. Doing so only introduces risk. The process is entirely managed in IIS using inherited privileges.

Applying Modify/Write Permissions to the Correct User Account

  1. Right-click the domain when it appears under the Sites list, and choose Edit Permissions

    enter image description here

    Under the Security tab, you will see MACHINE_NAME\IIS_IUSRS is listed. This means that IIS automatically has read-only permission on the directory (e.g. to run ASP.Net in the site). You do not need to edit this entry.

    enter image description here

  2. Click the Edit button, then Add...

  3. In the text box, type IIS AppPool\MyApplicationPoolName, substituting MyApplicationPoolName with your domain name or whatever application pool is accessing your site, e.g. IIS AppPool\mydomain.com

    enter image description here

  4. Press the Check Names button. The text you typed will transform (notice the underline):

    enter image description here

  5. Press OK to add the user

  6. With the new user (your domain) selected, now you can safely provide any Modify or Write permissions

    enter image description here

What's the difference between struct and class in .NET?

From Microsoft's Choosing Between Class and Struct ...

As a rule of thumb, the majority of types in a framework should be classes. There are, however, some situations in which the characteristics of a value type make it more appropriate to use structs.

? CONSIDER a struct instead of a class:

  • If instances of the type are small and commonly short-lived or are commonly embedded in other objects.

X AVOID a struct unless the type has all of the following characteristics:

  • It logically represents a single value, similar to primitive types (int, double, etc.).
  • It has an instance size under 16 bytes.
  • It is immutable. (cannot be changed)
  • It will not have to be boxed frequently.

How can I uninstall an application using PowerShell?

To fix up the second method in Jeff Hillman's post, you could either do a:

$app = Get-WmiObject 
            -Query "SELECT * FROM Win32_Product WHERE Name = 'Software Name'"

Or

$app = Get-WmiObject -Class Win32_Product `
                     -Filter "Name = 'Software Name'"

Practical uses for AtomicInteger

The primary use of AtomicInteger is when you are in a multithreaded context and you need to perform thread safe operations on an integer without using synchronized. The assignation and retrieval on the primitive type int are already atomic but AtomicInteger comes with many operations which are not atomic on int.

The simplest are the getAndXXX or xXXAndGet. For instance getAndIncrement() is an atomic equivalent to i++ which is not atomic because it is actually a short cut for three operations: retrieval, addition and assignation. compareAndSet is very useful to implements semaphores, locks, latches, etc.

Using the AtomicInteger is faster and more readable than performing the same using synchronization.

A simple test:

public synchronized int incrementNotAtomic() {
    return notAtomic++;
}

public void performTestNotAtomic() {
    final long start = System.currentTimeMillis();
    for (int i = 0 ; i < NUM ; i++) {
        incrementNotAtomic();
    }
    System.out.println("Not atomic: "+(System.currentTimeMillis() - start));
}

public void performTestAtomic() {
    final long start = System.currentTimeMillis();
    for (int i = 0 ; i < NUM ; i++) {
        atomic.getAndIncrement();
    }
    System.out.println("Atomic: "+(System.currentTimeMillis() - start));
}

On my PC with Java 1.6 the atomic test runs in 3 seconds while the synchronized one runs in about 5.5 seconds. The problem here is that the operation to synchronize (notAtomic++) is really short. So the cost of the synchronization is really important compared to the operation.

Beside atomicity AtomicInteger can be use as a mutable version of Integer for instance in Maps as values.

In javascript, how do you search an array for a substring match

Just search for the string in plain old indexOf

arr.forEach(function(a){
    if (typeof(a) == 'string' && a.indexOf('curl')>-1) {
            console.log(a);
    }        
});

Two dimensional array in python

the above method did not work for me for a for loop, where I wanted to transfer data from a 2D array to a new array under an if the condition. This method would work

a_2d_list = [[1, 2], [3, 4]]
a_2d_list.append([5, 6])
print(a_2d_list)

OUTPUT - [[1, 2], [3, 4], [5, 6]]

java.lang.IllegalArgumentException: contains a path separator

The solution is:

FileInputStream fis = new FileInputStream (new File(NAME_OF_FILE));  // 2nd line

The openFileInput method doesn't accept path separators.

Don't forget to

fis.close();

at the end.

How to add new line in Markdown presentation?

How to add new line in Markdown presentation?

Check the following resource Line Return

To force a line return, place two empty spaces at the end of a line.

Non-numeric Argument to Binary Operator Error in R

Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.

- is the 'binary operator' your error is referencing, and either CurrentDay or MA (or both) are non-numeric.

A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). + is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).

R only knows how to apply + (and other binary operators, such as -) to numeric arguments:

> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator

When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.

EDIT:

Your error lies in the use of [ instead of [[. Because Day is a list, subsetting with [ will return a list, not a numeric vector. [[, however, returns an object of the class of the item contained in the list:

> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator

> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3

Transaction, as you've defined it, returns a list of two vectors. Above, Day is a list contain one vector. Day2, however, is simply a vector.

Differences between ConstraintLayout and RelativeLayout

Following are the differences/advantages:

  1. Constraint Layout has dual power of both Relative Layout as well as Linear layout: Set relative positions of views ( like Relative layout ) and also set weights for dynamic UI (which was only possible in Linear Layout).

  2. A very powerful use is grouping of elements by forming a chain. This way we can form a group of views which as a whole can be placed in a desired way without adding another layer of hierarchy just to form another group of views.

  3. In addition to weights, we can apply horizontal and vertical bias which is nothing but the percentage of displacement from the centre. ( bias of 0.5 means centrally aligned. Any value less or more means corresponding movement in the respective direction ) .

  4. Another very important feature is that it respects and provides the functionality to handle the GONE views so that layouts do not break if some view is set to GONE through java code. More can be found here: https://developer.android.com/reference/android/support/constraint/ConstraintLayout.html#VisibilityBehavior

  5. Provides power of automatic constraint applying by the use of Blue print and Visual Editor tool which makes it easy to design a page.

All these features lead to flattening of the view hierarchy which improves performance and also helps in making responsive and dynamic UI which can more easily adapt to different screen size and density.

Here is the best place to learn quickly: https://codelabs.developers.google.com/codelabs/constraint-layout/#0

How to decrease prod bundle size?

Taken from the angular docs v9 (https://angular.io/guide/workspace-config#alternate-build-configurations):

By default, a production configuration is defined, and the ng build command has --prod option that builds using this configuration. The production configuration sets defaults that optimize the app in a number of ways, such as bundling files, minimizing excess whitespace, removing comments and dead code, and rewriting code to use short, cryptic names ("minification").

Additionally you can compress all your deployables with @angular-builders/custom-webpack:browser builder where your custom webpack.config.js looks like that:

module.exports = {
  entry: {
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].[hash].js'
  },
  plugins: [
    new CompressionPlugin({
      deleteOriginalAssets: true,
    })
  ]
};

Afterwards you will have to configure your web server to serve compressed content e.g. with nginx you have to add to your nginx.conf:

server {
    gzip on;
    gzip_types      text/plain application/xml;
    gzip_proxied    no-cache no-store private expired auth;
    gzip_min_length 1000;
    ...
}

In my case the dist folder shrank from 25 to 5 mb after just using the --prod in ng build and then further shrank to 1.5mb after compression.

Open application after clicking on Notification

Looks like you missed this part,

notification.contentIntent = pendingIntent;

Try adding this and it should work.

What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany association

I'd just like to add that @JoinColumn does not always have to be related to the physical information location as this answer suggests. You can combine @JoinColumn with @OneToMany even if the parent table has no table data pointing to the child table.

How to define unidirectional OneToMany relationship in JPA

Unidirectional OneToMany, No Inverse ManyToOne, No Join Table

It seems to only be available in JPA 2.x+ though. It's useful for situations where you want the child class to just contain the ID of the parent, not a full on reference.

Android Camera Preview Stretched

I'm using this method -> based on API Demos to get my Preview Size:

private Camera.Size getOptimalPreviewSize(List<Camera.Size> sizes, int w, int h) {
        final double ASPECT_TOLERANCE = 0.1;
        double targetRatio=(double)h / w;

        if (sizes == null) return null;

        Camera.Size optimalSize = null;
        double minDiff = Double.MAX_VALUE;

        int targetHeight = h;

        for (Camera.Size size : sizes) {
            double ratio = (double) size.width / size.height;
            if (Math.abs(ratio - targetRatio) > ASPECT_TOLERANCE) continue;
            if (Math.abs(size.height - targetHeight) < minDiff) {
                optimalSize = size;
                minDiff = Math.abs(size.height - targetHeight);
            }
        }

        if (optimalSize == null) {
            minDiff = Double.MAX_VALUE;
            for (Camera.Size size : sizes) {
                if (Math.abs(size.height - targetHeight) < minDiff) {
                    optimalSize = size;
                    minDiff = Math.abs(size.height - targetHeight);
                }
            }
        }
        return optimalSize;
    }

As you can see you have to input width and height of your screen. This method will calculate screen ratio based on those values and then from the list of supportedPreviewSizes it will choose the best for you from avaliable ones. Get your supportedPreviewSize list in place where Camera object isn't null by using

mSupportedPreviewSizes = mCamera.getParameters().getSupportedPreviewSizes();

And then on in onMeasure you can get your optimal previewSize like that:

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        final int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
        final int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
        setMeasuredDimension(width, height);

        if (mSupportedPreviewSizes != null) {
           mPreviewSize = getOptimalPreviewSize(mSupportedPreviewSizes, width, height);
        }
    }

And then (in my code in surfaceChanged method, like I said I'm using API Demos structure of CameraActivity code, you can generate it in Eclipse):

Camera.Parameters parameters = mCamera.getParameters();
parameters.setPreviewSize(mPreviewSize.width, mPreviewSize.height);
mCamera.setParameters(parameters);
mCamera.startPreview();

And one hint for you, because I did almost the same app like you. Good practice for Camera Activity is to hide StatusBar. Applications like Instagram are doing it. It reduces your screen height value and change your ratio value. It is possible to get strange Preview Sizes on some devices (your SurfaceView will be cut a little)


And to answer your question, how to check if your preview ratio is correct? Then get height and width of parameters that you set in:

mCamera.setParameters(parameters);

your set ratio is equal to height/width. If you want camera to look good on your screen then height/width ratio of parameters that you set to camera must be the same as height(minus status bar)/width ratio of your screen.

How to convert Map keys to array?

OK, let's go a bit more comprehensive and start with what's Map for those who don't know this feature in JavaScript... MDN says:

The Map object holds key-value pairs and remembers the original insertion order of the keys.
Any value (both objects and primitive values) may be used as either a key or a value.

As you mentioned, you can easily create an instance of Map using new keyword... In your case:

let myMap = new Map().set('a', 1).set('b', 2);

So let's see...

The way you mentioned is an OK way to do it, but yes, there are more concise ways to do that...

Map has many methods which you can use, like set() which you already used to assign the key values...

One of them is keys() which returns all the keys...

In your case, it will return:

MapIterator {"a", "b"}

and you easily convert them to an Array using ES6 ways, like spread operator...

const b = [...myMap.keys()];

C++ float array initialization

No, it sets all members/elements that haven't been explicitly set to their default-initialisation value, which is zero for numeric types.

How to auto-scroll to end of div when data is added?

If you don't know when data will be added to #data, you could set an interval to update the element's scrollTop to its scrollHeight every couple of seconds. If you are controlling when data is added, just call the internal of the following function after the data has been added.

window.setInterval(function() {
  var elem = document.getElementById('data');
  elem.scrollTop = elem.scrollHeight;
}, 5000);

Running conda with proxy

I was able to get it working without putting in the username and password:

conda config --set proxy_servers.https https://address:port

How to create a inner border for a box in html?

Html:

<div class="outerDiv">
    <div class="innerDiv">Content</div>
</div>

CSS:

.outerDiv{
    background: #000;
    padding: 10px;
 }

 .innerDiv{
     border: 2px dashed #fff;
     min-height: 200px; //adding min-height as there is no content inside

 }

Sort & uniq in Linux shell

Nothing, they will produce the same result

How can I write a regex which matches non greedy?

The non-greedy ? works perfectly fine. It's just that you need to select dot matches all option in the regex engines (regexpal, the engine you used, also has this option) you are testing with. This is because, regex engines generally don't match line breaks when you use .. You need to tell them explicitly that you want to match line-breaks too with .

For example,

<img\s.*?>

works fine!

Check the results here.

Also, read about how dot behaves in various regex flavours.

How to select ALL children (in any level) from a parent in jQuery?

It seems that the original test case is wrong.

I can confirm that the selector #my_parent_element * works with unbind().

Let's take the following html as an example:

<div id="#my_parent_element">
  <div class="div1">
    <div class="div2">hello</div>
    <div class="div3">my</div>
  </div>
  <div class="div4">name</div>
  <div class="div5">
    <div class="div6">is</div>
    <div class="div7">
      <div class="div8">marco</div>
      <div class="div9">(try and click on any word)!</div>
    </div>
  </div>
</div>
<button class="unbind">Now, click me and try again</button>

And the jquery bit:

$('.div1,.div2,.div3,.div4,.div5,.div6,.div7,.div8,.div9').click(function() {
  alert('hi!');
})
$('button.unbind').click(function() {
  $('#my_parent_element *').unbind('click');
})

You can try it here: http://jsfiddle.net/fLvwbazk/7/

Can you do a partial checkout with Subversion?

Not in any especially useful way, no. You can check out subtrees (as in Bobby Jack's suggestion), but then you lose the ability to update/commit them atomically; to do that, they need to be placed under their common parent, and as soon as you check out the common parent, you'll download everything under that parent. Non-recursive isn't a good option, because you want updates and commits to be recursive.

Python String and Integer concatenation

If we want output like 'string0123456789' then we can use map function and join method of string.

>>> 'string'+"".join(map(str,xrange(10)))
'string0123456789'

If we want List of string values then use list comprehension method.

>>> ['string'+i for i in map(str,xrange(10))]
['string0', 'string1', 'string2', 'string3', 'string4', 'string5', 'string6', 'string7', 'string8', 'string9']

Note:

Use xrange() for Python 2.x

USe range() for Python 3.x

.htaccess not working on localhost with XAMPP

Without seeing your system it's hard to tell what's wrong but try the following (comment answer if these didn't work WITH log error messages)

[STOP your Apache server instance. Ensure it's not running!]

1) move apache server/install to a folder that has no long file names and spaces

2) check httpd.conf in install\conf folder and look for AccessFileName. If it's .htaccess change it to a file name windows accepts (e.g. conf.htaccess)

3) double-check that your htaccess file gets read: add some uninterpretable garbage to it and start server: you should get an Error 500. If you don't, file is not getting read, re-visit httpd.conf file (if that looks OK, check if this is the only file which defines htaccess and it's location and it does at one place -within the file- only; also check if both httpd.conf and htaccess files are accessible: not encrypted, file access rights are not limited, drive/path available -and no long folder path and file names-)
STOP Apache again, then go on:
4) If you have IIS too on your system, stop it (uninstall it too if you can) from services.msc

5) Add the following to the top of your valid htaccess file:
RewriteEngine On
RewriteLog "/path/logs/rewrite.log" #make sure path is there!
RewriteLogLevel 9

6) Empty your [apache]\logs folder (if you use another folder, then that one :)

7) Check the following entries are set and correct:
Action application/x-httpd-php "c:/your-php5-path/php-cgi.exe"
LoadModule php5_module "c:/your-php5-path/php5apache2.dll"
LoadModule rewrite_module modules/mod_rewrite.so
Avoid long path names and spaces in folder names for phpX install too!

8) START apache server

You can do all the steps above or go one-by-one, your call. But at the end of the day make sure you tried everything above!
If system still blows up and you can't fix it, copy&paste error message(s) from log folder for further assistance

Error when trying to inject a service into an angular component "EXCEPTION: Can't resolve all parameters for component", why?

For the benefit of searchers; I got this error. It was simply a missing @ symbol.

I.e. This produces the Can't resolve all parameters for MyHttpService error.

Injectable()
export class MyHttpService{
}

Adding the missing @ symbol fixes it.

@Injectable()
export class MyHttpService{
}

Remove quotes from a character vector in R

nump function :)

> nump <- function(x) print(formatC(x, format="fg", big.mark=","), quote=FALSE)

correct answer:

x <- 1234567890123456

> nump(x)

[1] 1,234,567,890,123,456 

Plot 3D data in R

I think the following code is close to what you want

x    <- c(0.1, 0.2, 0.3, 0.4, 0.5)
y    <- c(1, 2, 3, 4, 5)
zfun <- function(a,b) {a*b * ( 0.9 + 0.2*runif(a*b) )}
z    <- outer(x, y, FUN="zfun")

It gives data like this (note that x and y are both increasing)

> x
[1] 0.1 0.2 0.3 0.4 0.5
> y
[1] 1 2 3 4 5
> z
          [,1]      [,2]      [,3]      [,4]      [,5]
[1,] 0.1037159 0.2123455 0.3244514 0.4106079 0.4777380
[2,] 0.2144338 0.4109414 0.5586709 0.7623481 0.9683732
[3,] 0.3138063 0.6015035 0.8308649 1.2713930 1.5498939
[4,] 0.4023375 0.8500672 1.3052275 1.4541517 1.9398106
[5,] 0.5146506 1.0295172 1.5257186 2.1753611 2.5046223

and a graph like

persp(x, y, z)

persp(x, y, z)

Return multiple values in JavaScript?

I know of two ways to do this: 1. Return as Array 2. Return as Object

Here's an example I found:

<script>
// Defining function
function divideNumbers(dividend, divisor){
    var quotient = dividend / divisor;
    var arr = [dividend, divisor, quotient];
    return arr;
}

// Store returned value in a variable
var all = divideNumbers(10, 2);

// Displaying individual values
alert(all[0]); // 0utputs: 10
alert(all[1]); // 0utputs: 2
alert(all[2]); // 0utputs: 5
</script>



<script>
// Defining function
function divideNumbers(dividend, divisor){
    var quotient = dividend / divisor;
    var obj = {
        dividend: dividend,
        divisor: divisor,
        quotient: quotient
    };
    return obj;
}

// Store returned value in a variable
var all = divideNumbers(10, 2);

// Displaying individual values
alert(all.dividend); // 0utputs: 10
alert(all.divisor); // 0utputs: 2
alert(all.quotient); // 0utputs: 5
</script>

How to open an Excel file in C#?

For editing Excel files from within a C# application, I recently started using NPOI. I'm very satisfied with it.

Reading a cell value in Excel vba and write in another Cell

I have this function for this case ..

Function GetValue(r As Range, Tag As String) As Integer
Dim c, nRet As String
Dim n, x As Integer
Dim bNum As Boolean

c = r.Value
n = InStr(c, Tag)
For x = n + 1 To Len(c)
  Select Case Mid(c, x, 1)
    Case ":":    bNum = True
    Case " ": Exit For
    Case Else: If bNum Then nRet = nRet & Mid(c, x, 1)
  End Select
Next
GetValue = val(nRet)
End Function

To fill cell BC .. (assumed that you check cell A1)

Worksheets("Übersicht_2013").Cells(i, "BC") = GetValue(range("A1"),"S")

Understanding the Linux oom-killer's logs

This webpage have an explanation and a solution.

The solution is:

To fix this problem the behavior of the kernel has to be changed, so it will no longer overcommit the memory for application requests. Finally I have included those mentioned values into the /etc/sysctl.conf file, so they get automatically applied on start-up:

vm.overcommit_memory = 2

vm.overcommit_ratio = 80

How do you find the row count for all your tables in Postgres

The hacky, practical answer for people trying to evaluate which Heroku plan they need and can't wait for heroku's slow row counter to refresh:

Basically you want to run \dt in psql, copy the results to your favorite text editor (it will look like this:

 public | auth_group                     | table | axrsosvelhutvw
 public | auth_group_permissions         | table | axrsosvelhutvw
 public | auth_permission                | table | axrsosvelhutvw
 public | auth_user                      | table | axrsosvelhutvw
 public | auth_user_groups               | table | axrsosvelhutvw
 public | auth_user_user_permissions     | table | axrsosvelhutvw
 public | background_task                | table | axrsosvelhutvw
 public | django_admin_log               | table | axrsosvelhutvw
 public | django_content_type            | table | axrsosvelhutvw
 public | django_migrations              | table | axrsosvelhutvw
 public | django_session                 | table | axrsosvelhutvw
 public | exercises_assignment           | table | axrsosvelhutvw

), then run a regex search and replace like this:

^[^|]*\|\s+([^|]*?)\s+\| table \|.*$

to:

select '\1', count(*) from \1 union/g

which will yield you something very similar to this:

select 'auth_group', count(*) from auth_group union
select 'auth_group_permissions', count(*) from auth_group_permissions union
select 'auth_permission', count(*) from auth_permission union
select 'auth_user', count(*) from auth_user union
select 'auth_user_groups', count(*) from auth_user_groups union
select 'auth_user_user_permissions', count(*) from auth_user_user_permissions union
select 'background_task', count(*) from background_task union
select 'django_admin_log', count(*) from django_admin_log union
select 'django_content_type', count(*) from django_content_type union
select 'django_migrations', count(*) from django_migrations union
select 'django_session', count(*) from django_session
;

(You'll need to remove the last union and add the semicolon at the end manually)

Run it in psql and you're done.

            ?column?            | count
--------------------------------+-------
 auth_group_permissions         |     0
 auth_user_user_permissions     |     0
 django_session                 |  1306
 django_content_type            |    17
 auth_user_groups               |   162
 django_admin_log               |  9106
 django_migrations              |    19
[..]

How do you test to see if a double is equal to NaN?

Use the static Double.isNaN(double) method, or your Double's .isNaN() method.

// 1. static method
if (Double.isNaN(doubleValue)) {
    ...
}
// 2. object's method
if (doubleObject.isNaN()) {
    ...
}

Simply doing:

if (var == Double.NaN) {
    ...
}

is not sufficient due to how the IEEE standard for NaN and floating point numbers is defined.

Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code

I had the same problem in Xcode 11.5 after revoking a certificate through Apple's developer homepage and adding it again (even though it looked different afterwards):

Every time I tried to archive my app, it would fail at the very end (not the pods but my actual app) with the same PhaseScriptExecution failed with a nonzero exit code error message. There is/was a valid team with an "Apple Development" signing certificate in "Signing & Capabilities" (project file in Xcode) and locking & unlocking the keychain, cleaning & building the project, restarting,... didn't work.

The problem was caused by having two active certificates of the same type that I must have added on accident, in addition to the renewed one. I deleted both the renewed one and the duplicate and it worked again.

You can find your certificates here or find the page like this:

Also check that there aren't any duplicates in your keychain! Be careful though - don't delete or add anything unless you know what you're doing, otherwise you might create a huge mess!

What is the difference between YAML and JSON?

This question is 6 years old, but strangely, none of the answers really addresses all four points (speed, memory, expressiveness, portability).

Speed

Obviously this is implementation-dependent, but because JSON is so widely used, and so easy to implement, it has tended to receive greater native support, and hence speed. Considering that YAML does everything that JSON does, plus a truckload more, it's likely that of any comparable implementations of both, the JSON one will be quicker.

However, given that a YAML file can be slightly smaller than its JSON counterpart (due to fewer " and , characters), it's possible that a highly optimised YAML parser might be quicker in exceptional circumstances.

Memory

Basically the same argument applies. It's hard to see why a YAML parser would ever be more memory efficient than a JSON parser, if they're representing the same data structure.

Expressiveness

As noted by others, Python programmers tend towards preferring YAML, JavaScript programmers towards JSON. I'll make these observations:

  • It's easy to memorise the entire syntax of JSON, and hence be very confident about understanding the meaning of any JSON file. YAML is not truly understandable by any human. The number of subtleties and edge cases is extreme.
  • Because few parsers implement the entire spec, it's even harder to be certain about the meaning of a given expression in a given context.
  • The lack of comments in JSON is, in practice, a real pain.

Portability

It's hard to imagine a modern language without a JSON library. It's also hard to imagine a JSON parser implementing anything less than the full spec. YAML has widespread support, but is less ubiquitous than JSON, and each parser implements a different subset. Hence YAML files are less interoperable than you might think.

Summary

JSON is the winner for performance (if relevant) and interoperability. YAML is better for human-maintained files. HJSON is a decent compromise although with much reduced portability. JSON5 is a more reasonable compromise, with well-defined syntax.

Android - How to achieve setOnClickListener in Kotlin?

Suppose you have textView to click

text_view.text = "Hello Kotlin";

text_view.setOnClickListener {
    val intent = Intent(this@MainActivity, SecondActivity::class.java)
    intent.putExtra("key", "Kotlin")
    startActivity(intent)
}

Amazon S3 - HTTPS/SSL - Is it possible?

payton109’s answer is correct if you’re in the default US-EAST-1 region. If your bucket is in a different region, use a slightly different URL:

https://s3-<region>.amazonaws.com/your.domain.com/some/asset

Where <region> is the bucket location name. For example, if your bucket is in the us-west-2 (Oregon) region, you can do this:

https://s3-us-west-2.amazonaws.com/your.domain.com/some/asset

How do I test if a string is empty in Objective-C?

The best way is to use the category.
You can check the following function. Which has all the conditions to check.

-(BOOL)isNullString:(NSString *)aStr{
        if([(NSNull *)aStr isKindOfClass:[NSNull class]]){
            return YES;
        }
        if ((NSNull *)aStr  == [NSNull null]) {
            return YES;
        }
        if ([aStr isKindOfClass:[NSNull class]]){
            return YES;
        }
        if(![[aStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]){
            return YES;
        }
        return NO;
    }

Preferred way of loading resources in Java

I know it really late for another answer but I just wanted to share what helped me at the end. It will also load resources/files from the absolute path of the file system (not only the classpath's).

public class ResourceLoader {

    public static URL getResource(String resource) {
        final List<ClassLoader> classLoaders = new ArrayList<ClassLoader>();
        classLoaders.add(Thread.currentThread().getContextClassLoader());
        classLoaders.add(ResourceLoader.class.getClassLoader());

        for (ClassLoader classLoader : classLoaders) {
            final URL url = getResourceWith(classLoader, resource);
            if (url != null) {
                return url;
            }
        }

        final URL systemResource = ClassLoader.getSystemResource(resource);
        if (systemResource != null) {
            return systemResource;
        } else {
            try {
                return new File(resource).toURI().toURL();
            } catch (MalformedURLException e) {
                return null;
            }
        }
    }

    private static URL getResourceWith(ClassLoader classLoader, String resource) {
        if (classLoader != null) {
            return classLoader.getResource(resource);
        }
        return null;
    }

}

When or Why to use a "SET DEFINE OFF" in Oracle Database

By default, SQL Plus treats '&' as a special character that begins a substitution string. This can cause problems when running scripts that happen to include '&' for other reasons:

SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');
Enter value for spencers: 
old   1: insert into customers (customer_name) values ('Marks & Spencers Ltd')
new   1: insert into customers (customer_name) values ('Marks  Ltd')

1 row created.

SQL> select customer_name from customers;

CUSTOMER_NAME
------------------------------
Marks  Ltd

If you know your script includes (or may include) data containing '&' characters, and you do not want the substitution behaviour as above, then use set define off to switch off the behaviour while running the script:

SQL> set define off
SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');

1 row created.

SQL> select customer_name from customers;

CUSTOMER_NAME
------------------------------
Marks & Spencers Ltd

You might want to add set define on at the end of the script to restore the default behaviour.

How can I force browsers to print background images in CSS?

Browsers, by default, have their option to print background-colors and images turned off. You can add some lines in CSS to bypass this. Just add:

* {
    -webkit-print-color-adjust: exact !important;   /* Chrome, Safari */
    color-adjust: exact !important;                 /*Firefox*/
}

Note: It's not working on the entire body but you could speciy it for a inner element or a container div element.

How to select records without duplicate on just one field in SQL?

DISTINCT is the keyword
For me your query is correct

Just try to do this first

SELECT DISTINCT title,id FROM tbl_countries

Later on you can try with order by.

Regex match digits, comma and semicolon?

You almost have it, you just left out 0 and forgot the quantifier.

word.matches("^[0-9,;]+$")

Resize iframe height according to content height in it

Below is my onload event handler.

I use an IFRAME within a jQuery UI dialog. Different usages will need some adjustments. This seems to do the trick for me (for now) in Internet Explorer 8 and Firefox 3.5. It might need some extra tweaking, but the general idea should be clear.

    function onLoadDialog(frame) {
    try {
        var body = frame.contentDocument.body;
        var $body = $(body);
        var $frame = $(frame);
        var contentDiv = frame.parentNode;
        var $contentDiv = $(contentDiv);

        var savedShow = $contentDiv.dialog('option', 'show');
        var position = $contentDiv.dialog('option', 'position');
        // disable show effect to enable re-positioning (UI bug?)
        $contentDiv.dialog('option', 'show', null);
        // show dialog, otherwise sizing won't work
        $contentDiv.dialog('open');

        // Maximize frame width in order to determine minimal scrollHeight
        $frame.css('width', $contentDiv.dialog('option', 'maxWidth') -
                contentDiv.offsetWidth + frame.offsetWidth);

        var minScrollHeight = body.scrollHeight;
        var maxWidth = body.offsetWidth;
        var minWidth = 0;
        // decrease frame width until scrollHeight starts to grow (wrapping)
        while (Math.abs(maxWidth - minWidth) > 10) {
            var width = minWidth + Math.ceil((maxWidth - minWidth) / 2);
            $body.css('width', width);
            if (body.scrollHeight > minScrollHeight) {
                minWidth = width;
            } else {
                maxWidth = width;
            }
        }
        $frame.css('width', maxWidth);
        // use maximum height to avoid vertical scrollbar (if possible)
        var maxHeight = $contentDiv.dialog('option', 'maxHeight')
        $frame.css('height', maxHeight);
        $body.css('width', '');
        // correct for vertical scrollbar (if necessary)
        while (body.clientWidth < maxWidth) {
            $frame.css('width', maxWidth + (maxWidth - body.clientWidth));
        }

        var minScrollWidth = body.scrollWidth;
        var minHeight = Math.min(minScrollHeight, maxHeight);
        // descrease frame height until scrollWidth decreases (wrapping)
        while (Math.abs(maxHeight - minHeight) > 10) {
            var height = minHeight + Math.ceil((maxHeight - minHeight) / 2);
            $body.css('height', height);
            if (body.scrollWidth < minScrollWidth) {
                minHeight = height;
            } else {
                maxHeight = height;
            }
        }
        $frame.css('height', maxHeight);
        $body.css('height', '');

        // reset widths to 'auto' where possible
        $contentDiv.css('width', 'auto');
        $contentDiv.css('height', 'auto');
        $contentDiv.dialog('option', 'width', 'auto');

        // re-position the dialog
        $contentDiv.dialog('option', 'position', position);

        // hide dialog
        $contentDiv.dialog('close');
        // restore show effect
        $contentDiv.dialog('option', 'show', savedShow);
        // open using show effect
        $contentDiv.dialog('open');
        // remove show effect for consecutive requests
        $contentDiv.dialog('option', 'show', null);

        return;
    }

    //An error is raised if the IFrame domain != its container's domain
    catch (e) {
        window.status = 'Error: ' + e.number + '; ' + e.description;
        alert('Error: ' + e.number + '; ' + e.description);
    }
};

ImportError: No module named Crypto.Cipher

Worked for me (Ubuntu 17.10)

Removing venv and creating it again with python v3.6

pip3 install PyJWT
sudo apt-get install build-essential libgmp3-dev python3-dev
pip3 install cryptography
pip3 install pycryptodome
pip3 install pycryptodomex

Pycrypto is deprecated, had problems with it, used Pycryptodome

Fixed header, footer with scrollable content

As of 2013: This would be my approach. jsFiddle:


HTML

<header class="container global-header">
    <h1>Header (fixed)</h1>
</header>

<div class="container main-content">
    <div class="inner-w">
        <h1>Main Content</h1>
    </div><!-- .inner-w -->
</div> <!-- .main-content -->

<footer class="container global-footer">
    <h3>Footer (fixed)</h3>
</footer>


SCSS

// User reset

* { // creates a natural box model layout
    -moz-box-sizing: border-box; 
    -webkit-box-sizing: border-box; 
    box-sizing: border-box; 
} // asume normalize.css


// structure

.container {
    position: relative;
    width: 100%;
    float: left;
    padding: 1em;
}


// type

body {
    font-family: arial;   
}

.main-content {
    h1 {
        font-size: 2em;
        font-weight: bold;
        margin-bottom: .2em;
    }
} // .main-content


// style

    // variables
    $global-header-height: 8em;
    $global-footer-height: 6em;

.global-header {
    position: fixed;
    top: 0; left: 0;
    background-color: gray;
    height: $global-header-height;
}

.main-content {
    background-color: orange;
    margin-top: $global-header-height;
    margin-bottom: $global-footer-height;
    z-index: -1; // so header will be on top
    min-height: 50em; // to make it long so you can see the scrolling
}

.global-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    height: $global-footer-height;
    background-color: gray;
}

Error: Uncaught (in promise): Error: Cannot match any routes Angular 2

As for me resetConfig only works

this.router.resetConfig(newRoutes);

Or concat with previous

this.router.resetConfig([...newRoutes, ...this.router.config]);

But keep in mind that the last must be always route with path **

Should you use rgba(0, 0, 0, 0) or rgba(255, 255, 255, 0) for transparency in CSS?

There are two ways of storing a color with alpha. The first is exactly as you see it, with each component as-is. The second is to use pre-multiplied alpha, where the color values are multiplied by the alpha after converting it to the range 0.0-1.0; this is done to make compositing easier. Ordinarily you shouldn't notice or care which way is implemented by any particular engine, but there are corner cases where you might, for example if you tried to increase the opacity of the color. If you use rgba(0, 0, 0, 0) you are less likely to to see a difference between the two approaches.

How to restart Jenkins manually?

Use the command line interface:

java -jar jenkins-cli.jar -s http://jenkins.example.com:8080/ -i /root/.ssh/id_rsa safe-restart

What is the difference between NULL, '\0' and 0?

A byte with a value of 0x00 is, on the ASCII table, the special character called NUL or NULL. In C, since you shouldn't embed control characters in your source code, this is represented in C strings with an escaped 0, i.e., \0.

But a true NULL is not a value. It is the absence of a value. For a pointer, it means the pointer has nothing to point to. In a database, it means there is no value in a field (which is not the same thing as saying the field is blank, 0, or filled with spaces).

The actual value a given system or database file format uses to represent a NULL isn't necessarily 0x00.

Ignoring upper case and lower case in Java

You have to use the String method .toLowerCase() or .toUpperCase() on both the input and the string you are trying to match it with.

Example:

public static void findPatient() {
    System.out.print("Enter part of the patient name: ");
    String name = sc.nextLine();

    System.out.print(myPatientList.showPatients(name));
}

//the other class
ArrayList<String> patientList;

public void showPatients(String name) {
    boolean match = false;

    for(String matchingname : patientList) {
        if (matchingname.toLowerCase().contains(name.toLowerCase())) {
            match = true;
        }
    }
}

Requested registry access is not allowed

This issue has to do with granting the necessary authorization to the user account the application runs on. To read a similar situation and a detailed response for the correct solution, as documented by Microsoft, feel free to visit this post: http://rambletech.wordpress.com/2011/10/17/requested-registry-access-is-not-allowed/

How to Define Callbacks in Android?

No need to define a new interface when you can use an existing one: android.os.Handler.Callback. Pass an object of type Callback, and invoke callback's handleMessage(Message msg).

Custom seekbar (thumb size, color and background)

Android custom SeekBar - custom track or progress, shape, size, background and thumb and for other seekbar customization see http://www.zoftino.com/android-seekbar-and-custom-seekbar-examples

Custom Track drawable

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background"
        android:gravity="center_vertical|fill_horizontal">
        <shape android:shape="rectangle"
            android:tint="#ffd600">
            <corners android:radius="8dp"/>
            <size android:height="30dp" />
            <solid android:color="#ffd600" />
        </shape>
    </item>
    <item android:id="@android:id/progress"
        android:gravity="center_vertical|fill_horizontal">
        <scale android:scaleWidth="100%">
            <selector>
                <item android:state_enabled="false"
                    android:drawable="@android:color/transparent" />
                <item>
                    <shape android:shape="rectangle"
                        android:tint="#f50057">
                        <corners android:radius="8dp"/>
                        <size android:height="30dp" />
                        <solid android:color="#f50057" />
                    </shape>
                </item>
            </selector>
        </scale>
    </item>
</layer-list>

Custom thumb drawable

?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle"
    android:thickness="4dp"
    android:useLevel="false"
    android:tint="#ad1457">
    <solid
        android:color="#ad1457" />
    <size
        android:width="32dp"
        android:height="32dp" />
</shape>

Output

enter image description here

Turning off eslint rule for a specific file

You can turn off specific rule for a file by using /*eslint [<rule: "off"], >]*/

/* eslint no-console: "off", no-mixed-operators: "off" */

Version: [email protected]

What is the Git equivalent for revision number?

I'd just like to note another possible approach - and that is by using git git-notes(1), in existence since v 1.6.6 (Note to Self - Git) (I'm using git version 1.7.9.5).

Basically, I used git svn to clone an SVN repository with linear history (no standard layout, no branches, no tags), and I wanted to compare revision numbers in the cloned git repository. This git clone doesn't have tags by default, so I cannot use git describe. The strategy here likely would work only for linear history - not sure how it would turn out with merges etc.; but here is the basic strategy:

  • Ask git rev-list for list of all commit history
    • Since rev-list is by default in "reverse chronological order", we'd use its --reverse switch to get list of commits sorted by oldest first
  • Use bash shell to
    • increase a counter variable on each commit as a revision counter,
    • generate and add a "temporary" git note for each commit
  • Then, browse the log by using git log with --notes, which will also dump a commit's note, which in this case would be the "revision number"
  • When done, erase the temporary notes (NB: I'm not sure if these notes are committed or not; they don't really show in git status)

First, let's note that git has a default location of notes - but you can also specify a ref(erence) for notes - which would store them in a different directory under .git; for instance, while in a git repo folder, you can call git notes get-ref to see what directory that will be:

$ git notes get-ref
refs/notes/commits
$ git notes --ref=whatever get-ref
refs/notes/whatever

The thing to be noted is that if you notes add with a --ref, you must also afterwards use that reference again - otherwise you may get errors like "No note found for object XXX...".

For this example, I have chosen to call the ref of the notes "linrev" (for linear revision) - this also means it is not likely the procedure will interfere with already existing notes. I am also using the --git-dir switch, since being a git newbie, I had some problems understanding it - so I'd like to "remember for later" :); and I also use --no-pager to suppress spawning of less when using git log.

So, assuming you're in a directory, with a subfolder myrepo_git which is a git repository; one could do:

### check for already existing notes:

$ git --git-dir=./myrepo_git/.git notes show
# error: No note found for object 04051f98ece25cff67e62d13c548dacbee6c1e33.
$ git --git-dir=./myrepo_git/.git notes --ref=linrev show
# error: No note found for object 04051f98ece25cff67e62d13c548dacbee6c1e33.

### iterate through rev-list three, oldest first,
### create a cmdline adding a revision count as note to each revision

$ ix=0; for ih in $(git --git-dir=./myrepo_git/.git rev-list --reverse HEAD); do \
  TCMD="git --git-dir=./myrepo_git/.git notes --ref linrev"; \
  TCMD="$TCMD add $ih -m \"(r$((++ix)))\""; \
  echo "$TCMD"; \
  eval "$TCMD"; \
done

# git --git-dir=./myrepo_git/.git notes --ref linrev add 6886bbb7be18e63fc4be68ba41917b48f02e09d7 -m "(r1)"
# git --git-dir=./myrepo_git/.git notes --ref linrev add f34910dbeeee33a40806d29dd956062d6ab3ad97 -m "(r2)"
# ...
# git --git-dir=./myrepo_git/.git notes --ref linrev add 04051f98ece25cff67e62d13c548dacbee6c1e33 -m "(r15)"

### check status - adding notes seem to not affect it:

$ cd myrepo_git/
$ git status
# # On branch master
# nothing to commit (working directory clean)
$ cd ../

### check notes again:

$ git --git-dir=./myrepo_git/.git notes show
# error: No note found for object 04051f98ece25cff67e62d13c548dacbee6c1e33.
$ git --git-dir=./myrepo_git/.git notes --ref=linrev show
# (r15)

### note is saved - now let's issue a `git log` command, using a format string and notes:

$ git --git-dir=./myrepo_git/.git --no-pager log --notes=linrev --format=format:"%h: %an: %ad:  >>%s<< %N" HEAD
# 04051f9: _user_: Sun Apr 21 18:29:02 2013 +0000:  >>test message 15 << (r15)
# 77f3902: _user_: Sun Apr 21 18:29:00 2013 +0000:  >>test message 14<< (r14)
# ...
# 6886bbb: _user_: Sun Apr 21 17:11:52 2013 +0000:  >>initial test message 1<< (r1)

### test git log with range:

$ git --git-dir=./myrepo_git/.git --no-pager log --notes=linrev --format=format:"%h: %an: %ad:  >>%s<< %N" HEAD^..HEAD
# 04051f9: _user_: Sun Apr 21 18:29:02 2013 +0000:  >>test message 15 << (r15)

### erase notes - again must iterate through rev-list

$ ix=0; for ih in $(git --git-dir=./myrepo_git/.git rev-list --reverse HEAD); do \
  TCMD="git --git-dir=./myrepo_git/.git notes --ref linrev"; \
  TCMD="$TCMD remove $ih"; \
  echo "$TCMD"; \
  eval "$TCMD"; \
done
# git --git-dir=./myrepo_git/.git notes --ref linrev remove 6886bbb7be18e63fc4be68ba41917b48f02e09d7
# Removing note for object 6886bbb7be18e63fc4be68ba41917b48f02e09d7
# git --git-dir=./myrepo_git/.git notes --ref linrev remove f34910dbeeee33a40806d29dd956062d6ab3ad97
# Removing note for object f34910dbeeee33a40806d29dd956062d6ab3ad97
# ...
# git --git-dir=./myrepo_git/.git notes --ref linrev remove 04051f98ece25cff67e62d13c548dacbee6c1e33
# Removing note for object 04051f98ece25cff67e62d13c548dacbee6c1e33

### check notes again:

$ git --git-dir=./myrepo_git/.git notes show
# error: No note found for object 04051f98ece25cff67e62d13c548dacbee6c1e33.
$ git --git-dir=./myrepo_git/.git notes --ref=linrev show
# error: No note found for object 04051f98ece25cff67e62d13c548dacbee6c1e33.

So, at least in my specific case of fully linear history with no branches, the revision numbers seem to match with this approach - and additionally, it seems that this approach will allow using git log with revision ranges, while still getting the right revision numbers - YMMV with a different context, though...

Hope this helps someone,
Cheers!


EDIT: Ok, here it is a bit easier, with git aliases for the above loops, called setlinrev and unsetlinrev; when in your git repository folder, do (Note the nasty bash escaping, see also #16136745 - Add a Git alias containing a semicolon):

cat >> .git/config <<"EOF"
[alias]
  setlinrev = "!bash -c 'ix=0; for ih in $(git rev-list --reverse HEAD); do \n\
      TCMD=\"git notes --ref linrev\"; \n\
      TCMD=\"$TCMD add $ih -m \\\"(r\\$((++ix)))\\\"\"; \n\
      #echo \"$TCMD\"; \n\
      eval \"$TCMD\"; \n\
    done; \n\
    echo \"Linear revision notes are set.\" '"

  unsetlinrev = "!bash -c 'ix=0; for ih in $(git rev-list --reverse HEAD); do \n\
      TCMD=\"git notes --ref linrev\"; \n\
      TCMD=\"$TCMD remove $ih\"; \n\
      #echo \"$TCMD\"; \n\
      eval \"$TCMD 2>/dev/null\"; \n\
    done; \n\
    echo \"Linear revision notes are unset.\" '"
EOF

... so you can simply invoke git setlinrev before trying to do log involving linear revision notes; and git unsetlinrev to delete those notes when you're done; an example from inside the git repo directory:

$ git log --notes=linrev --format=format:"%h: %an: %ad:  >>%s<< %N" HEAD^..HEAD
04051f9: _user_: Sun Apr 21 18:29:02 2013 +0000:  >>test message 15 <<

$ git setlinrev
Linear revision notes are set.
$ git log --notes=linrev --format=format:"%h: %an: %ad:  >>%s<< %N" HEAD^..HEAD
04051f9: _user_: Sun Apr 21 18:29:02 2013 +0000:  >>test message 15 << (r15)
$ git unsetlinrev
Linear revision notes are unset.

$ git log --notes=linrev --format=format:"%h: %an: %ad:  >>%s<< %N" HEAD^..HEAD
04051f9: _user_: Sun Apr 21 18:29:02 2013 +0000:  >>test message 15 <<

The time it would take the shell to complete these aliases, would depend on the size of the repository history.

how to display toolbox on the left side of window of Visual Studio Express for windows phone 7 development?

In Visual Studio Express 2013 for web it's hidden away in View > Other Windows > Toolbox.

Create a HTML table where each TR is a FORM

If using JavaScript is an option and you want to avoid nesting tables, include jQuery and try the following method.

First, you'll have to give each row a unique id like so:

<table>
  <tr id="idrow1"><td> ADD AS MANY COLUMNS AS YOU LIKE  </td><td><button onclick="submitRowAsForm('idrow1')">SUBMIT ROW1</button></td></tr>
  <tr id="idrow2"><td> PUT INPUT FIELDS IN THE COLUMNS  </td><td><button onclick="submitRowAsForm('idrow2')">SUBMIT ROW2</button></td></tr>
  <tr id="idrow3"><td>ADD MORE THAN ONE INPUT PER COLUMN</td><td><button onclick="submitRowAsForm('idrow3')">SUBMIT ROW3</button></td></tr>
</table>

Then, include the following function in your JavaScript for your page.

<script>
function submitRowAsForm(idRow) {
  form = document.createElement("form"); // CREATE A NEW FORM TO DUMP ELEMENTS INTO FOR SUBMISSION
  form.method = "post"; // CHOOSE FORM SUBMISSION METHOD, "GET" OR "POST"
  form.action = ""; // TELL THE FORM WHAT PAGE TO SUBMIT TO
  $("#"+idRow+" td").children().each(function() { // GRAB ALL CHILD ELEMENTS OF <TD>'S IN THE ROW IDENTIFIED BY idRow, CLONE THEM, AND DUMP THEM IN OUR FORM
        if(this.type.substring(0,6) == "select") { // JQUERY DOESN'T CLONE <SELECT> ELEMENTS PROPERLY, SO HANDLE THAT
            input = document.createElement("input"); // CREATE AN ELEMENT TO COPY VALUES TO
            input.type = "hidden";
            input.name = this.name; // GIVE ELEMENT SAME NAME AS THE <SELECT>
            input.value = this.value; // ASSIGN THE VALUE FROM THE <SELECT>
            form.appendChild(input);
        } else { // IF IT'S NOT A SELECT ELEMENT, JUST CLONE IT.
            $(this).clone().appendTo(form);
        }

    });
  form.submit(); // NOW SUBMIT THE FORM THAT WE'VE JUST CREATED AND POPULATED
}
</script>

So what have we done here? We've given each row a unique id and included an element in the row that can trigger the submission of that row's unique identifier. When the submission element is activated, a new form is dynamically created and set up. Then using jQuery, we clone all of the elements contained in <td>'s of the row that we were passed and append the clones to our dynamically created form. Finally, we submit said form.

No assembly found containing an OwinStartupAttribute Error

I got this error because there was an extra white space in the code

Instead of

<add key="owin:AutomaticAppStartup" value="false" />

It was

<add key="owin:AutomaticAppStartup " value="false" />

Is there a method to generate a UUID with go language

There is an official implementation by Google: https://github.com/google/uuid

Generating a version 4 UUID works like this:

package main

import (
    "fmt"
    "github.com/google/uuid"
)

func main() {
    id := uuid.New()
    fmt.Println(id.String())
}

Try it here: https://play.golang.org/p/6YPi1djUMj9

Programmatically saving image to Django ImageField

Working! You can save image by using FileSystemStorage. check the example below

def upload_pic(request):
if request.method == 'POST' and request.FILES['photo']:
    photo = request.FILES['photo']
    name = request.FILES['photo'].name
    fs = FileSystemStorage()
##### you can update file saving location too by adding line below #####
    fs.base_location = fs.base_location+'/company_coverphotos'
##################
    filename = fs.save(name, photo)
    uploaded_file_url = fs.url(filename)+'/company_coverphotos'
    Profile.objects.filter(user=request.user).update(photo=photo)

Yarn: How to upgrade yarn version using terminal?

I had an outdated symlink that was preventing me from accessing the proper bin. I had also recently gone through a node upgrade which means a lot of my newer bins were available in a different folder with what i think was a lower priority

Here is what worked for me:

yarn -v 
> 1.15.2

which yarn
> /Users/lfender/.yarn/bin/yarn 

rm -rf /Users/lfender/.yarn/bin/yarn
npm uninstall --global yarn; npm install --global yarn

> + [email protected]
> added 1 package in 0.179s

which yarn
> /Users/lfender/.nvm/versions/node/v12.2.0/bin/yarn

yarn -v
> 1.16.0

If you are not using NVM, the location of your bin installs are likely to be unique to your system

From there, I've switched to doing yarn policies set-version as outlined here https://stackoverflow.com/a/55278430/1426788 to define my yarn version at the repo level

Regular Expression for alphanumeric and underscores

use lookaheads to do the "at least one" stuff. Trust me it's much easier.

Here's an example that would require 1-10 characters, containing at least one digit and one letter:

^(?=.*\d)(?=.*[A-Za-z])[A-Za-z0-9]{1,10}$

NOTE: could have used \w but then ECMA/Unicode considerations come into play increasing the character coverage of the \w "word character".

How to find whether or not a variable is empty in Bash?

Presuming Bash:

var=""

if [ -n "$var" ]; then
    echo "not empty"
else
    echo "empty"
fi

"You tried to execute a query that does not include the specified aggregate function"

The error is because fName is included in the SELECT list, but is not included in a GROUP BY clause and is not part of an aggregate function (Count(), Min(), Max(), Sum(), etc.)

You can fix that problem by including fName in a GROUP BY. But then you will face the same issue with surname. So put both in the GROUP BY:

SELECT
    fName,
    surname,
    Count(*) AS num_rows
FROM
    author
    INNER JOIN book
    ON author.aID = book.authorID;
GROUP BY
    fName,
    surname

Note I used Count(*) where you wanted SUM(orders.quantity). However, orders isn't included in the FROM section of your query, so you must include it before you can Sum() one of its fields.

If you have Access available, build the query in the query designer. It can help you understand what features are possible and apply the correct Access SQL syntax.

Excel: Can I create a Conditional Formula based on the Color of a Cell?

Unfortunately, there is not a direct way to do this with a single formula. However, there is a fairly simple workaround that exists.

On the Excel Ribbon, go to "Formulas" and click on "Name Manager". Select "New" and then enter "CellColor" as the "Name". Jump down to the "Refers to" part and enter the following:

=GET.CELL(63,OFFSET(INDIRECT("RC",FALSE),1,1))

Hit OK then close the "Name Manager" window.

Now, in cell A1 enter the following:

=IF(CellColor=3,"FQS",IF(CellColor=6,"SM",""))

This will return FQS for red and SM for yellow. For any other color the cell will remain blank.

***If the value in A1 doesn't update, hit 'F9' on your keyboard to force Excel to update the calculations at any point (or if the color in B2 ever changes).

Below is a reference for a list of cell fill colors (there are 56 available) if you ever want to expand things: http://www.smixe.com/excel-color-pallette.html

Cheers.

::Edit::

The formula used in Name Manager can be further simplified if it helps your understanding of how it works (the version that I included above is a lot more flexible and is easier to use in checking multiple cell references when copied around as it uses its own cell address as a reference point instead of specifically targeting cell B2).

Either way, if you'd like to simplify things, you can use this formula in Name Manager instead:

=GET.CELL(63,Sheet1!B2)

How to properly use jsPDF library

how about in vuejs how is it applicable?

_x000D_
_x000D_
function onClick() {_x000D_
  var pdf = new jsPDF('p', 'pt', 'letter');_x000D_
  pdf.canvas.height = 72 * 11;_x000D_
  pdf.canvas.width = 72 * 8.5;_x000D_
_x000D_
  pdf.fromHTML(document.body);_x000D_
_x000D_
  pdf.save('test.pdf');_x000D_
};_x000D_
_x000D_
var element = document.getElementById("clickbind");_x000D_
element.addEventListener("click", onClick);
_x000D_
<h1>Dsdas</h1>_x000D_
_x000D_
<a id="clickbind" href="#">Click</a>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>
_x000D_
_x000D_
_x000D_

How to give Jenkins more heap space when it´s started as a service under Windows?

If you are using Jenkins templates you could have additional VM settings defined in it and this might conflicting with your system VM settings

example your tempalate may have references such as these

 <mavenOpts>-Xms512m -Xmx1024m -Xss1024k -XX:MaxPermSize=1024m -Dmaven.test.failure.ignore=false</mavenOpts> 

Ensure to align these template entries with the VM setting of your system

What is the purpose of the vshost.exe file?

It seems to be a long-running framework process for debugging (to decrease load times?). I discovered that when you start your application twice from the debugger often the same vshost.exe process will be used. It just unloads all user-loaded DLLs first. This does odd things if you are fooling around with API hooks from managed processes.

XPath:: Get following Sibling

You can go for identifying a list of elements with xPath:

//td[text() = ' Color Digest ']/following-sibling::td[1]

This will give you a list of two elements, than you can use the 2nd element as your intended one. For example:

List<WebElement> elements = driver.findElements(By.xpath("//td[text() = ' Color Digest ']/following-sibling::td[1]"))

Now, you can use the 2nd element as your intended element, which is elements.get(1)

Best Way to read rss feed in .net Using C#

You're looking for the SyndicationFeed class, which does exactly that.

C# LINQ select from list

The "in" in Linq-To-Sql uses a reverse logic compared to a SQL query.

Let's say you have a list of integers, and want to find the items that match those integers.

int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

var items = from p in context.Items
                 where numbers.Contains(p.ItemId)
                select p;

Anyway, the above works fine in linq-to-sql but not in EF 1.0. Haven't tried it in EF 4.0

Convert a JSON string to object in Java ME?

I used a few of them and my favorite is,

http://code.google.com/p/json-simple/

The library is very small so it's perfect for J2ME.

You can parse JSON into Java object in one line like this,

JSONObject json = (JSONObject)new JSONParser().parse("{\"name\":\"MyNode\", \"width\":200, \"height\":100}");
System.out.println("name=" + json.get("name"));
System.out.println("width=" + json.get("width"));

Not unique table/alias

 select persons.personsid,name,info.id,address
    -> from persons
    -> inner join persons on info.infoid = info.info.id;

Convert date to another timezone in JavaScript

Set a variable with year, month, and day separated with '-' symbols, plus a 'T' and the time in HH:mm:ss pattern, followed by +01:00 at the end of the string (in my case the time zone is +1). Then use this string as the argument for the date constructor.

//desired format: 2001-02-04T08:16:32+01:00
dateAndTime = year+"-"+month+"-"+day+"T"+hour+":"+minutes+":00+01:00";

var date = new Date(dateAndTime );

unsigned int vs. size_t

Classic C (the early dialect of C described by Brian Kernighan and Dennis Ritchie in The C Programming Language, Prentice-Hall, 1978) didn't provide size_t. The C standards committee introduced size_t to eliminate a portability problem

Explained in detail at embedded.com (with a very good example)

Make an image responsive - the simplest way

Images should be set like this

img { max-width: 100%; }

Play sound on button click android

Instead of resetting it as proposed by DeathRs:

if (mp.isPlaying()) {
       mp.stop();
       mp.release();
       mp = MediaPlayer.create(context, R.raw.sound);
} mp.start();

we can just reset the MediaPlayer to it's begin using:

if (mp.isPlaying()) {
       mp.seekTo(0)
}

Angular: How to update queryParams without changing route

In Angular 5 you can easily obtain and modify a copy of the urlTree by parsing the current url. This will include query params and fragments.

  let urlTree = this.router.parseUrl(this.router.url);
  urlTree.queryParams['newParamKey'] = 'newValue';

  this.router.navigateByUrl(urlTree); 

The "correct way" to modify a query parameter is probably with the createUrlTree like below which creates a new UrlTree from the current while letting us modify it using NavigationExtras.

import { Router } from '@angular/router';

constructor(private router: Router) { }

appendAQueryParam() {

  const urlTree = this.router.createUrlTree([], {
    queryParams: { newParamKey: 'newValue' },
    queryParamsHandling: "merge",
    preserveFragment: true });

  this.router.navigateByUrl(urlTree); 
}

In order to remove a query parameter this way you can set it to undefined or null.

How to check if an element does NOT have a specific class?

reading through this 6yrs later and thought I'd also take a hack at it, also in the TIMTOWTDI vein...:D, hoping it isn't incorrect 'JS etiquette'.

I usually set up a var with the condition and then refer to it later on..i.e;

// var set up globally OR locally depending on your requirements
var hC;

function(el) {
  var $this = el;
  hC = $this.hasClass("test");

  // use the variable in the conditional statement
  if (!hC) {
    //
  }
}

Although I should mention that I do this because I mainly use the conditional ternary operator and want clean code. So in this case, all i'd have is this:

hC ? '' : foo(x, n) ;
   // OR -----------
!hC ? foo(x, n) : '' ;

...instead of this:

$this.hasClass("test") ? '' : foo(x, n) ;
   // OR -----------
(!$this.hasClass("test")) ? foo(x, n) : '' ;

NumPy ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

As it says, it is ambiguous. Your array comparison returns a boolean array. Methods any() and all() reduce values over the array (either logical_or or logical_and). Moreover, you probably don't want to check for equality. You should replace your condition with:

np.allclose(A.dot(eig_vec[:,col]), eig_val[col] * eig_vec[:,col])

Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

Since this topic is not close I'll post this answer, I hope this helps someone to understand why java does not allow multiple inheritance.

Consider the following class:

public class Abc{

    public void doSomething(){

    }

}

In this case the class Abc does not extends nothing right? Not so fast, this class implicit extends the class Object, base class that allow everything work in java. Everything is an object.

If you try to use the class above you'll see that your IDE allow you to use methods like: equals(Object o), toString(), etc, but you didn't declare those methods, they came from the base class Object

You could try:

public class Abc extends String{

    public void doSomething(){

    }

}

This is fine, because your class will not implicit extends Object but will extends String because you said it. Consider the following change:

public class Abc{

    public void doSomething(){

    }

    @Override
    public String toString(){
        return "hello";
    }

}

Now your class will always return "hello" if you call toString().

Now imagine the following class:

public class Flyer{

    public void makeFly(){

    }

}

public class Bird extends Abc, Flyer{

    public void doAnotherThing(){

    }

}

Again class Flyer implicit extends Object which has the method toString(), any class will have this method since they all extends Object indirectly, so, if you call toString() from Bird, which toString() java would have to use? From Abc or Flyer? This will happen with any class that try to extends two or more classes, to avoid this kind of "method collision" they built the idea of interface, basically you could think them as an abstract class that does not extends Object indirectly. Since they are abstract they will have to be implemented by a class, which is an object (you cannot instanciate an interface alone, they must be implemented by a class), so everything will continue to work fine.

To differ classes from interfaces, the keyword implements was reserved just for interfaces.

You could implement any interface you like in the same class since they does not extends anything by default (but you could create a interface that extends another interface, but again, the "father" interface would not extends Object"), so an interface is just an interface and they will not suffer from "methods signature colissions", if they do the compiler will throw a warning to you and you will just have to change the method signature to fix it (signature = method name + params + return type).

public interface Flyer{

    public void makeFly(); // <- method without implementation

}

public class Bird extends Abc implements Flyer{

    public void doAnotherThing(){

    }

    @Override
    public void makeFly(){ // <- implementation of Flyer interface

    }

    // Flyer does not have toString() method or any method from class Object, 
    // no method signature collision will happen here

}

How to call javascript from a href?

I would avoid inline javascript altogether, and as I mentioned in my comment, I'd also probably use <input type="button" /> for this. That being said...

<a href="http://stackoverflow.com/questions/16337937/how-to-call-javascript-from-a-href" id="mylink">Link.</a>

var clickHandler = function() {
     alert('Stuff happens now.');   
}


if (document.addEventListener) {
    document.getElementById('mylink').addEventListener('click', clickHandler, false);
} else {
    document.getElementById('mylink').attachEvent('click', clickHandler);
}

http://jsfiddle.net/pDp4T/1/

how to convert long date value to mm/dd/yyyy format

Try this example

 String[] formats = new String[] {
   "yyyy-MM-dd",
   "yyyy-MM-dd HH:mm",
   "yyyy-MM-dd HH:mmZ",
   "yyyy-MM-dd HH:mm:ss.SSSZ",
   "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
 };
 for (String format : formats) {
   SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
   System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
   sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
   System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
 }

and read this http://developer.android.com/reference/java/text/SimpleDateFormat.html

jQuery If DIV Doesn't Have Class "x"

How about instead of using an if inside the event, you unbind the event when the select class is applied? I'm guessing you add the class inside your code somewhere, so unbinding the event there would look like this:

$(element).addClass( 'selected' ).unbind( 'hover' );

The only downside is that if you ever remove the selected class from the element, you have to subscribe it to the hover event again.

How to call on a function found on another file?

Your sprite is created mid way through the playerSprite function... it also goes out of scope and ceases to exist at the end of that same function. The sprite must be created where you can pass it to playerSprite to initialize it and also where you can pass it to your draw function.

Perhaps declare it above your first while?

TCPDF not render all CSS properties

I found this:

// Remove tag bottom and top margins

$tagvs = array( 'p' => array( 
                              0 => array('h' => 0, 'n' => 0), 
                              1 => array('h' => 0, 'n' => 0)
                             ) 
              );
$pdf->setHtmlVSpace($tagvs);

in here: https://tcpdf.org/examples/example_061/

Use it to remove 'p' tags properties (bottom and top), then position the 'p' text inside a cell.

For div to extend full height

This might be of some help: http://www.webmasterworld.com/forum83/200.htm

A relevant quote:

Most attempts to accomplish this were made by assigning the property and value: div{height:100%} - this alone will not work. The reason is that without a parent defined height, the div{height:100%;} has nothing to factor 100% percent of, and will default to a value of div{height:auto;} - auto is an "as needed value" which is governed by the actual content, so that the div{height:100%} will a=only extend as far as the content demands.

The solution to the problem is found by assigning a height value to the parent container, in this case, the body element. Writing your body stlye to include height 100% supplies the needed value.

html, body { 
  margin:0; 
  padding:0; 
  height:100%; 
}