Programs & Examples On #Goo.gl

URL shortening service from Google

getCurrentPosition() and watchPosition() are deprecated on insecure origins

Give some time to install an SSL cert getCurrentPosition() and watchPosition() no longer work on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS.

How to enable CORS in AngularJs

This answer outlines two ways to workaround APIs that don't support CORS:

  • Use a CORS Proxy
  • Use JSONP if the API Supports it

One workaround is to use a CORS PROXY:

_x000D_
_x000D_
angular.module("app",[])
.run(function($rootScope,$http) { 
     var proxy = "//cors-anywhere.herokuapp.com";
     var url = "http://api.ipify.org/?format=json";
     $http.get(proxy +'/'+ url)
       .then(function(response) {
         $rootScope.response = response.data;
     }).catch(function(response) {
         $rootScope.response = 'ERROR: ' + response.status;
     })     
})
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
   Response = {{response}}
</body>
_x000D_
_x000D_
_x000D_

For more information, see


Use JSONP if the API supports it:

 var url = "//api.ipify.org/";
 var trust = $sce.trustAsResourceUrl(url);
 $http.jsonp(trust,{params: {format:'jsonp'}})
   .then(function(response) {
     console.log(response);
     $scope.response = response.data;
 }).catch(function(response) {
     console.log(response);
     $scope.response = 'ERROR: ' + response.status;
 }) 

The DEMO on PLNKR

For more information, see

Do copyright dates need to be updated?

It is important to recognize that the copyright laws have changed and that for non-US sources, especially after the USA joining the Berne Convention on March 1, 1989, copyright registration in not necessary for enforcement of a copyright notice.
Here is a resumé quoted from the Cornell University Law School (copied on March 4, 2015 from https://www.law.cornell.edu/wex/copyright:

"Copyright copyright: an overview

The U.S. Copyright Act, 17 U.S.C. §§ 101 - 810, is Federal legislation enacted by Congress under its Constitutional grant of authority to protect the writings of authors. See U.S. Constitution, Article I, Section 8. Changing technology has led to an ever expanding understanding of the word "writings." The Copyright Act now reaches architectural design, software, the graphic arts, motion pictures, and sound recordings. See § 106. As of January 1, 1978, all works of authorship fixed in a tangible medium of expression and within the subject matter of copyright were deemed to fall within the exclusive jurisdiction of the Copyright Act regardless of whether the work was created before or after that date and whether published or unpublished. See § 301. See also preemption.

The owner of a copyright has the exclusive right to reproduce, distribute, perform, display, license, and to prepare derivative works based on the copyrighted work. See § 106. The exclusive rights of the copyright owner are subject to limitation by the doctrine of "fair use." See § 107. Fair use of a copyrighted work for purposes such as criticism, comment, news reporting, teaching, scholarship, or research is not copyright infringement. To determine whether or not a particular use qualifies as fair use, courts apply a multi-factor balancing test. See § 107.

Copyright protection subsists in original works of authorship fixed in any tangible medium of expression from which they can be perceived, reproduced, or otherwise communicated, either directly or with the aid of a machine or device. See § 102. Copyright protection does not extend to any idea, procedure, process, system, method of operation, concept, principle, or discovery. For example, if a book is written describing a new system of bookkeeping, copyright protection only extends to the author's description of the bookkeeping system; it does not protect the system itself. See Baker v. Selden, 101 U.S. 99 (1879).

According to the Copyright Act of 1976, registration of copyright is voluntary and may take place at any time during the term of protection. See § 408. Although registration of a work with the Copyright Office is not a precondition for protection, an action for copyright infringement may not be commenced until the copyright has been formally registered with the Copyright Office. See § 411.

Deposit of copies with the Copyright Office for use by the Library of Congress is a separate requirement from registration. Failure to comply with the deposit requirement within three months of publication of the protected work may result in a civil fine. See § 407. The Register of Copyrights may exempt certain categories of material from the deposit requirement.

In 1989 the U.S. joined the Berne Convention for the Protection of Literary and Artistic Works. In accordance with the requirements of the Berne Convention, notice is no longer a condition of protection for works published after March 1, 1989. This change to the notice requirement applies only prospectively to copies of works publicly distributed after March 1, 1989.

The Berne Convention also modified the rule making copyright registration a precondition to commencing a lawsuit for infringement. For works originating from a Berne Convention country, an infringement action may be initiated without registering the work with the U.S. Copyright Office. However, for works of U.S. origin, registration prior to filing suit is still required.

The federal agency charged with administering the act is the Copyright Office of the Library of Congress. See § 701 of the act. Its regulations are found in Parts 201 - 204 of title 37 of the Code of Federal Regulations."

Can't install APK from browser downloads

It shouldn't be HTTP headers if the file has been downloaded successfully and it's the same file that you can open from OI.

A shot in the dark, but could it be that you are not allowing installation from unknown sources, and that OI is somehow bypassing that?

Settings > Applications > Unknown sources...

Edit

Answer extracted from comments which worked. Ensure the Content-Type is set to application/vnd.android.package-archive

Get individual query parameters from Uri

For isolated projects, where dependencies must be kept to a minimum, I found myself using this implementation:

var arguments = uri.Query
  .Substring(1) // Remove '?'
  .Split('&')
  .Select(q => q.Split('='))
  .ToDictionary(q => q.FirstOrDefault(), q => q.Skip(1).FirstOrDefault());

Do note, however, that I do not handle encoded strings of any kind, as I was using this in a controlled setting, where encoding issues would be a coding error on the server side that should be fixed.

Origin http://localhost is not allowed by Access-Control-Allow-Origin

This approach resolved my issue to allow multiple domain

app.use(function(req, res, next) {
      var allowedOrigins = ['http://127.0.0.1:8020', 'http://localhost:8020', 'http://127.0.0.1:9000', 'http://localhost:9000'];
      var origin = req.headers.origin;
      if(allowedOrigins.indexOf(origin) > -1){
           res.setHeader('Access-Control-Allow-Origin', origin);
      }
      //res.header('Access-Control-Allow-Origin', 'http://127.0.0.1:8020');
      res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
      res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
      res.header('Access-Control-Allow-Credentials', true);
      return next();
    });

How to install an npm package from GitHub directly?

Simple :

npm install *GithubUrl*.git --save

example :

npm install https://github.com/visionmedia/express.git --save

parsing JSONP $http.jsonp() response in angular.js

The MOST IMPORTANT THING I didn't understand for quite awhile is that the request MUST contain "callback=JSON_CALLBACK", because AngularJS modifies the request url, substituting a unique identifier for "JSON_CALLBACK". The server response must use the value of the 'callback' parameter instead of hard coding "JSON_CALLBACK":

JSON_CALLBACK(json_response);  // wrong!

Since I was writing my own PHP server script, I thought I knew what function name it wanted and didn't need to pass "callback=JSON_CALLBACK" in the request. Big mistake!

AngularJS replaces "JSON_CALLBACK" in the request with a unique function name (like "callback=angular.callbacks._0"), and the server response must return that value:

angular.callbacks._0(json_response);

Using multiple parameters in URL in express

app.get('/fruit/:fruitName/:fruitColor', function(req, res) {
    var data = {
        "fruit": {
            "apple": req.params.fruitName,
            "color": req.params.fruitColor
        }
    }; 

    send.json(data);
});

If that doesn't work, try using console.log(req.params) to see what it is giving you.

Understanding the results of Execute Explain Plan in Oracle SQL Developer

The output of EXPLAIN PLAN is a debug output from Oracle's query optimiser. The COST is the final output of the Cost-based optimiser (CBO), the purpose of which is to select which of the many different possible plans should be used to run the query. The CBO calculates a relative Cost for each plan, then picks the plan with the lowest cost.

(Note: in some cases the CBO does not have enough time to evaluate every possible plan; in these cases it just picks the plan with the lowest cost found so far)

In general, one of the biggest contributors to a slow query is the number of rows read to service the query (blocks, to be more precise), so the cost will be based in part on the number of rows the optimiser estimates will need to be read.

For example, lets say you have the following query:

SELECT emp_id FROM employees WHERE months_of_service = 6;

(The months_of_service column has a NOT NULL constraint on it and an ordinary index on it.)

There are two basic plans the optimiser might choose here:

  • Plan 1: Read all the rows from the "employees" table, for each, check if the predicate is true (months_of_service=6).
  • Plan 2: Read the index where months_of_service=6 (this results in a set of ROWIDs), then access the table based on the ROWIDs returned.

Let's imagine the "employees" table has 1,000,000 (1 million) rows. Let's further imagine that the values for months_of_service range from 1 to 12 and are fairly evenly distributed for some reason.

The cost of Plan 1, which involves a FULL SCAN, will be the cost of reading all the rows in the employees table, which is approximately equal to 1,000,000; but since Oracle will often be able to read the blocks using multi-block reads, the actual cost will be lower (depending on how your database is set up) - e.g. let's imagine the multi-block read count is 10 - the calculated cost of the full scan will be 1,000,000 / 10; Overal cost = 100,000.

The cost of Plan 2, which involves an INDEX RANGE SCAN and a table lookup by ROWID, will be the cost of scanning the index, plus the cost of accessing the table by ROWID. I won't go into how index range scans are costed but let's imagine the cost of the index range scan is 1 per row; we expect to find a match in 1 out of 12 cases, so the cost of the index scan is 1,000,000 / 12 = 83,333; plus the cost of accessing the table (assume 1 block read per access, we can't use multi-block reads here) = 83,333; Overall cost = 166,666.

As you can see, the cost of Plan 1 (full scan) is LESS than the cost of Plan 2 (index scan + access by rowid) - which means the CBO would choose the FULL scan.

If the assumptions made here by the optimiser are true, then in fact Plan 1 will be preferable and much more efficient than Plan 2 - which disproves the myth that FULL scans are "always bad".

The results would be quite different if the optimiser goal was FIRST_ROWS(n) instead of ALL_ROWS - in which case the optimiser would favour Plan 2 because it will often return the first few rows quicker, at the cost of being less efficient for the entire query.

How can I switch to a tag/branch in hg?

Once you have cloned the repo, you have everything: you can then hg up branchname or hg up tagname to update your working copy.

UP: hg up is a shortcut of hg update, which also has hg checkout alias for people with git habits.

How to delete rows in tables that contain foreign keys to other tables

From your question, I think it is safe to assume you have CASCADING DELETES turned on.
All that is needed in that case is

DELETE FROM MainTable
WHERE PrimaryKey = ???

You database engine will take care of deleting the corresponding referencing records.

Difference between dates in JavaScript

If you are looking for a difference expressed as a combination of years, months, and days, I would suggest this function:

_x000D_
_x000D_
function interval(date1, date2) {_x000D_
    if (date1 > date2) { // swap_x000D_
        var result = interval(date2, date1);_x000D_
        result.years  = -result.years;_x000D_
        result.months = -result.months;_x000D_
        result.days   = -result.days;_x000D_
        result.hours  = -result.hours;_x000D_
        return result;_x000D_
    }_x000D_
    result = {_x000D_
        years:  date2.getYear()  - date1.getYear(),_x000D_
        months: date2.getMonth() - date1.getMonth(),_x000D_
        days:   date2.getDate()  - date1.getDate(),_x000D_
        hours:  date2.getHours() - date1.getHours()_x000D_
    };_x000D_
    if (result.hours < 0) {_x000D_
        result.days--;_x000D_
        result.hours += 24;_x000D_
    }_x000D_
    if (result.days < 0) {_x000D_
        result.months--;_x000D_
        // days = days left in date1's month, _x000D_
        //   plus days that have passed in date2's month_x000D_
        var copy1 = new Date(date1.getTime());_x000D_
        copy1.setDate(32);_x000D_
        result.days = 32-date1.getDate()-copy1.getDate()+date2.getDate();_x000D_
    }_x000D_
    if (result.months < 0) {_x000D_
        result.years--;_x000D_
        result.months+=12;_x000D_
    }_x000D_
    return result;_x000D_
}_x000D_
_x000D_
// Be aware that the month argument is zero-based (January = 0)_x000D_
var date1 = new Date(2015, 4-1, 6);_x000D_
var date2 = new Date(2015, 5-1, 9);_x000D_
_x000D_
document.write(JSON.stringify(interval(date1, date2)));
_x000D_
_x000D_
_x000D_

This solution will treat leap years (29 February) and month length differences in a way we would naturally do (I think).

So for example, the interval between 28 February 2015 and 28 March 2015 will be considered exactly one month, not 28 days. If both those days are in 2016, the difference will still be exactly one month, not 29 days.

Dates with exactly the same month and day, but different year, will always have a difference of an exact number of years. So the difference between 2015-03-01 and 2016-03-01 will be exactly 1 year, not 1 year and 1 day (because of counting 365 days as 1 year).

How to convert uint8 Array to base64 Encoded String?

To base64-encode a UInt8Array with arbitrary data (not necessarily UTF-8) using native browser functionality:

const base64_arraybuffer = async (data) => {
    // Use a FileReader to generate a base64 data URI
    const base64url = await new Promise((r) => {
        const reader = new FileReader()
        reader.onload = () => r(reader.result)
        reader.readAsDataURL(new Blob([data]))
    })

    /*
    The result looks like 
    "data:application/octet-stream;base64,<your base64 data>", 
    so we split off the beginning:
    */
    return base64url.split(",", 2)[1]
}

// example use:
await base64_arraybuffer(new UInt8Array([1,2,3,100,200]))

ASP.NET MVC Razor pass model to layout

Seems like you have modeled your viewmodels a bit wrong if you have this problem.

Personally I would never type a layout page. But if you want to do that you should have a base viewmodel that your other viewmodels inherits from and type your layout to the base viewmodel and you pages to the specific once.

Printing without newline (print 'a',) prints a space, how to remove?

Python 3.x:

for i in range(20):
    print('a', end='')

Python 2.6 or 2.7:

from __future__ import print_function
for i in xrange(20):
    print('a', end='')

Array of char* should end at '\0' or "\0"?

Null termination is a bad design pattern best left in the history books. There's still plenty of inertia behind c-strings, so it can't be avoided there. But there's no reason to use it in the OP's example.

Don't use any terminator, and use sizeof(array) / sizeof(array[0]) to get the number of elements.

How to enable copy paste from between host machine and virtual machine in vmware, virtual machine is ubuntu

the mremote option offers more automation and almost replicates the vmware workstation graphical experience plus major benefits: NO DPI (guest resolution) hassle no copy pose hassle Automation = starting vms and suspending them automatically plus more if you look deeper

How to Create a Form Dynamically Via Javascript

some thing as follows ::

Add this After the body tag

This is a rough sketch, you will need to modify it according to your needs.

<script>
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");

var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");

var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");

f.appendChild(i);
f.appendChild(s);

//and some more input elements here
//and dont forget to add a submit button

document.getElementsByTagName('body')[0].appendChild(f);

</script>

How to add header to a dataset in R?

You can do the following:

Load the data:

test <- read.csv(
          "http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data",
          header=FALSE)

Note that the default value of the header argument for read.csv is TRUE so in order to get all lines you need to set it to FALSE.

Add names to the different columns in the data.frame

names(test) <- c("A","B","C","D","E","F","G","H","I","J","K")

or alternative and faster as I understand (not reloading the entire dataset):

colnames(test) <- c("A","B","C","D","E","F","G","H","I","J","K")

Bootstrap 3 with remote Modal

Here's my solution (leveraging a few above) that makes use of BS3's own structure to re-instate the old remote loading behaviour. It should be seamless.

I'm going to keep the code variable heavy and descriptive to keep things understandable. I'm also assuming the presence of JQuery. Javascript heavy lifter types will handily streamline the code.

For reference here's a link that invokes a BS3 modal:

<li><a data-toggle="modal" href="terms.html" data-target="#terms">Terms of Use</a></li>

In youre Javascript you're going to need the following.

// Make sure the DOM elements are loaded and accounted for
$(document).ready(function() {

  // Match to Bootstraps data-toggle for the modal
  // and attach an onclick event handler
  $('a[data-toggle="modal"]').on('click', function(e) {

    // From the clicked element, get the data-target arrtibute
    // which BS3 uses to determine the target modal
    var target_modal = $(e.currentTarget).data('target');
    // also get the remote content's URL
    var remote_content = e.currentTarget.href;

    // Find the target modal in the DOM
    var modal = $(target_modal);
    // Find the modal's <div class="modal-body"> so we can populate it
    var modalBody = $(target_modal + ' .modal-body');

    // Capture BS3's show.bs.modal which is fires
    // immediately when, you guessed it, the show instance method
    // for the modal is called
    modal.on('show.bs.modal', function () {
            // use your remote content URL to load the modal body
            modalBody.load(remote_content);
        }).modal();
        // and show the modal

    // Now return a false (negating the link action) to prevent Bootstrap's JS 3.1.1
    // from throwing a 'preventDefault' error due to us overriding the anchor usage.
    return false;
  });
});

We're just about there. One thing you may want to do is style the modal body with a max-height, so that long content will scroll.

In your CSS, you'll need the following:

.modal-body{
    max-height: 300px;
    overflow-y: scroll;
}

Just for refference I'll include the modal's HTML, which is a knock-off of every Bootsrap Modal Example you've ever seen:

<div id="terms" class="modal fade">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h3 id="termsLabel" class="modal-title">TERMS AND CONDITIONS</h3>
      </div>
      <div class="modal-body">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

Docker - Ubuntu - bash: ping: command not found

Every time you get this kind of error

bash: <command>: command not found
  • On a host with that command already working with this solution:

    dpkg -S $(which <command>)
    
  • Don't have a host with that package installed? Try this:

    apt-file search /bin/<command>
    

MySQL: Get column name or alias from query

You can also do this to just get the field titles:

table = cursor.description
check = 0
for fields in table:
    for name in fields:
        if check < 1:
            print(name),
        check +=1
    check =0

Several ports (8005, 8080, 8009) required by Tomcat Server at localhost are already in use

Step 1: netstat -a -o -n and it will bring up a network list,search for the local address like 127.0.0.1:8080 and note the PID (eq 3624)

C:\>netstat -a -o -n

Step2 : taskkill /F /PID 3624 . Run this command to kill that process.

C:\>taskkill /F /PID 3624

link to post

Center Align on a Absolutely Positioned Div

To center it both vertically and horizontally do this:

div#thing {
   position: absolute;
   left: 50%;
   top: 50%;
   transform: translate(-50%, -50%);
}

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

The probably shortest answer is

val==null || val==''

if you change rigth side to val==='' then empty array will give false. Proof

_x000D_
_x000D_
function isEmpty(val){_x000D_
    return val==null || val==''_x000D_
}_x000D_
_x000D_
// ------------_x000D_
// TEST_x000D_
// ------------_x000D_
_x000D_
var log = (name,val) => console.log(`${name} -> ${isEmpty(val)}`);_x000D_
_x000D_
log('null', null);_x000D_
log('undefined', undefined);_x000D_
log('NaN', NaN);_x000D_
log('""', "");_x000D_
log('{}', {});_x000D_
log('[]', []);_x000D_
log('[1]', [1]);_x000D_
log('[0]', [0]);_x000D_
log('[[]]', [[]]);_x000D_
log('true', true);_x000D_
log('false', false);_x000D_
log('"true"', "true");_x000D_
log('"false"', "false");_x000D_
log('Infinity', Infinity);_x000D_
log('-Infinity', -Infinity);_x000D_
log('1', 1);_x000D_
log('0', 0);_x000D_
log('-1', -1);_x000D_
log('"1"', "1");_x000D_
log('"0"', "0");_x000D_
log('"-1"', "-1");_x000D_
_x000D_
// "void 0" case_x000D_
console.log('---\n"true" is:', true);_x000D_
console.log('"void 0" is:', void 0);_x000D_
log(void 0,void 0); // "void 0" is "undefined" - so we should get here TRUE
_x000D_
_x000D_
_x000D_

More details about == (source here)

Enter image description here

BONUS: Reason why === is more clear than ==

Enter image description here

To write clear and easy understandable code, use explicite list of accepted values

val===undefined || val===null || val===''|| (Array.isArray(val) && val.length===0)

_x000D_
_x000D_
function isEmpty(val){_x000D_
    return val===undefined || val===null || val==='' || (Array.isArray(val) && val.length===0)_x000D_
}_x000D_
_x000D_
// ------------_x000D_
// TEST_x000D_
// ------------_x000D_
_x000D_
var log = (name,val) => console.log(`${name} -> ${isEmpty(val)}`);_x000D_
_x000D_
log('null', null);_x000D_
log('undefined', undefined);_x000D_
log('NaN', NaN);_x000D_
log('""', "");_x000D_
log('{}', {});_x000D_
log('[]', []);_x000D_
log('[1]', [1]);_x000D_
log('[0]', [0]);_x000D_
log('[[]]', [[]]);_x000D_
log('true', true);_x000D_
log('false', false);_x000D_
log('"true"', "true");_x000D_
log('"false"', "false");_x000D_
log('Infinity', Infinity);_x000D_
log('-Infinity', -Infinity);_x000D_
log('1', 1);_x000D_
log('0', 0);_x000D_
log('-1', -1);_x000D_
log('"1"', "1");_x000D_
log('"0"', "0");_x000D_
log('"-1"', "-1");_x000D_
_x000D_
// "void 0" case_x000D_
console.log('---\n"true" is:', true);_x000D_
console.log('"void 0" is:', void 0);_x000D_
log(void 0,void 0); // "void 0" is "undefined" - so we should get here TRUE
_x000D_
_x000D_
_x000D_

Find specific string in a text file with VBS script

Wow, after few attempts I finally figured out how to deal with my text edits in vbs. The code works perfectly, it gives me the result I was expecting. Maybe it's not the best way to do this, but it does its job. Here's the code:

Option Explicit

Dim StdIn:  Set StdIn = WScript.StdIn
Dim StdOut: Set StdOut = WScript


Main()

Sub Main()

Dim objFSO, filepath, objInputFile, tmpStr, ForWriting, ForReading, count, text, objOutputFile, index, TSGlobalPath, foundFirstMatch
Set objFSO = CreateObject("Scripting.FileSystemObject")
TSGlobalPath = "C:\VBS\TestSuiteGlobal\Test suite Dispatch Decimal - Global.txt"
ForReading = 1
ForWriting = 2
Set objInputFile = objFSO.OpenTextFile(TSGlobalPath, ForReading, False)
count = 7
text=""
foundFirstMatch = false

Do until objInputFile.AtEndOfStream
    tmpStr = objInputFile.ReadLine
    If foundStrMatch(tmpStr)=true Then
        If foundFirstMatch = false Then
            index = getIndex(tmpStr)
            foundFirstMatch = true
            text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
        End If
        If index = getIndex(tmpStr) Then
            text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
        ElseIf index < getIndex(tmpStr) Then
            index = getIndex(tmpStr)
            text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
        End If
    Else
        text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
    End If
Loop
Set objOutputFile = objFSO.CreateTextFile("C:\VBS\NuovaProva.txt", ForWriting, true)
objOutputFile.Write(text)
End Sub


Function textSubstitution(tmpStr,index,foundMatch)
Dim strToAdd
strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_CF5.0_Features_TC" & CStr(index) & "</a></td></tr>"
If foundMatch = "false" Then
    textSubstitution = tmpStr
ElseIf foundMatch = "true" Then
    textSubstitution = strToAdd & vbCrLf & tmpStr
End If
End Function


Function getIndex(tmpStr)
Dim substrToFind, charAtPos, char1, char2
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
charAtPos = len(substrToFind) + 1
char1 = Mid(tmpStr, charAtPos, 1)
char2 = Mid(tmpStr, charAtPos+1, 1)
If IsNumeric(char2) Then
    getIndex = CInt(char1 & char2)
Else
    getIndex = CInt(char1)
End If
End Function

Function foundStrMatch(tmpStr)
Dim substrToFind
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
If InStr(tmpStr, substrToFind) > 0 Then
    foundStrMatch = true
Else
    foundStrMatch = false
End If
End Function

This is the original txt file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta content="text/html; charset=UTF-8" http-equiv="content-type" />
  <title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>

And this is the result I'm expecting

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta content="text/html; charset=UTF-8" http-equiv="content-type" />
  <title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC5.html">Beginning_of_CF5.0_Features_TC5</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC6.html">Beginning_of_CF5.0_Features_TC6</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC7.html">Beginning_of_CF5.0_Features_TC7</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>

100% height minus header?

If your browser supports CSS3, try using the CSS element Calc()

height: calc(100% - 65px);

you might also want to adding browser compatibility options:

height: -o-calc(100% - 65px); /* opera */
height: -webkit-calc(100% - 65px); /* google, safari */
height: -moz-calc(100% - 65px); /* firefox */

also make sure you have spaces between values, see: https://stackoverflow.com/a/16291105/427622

How to run .NET Core console app from the command line

If it's a framework-dependent application (the default), you run it by dotnet yourapp.dll.

If it's a self-contained application, you run it using yourapp.exe on Windows and ./yourapp on Unix.

For more information about the differences between the two app types, see the .NET Core Application Deployment article on .Net Docs.

Python for and if on one line

When you perform

>>> [(i) for i in my_list if i=="two"]

i is iterated through the list my_list. As the list comprehension finishes evaluation, i is assigned to the last item in iteration, which is "three".

How do I convert strings between uppercase and lowercase in Java?

Coverting the first letter of word capital

input:

hello world

String A = hello;
String B = world;
System.out.println(A.toUpperCase().charAt(0)+A.substring(1) + " " + B.toUpperCase().charAt(0)+B.substring(1));

Output:

Hello World

Difference between EXISTS and IN in SQL?

Difference lies here:

select * 
from abcTable
where exists (select null)

Above query will return all the records while below one would return empty.

select *
from abcTable
where abcTable_ID in (select null)

Give it a try and observe the output.

Returning data from Axios API

I know this post is old. But i have seen several attempts of guys trying to answer using async and await but getting it wrong. This should clear it up for any new references

async function axiosTest() {
      try {
        const {data:response} = await axios.get(url) //use data destructuring to get data from the promise object
        return response
      }

      catch (error) {
        console.log(error);
      }
    }

Spring @Value is not resolving to value from property file

Problem is due to problem in my applicationContext.xml vs spring-servlet.xml - it was scoping issue between the beans.

pedjaradenkovic kindly pointed me to an existing resource: Spring @Value annotation in @Controller class not evaluating to value inside properties file and Spring 3.0.5 doesn't evaluate @Value annotation from properties

Skip first entry in for loop in python?

Based on @SvenMarnach 's Answer, but bit simpler and without using deque

>>> def skip(iterable, at_start=0, at_end=0):
    it = iter(iterable)
    it = itertools.islice(it, at_start, None)
    it, it1 = itertools.tee(it)
    it1 = itertools.islice(it1, at_end, None)
    return (next(it) for _ in it1)

>>> list(skip(range(10), at_start=2, at_end=2))
[2, 3, 4, 5, 6, 7]
>>> list(skip(range(10), at_start=2, at_end=5))
[2, 3, 4]

Also Note, based on my timeit result, this is marginally faster than the deque solution

>>> iterable=xrange(1000)
>>> stmt1="""
def skip(iterable, at_start=0, at_end=0):
    it = iter(iterable)
    it = itertools.islice(it, at_start, None)
    it, it1 = itertools.tee(it)
    it1 = itertools.islice(it1, at_end, None)
    return (next(it) for _ in it1)
list(skip(iterable,2,2))
    """
>>> stmt2="""
def skip(iterable, at_start=0, at_end=0):
    it = iter(iterable)
    for x in itertools.islice(it, at_start):
        pass
    queue = collections.deque(itertools.islice(it, at_end))
    for x in it:
        queue.append(x)
        yield queue.popleft()
list(skip(iterable,2,2))
        """
>>> timeit.timeit(stmt = stmt1, setup='from __main__ import iterable, skip, itertools', number = 10000)
2.0313770640908047
>>> timeit.timeit(stmt = stmt2, setup='from __main__ import iterable, skip, itertools, collections', number = 10000)
2.9903135454296716

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

Well, there are many solutions already given above. If there are none of them works, maybe you should just try to reset your password again to 'root' as described here, and then reopen http://localhost/phpMyAdmin/ in other browser. At least this solution works for me.

How to safely upgrade an Amazon EC2 instance from t1.micro to large?

From my experience, the way I do it is create a snapshot of your current image, then once its done you'll see it as an option when launching new instances. Simply launch it as a large instance at that point.

This is my approach if I do not want any downtime(i.e. production server) because this solution only takes a server offline only after the new one is up and running(I also use it to add new machines to my clusters by using this approach to only add new machines). If Downtime is acceptable then see Marcel Castilho's answer.

SQL Server procedure declare a list

You can convert the list of passed values into a table valued parameter and then select against this list

DECLARE @list NVARCHAR(MAX)
SET @list = '1,2,5,7,10';

DECLARE @pos INT
DECLARE @nextpos INT
DECLARE @valuelen INT
DECLARE @tbl TABLE (number int NOT NULL)

SELECT @pos = 0, @nextpos = 1;

WHILE @nextpos > 0
BEGIN
    SELECT @nextpos = charindex(',', @list, @pos + 1)
    SELECT @valuelen = CASE WHEN @nextpos > 0
                            THEN @nextpos
                            ELSE len(@list) + 1
                        END - @pos - 1
    INSERT @tbl (number)
        VALUES (convert(int, substring(@list, @pos + 1, @valuelen)))
    SELECT @pos = @nextpos;
END

SELECT * FROM DBTable WHERE id IN (SELECT number FROM @tbl);

In this example the string passed in '1,2,5,7,10' is split by the commas and each value is added as a new row within the @tbl table variable. This can then be selected against using standard SQL.

If you intend to reuse this functionality you could go further and convert this into a function.

Reading/writing an INI file

Here is my own version, using regular expressions. This code assumes that each section name is unique - if however this is not true - it makes sense to replace Dictionary with List. This function supports .ini file commenting, starting from ';' character. Section starts normally [section], and key value pairs also comes normally "key = value". Same assumption as for sections - key name is unique.

/// <summary>
/// Loads .ini file into dictionary.
/// </summary>
public static Dictionary<String, Dictionary<String, String>> loadIni(String file)
{
    Dictionary<String, Dictionary<String, String>> d = new Dictionary<string, Dictionary<string, string>>();

    String ini = File.ReadAllText(file);

    // Remove comments, preserve linefeeds, if end-user needs to count line number.
    ini = Regex.Replace(ini, @"^\s*;.*$", "", RegexOptions.Multiline);

    // Pick up all lines from first section to another section
    foreach (Match m in Regex.Matches(ini, "(^|[\r\n])\\[([^\r\n]*)\\][\r\n]+(.*?)(\\[([^\r\n]*)\\][\r\n]+|$)", RegexOptions.Singleline))
    {
        String sectionName = m.Groups[2].Value;
        Dictionary<String, String> lines = new Dictionary<String, String>();

        // Pick up "key = value" kind of syntax.
        foreach (Match l in Regex.Matches(ini, @"^\s*(.*?)\s*=\s*(.*?)\s*$", RegexOptions.Multiline))
        {
            String key = l.Groups[1].Value;
            String value = l.Groups[2].Value;

            // Open up quotation if any.
            value = Regex.Replace(value, "^\"(.*)\"$", "$1");

            if (!lines.ContainsKey(key))
                lines[key] = value;
        }

        if (!d.ContainsKey(sectionName))
            d[sectionName] = lines;
    }

    return d;
}

replace all occurrences in a string

Use the global flag.

str.replace(/\n/g, '<br />');

Multiline strings in VB.NET

Multiline string literals are introduced in Visual Basic 14.0 - https://roslyn.codeplex.com/discussions/571884

You can use then in the VS2015 Preview, out now - http://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs (note that you can still use VS2015 even when targeting an older version of the .NET framework)

Dim multiline = "multi
line
string"

VB strings are basically now the same as C# verbatim strings - they don't support backslash escape sequences like \n, and they do allow newlines within the string, and you escape the quote symbol with double-quotes ""

error code 1292 incorrect date value mysql

With mysql 5.7, date value like 0000-00-00 00:00:00 is not allowed.

If you want to allow it, you have to update your my.cnf like:

sudo nano /etc/mysql/my.cnf

find

[mysqld]

Add after:

sql_mode="NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

Restart mysql service:

sudo service mysql restart

Done!

g++ ld: symbol(s) not found for architecture x86_64

I had a similar warning/error/failure when I was simply trying to make an executable from two different object files (main.o and add.o). I was using the command:

gcc -o exec main.o add.o

But my program is a C++ program. Using the g++ compiler solved my issue:

g++ -o exec main.o add.o

I was always under the impression that gcc could figure these things out on its own. Apparently not. I hope this helps someone else searching for this error.

Why doesn't java.io.File have a close method?

The javadoc of the File class describes the class as:

An abstract representation of file and directory pathnames.

File is only a representation of a pathname, with a few methods concerning the filesystem (like exists()) and directory handling but actual streaming input and output is done elsewhere. Streams can be opened and closed, files cannot.

(My personal opinion is that it's rather unfortunate that Sun then went on to create RandomAccessFile, causing much confusion with its inconsistent naming.)

How to use aria-expanded="true" to change a css property

_x000D_
_x000D_
li a[aria-expanded="true"] span{_x000D_
    color: red;_x000D_
}
_x000D_
<li class="active">_x000D_
    <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true">_x000D_
        <span class="network-name">Google+</span>_x000D_
    </a>_x000D_
</li>_x000D_
<li class="active">_x000D_
    <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="false">_x000D_
        <span class="network-name">Google+</span>_x000D_
    </a>_x000D_
</li>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
li a[aria-expanded="true"]{_x000D_
    background: yellow;_x000D_
}
_x000D_
<li class="active">_x000D_
    <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="true">_x000D_
        <span class="network-name">Google+</span>_x000D_
    </a>_x000D_
</li>_x000D_
<li class="active">_x000D_
    <a href="#3a" class="btn btn-default btn-lg" data-toggle="tab" aria-expanded="false">_x000D_
        <span class="network-name">Google+</span>_x000D_
    </a>_x000D_
</li>
_x000D_
_x000D_
_x000D_

Silent installation of a MSI package

The proper way to install an MSI silently is via the msiexec.exe command line as follows:

msiexec.exe /i c:\setup.msi /QN /L*V "C:\Temp\msilog.log"

Quick explanation:

 /L*V "C:\Temp\msilog.log"= verbose logging
 /QN = run completely silently
 /i = run install sequence 

There is a much more comprehensive answer here: Batch script to install MSI. This answer provides details on the msiexec.exe command line options and a description of how to find the "public properties" that you can set on the command line at install time. These properties are generally different for each MSI.

JavaScript "cannot read property "bar" of undefined

You can safeguard yourself either of these two ways:

function myFunc(thing) {
    if (thing && thing.foo && thing.foo.bar) {
        // safe to use thing.foo.bar here
    }
}

function myFunc(thing) {
    try {
        var x = thing.foo.bar;
        // do something with x
    } catch(e) {
        // do whatever you want when thing.foo.bar didn't work
    }
}

In the first example, you explicitly check all the possible elements of the variable you're referencing to make sure it's safe before using it so you don't get any unplanned reference exceptions.

In the second example, you just put an exception handler around it. You just access thing.foo.bar assuming it exists. If it does exist, then the code runs normally. If it doesn't exist, then it will throw an exception which you will catch and ignore. The end result is the same. If thing.foo.bar exists, your code using it executes. If it doesn't exist that code does not execute. In all cases, the function runs normally.

The if statement is faster to execute. The exception can be simpler to code and use in complex cases where there may be many possible things to protect against and your code is structured so that throwing an exception and handling it is a clean way to skip execution when some piece of data does not exist. Exceptions are a bit slower when the exception is thrown.

How to include SCSS file in HTML

You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...

For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.

How to create a RelativeLayout programmatically with two buttons one on top of the other?

public class AndroidWalkthroughApp1 extends Activity implements View.OnClickListener {

    final int TOP_ID = 3;
    final int BOTTOM_ID = 4;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // create two layouts to hold buttons
        RelativeLayout top = new RelativeLayout(this);
        top.setId(TOP_ID);
        RelativeLayout bottom = new RelativeLayout(this);
        bottom.setId(BOTTOM_ID);

        // create buttons in a loop
        for (int i = 0; i < 2; i++) {
            Button button = new Button(this);
            button.setText("Button " + i);
            // R.id won't be generated for us, so we need to create one
            button.setId(i);

            // add our event handler (less memory than an anonymous inner class)
            button.setOnClickListener(this);

            // add generated button to view
            if (i == 0) {
                top.addView(button);
            }
            else {
                bottom.addView(button);
            }
        }

        RelativeLayout root = (RelativeLayout) findViewById(R.id.root_layout);

        // add generated layouts to root layout view
       // LinearLayout root = (LinearLayout)this.findViewById(R.id.root_layout);

        root.addView(top);
        root.addView(bottom);
    }

    @Override
    public void onClick(View v) {
        // show a message with the button's ID
        Toast toast = Toast.makeText(AndroidWalkthroughApp1.this, "You clicked button " + v.getId(), Toast.LENGTH_LONG);
        toast.show();

        // get the parent layout and remove the clicked button
        RelativeLayout parentLayout = (RelativeLayout)v.getParent();
        parentLayout.removeView(v);



    }
}

HTML: How to center align a form

Just put some CSS into the stylesheet like this

form {
  text-align: center;
}

then you're done!

How can I find the number of elements in an array?

int a[20];
int length;
length = sizeof(a) / sizeof(int);

and you can use another way to make your code not be hard-coded to int

Say if you have an array array

you just need to:

int len = sizeof(array) / sizeof(array[0]);

"Parameter" vs "Argument"

A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.

Consider the following code:

void Foo(int i, float f)
{
    // Do things
}

void Bar()
{
    int anInt = 1;
    Foo(anInt, 2.0);
}

Here i and f are the parameters, and anInt and 2.0 are the arguments.

MySQL "Group By" and "Order By"

Here's one approach:

SELECT cur.textID, cur.fromEmail, cur.subject, 
     cur.timestamp, cur.read
FROM incomingEmails cur
LEFT JOIN incomingEmails next
    on cur.fromEmail = next.fromEmail
    and cur.timestamp < next.timestamp
WHERE next.timestamp is null
and cur.toUserID = '$userID' 
ORDER BY LOWER(cur.fromEmail)

Basically, you join the table on itself, searching for later rows. In the where clause you state that there cannot be later rows. This gives you only the latest row.

If there can be multiple emails with the same timestamp, this query would need refining. If there's an incremental ID column in the email table, change the JOIN like:

LEFT JOIN incomingEmails next
    on cur.fromEmail = next.fromEmail
    and cur.id < next.id

Android - How to regenerate R class?

For me, it was a String value Resource not being defined … after I added it by hand to Strings.xml, the R class was automagically regenerated!

sequelize findAll sort order in nodejs

You can accomplish this in a very back-handed way with the following code:

exports.getStaticCompanies = function () {
    var ids = [46128, 2865, 49569, 1488, 45600, 61991, 1418, 61919, 53326, 61680]
    return Company.findAll({
        where: {
            id: ids
        },
        attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at'],
        order: sequelize.literal('(' + ids.map(function(id) {
            return '"Company"."id" = \'' + id + '\'');
        }).join(', ') + ') DESC')
    });
};

This is somewhat limited because it's got very bad performance characteristics past a few dozen records, but it's acceptable at the scale you're using.

This will produce a SQL query that looks something like this:

[...] ORDER BY ("Company"."id"='46128', "Company"."id"='2865', "Company"."id"='49569', [...])

Ruby value of a hash key?

It seems that your question is maybe a bit ambiguous.

If “values” in the first sentence means any generic value (i.e. object, since everything in Ruby can be viewed as an object), then one of the other answers probably tells you what you need to know (i.e. use Hash#[] (e.g. hash[some_key]) to find the value associated with a key).

If, however, “values” in first sentence is taken to mean the value part of the “key, value pairs” (as are stored in hashes), then your question seems like it might be about working in the other direction (key for a given value).

You can find a key that leads to a certain value with Hash#key.

ruby-1.9.2-head :001 > hash = { :a => '1', :b => :two, :c => 3, 'bee' => :two }
 => {:a=>"1", :b=>:two, :c=>3, "bee"=>:two} 
ruby-1.9.2-head :002 > a_value = :two
 => :two 
ruby-1.9.2-head :003 > hash.key(a_value)
 => :b 

If you are using a Ruby earlier than 1.9, you can use Hash#index.

When there are multiple keys with the desired value, the method will only return one of them. If you want all the keys with a given value, you may have to iterate a bit:

ruby-1.9.2-head :004 > hash[:b] == hash['bee']
 => true 
ruby-1.9.2-head :005 > keys = hash.inject([]) do # all keys with value a_value
ruby-1.9.2-head :006 >       |l,kv| kv[1] == a_value ? l << kv[0] : l
ruby-1.9.2-head :007?>   end
 => [:b, "bee"] 

Once you have a key (the keys) that lead to the value, you can compare them and act on them with if/unless/case expressions, custom methods that take blocks, et cetera. Just how you compare them depends on the kind of objects you are using for keys (people often use strings and symbols, but Ruby hashes can use any kind of object as keys (as long as they are not modified while they serve as keys)).

Remove characters after specific character in string, then remove substring?

To remove everything before the first /

input = input.Substring(input.IndexOf("/"));

To remove everything after the first /

input = input.Substring(0, input.IndexOf("/") + 1);

To remove everything before the last /

input = input.Substring(input.LastIndexOf("/"));

To remove everything after the last /

input = input.Substring(0, input.LastIndexOf("/") + 1);

An even more simpler solution for removing characters after a specified char is to use the String.Remove() method as follows:

To remove everything after the first /

input = input.Remove(input.IndexOf("/") + 1);

To remove everything after the last /

input = input.Remove(input.LastIndexOf("/") + 1);

Is there a php echo/print equivalent in javascript

From w3school's page on JavaScript output,

JavaScript can "display" data in different ways:

Writing into an alert box, using window.alert().

Writing into the HTML output using document.write().

Writing into an HTML element, using innerHTML.

Writing into the browser console, using console.log().

Java parsing XML document gives "Content not allowed in prolog." error

If you're able to control the xml file, try adding a bit more information to the beginning of the file:

<?xml version="1.0" encoding="UTF-16" standalone="no"?>

Highlight Anchor Links when user manually scrolls?

You can use Jquery's on method and listen for the scroll event.

How do I redirect users after submit button click?

It would be

window.location="login.php";

Fluid width with equally spaced DIVs

This worked for me with 5 images in diferent sizes.

  1. Create a container div
  2. An Unordered list for the images
  3. On css the unordened must be displayed vertically and without bullets
  4. Justify content of container div

This works because of justify-content:space-between, and it's on a list, displayed horizontally.

On CSS

 #container {
            display: flex;
            justify-content: space-between;
 }
    #container ul li{ display:inline; list-style-type:none;
}

On html

<div id="container"> 
  <ul>  
        <li><img src="box1.png"><li>
        <li><img src="box2.png"><li>
        <li><img src="box3.png"><li>
        <li><img src="box4.png"><li>
        <li><img src="box5.png"><li>
    </ul>
</div>

how to remove only one style property with jquery

The documentation for css() says that setting the style property to the empty string will remove that property if it does not reside in a stylesheet:

Setting the value of a style property to an empty string — e.g. $('#mydiv').css('color', '') — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's .css() method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or <style> element.

Since your styles are inline, you can write:

$(selector).css("-moz-user-select", "");

Installing SciPy and NumPy using pip

Since the previous instructions for installing with yum are broken here are the updated instructions for installing on something like fedora. I've tested this on "Amazon Linux AMI 2016.03"

sudo yum install atlas-devel lapack-devel blas-devel libgfortran
pip install scipy

htmlentities() vs. htmlspecialchars()

This is being encoded with htmlentities.

implode( "\t", array_values( get_html_translation_table( HTML_ENTITIES ) ) ):

" & < >
¡ ¢ £ ¤ ¥ ¦ § ¨ © ª « ¬ ­ ® ¯ ° ± ² ³ ´ µ ¶ · ¸ ¹ º » ¼ ½ ¾ ¿ À Á Â Ã Ä Å Æ Ç È É Ê Ë Ì Í Î Ï Ð Ñ Ò Ó Ô Õ Ö × Ø Ù Ú Û Ü Ý Þ ß à á â ã ä å æ ç è é ê ë ì í î ï ð ñ ò ó ô õ ö ÷ ø ù ú û ü ý þ ÿ Œ œ Š š Ÿ ƒ ˆ ˜ ? ? G ? ? ? ? T ? ? ? ? ? ? ? ? ? S ? ? F ? ? O a ß ? d e ? ? ? ? ? ? µ ? ? ? p ? ? s t ? f ? ? ? ? ? ? ? ? ? ? – — ‘ ’ ‚ “ ” „ † ‡ • … ‰ ' " ‹ › ? / € I P R ™ ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Ø ? ? ? ? ? ? - * v ? 8 ? ? ? n ? ? ? ~ ? ˜ ? = = = ? ? ? ? ? ? ? ? · ? ? ? ? ? ? ? ? ? ? ?

This is being encoded with htmlspecialchars.

implode( "\t", array_values( get_html_translation_table( HTML_SPECIALCHARS ) ) ):

" & < >

Simple way to change the position of UIView?

swift

view.frame = view.frame.offsetBy(dx: offsetX, dy: offsetY)

Get fragment (value after hash '#') from a URL in php

If you want to get the value after the hash mark or anchor as shown in a user's browser: This isn't possible with "standard" HTTP as this value is never sent to the server (hence it won't be available in $_SERVER["REQUEST_URI"] or similar predefined variables). You would need some sort of JavaScript magic on the client side, e.g. to include this value as a POST parameter.

If it's only about parsing a known URL from whatever source, the answer by mck89 is perfectly fine though.

Path to Powershell.exe (v 2.0)

I think $PsHome has the information you're after?

PS .> $PsHome
C:\Windows\System32\WindowsPowerShell\v1.0

PS .> Get-Help about_automatic_variables

TOPIC
    about_Automatic_Variables ...

SQL select max(date) and corresponding value

There's no easy way to do this, but something like this will work:

SELECT ET.TrainingID, 
  ET.CompletedDate, 
  ET.Notes
FROM 
HR_EmployeeTrainings ET
inner join
(
  select TrainingID, Max(CompletedDate) as CompletedDate
  FROM HR_EmployeeTrainings
  WHERE (ET.AvantiRecID IS NULL OR ET.AvantiRecID = @avantiRecID)
  GROUP BY AvantiRecID, TrainingID  
) ET2 
  on ET.TrainingID = ET2.TrainingID
  and ET.CompletedDate = ET2.CompletedDate

htaccess redirect to https://www

BAD SOLUTION AND WHY!

Don't ever use the solution below because when you are using their code that is something like:

RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.example.com%{REQUEST_URI} [L,R=301]

The browser goes to:

http://example.com

Then redirects to:

https://example.com

Then redirects to:

https://www.example.com

This is too much request to the server.

Most of the answers even accepted one has this problem.


BEST SOLUTION AND THE ANSWER

This code has an [OR] condition to prevent dual changes at url!

RewriteEngine on
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule (.*) https://www.example.com%{REQUEST_URI} [R=301,L]

What's the difference between RANK() and DENSE_RANK() functions in oracle?

select empno
       ,salary
       ,row_number() over(order by salary desc) as Serial
       ,Rank() over(order by salary desc) as rank
       ,dense_rank() over(order by salary desc) as denseRank
from emp ;

Row_number() -> Used for generating serial number

Dense_rank() will give continuous rank but rank will skip rank in case of clash of rank.

What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)

DateTimeExtensions

Examples:

DateTime firstDayOfMonth = DateTime.Now.First();
DateTime lastdayOfMonth = DateTime.Now.Last();
DateTime lastFridayInMonth = DateTime.Now.Last(DayOfWeek.Friday);
DateTime nextFriday = DateTime.Now.Next(DayOfWeek.Friday);
DateTime lunchTime = DateTime.Now.SetTime(11, 30);
DateTime noonOnFriday = DateTime.Now.Next(DayOfWeek.Friday).Noon();
DateTime secondMondayOfMonth = DateTime.Now.First(DayOfWeek.Monday).Next(DayOfWeek.Monday).Midnight();

How to trigger checkbox click event even if it's checked through Javascript code?

You can use .change() function too

E.g.:

$('form input[type=checkbox]').change(function() { console.log('hello') });

ViewBag, ViewData and TempData

ASP.NET MVC offers us three options ViewData, ViewBag, and TempData for passing data from controller to view and in next request. ViewData and ViewBag are almost similar and TempData performs additional responsibility. Lets discuss or get key points on those three objects:

Similarities between ViewBag & ViewData :

  • Helps to maintain data when you move from controller to view.
  • Used to pass data from controller to corresponding view.
  • Short life means value becomes null when redirection occurs. This is because their goal is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.

Difference between ViewBag & ViewData:

  • ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys.
  • ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
  • ViewData requires typecasting for complex data type and check for null values to avoid error.
  • ViewBag doesn’t require typecasting for complex data type.

ViewBag & ViewData Example:

public ActionResult Index()
{
    ViewBag.Name = "Monjurul Habib";
    return View();
}


public ActionResult Index()
{
    ViewData["Name"] = "Monjurul Habib";
    return View();
} 

In View:

@ViewBag.Name 
@ViewData["Name"] 

TempData:

TempData is also a dictionary derived from TempDataDictionary class and stored in short lives session and it is a string key and object value. The difference is that the life cycle of the object. TempData keep the information for the time of an HTTP Request. This mean only from one page to another. This also work with a 302/303 redirection because it’s in the same HTTP Request. Helps to maintain data when you move from one controller to other controller or from one action to other action. In other words when you redirect, “TempData” helps to maintain data between those redirects. It internally uses session variables. Temp data use during the current and subsequent request only means it is use when you are sure that next request will be redirecting to next view. It requires typecasting for complex data type and check for null values to avoid error. Generally used to store only one time messages like error messages, validation messages.

public ActionResult Index()
{
  var model = new Review()
            {
                Body = "Start",
                Rating=5
            };
    TempData["ModelName"] = model;
    return RedirectToAction("About");
}

public ActionResult About()
{
    var model= TempData["ModelName"];
    return View(model);
}

The last mechanism is the Session which work like the ViewData, like a Dictionary that take a string for key and object for value. This one is stored into the client Cookie and can be used for a much more long time. It also need more verification to never have any confidential information. Regarding ViewData or ViewBag you should use it intelligently for application performance. Because each action goes through the whole life cycle of regular asp.net mvc request. You can use ViewData/ViewBag in your child action but be careful that you are not using it to populate the unrelated data which can pollute your controller.

How can I determine the URL that a local Git repository was originally cloned from?

The Git URL will be inside the Git configuration file. The value corresponds to the key url.

For Mac and Linux use the commands below:

 cd project_dir
 cat .git/config | grep url | awk '{print $3}'

For Windows open the below file in any text editor and find the value for key url.

project_dir/.git/config

Note: This will work even if you are offline or the remote git server has been taken down.

How to retrieve data from a SQL Server database in C#?

You can use this simple method after setting up your connection:

private void getAgentInfo(string key)//"key" is your search paramter inside database
    {
        con.Open();
        string sqlquery = "SELECT * FROM TableName WHERE firstname = @fName";

        SqlCommand command = new SqlCommand(sqlquery, con); 
        SqlDataReader sReader;

        command.Parameters.Clear();
        command.Parameters.AddWithValue("@fName", key);
        sReader = command.ExecuteReader();

        while (sReader.Read())
        {
            textBoxLastName.Text = sReader["Lastname"].ToString(); //SqlDataReader
            //["LastName"] the name of your column you want to retrieve from DB

            textBoxAge.Text = sReader["age"].ToString();
            //["age"] another column you want to retrieve
        }
        con.Close();
    }

Now you can pass the key to this method by your textBoxFirstName like:

getAgentInfo(textBoxFirstName.Text);

Sending multipart/formdata with jQuery.ajax

I just built this function based on some info I read.

Use it like using .serialize(), instead just put .serializefiles();.
Working here in my tests.

//USAGE: $("#form").serializefiles();
(function($) {
$.fn.serializefiles = function() {
    var obj = $(this);
    /* ADD FILE TO PARAM AJAX */
    var formData = new FormData();
    $.each($(obj).find("input[type='file']"), function(i, tag) {
        $.each($(tag)[0].files, function(i, file) {
            formData.append(tag.name, file);
        });
    });
    var params = $(obj).serializeArray();
    $.each(params, function (i, val) {
        formData.append(val.name, val.value);
    });
    return formData;
};
})(jQuery);

INSTALL_FAILED_UPDATE_INCOMPATIBLE when I try to install compiled .apk on device

Uninstalling the application would be enough to avoid this problem.

INSTALL_FAILED_UPDATE_INCOMPATIBLE

but sometimes even uninstalling the message is raised again, it occurs in Android OS 5.0 +, so this is the solution:

Go to Settings > Apps and you will find your app with the message:

"Not installed for this user" enter image description here

We have to uninstall manually for all users!, then we can install our compiled application with no problems.

enter image description here

Another options:

  • Remove the old application and install again.

  • Use Android Debug Bridge command:

    adb uninstall [PACKAGE NAME]

How to get year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java?

Use the formatting pattern 'dd-MM-yyyy HH:mm:ss aa' to get date as 21-10-2020 20:53:42 pm

The easiest way to replace white spaces with (underscores) _ in bash

This is borderline programming, but look into using tr:

$ echo "this is just a test" | tr -s ' ' | tr ' ' '_'

Should do it. The first invocation squeezes the spaces down, the second replaces with underscore. You probably need to add TABs and other whitespace characters, this is for spaces only.

How do I "select Android SDK" in Android Studio?

The simplest solution for this problem:

First make sure your sdk path is currect. Then Please close current project and in android startup menu click on import project and choose your project from explorer. This will always solve my problem

Which websocket library to use with Node.js?

Update: This answer is outdated as newer versions of libraries mentioned are released since then.

Socket.IO v0.9 is outdated and a bit buggy, and Engine.IO is the interim successor. Socket.IO v1.0 (which will be released soon) will use Engine.IO and be much better than v0.9. I'd recommend you to use Engine.IO until Socket.IO v1.0 is released.

"ws" does not support fallback, so if the client browser does not support websockets, it won't work, unlike Socket.IO and Engine.IO which uses long-polling etc if websockets are not available. However, "ws" seems like the fastest library at the moment.

See my article comparing Socket.IO, Engine.IO and Primus: https://medium.com/p/b63bfca0539

How to transfer some data to another Fragment?

From Activity Class:

Send the data using bundle arguments to the fragment and load the fragment

   Fragment fragment = new myFragment();
   Bundle bundle = new Bundle();
   bundle.putString("pName", personName);
   bundle.putString("pEmail", personEmail);
   bundle.putString("pId", personId);
   fragment.setArguments(bundle);

   getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    fragment).commit();

From myFragment Class:

Get the arguments from the bundle and set them to xml

    Bundle arguments = getArguments();
    String personName = arguments.getString("pName");
    String personEmail = arguments.getString("pEmail");
    String personId = arguments.getString("pId");

    nameTV = v.findViewById(R.id.name);
    emailTV = v.findViewById(R.id.email);
    idTV = v.findViewById(R.id.id);

    nameTV.setText("Name: "+ personName);
    emailTV.setText("Email: "+ personEmail);
    idTV.setText("ID: "+ personId);

RelativeLayout center vertical

For me, I had to remove

<item name="android:gravity">center_vertical</item>

from RelativeLayout, so children's configuration would work:

<item name="android:layout_centerVertical">true</item>

Should CSS always preceed Javascript?

Is the recommendation to include CSS before JavaScript invalid?

Not if you treat it as simply a recommendation. But if your treat it as a hard and fast rule?, yes, it is invalid.

From https://developer.mozilla.org/en-US/docs/Web/Reference/Events/DOMContentLoaded

Stylesheet loads block script execution, so if you have a <script> after a <link rel="stylesheet" ...> the page will not finish parsing - and DOMContentLoaded will not fire - until the stylesheet is loaded.

It appears that you need to know what each script relies on and make sure that execution of the script is delayed until after the right completion event. If the script relies only on the DOM, it can resume in ondomready/domcontentloaded, if it relies on images to be loaded or stylesheets to be applied, then if I read the above reference correctly, that code must be deferred until the onload event.

I don't think that one sock size fits all, even though that is the way they are sold and I know that one shoe size does not fit all. I don't think that there is a definitive answer to which to load first, styles or script. It is more a case by case decision of what must be loaded in what order and what can be deferred until later as not being on the "critical path".

To speak to the observer that commented that it is better to delay the users ability to interact until the sheet is pretty. There are many of you out there and you annoy your counterparts that feel the opposite. They came to a site to accomplish a purpose and delays to their ability to interact with a site while waiting for things that don't matter to finish loading are very frustrating. I am not saying that you are wrong, only that you should be aware that there is another faction that exists that does not share your priority.

This question particularly applies to all of the ads being placed on web sites. I would love it if site authors rendered just placeholder divs for the ad content and made sure that their site was loaded and interactive before injecting the ads in an onload event. Even then I would like to see the ads loaded serially instead of all at once because they impact my ability to even scroll the site content while the bloated ads are loading. But that is just one persons point of view.

  • Know your users and what they value.
  • Know your users and what browsing environment they use.
  • Know what each file does, and what its pre-requisites are. Making everything work will take precedence over both speed and pretty.
  • Use tools that show you the network time line when developing.
  • Test in each of the environments that your users use. It may be needed to dynamically (server side, when creating the page) alter the order of loading based on the users environment.
  • When in doubt, alter the order and measure again.
  • It is possible that intermixing styles and scripts in the load order will be optimal; not all of one then all of the other.
  • Experiment not just what order to load the files but where. Head? In Body? After Body? DOM Ready/Loaded? Loaded?
  • Consider async and defer options when appropriate to reduce the net delay the user will experience before being able to interact with the page. Test to determine if they help or hurt.
  • There will always be trade offs to consider when evaluating the optimal load order. Pretty vs. Responsive being just one.

SQL Server : converting varchar to INT

This question has got 91,000 views so perhaps many people are looking for a more generic solution to the issue in the title "error converting varchar to INT"

If you are on SQL Server 2012+ one way of handling this invalid data is to use TRY_CAST

SELECT TRY_CAST (userID AS INT)
FROM   audit 

On previous versions you could use

SELECT CASE
         WHEN ISNUMERIC(RTRIM(userID) + '.0e0') = 1
              AND LEN(userID) <= 11
           THEN CAST(userID AS INT)
       END
FROM   audit 

Both return NULL if the value cannot be cast.

In the specific case that you have in your question with known bad values I would use the following however.

CAST(REPLACE(userID COLLATE Latin1_General_Bin, CHAR(0),'') AS INT)

Trying to replace the null character is often problematic except if using a binary collation.

What is the size limit of a post request?

For developers who cannot change php configuration because of the webhosting. (My settings 256MB max size, 1000 max variables)

I got the same issue that just 2 out of 5 big data objects (associative arrays) with substructures were received on the server side.

I find out that the whole substructure is being "flattened" in the post request. So, one object becomes a hundreds of literal variables. At the end, instead of 5 Object variables it is in reality sending dozens of hundreds elementar variables.

Solution in this case is to serialize each of the substructures into String. Then it is received on the server as 5 String variables. Example: {variable1:JSON.stringify(myDataObject1),variable2:JSON.stringify(myDataObject2)...}

Remote desktop connection protocol error 0x112f

If the server accessible with RPC (basically, if you can access a shared folder on it), you could free some memory and thus let the RDP service work properly. The following windows native commands can be used:

To get the list of memory consuming tasks:

tasklist /S <remote_server> /V /FI "MEMUSAGE gt 10000"

To kill a task by its name:

taskkill /S <remote_server> /IM <process_image_name> /F

To show the list of desktop sessions:

qwinsta.exe /SERVER:<remote_server>

To close an old abandoned desktop session:

logoff <session_id> /SERVER:<remote_server> 

After some memory is freed, the RDP should start working.

Turning multiple lines into one comma separated line

based on your input example, this awk line works. (without trailing comma)

awk -vRS="" -vOFS=',' '$1=$1' file

test:

kent$  echo "foo
bar
qux
zuu
sdf
sdfasdf"|awk -vRS="" -vOFS=',' '$1=$1' 
foo,bar,qux,zuu,sdf,sdfasdf

How can I do a case insensitive string comparison?

You can (although controverse) extend System.String to provide a case insensitive comparison extension method:

public static bool CIEquals(this String a, String b) {
    return a.Equals(b, StringComparison.CurrentCultureIgnoreCase);
}

and use as such:

x.Username.CIEquals((string)drUser["Username"]);

C# allows you to create extension methods that can serve as syntax suggar in your project, quite useful I'd say.

It's not the answer and I know this question is old and solved, I just wanted to add these bits.

How can I hide the Android keyboard using JavaScript?

Giving soft keyboard some time to close works for me.

$('#ButtonCancel').click(function () {
    document.body.focus();

    setTimeout(function () {
        //close the dialog, switch to another screen, etc.
    }, 300);
});

Java 8 Filter Array Using Lambda

even simpler, adding up to String[],

use built-in filter filter(StringUtils::isNotEmpty) of org.apache.commons.lang3

import org.apache.commons.lang3.StringUtils;

    String test = "a\nb\n\nc\n";
    String[] lines = test.split("\\n", -1);


    String[]  result = Arrays.stream(lines).filter(StringUtils::isNotEmpty).toArray(String[]::new);
    System.out.println(Arrays.toString(lines));
    System.out.println(Arrays.toString(result));

and output: [a, b, , c, ] [a, b, c]

How to return dictionary keys as a list in Python?

A bit off on the "duck typing" definition -- dict.keys() returns an iterable object, not a list-like object. It will work anywhere an iterable will work -- not any place a list will. a list is also an iterable, but an iterable is NOT a list (or sequence...)

In real use-cases, the most common thing to do with the keys in a dict is to iterate through them, so this makes sense. And if you do need them as a list you can call list().

Very similarly for zip() -- in the vast majority of cases, it is iterated through -- why create an entire new list of tuples just to iterate through it and then throw it away again?

This is part of a large trend in python to use more iterators (and generators), rather than copies of lists all over the place.

dict.keys() should work with comprehensions, though -- check carefully for typos or something... it works fine for me:

>>> d = dict(zip(['Sounder V Depth, F', 'Vessel Latitude, Degrees-Minutes'], [None, None]))
>>> [key.split(", ") for key in d.keys()]
[['Sounder V Depth', 'F'], ['Vessel Latitude', 'Degrees-Minutes']]

Finding the number of non-blank columns in an Excel sheet using VBA

Your example code gets the row number of the last non-blank cell in the current column, and can be rewritten as follows:

Dim lastRow As Long
lastRow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
MsgBox lastRow

It is then easy to see that the equivalent code to get the column number of the last non-blank cell in the current row is:

Dim lastColumn As Long
lastColumn = Sheet1.Cells(1, Columns.Count).End(xlToLeft).Column
MsgBox lastColumn

This may also be of use to you:

With Sheet1.UsedRange
    MsgBox .Rows.Count & " rows and " & .Columns.Count & " columns"
End With

but be aware that if column A and/or row 1 are blank, then this will not yield the same result as the other examples above. For more, read up on the UsedRange property.

How to check if mysql database exists

SELECT SCHEMA_NAME
  FROM INFORMATION_SCHEMA.SCHEMATA
 WHERE SCHEMA_NAME = 'DBName'

If you just need to know if a db exists so you won't get an error when you try to create it, simply use (From here):

CREATE DATABASE IF NOT EXISTS DBName;

Android Facebook integration with invalid key hash

Use the below code in the onCreate() method of your activity:

try {
    PackageInfo info = getPackageManager().getPackageInfo(
                           "your application package name",
                           PackageManager.GET_SIGNATURES);
    for (Signature signature : info.signatures) {
        MessageDigest md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
    }
}
catch (NameNotFoundException e) {
}
catch (NoSuchAlgorithmException e) {
}

Run this code. This will generate the hash key. Copy this KeyHash in the Facebook application setting, and save changes. Then log into your application. This will work perfectly in the future too.

Using G++ to compile multiple .cpp and .h files

To compile separately without linking you need to add -c option:

g++ -c myclass.cpp
g++ -c main.cpp
g++ myclass.o main.o
./a.out

How to get all selected values from <select multiple=multiple>?

Works everywhere without jquery:

var getSelectValues = function (select) {
    var ret = [];

    // fast but not universally supported
    if (select.selectedOptions != undefined) {
        for (var i=0; i < select.selectedOptions.length; i++) {
            ret.push(select.selectedOptions[i].value);
        }

    // compatible, but can be painfully slow
    } else {
        for (var i=0; i < select.options.length; i++) {
            if (select.options[i].selected) {
                ret.push(select.options[i].value);
            }
        }
    }
    return ret;
};

how to convert String into Date time format in JAVA?

With SimpleDateFormat. And steps are -

  1. Create your date pattern string
  2. Create SimpleDateFormat Object
  3. And parse with it.
  4. It will return Date Object.

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

You can use map :

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

EDIT :

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

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

Shall we always use [unowned self] inside closure in Swift

Here is brilliant quotes from Apple Developer Forums described delicious details:

unowned vs unowned(safe) vs unowned(unsafe)

unowned(safe) is a non-owning reference that asserts on access that the object is still alive. It's sort of like a weak optional reference that's implicitly unwrapped with x! every time it's accessed. unowned(unsafe) is like __unsafe_unretained in ARC—it's a non-owning reference, but there's no runtime check that the object is still alive on access, so dangling references will reach into garbage memory. unowned is always a synonym for unowned(safe) currently, but the intent is that it will be optimized to unowned(unsafe) in -Ofast builds when runtime checks are disabled.

unowned vs weak

unowned actually uses a much simpler implementation than weak. Native Swift objects carry two reference counts, and unowned references bump the unowned reference count instead of the strong reference count. The object is deinitialized when its strong reference count reaches zero, but it isn't actually deallocated until the unowned reference count also hits zero. This causes the memory to be held onto slightly longer when there are unowned references, but that isn't usually a problem when unowned is used because the related objects should have near-equal lifetimes anyway, and it's much simpler and lower-overhead than the side-table based implementation used for zeroing weak references.

Update: In modern Swift weak internally uses the same mechanism as unowned does. So this comparison is incorrect because it compares Objective-C weak with Swift unonwed.

Reasons

What is the purpose of keeping the memory alive after owning references reach 0? What happens if code attempts to do something with the object using an unowned reference after it is deinitialized?

The memory is kept alive so that its retain counts are still available. This way, when someone attempts to retain a strong reference to the unowned object, the runtime can check that the strong reference count is greater than zero in order to ensure that it is safe to retain the object.

What happens to owning or unowned references held by the object? Is their lifetime decoupled from the object when it is deinitialized or is their memory also retained until the object is deallocated after the last unowned reference is released?

All resources owned by the object are released as soon as the object's last strong reference is released, and its deinit is run. Unowned references only keep the memory alive—aside from the header with the reference counts, its contents is junk.

Excited, huh?

How to select a div element in the code-behind page?

Give ID and attribute runat='server' as :

<div class="tab-pane active" id="portlet_tab1" runat="server">

//somecode Codebehind:

Access at code behind

    Control Test = Page.FindControl("portlet_tab1");
    Test.Style.Add("display", "none"); 

    or 

    portlet_tab1.Style.Add("display", "none"); 

Update Fragment from ViewPager

Very simple to override the method in the fragment:

@Override

public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    if(isVisibleToUser){
        actionView();
    }
    else{
        //no
    }      
}

How can I join on a stored procedure?

insert the result of the SP into a temp table, then join:

CREATE TABLE #Temp (
    TenantID int, 
    TenantBalance int
)

INSERT INTO #Temp
EXEC TheStoredProc

SELECT t.TenantName, t.CarPlateNumber, t.CarColor, t.Sex, t.SSNO, t.Phone, t.Memo,
    u.UnitNumber, p.PropertyName
FROM tblTenant t
INNER JOIN #Temp ON t.TenantID = #Temp.TenantID
...

How to filter specific apps for ACTION_SEND intent (and set a different text for each app)

If you want a customized option then you should not rely on the default dialog provided by android for this action.

What you need to do instead is roll out your own. You will need to query the PackageManager on which packages handle the action you require and then based on the reply, you apply filtering and customized text.

Specifically, take a look at the method queryIntentActivities of the PackageManager class. You build the intent that would launch the default dialog (the ACTION_SEND intent), pass that to this method and you will receive a list of objects that contain info on the activities that can handle that intent. Using that, you can choose the ones you want.

Once you build your list of packages you want to present, you need to build your own list dialog (preferably an activity with the dialog theme) which will display that list.

One thing to note though is that it's very hard to make that custom dialog look like the default one. The problem is that the theme used in that dialog is an internal theme and cannot be used by your application. You can either try to make it as similar to the native one as you want or go for a completely custom look (many apps do that like the gallery app etc)

Tomcat Servlet: Error 404 - The requested resource is not available

this is may be due to the thing that you have created your .jsp or the .html file in the WEB-INF instead of the WebContent folder.

Solution: Just replace the files that are there in the WEB-INF folder to the Webcontent folder and try executing the same - You will get the appropriate output

How to use OAuth2RestTemplate?

My simple solution. IMHO it's the cleanest.

First create a application.yml

spring.main.allow-bean-definition-overriding: true

security:
  oauth2:
    client:
      clientId: XXX
      clientSecret: XXX
      accessTokenUri: XXX
      tokenName: access_token
      grant-type: client_credentials

Create the main class: Main

@SpringBootApplication
@EnableOAuth2Client
public class Main extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/").permitAll();
    }

    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }

    @Bean
    public OAuth2RestTemplate oauth2RestTemplate(ClientCredentialsResourceDetails details) {
        return new OAuth2RestTemplate(details);
    }

}

Then Create the controller class: Controller

@RestController
class OfferController {

    @Autowired
    private OAuth2RestOperations restOperations;

    @RequestMapping(value = "/<your url>"
            , method = RequestMethod.GET
            , produces = "application/json")
    public String foo() {
        ResponseEntity<String> responseEntity = restOperations.getForEntity(<the url you want to call on the server>, String.class);
        return responseEntity.getBody();
    }
}

Maven dependencies

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.5.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth.boot</groupId>
        <artifactId>spring-security-oauth2-autoconfigure</artifactId>
        <version>2.1.5.RELEASE</version>
    </dependency>
</dependencies>

checking if number entered is a digit in jquery

I would suggest using regexes:

var intRegex = /^\d+$/;
var floatRegex = /^((\d+(\.\d *)?)|((\d*\.)?\d+))$/;

var str = $('#myTextBox').val();
if(intRegex.test(str) || floatRegex.test(str)) {
   alert('I am a number');
   ...
}

Or with a single regex as per @Platinum Azure's suggestion:

var numberRegex = /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/;
var str = $('#myTextBox').val();
if(numberRegex.test(str)) {
   alert('I am a number');
   ...
}    

Using if-else in JSP

Instead of if-else condition use if in both conditions. it will work that way but not sure why.

MySQL, update multiple tables with one query

UPDATE t1
INNER JOIN t2 ON t2.t1_id = t1.id
INNER JOIN t3 ON t2.t3_id = t3.id
SET t1.a = 'something',
    t2.b = 42,
    t3.c = t2.c
WHERE t1.a = 'blah';

To see what this is going to update, you can convert this into a select statement, e.g.:

SELECT t2.t1_id, t2.t3_id, t1.a, t2.b, t2.c AS t2_c, t3.c AS t3_c
FROM t1
INNER JOIN t2 ON t2.t1_id = t1.id
INNER JOIN t3 ON t2.t3_id = t3.id
WHERE t1.a = 'blah';

An example using the same tables as the other answer:

SELECT Books.BookID, Orders.OrderID,
    Orders.Quantity AS CurrentQuantity,
    Orders.Quantity + 2 AS NewQuantity,
    Books.InStock AS CurrentStock,
    Books.InStock - 2 AS NewStock
FROM Books
INNER JOIN Orders ON Books.BookID = Orders.BookID
WHERE Orders.OrderID = 1002;

UPDATE Books
INNER JOIN Orders ON Books.BookID = Orders.BookID
SET Orders.Quantity = Orders.Quantity + 2,
    Books.InStock = Books.InStock - 2
WHERE Orders.OrderID = 1002;

EDIT:

Just for fun, let's add something a bit more interesting.

Let's say you have a table of books and a table of authors. Your books have an author_id. But when the database was originally created, no foreign key constraints were set up and later a bug in the front-end code caused some books to be added with invalid author_ids. As a DBA you don't want to have to go through all of these books to check what the author_id should be, so the decision is made that the data capturers will fix the books to point to the right authors. But there are too many books to go through each one and let's say you know that the ones that have an author_id that corresponds with an actual author are correct. It's just the ones that have nonexistent author_ids that are invalid. There is already an interface for the users to update the book details and the developers don't want to change that just for this problem. But the existing interface does an INNER JOIN authors, so all of the books with invalid authors are excluded.

What you can do is this: Insert a fake author record like "Unknown author". Then update the author_id of all the bad records to point to the Unknown author. Then the data capturers can search for all books with the author set to "Unknown author", look up the correct author and fix them.

How do you update all of the bad records to point to the Unknown author? Like this (assuming the Unknown author's author_id is 99999):

UPDATE books
LEFT OUTER JOIN authors ON books.author_id = authors.id
SET books.author_id = 99999
WHERE authors.id IS NULL;

The above will also update books that have a NULL author_id to the Unknown author. If you don't want that, of course you can add AND books.author_id IS NOT NULL.

Send push to Android by C# using FCM (Firebase Cloud Messaging)

Here's the code for server side firebase cloud request from C# / Asp.net.
Please note that your client side should have same topic.
e.g.

FirebaseMessaging.getInstance().subscribeToTopic("news");

public String SendNotificationFromFirebaseCloud()
{
    var result = "-1";
    var webAddr = "https://fcm.googleapis.com/fcm/send";

    var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Headers.Add("Authorization:key=" + YOUR_FIREBASE_SERVER_KEY);
    httpWebRequest.Method = "POST";

    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        string json = "{\"to\": \"/topics/news\",\"data\": {\"message\": \"This is a Firebase Cloud Messaging Topic Message!\",}}";


        streamWriter.Write(json);
        streamWriter.Flush();
    }

    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        result = streamReader.ReadToEnd();
    }

    return result;
}

Does Java SE 8 have Pairs or Tuples?

Vavr (formerly called Javaslang) (http://www.vavr.io) provides tuples (til size of 8) as well. Here is the javadoc: https://static.javadoc.io/io.vavr/vavr/0.9.0/io/vavr/Tuple.html.

This is a simple example:

Tuple2<Integer, String> entry = Tuple.of(1, "A");

Integer key = entry._1;
String value = entry._2;

Why JDK itself did not come with a simple kind of tuples til now is a mystery to me. Writing wrapper classes seems to be an every day business.

Return multiple values from a function, sub or type?

I always approach returning more than one result from a function by always returning an ArrayList. By using an ArrayList I can return only one item, consisting of many multiple values, mixing between Strings and Integers.

Once I have the ArrayList returned in my main sub, I simply use ArrayList.Item(i).ToString where i is the index of the value I want to return from the ArrayList

An example:

 Public Function Set_Database_Path()
        Dim Result As ArrayList = New ArrayList
        Dim fd As OpenFileDialog = New OpenFileDialog()


        fd.Title = "Open File Dialog"
        fd.InitialDirectory = "C:\"
        fd.RestoreDirectory = True
        fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
        fd.FilterIndex = 2
        fd.Multiselect = False


        If fd.ShowDialog() = DialogResult.OK Then

            Dim Database_Location = Path.GetFullPath(fd.FileName)

            Dim Database_Connection_Var = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=""" & Database_Location & """"

            Result.Add(Database_Connection_Var)
            Result.Add(Database_Location)

            Return (Result)

        Else

            Return (Nothing)

        End If
    End Function

And then call the Function like this:

Private Sub Main_Load()
  Dim PathArray As ArrayList

            PathArray = Set_Database_Path()
            My.Settings.Database_Connection_String = PathArray.Item(0).ToString
            My.Settings.FilePath = PathArray.Item(1).ToString
            My.Settings.Save()
End Sub

How to get value in the session in jQuery

Sessions are stored on the server and are set from server side code, not client side code such as JavaScript.

What you want is a cookie, someone's given a brilliant explanation in this Stack Overflow question here: How do I set/unset cookie with jQuery?

You could potentially use sessions and set/retrieve them with jQuery and AJAX, but it's complete overkill if Cookies will do the trick.

How do I get IntelliJ to recognize common Python modules?

I got it to work after I unchecked the following options in the Run/Debug Configurations for main.py

Add content roots to PYTHONPATH

Add source roots to PYTHONPATH

This is after I had invalidated the cache and restarted.

relative path to CSS file

if the file containing that link tag is in the root dir of the project, then the correct path would be "css/styles.css"

How to select some rows with specific rownames from a dataframe?

df <- data.frame(x=rnorm(10), y=rnorm(10))
rownames(df) <-  letters[1:10]
df[c('a','b'),]

How to export data from Spark SQL to CSV

Since Spark 2.X spark-csv is integrated as native datasource. Therefore, the necessary statement simplifies to (windows)

df.write
  .option("header", "true")
  .csv("file:///C:/out.csv")

or UNIX

df.write
  .option("header", "true")
  .csv("/var/out.csv")

Notice: as the comments say, it is creating the directory by that name with the partitions in it, not a standard CSV file. This, however, is most likely what you want since otherwise your either crashing your driver (out of RAM) or you could be working with a non distributed environment.

how to append a css class to an element by javascript?

You should be able to set the className property of the element. You could do a += to append it.

how to format date in Component of angular 5

Another option can be using built in angular formatDate function. I am assuming that you are using reactive forms. Here todoDate is a date input field in template.

import {formatDate} from '@angular/common';

this.todoForm.controls.todoDate.setValue(formatDate(this.todo.targetDate, 'yyyy-MM-dd', 'en-US'));

How does HttpContext.Current.User.Identity.Name know which usernames exist?

The HttpContext.Current.User.Identity.Name returns null

This depends on whether the authentication mode is set to Forms or Windows in your web.config file.

For example, if I write the authentication like this:

<authentication mode="Forms"/>

Then because the authentication mode="Forms", I will get null for the username. But if I change the authentication mode to Windows like this:

<authentication mode="Windows"/>

I can run the application again and check for the username, and I will get the username successfully.

For more information, see System.Web.HttpContext.Current.User.Identity.Name Vs System.Environment.UserName in ASP.NET.

How to use a parameter in ExecStart command line?

Although systemd indeed does not provide way to pass command-line arguments for unit files, there are possibilities to write instances: http://0pointer.de/blog/projects/instances.html

For example: /lib/systemd/system/[email protected] looks something like this:

[Unit]
Description=Serial Getty on %I
BindTo=dev-%i.device
After=dev-%i.device systemd-user-sessions.service

[Service]
ExecStart=-/sbin/agetty -s %I 115200,38400,9600
Restart=always
RestartSec=0

So, you may start it like:

$ systemctl start [email protected]
$ systemctl start [email protected]

For systemd it will different instances:

$ systemctl status [email protected]
[email protected] - Getty on ttyUSB0
      Loaded: loaded (/lib/systemd/system/[email protected]; static)
      Active: active (running) since Mon, 26 Sep 2011 04:20:44 +0200; 2s ago
    Main PID: 5443 (agetty)
      CGroup: name=systemd:/system/[email protected]/ttyUSB0
          + 5443 /sbin/agetty -s ttyUSB0 115200,38400,9600

It also mean great possibility enable and disable it separately.

Off course it lack much power of command line parsing, but in common way it is used as some sort of config files selection. For example you may look at Fedora [email protected]: http://pkgs.fedoraproject.org/cgit/openvpn.git/tree/[email protected]

Make multiple-select to adjust its height to fit options without scroll bar

To adjust the size (height) of all multiple selects to the number of options, use jQuery:

$('select[multiple = multiple]').each(function() {
    $(this).attr('size', $(this).find('option').length)
})

Are parameters in strings.xml possible?

If you need two variables in the XML, you can use:

%1$d text... %2$d or %1$s text... %2$s for string variables.

Example :

strings.xml

<string name="notyet">Website %1$s isn\'t yet available, I\'m working on it, please wait %2$s more days</string>

activity.java

String site = "site.tld";
String days = "11";

//Toast example
String notyet = getString(R.string.notyet, site, days);
Toast.makeText(getApplicationContext(), notyet, Toast.LENGTH_LONG).show();

Recursively looping through an object to build a property list

Here is a simple solution. This is a late answer but may be simple one-

_x000D_
_x000D_
const data = {
  city: 'foo',
  year: 2020,
  person: {
    name: {
      firstName: 'john',
      lastName: 'doe'
    },
    age: 20,
    type: {
      a: 2,
      b: 3,
      c: {
        d: 4,
        e: 5
      }
    }
  },
}

function getKey(obj, res = [], parent = '') {
  const keys = Object.keys(obj);
  
  /** Loop throw the object keys and check if there is any object there */
  keys.forEach(key => {
    if (typeof obj[key] !== 'object') {
      // Generate the heirarchy
      parent ? res.push(`${parent}.${key}`) : res.push(key);
    } else {
      // If object found then recursively call the function with updpated parent
      let newParent = parent ? `${parent}.${key}` : key;
      getKey(obj[key], res, newParent);
    }
    
  });
}

const result = [];

getKey(data, result, '');

console.log(result);
_x000D_
.as-console-wrapper{min-height: 100%!important; top: 0}
_x000D_
_x000D_
_x000D_

Converting an integer to a string in PHP

You can use the strval() function to convert a number to a string.

From a maintenance perspective its obvious what you are trying to do rather than some of the other more esoteric answers. Of course, it depends on your context.

$var = 5;

// Inline variable parsing
echo "I'd like {$var} waffles"; // = I'd like 5 waffles

// String concatenation 
echo "I'd like ".$var." waffles"; // I'd like 5 waffles

// The two examples above have the same end value...
// ... And so do the two below

// Explicit cast 
$items = (string)$var; // $items === "5";

// Function call
$items = strval($var); // $items === "5";

"Expected an indented block" error?

I also experienced that for example:

This code doesnt work and get the intended block error.

class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()

def __unicode__(self):
return self.title

However, when i press tab before typing return self.title statement, the code works.

class Foo(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')
likes = models.IntegerField()

def __unicode__(self):
    return self.title

Hope, this will help others.

Sharepoint: How do I filter a document library view to show the contents of a subfolder?

Have you thought about creating a view with 'Folder = Show all items without folders', that would get all your documents out of their folders and then perhaps you could create your filter(s) over that view.

java.io.IOException: Broken pipe

Error message suggests that the client has closed the connection while the server is still trying to write out a response.

Refer to this link for more details:

https://markhneedham.com/blog/2014/01/27/neo4j-org-eclipse-jetty-io-eofexception-caused-by-java-io-ioexception-broken-pipe/

Getting unix timestamp from Date()

Use SimpleDateFormat class. Take a look on its javadoc: it explains how to use format switches.

how to get domain name from URL

So if you just have a string and not a window.location you could use...

String.prototype.toUrl = function(){

if(!this && 0 < this.length)
{
    return undefined;
}
var original = this.toString();
var s = original;
if(!original.toLowerCase().startsWith('http'))
{
    s = 'http://' + original;
}

s = this.split('/');

var protocol = s[0];
var host = s[2];
var relativePath = '';

if(s.length > 3){
    for(var i=3;i< s.length;i++)
    {
        relativePath += '/' + s[i];
    }
}

s = host.split('.');
var domain = s[s.length-2] + '.' + s[s.length-1];    

return {
    original: original,
    protocol: protocol,
    domain: domain,
    host: host,
    relativePath: relativePath,
    getParameter: function(param)
    {
        return this.getParameters()[param];
    },
    getParameters: function(){
        var vars = [], hash;
        var hashes = this.original.slice(this.original.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }
};};

How to use.

var str = "http://en.wikipedia.org/wiki/Knopf?q=1&t=2";
var url = str.toUrl;

var host = url.host;
var domain = url.domain;
var original = url.original;
var relativePath = url.relativePath;
var paramQ = url.getParameter('q');
var paramT = url.getParamter('t');

Java String split removed empty values

String[] split = data.split("\\|",-1);

This is not the actual requirement in all the time. The Drawback of above is show below:

Scenerio 1:
When all data are present:
    String data = "5|6|7||8|9|10|";
    String[] split = data.split("\\|");
    String[] splt = data.split("\\|",-1);
    System.out.println(split.length); //output: 7
    System.out.println(splt.length); //output: 8

When data is missing:

Scenerio 2: Data Missing
    String data = "5|6|7||8|||";
    String[] split = data.split("\\|");
    String[] splt = data.split("\\|",-1);
    System.out.println(split.length); //output: 5
    System.out.println(splt.length); //output: 8

Real requirement is length should be 7 although there is data missing. Because there are cases such as when I need to insert in database or something else. We can achieve this by using below approach.

    String data = "5|6|7||8|||";
    String[] split = data.split("\\|");
    String[] splt = data.replaceAll("\\|$","").split("\\|",-1);
    System.out.println(split.length); //output: 5
    System.out.println(splt.length); //output:7

What I've done here is, I'm removing "|" pipe at the end and then splitting the String. If you have "," as a seperator then you need to add ",$" inside replaceAll.

JS strings "+" vs concat method

You can try with this code (Same case)

chaine1 + chaine2; 

I suggest you also (I prefer this) the string.concat method

Chart.js - Formatting Y axis

An undocumented feature of the ChartJS library is that if you pass in a function instead of a string, it will use your function to render the y-axis's scaleLabel.

So while, "<%= Number(value).toFixed(2).replace('.',',') + ' $' %>" works, you could also do:

scaleLabel: function (valuePayload) {
    return Number(valuePayload.value).toFixed(2).replace('.',',') + '$';
}

If you're doing anything remotely complicated, I'd recommend doing this instead.

How do you delete a column by name in data.table?

Here is a way when you want to set a # of columns to NULL given their column names a function for your usage :)

deleteColsFromDataTable <- function (train, toDeleteColNames) {

       for (myNm in toDeleteColNames)

       train <- train [,(myNm):=NULL]

       return (train)
}

Spool Command: Do not output SQL statement to file

My shell script calls the sql file and executes it. The spool output had the SQL query at the beginning followed by the query result.

This did not resolve my problem:

set echo off

This resolved my problem:

set verify off

How to check if a Constraint exists in Sql server?

try this:

SELECT
    * 
    FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS 
    WHERE CONSTRAINT_NAME ='FK_ChannelPlayerSkins_Channels'

-- EDIT --

When I originally answered this question, I was thinking "Foreign Key" because the original question asked about finding "FK_ChannelPlayerSkins_Channels". Since then many people have commented on finding other "constraints" here are some other queries for that:

--Returns one row for each CHECK, UNIQUE, PRIMARY KEY, and/or FOREIGN KEY
SELECT * 
    FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
    WHERE CONSTRAINT_NAME='XYZ'  


--Returns one row for each FOREIGN KEY constrain
SELECT * 
    FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS 
    WHERE CONSTRAINT_NAME='XYZ'


--Returns one row for each CHECK constraint 
SELECT * 
    FROM INFORMATION_SCHEMA.CHECK_CONSTRAINTS
    WHERE CONSTRAINT_NAME='XYZ'

here is an alternate method

--Returns 1 row for each CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY, and/or DEFAULT
SELECT 
    OBJECT_NAME(OBJECT_ID) AS NameofConstraint
        ,SCHEMA_NAME(schema_id) AS SchemaName
        ,OBJECT_NAME(parent_object_id) AS TableName
        ,type_desc AS ConstraintType
    FROM sys.objects
    WHERE type_desc LIKE '%CONSTRAINT'
        AND OBJECT_NAME(OBJECT_ID)='XYZ'

If you need even more constraint information, look inside the system stored procedure master.sys.sp_helpconstraint to see how to get certain information. To view the source code using SQL Server Management Studio get into the "Object Explorer". From there you expand the "Master" database, then expand "Programmability", then "Stored Procedures", then "System Stored Procedures". You can then find "sys.sp_helpconstraint" and right click it and select "modify". Just be careful to not save any changes to it. Also, you can just use this system stored procedure on any table by using it like EXEC sp_helpconstraint YourTableNameHere.

Reading rather large json files in Python

The issue here is that JSON, as a format, is generally parsed in full and then handled in-memory, which for such a large amount of data is clearly problematic.

The solution to this is to work with the data as a stream - reading part of the file, working with it, and then repeating.

The best option appears to be using something like ijson - a module that will work with JSON as a stream, rather than as a block file.

Edit: Also worth a look - kashif's comment about json-streamer and Henrik Heino's comment about bigjson.

How to access shared folder without giving username and password

I found one way to access the shared folder without giving the username and password.

We need to change the share folder protect settings in the machine where the folder has been shared.

Go to Control Panel > Network and sharing center > Change advanced sharing settings > Enable Turn Off password protect sharing option.

By doing the above settings we can access the shared folder without any username/password.

MySQL search and replace some text in a field

The Replace string function will do that.

What are .NET Assemblies?

In addition to the accepted answer, I want to give you an example!

For instance, we all use

System.Console.WriteLine()

But Where is the code for System.Console.WriteLine!?
which is the code that actually puts the text on the console?

If you look at the first page of the documentation for the Console class, you‘ll see near the top the following: Assembly: mscorlib (in mscorlib.dll) This indicates that the code for the Console class is located in an assem-bly named mscorlib. An assembly can consist of multiple files, but in this case it‘s only one file, which is the dynamic link library mscorlib.dll.

The mscorlib.dll file is very important in .NET, It is the main DLL for class libraries in .NET, and it contains all the basic .NET classes and structures.

if you know C or C++, generally you need a #include directive at the top that references a header file. The include file provides function prototypes to the compiler. on the contrast The C# compiler does not need header files. During compilation, the C# compiler access the mscorlib.dll file directly and obtains information from metadata in that file concerning all the classes and other types defined therein.

The C# compiler is able to establish that mscorlib.dll does indeed contain a class named Console in a namespace named System with a method named WriteLine that accepts a single argument of type string.

The C# compiler can determine that the WriteLine call is valid, and the compiler establishes a reference to the mscorlib assembly in the executable.

by default The C# compiler will access mscorlib.dll, but for other DLLs, you‘ll need to tell the compiler the assembly in which the classes are located. These are known as references.

I hope that it's clear now!

From DotNetBookZero Charles pitzold

Only detect click event on pseudo-element

This is edited answer by Fasoeu with latest CSS3 and JS ES6

Edited demo without using JQuery.

Shortest example of code:

<p><span>Some text</span></p>
p {
    position: relative;
    pointer-events: none;
}
p::before {
    content: "";
    position: absolute;
    pointer-events: auto;
}
p span {
    display: contents;
    pointer-events: auto;
}
const all_p = Array.from(document.querySelectorAll('p'));

for (let p of all_p) {
    p.addEventListener("click", listener, false);
};

Explanation:

pointer-events control detection of events, removing receiving events from target, but keep receiving from pseudo-elements make possible to click on ::before and ::after and you will always know what you are clicking on pseudo-element, however if you still need to click, you put all content in nested element (span in example), but because we don't want to apply any additional styles, display: contents; become very handy solution and it supported by most browsers. pointer-events: none; as already mentioned in original post also widely supported.

The JavaScript part also used widely supported Array.from and for...of, however they are not necessary to use in code.

HTML/CSS font color vs span style

Actually I would say the 1st preference would be an external style sheet (External CSS), the 2nd preference would be writing CSS in style tags in the header section of the current page (Internal CSS)

<style type="text/css">
<!-- CSS goes here -->
</style>

And as a 3rd option - or last resort rather - I'd use CSS in the tags themselves (Inline CSS).

How to create a XML object from String in Java?

If you can create a string xml you can easily transform it to the xml document object e.g. -

String xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><a><b></b><c></c></a>";  

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
DocumentBuilder builder;  
try {  
    builder = factory.newDocumentBuilder();  
    Document document = builder.parse(new InputSource(new StringReader(xmlString)));  
} catch (Exception e) {  
    e.printStackTrace();  
} 

You can use the document object and xml parsing libraries or xpath to get back the ip address.

CardView not showing Shadow in Android L

You can try by adding this line

 card_view:cardUseCompatPadding="true"

The Whole code will seems like this

  <android.support.v7.widget.CardView 
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_margin="5dp"
        android:orientation="horizontal"
        card_view:cardUseCompatPadding="true"
        card_view:cardCornerRadius="5dp">
 </android.support.v7.widget.CardView

How to initialize a vector with fixed length in R

If you want to initialize a vector with numeric values other than zero, use rep

n <- 10
v <- rep(0.05, n)
v

which will give you:

[1] 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05

How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?

The easiest way to convert a byte array to a stream is using the MemoryStream class:

Stream stream = new MemoryStream(byteArray);

Evaluate empty or null JSTL c tags

You can use

    ${var == null}

alternatively.

Refused to apply inline style because it violates the following Content Security Policy directive

You can also relax your CSP for styles by adding style-src 'self' 'unsafe-inline';

"content_security_policy": "default-src 'self' style-src 'self' 'unsafe-inline';" 

This will allow you to keep using inline style in your extension.

Important note

As others have pointed out, this is not recommended, and you should put all your CSS in a dedicated file. See the OWASP explanation on why CSS can be a vector for attacks (kudos to @ KayakinKoder for the link).

Merge two array of objects based on a key

We can use lodash here. _.merge works as you expected. It works with the common key present.

_.merge(array1, array2)

How to find the unclosed div tag

1- Count the number of <div in notepad++ (Ctrl + F)
2- Count the number of </div

Compare the two numbers!

What is a monad?

My favorite Monad tutorial:

http://www.haskell.org/haskellwiki/All_About_Monads

(out of 170,000 hits on a Google search for "monad tutorial"!)

@Stu: The point of monads is to allow you to add (usually) sequential semantics to otherwise pure code; you can even compose monads (using Monad Transformers) and get more interesting and complicated combined semantics, like parsing with error handling, shared state, and logging, for example. All of this is possible in pure code, monads just allow you to abstract it away and reuse it in modular libraries (always good in programming), as well as providing convenient syntax to make it look imperative.

Haskell already has operator overloading[1]: it uses type classes much the way one might use interfaces in Java or C# but Haskell just happens to also allow non-alphanumeric tokens like + && and > as infix identifiers. It's only operator overloading in your way of looking at it if you mean "overloading the semicolon" [2]. It sounds like black magic and asking for trouble to "overload the semicolon" (picture enterprising Perl hackers getting wind of this idea) but the point is that without monads there is no semicolon, since purely functional code does not require or allow explicit sequencing.

This all sounds much more complicated than it needs to. sigfpe's article is pretty cool but uses Haskell to explain it, which sort of fails to break the chicken and egg problem of understanding Haskell to grok Monads and understanding Monads to grok Haskell.

[1] This is a separate issue from monads but monads use Haskell's operator overloading feature.

[2] This is also an oversimplification since the operator for chaining monadic actions is >>= (pronounced "bind") but there is syntactic sugar ("do") that lets you use braces and semicolons and/or indentation and newlines.

JavaScript: How do I print a message to the error console?

This does not print to the Console, but will open you an alert Popup with your message which might be useful for some debugging:

just do:

alert("message");

Where does gcc look for C and C++ header files?

You can create a file that attempts to include a bogus system header. If you run gcc in verbose mode on such a source, it will list all the system include locations as it looks for the bogus header.

$ echo "#include <bogus.h>" > t.c; gcc -v t.c; rm t.c

[..]

#include "..." search starts here:
#include <...> search starts here:
 /usr/local/include
 /usr/lib/gcc/i686-apple-darwin9/4.0.1/include
 /usr/include
 /System/Library/Frameworks (framework directory)
 /Library/Frameworks (framework directory)
End of search list.

[..]

t.c:1:32: error: bogus.h: No such file or directory

How to distinguish mouse "click" and "drag"

If you feel like using Rxjs:

_x000D_
_x000D_
var element = document;_x000D_
_x000D_
Rx.Observable_x000D_
  .merge(_x000D_
    Rx.Observable.fromEvent(element, 'mousedown').mapTo(0),_x000D_
    Rx.Observable.fromEvent(element, 'mousemove').mapTo(1)_x000D_
  )_x000D_
  .sample(Rx.Observable.fromEvent(element, 'mouseup'))_x000D_
  .subscribe(flag => {_x000D_
      console.clear();_x000D_
      console.log(flag ? "drag" : "click");_x000D_
  });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://unpkg.com/@reactivex/[email protected]/dist/global/Rx.js"></script>
_x000D_
_x000D_
_x000D_

This is a direct clone of what @wong2 did in his answer, but converted to RxJs.

Also interesting use of sample. The sample operator will take the latest value from the source (the merge of mousedown and mousemove) and emit it when the inner observable (mouseup) emits.

java.lang.IllegalAccessError: tried to access method

I was getting same error because of configuration issue in intellij. As shown in screenshot. Main and test module was pointing to two different JDK. (Press F12 on the intellij project to open module settings)

Also all my dto's were using @lombok.Builder which I changed it to @Data.

enter image description here

enter image description here

Static extension methods

No, but you could have something like:

bool b;
b = b.YourExtensionMethod();

What is this Javascript "require"?

You know how when you are running JavaScript in the browser, you have access to variables like "window" or Math? You do not have to declare these variables, they have been written for you to use whenever you want.

Well, when you are running a file in the Node.js environment, there is a variable that you can use. It is called "module" It is an object. It has a property called "exports." And it works like this:

In a file that we will name example.js, you write:

example.js

module.exports = "some code";

Now, you want this string "some code" in another file.

We will name the other file otherFile.js

In this file, you write:

otherFile.js

let str = require('./example.js')

That require() statement goes to the file that you put inside of it, finds whatever data is stored on the module.exports property. The let str = ... part of your code means that whatever that require statement returns is stored to the str variable.

So, in this example, the end-result is that in otherFile.js you now have this:

let string = "some code";

  • or -

let str = ('./example.js').module.exports

Note:

the file-name that is written inside of the require statement: If it is a local file, it should be the file-path to example.js. Also, the .js extension is added by default, so I didn't have to write it.

You do something similar when requiring node.js libraries, such as Express. In the express.js file, there is an object named 'module', with a property named 'exports'.

So, it looks something like along these lines, under the hood (I am somewhat of a beginner so some of these details might not be exact, but it's to show the concept:

express.js

module.exports = function() {
    //It returns an object with all of the server methods
    return {
        listen: function(port){},
        get: function(route, function(req, res){}){}
     }
}

If you are requiring a module, it looks like this: const moduleName = require("module-name");

If you are requiring a local file, it looks like this: const localFile = require("./path/to/local-file");

(notice the ./ at the beginning of the file name)


Also note that by default, the export is an object .. eg module.exports = {} So, you can write module.exports.myfunction = () => {} before assigning a value to the module.exports. But you can also replace the object by writing module.exports = "I am not an object anymore."

Auto height div with overflow and scroll when needed

You can do this assignment easily by using jquery. In this way, you can define number of row limitation. Furthermore, you can regular breakpoints height that want adding vertical scrolling. I must say that more than 3 rows get modify class and also height is 76px.

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  var length = $(this).find('li').length;_x000D_
  if (length > 3) {_x000D_
    $(".parent").addClass('modify');_x000D_
  }_x000D_
})
_x000D_
/*for beauty*/_x000D_
_x000D_
ul {_x000D_
  margin: 0 auto;_x000D_
  width: 50%;_x000D_
  border: 1px solid #ccc;_x000D_
  padding: 3px;_x000D_
}_x000D_
_x000D_
ul li {_x000D_
  padding: 3px;_x000D_
  background: #ccc;_x000D_
  margin: 2px 0;_x000D_
  list-style: none;_x000D_
}_x000D_
_x000D_
/*main class*/_x000D_
_x000D_
.modify {_x000D_
  overflow-y: scroll;_x000D_
  height: 76px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<ul class="parent">_x000D_
  <li>item 1</li>_x000D_
  <li>item 2</li>_x000D_
  <li>item 3</li>_x000D_
  <li>item 4</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

PHP CURL CURLOPT_SSL_VERIFYPEER ignored

We had the same problem on a CentOS7 machine. Disabling the VERIFYHOST VERIFYPEER did not solve the problem, we did not have the cURL error anymore but the response still was invalid. Doing a wget to the same link as the cURL was doing also resulted in a certificate error.

-> Our solution also was to reboot the VPS, this solved it and we were able to complete the request again.

For us this seemed to be a memory corruption problem. Rebooting the VPS reloaded the libary in the memory again and now it works. So if the above solution from @clover does not work try to reboot your machine.

Proxies with Python 'Requests' module

You can refer to the proxy documentation here.

If you need to use a proxy, you can configure individual requests with the proxies argument to any request method:

import requests

proxies = {
  "http": "http://10.10.1.10:3128",
  "https": "https://10.10.1.10:1080",
}

requests.get("http://example.org", proxies=proxies)

To use HTTP Basic Auth with your proxy, use the http://user:[email protected]/ syntax:

proxies = {
    "http": "http://user:[email protected]:3128/"
}

Spring Boot, Spring Data JPA with multiple DataSources

There is another way to have multiple dataSources by using @EnableAutoConfiguration and application.properties.

Basically put multiple dataSource configuration info on application.properties and generate default setup (dataSource and entityManagerFactory) automatically for first dataSource by @EnableAutoConfiguration. But for next dataSource, create dataSource, entityManagerFactory and transactionManager all manually by the info from property file.

Below is my example to setup two dataSources. First dataSource is setup by @EnableAutoConfiguration which can be assigned only for one configuration, not multiple. And that will generate 'transactionManager' by DataSourceTransactionManager, that looks default transactionManager generated by the annotation. However I have seen the transaction not beginning issue on the thread from scheduled thread pool only for the default DataSourceTransactionManager and also when there are multiple transaction managers. So I create transactionManager manually by JpaTransactionManager also for the first dataSource with assigning 'transactionManager' bean name and default entityManagerFactory. That JpaTransactionManager for first dataSource surely resolves the weird transaction issue on the thread from ScheduledThreadPool.

Update for Spring Boot 1.3.0.RELEASE

I found my previous configuration with @EnableAutoConfiguration for default dataSource has issue on finding entityManagerFactory with Spring Boot 1.3 version. Maybe default entityManagerFactory is not generated by @EnableAutoConfiguration, once after I introduce my own transactionManager. So now I create entityManagerFactory by myself. So I don't need to use @EntityScan. So it looks I'm getting more and more out of the setup by @EnableAutoConfiguration.

Second dataSource is setup without @EnableAutoConfiguration and create 'anotherTransactionManager' by manual way.

Since there are multiple transactionManager extends from PlatformTransactionManager, we should specify which transactionManager to use on each @Transactional annotation

Default Repository Config

@Configuration
@EnableTransactionManagement
@EnableAutoConfiguration
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactory",
        transactionManagerRef = "transactionManager",
        basePackages = {"com.mysource.repository"})
public class RepositoryConfig {
    @Autowired
    JpaVendorAdapter jpaVendorAdapter;

    @Autowired
    DataSource dataSource;

    @Bean(name = "entityManager")
    public EntityManager entityManager() {
        return entityManagerFactory().createEntityManager();
    }

    @Primary
    @Bean(name = "entityManagerFactory")
    public EntityManagerFactory entityManagerFactory() {
        LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
        emf.setDataSource(dataSource);
        emf.setJpaVendorAdapter(jpaVendorAdapter);
        emf.setPackagesToScan("com.mysource.model");
        emf.setPersistenceUnitName("default");   // <- giving 'default' as name
        emf.afterPropertiesSet();
        return emf.getObject();
    }

    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager tm = new JpaTransactionManager();
        tm.setEntityManagerFactory(entityManagerFactory());
        return tm;
    }
}

Another Repository Config

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "anotherEntityManagerFactory",
        transactionManagerRef = "anotherTransactionManager",
        basePackages = {"com.mysource.anothersource.repository"})
public class AnotherRepositoryConfig {
    @Autowired
    JpaVendorAdapter jpaVendorAdapter;

    @Value("${another.datasource.url}")
    private String databaseUrl;

    @Value("${another.datasource.username}")
    private String username;

    @Value("${another.datasource.password}")
    private String password;

    @Value("${another.dataource.driverClassName}")
    private String driverClassName;

    @Value("${another.datasource.hibernate.dialect}")
    private String dialect;

    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource(databaseUrl, username, password);
        dataSource.setDriverClassName(driverClassName);
        return dataSource;
    }

    @Bean(name = "anotherEntityManager")
    public EntityManager entityManager() {
        return entityManagerFactory().createEntityManager();
    }

    @Bean(name = "anotherEntityManagerFactory")
    public EntityManagerFactory entityManagerFactory() {
        Properties properties = new Properties();
        properties.setProperty("hibernate.dialect", dialect);

        LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
        emf.setDataSource(dataSource());
        emf.setJpaVendorAdapter(jpaVendorAdapter);
        emf.setPackagesToScan("com.mysource.anothersource.model");   // <- package for entities
        emf.setPersistenceUnitName("anotherPersistenceUnit");
        emf.setJpaProperties(properties);
        emf.afterPropertiesSet();
        return emf.getObject();
    }

    @Bean(name = "anotherTransactionManager")
    public PlatformTransactionManager transactionManager() {
        return new JpaTransactionManager(entityManagerFactory());
    }
}

application.properties

# database configuration
spring.datasource.url=jdbc:h2:file:~/main-source;AUTO_SERVER=TRUE
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.continueOnError=true
spring.datasource.initialize=false

# another database configuration
another.datasource.url=jdbc:sqlserver://localhost:1433;DatabaseName=another;
another.datasource.username=username
another.datasource.password=
another.datasource.hibernate.dialect=org.hibernate.dialect.SQLServer2008Dialect 
another.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver

Choose proper transactionManager for @Transactional annotation

Service for first datasource

@Service("mainService")
@Transactional("transactionManager")
public class DefaultDataSourceServiceImpl implements DefaultDataSourceService       
{

   //

}

Service for another datasource

@Service("anotherService")
@Transactional("anotherTransactionManager")
public class AnotherDataSourceServiceImpl implements AnotherDataSourceService 
{

   //

}

How to get the first item from an associative PHP array?

reset() gives you the first value of the array if you have an element inside the array:

$value = reset($array);

It also gives you FALSE in case the array is empty.

Setting up and using environment variables in IntelliJ Idea

Path Variables dialog has nothing to do with the environment variables.

Environment variables can be specified in your OS or customized in the Run configuration:

env

Why does AngularJS include an empty option in select?

I would like to add that if the initial value comes from a binding from some parent element or 1.5 component, make sure that the proper type is passed. If using @ in binding, the variable passed will be string and if the options are eg. integers then the empty option will show up.

Either parse properly the value in init, or binding with < and not @ (less recommended for performance unless necessary).

What are the differences between LDAP and Active Directory?

LDAP is a standard, AD is Microsoft's (proprietary) implementation (and more). Wikipedia has a good article that delves into the specifics. I found this document with a very detailed evaluation of AD from an LDAP perspective.

How to pass parameters or arguments into a gradle task

I would suggest the method presented on the Gradle forum:

def createMinifyCssTask(def brand, def sourceFile, def destFile) {
    return tasks.create("minify${brand}Css", com.eriwen.gradle.css.tasks.MinifyCssTask) {
        source = sourceFile
        dest = destFile
    }
}

I have used this method myself to create custom tasks, and it works very well.

Android notification is not showing

Creation of notification channels are compulsory for Android versions after Android 8.1 (Oreo) for making notifications visible. If notifications are not visible in your app for Oreo+ Androids, you need to call the following function when your app starts -

private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = getString(R.string.channel_name);
        String description = getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name,
       importance);
        channel.setDescription(description);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviours after this
        NotificationManager notificationManager =
        getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
   }
}

Adding local .aar files to Gradle build using "flatDirs" is not working

Add below in app gradle file implementation project(path: ':project name')

Android Camera : data intent returns null

Simple working camera app avoiding the null intent problem

- all changed code included in this reply; close to android tutorial

I've been spending plenty of time on this issue, so I decided to create an account and share my outcomes with you.

The official android tutorial "Taking Photos Simply" turned out to not quite hold what it promised. The code provided there did not work on my device: a Samsung Galaxy S4 Mini GT-I9195 running android version 4.4.2 / KitKat / API Level 19.

I figured out that the main problem was the following line in the method invoked when capturing the photo (dispatchTakePictureIntent in the tutorial):

takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);

It resulted in the intent subsequently catched by onActivityResult being null.

To solve this problem, I pulled much inspiration out of earlier replies here and some helpful posts on github (mostly this one by deepwinter - big thanks to him; you might want to check out his reply on a closely related post as well).

Following these pleasant pieces of advice, I chose the strategy of deleting the mentioned putExtra line and doing the corresponding thing of getting back the taken picture from the camera within the onActivityResult() method instead. The decisive lines of code to get back the bitmap associated with the picture are:

        Uri uri = intent.getData();
        Bitmap bitmap = null;
        try {
            bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
        } catch (IOException e) {
            e.printStackTrace();
        }

I created an exemplary app which just has the ability to take a picture, save it on the SD card and display it. I think this might be helpful to people in the same situation as me when I stumbled on this issue, since the current help suggestions mostly refer to rather extensive github posts which do the thing in question but aren't too easy to oversee for newbies like me. With respect to the file system Android Studio creates per default when creating a new project, I just had to change three files for my purpose:

activity_main.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.simpleworkingcameraapp.MainActivity">

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="takePicAndDisplayIt"
    android:text="Take a pic and display it." />

<ImageView
    android:id="@+id/image1"
    android:layout_width="match_parent"
    android:layout_height="200dp" />

</LinearLayout>

MainActivity.java :

package com.example.android.simpleworkingcameraapp;

import android.content.Intent;
import android.graphics.Bitmap;
import android.media.Image;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

private ImageView image;
static final int REQUEST_TAKE_PHOTO = 1;
String mCurrentPhotoPath;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    image = (ImageView) findViewById(R.id.image1);
}

// copied from the android development pages; just added a Toast to show the storage location
private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmm").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    mCurrentPhotoPath = image.getAbsolutePath();
    Toast.makeText(this, mCurrentPhotoPath, Toast.LENGTH_LONG).show();
    return image;
}

public void takePicAndDisplayIt(View view) {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (intent.resolveActivity(getPackageManager()) != null) {
        File file = null;
        try {
            file = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
        }

        startActivityForResult(intent, REQUEST_TAKE_PHOTO);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultcode, Intent intent) {
    if (requestCode == REQUEST_TAKE_PHOTO && resultcode == RESULT_OK) {
        Uri uri = intent.getData();
        Bitmap bitmap = null;
        try {
            bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
        } catch (IOException e) {
            e.printStackTrace();
        }
        image.setImageBitmap(bitmap);
    }
}
}

AndroidManifest.xml :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.simpleworkingcameraapp">


<!--only added paragraph-->
<uses-feature
    android:name="android.hardware.camera"
    android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  <!-- only crucial line to add; for me it still worked without the other lines in this paragraph -->
<uses-permission android:name="android.permission.CAMERA" />


<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

Note that the solution I found for the problem also led to a simplification of the android manifest file: the changes suggested by the android tutorial in terms of adding a provider are no longer needed since I am not making use of any in my java code. Hence, only few standard lines -mostly regarding permissions- had to be added to the manifest file.

It might additionally be valuable to point out that Android Studio's autoimport may not be capable of handling java.text.SimpleDateFormat and java.util.Date. I had to import both of them manually.

Setting ANDROID_HOME enviromental variable on Mac OS X

Where the Android-SDK is installed depends on how you installed it.

  1. If you downloaded the SDK through their website and then dragged/dropped the Application to your Applications folder, it's most likely here:

    /Applications/ADT/sdk (as it is in your case).

  2. If you installed the SDK using Homebrew (brew cask install android-sdk), then it's located here:

    /usr/local/Caskroom/android-sdk/{YOUR_SDK_VERSION_NUMBER}

  3. If the SDK was installed automatically as part of Android Studio then it's located here:

    /Users/{YOUR_USER_NAME}/Library/Android/sdk

Once you know the location, open a terminal window and enter the following (changing out the path to the SDK to be however you installed it):

export ANDROID_HOME={YOUR_PATH}

Once you have this set, you need to add this to the PATH environment variable:

export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

Lastly apply these changes by re-sourcing .bash_profile:

source ~/.bash_profile

  1. Type - echo $ANDROID_HOME to check if the home is set.

echo $ANDROID_HOME

Combining two Series into a DataFrame in pandas

If you are trying to join Series of equal length but their indexes don't match (which is a common scenario), then concatenating them will generate NAs wherever they don't match.

x = pd.Series({'a':1,'b':2,})
y = pd.Series({'d':4,'e':5})
pd.concat([x,y],axis=1)

#Output (I've added column names for clarity)
Index   x    y
a      1.0  NaN
b      2.0  NaN
d      NaN  4.0
e      NaN  5.0

Assuming that you don't care if the indexes match, the solution is to reindex both Series before concatenating them. If drop=False, which is the default, then Pandas will save the old index in a column of the new dataframe (the indexes are dropped here for simplicity).

pd.concat([x.reset_index(drop=True),y.reset_index(drop=True)],axis=1)

#Output (column names added):
Index   x   y
0       1   4
1       2   5

What does "to stub" mean in programming?

A stub, in this context, means a mock implementation.

That is, a simple, fake implementation that conforms to the interface and is to be used for testing.

PHP Curl And Cookies

You can specify the cookie file with a curl opt. You could use a unique file for each user.

curl_setopt( $curl_handle, CURLOPT_COOKIESESSION, true );
curl_setopt( $curl_handle, CURLOPT_COOKIEJAR, uniquefilename );
curl_setopt( $curl_handle, CURLOPT_COOKIEFILE, uniquefilename );

The best way to handle it would be to stick your request logic into a curl function and just pass the unique file name in as a parameter.

    function fetch( $url, $z=null ) {
            $ch =  curl_init();

            $useragent = isset($z['useragent']) ? $z['useragent'] : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2';

            curl_setopt( $ch, CURLOPT_URL, $url );
            curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
            curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
            curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
            curl_setopt( $ch, CURLOPT_POST, isset($z['post']) );

            if( isset($z['post']) )         curl_setopt( $ch, CURLOPT_POSTFIELDS, $z['post'] );
            if( isset($z['refer']) )        curl_setopt( $ch, CURLOPT_REFERER, $z['refer'] );

            curl_setopt( $ch, CURLOPT_USERAGENT, $useragent );
            curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, ( isset($z['timeout']) ? $z['timeout'] : 5 ) );
            curl_setopt( $ch, CURLOPT_COOKIEJAR,  $z['cookiefile'] );
            curl_setopt( $ch, CURLOPT_COOKIEFILE, $z['cookiefile'] );

            $result = curl_exec( $ch );
            curl_close( $ch );
            return $result;
    }

I use this for quick grabs. It takes the url and an array of options.

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

The solution at my end was to explicitly add a JoinColumn annotation like this:

@JoinColumn(name="mapping_type_id")

The column name is usually the table name + "_id" if there is an id field. Additionally, keep in mind which field it should be based on the relationship, OneToMany or ManyToOne.

Hope this helps.

How to display a list using ViewBag

To put it all together, this is what it should look like:

In the controller:

List<Fund> fundList = db.Funds.ToList();
ViewBag.Funds = fundList;

Then in the view:

@foreach (var item in ViewBag.Funds)
{
    <span> @item.FundName </span>
}

Creating a new ArrayList in Java

You're very close. Use same type on both sides, and include ().

ArrayList<Class> myArray = new ArrayList<Class>();

XMLHttpRequest cannot load file. Cross origin requests are only supported for HTTP

This error is happening because you are just opening html documents directly from the browser. To fix this you will need to serve your code from a webserver and access it on localhost. If you have Apache setup, use it to serve your files. Some IDE's have built in web servers, like JetBrains IDE's, Eclipse...

If you have Node.Js setup then you can use http-server. Just run npm install http-server -g and you will be able to use it in terminal like http-server C:\location\to\app. Kirill Fuchs

Apply multiple functions to multiple groupby columns

For the first part you can pass a dict of column names for keys and a list of functions for the values:

In [28]: df
Out[28]:
          A         B         C         D         E  GRP
0  0.395670  0.219560  0.600644  0.613445  0.242893    0
1  0.323911  0.464584  0.107215  0.204072  0.927325    0
2  0.321358  0.076037  0.166946  0.439661  0.914612    1
3  0.133466  0.447946  0.014815  0.130781  0.268290    1

In [26]: f = {'A':['sum','mean'], 'B':['prod']}

In [27]: df.groupby('GRP').agg(f)
Out[27]:
            A                   B
          sum      mean      prod
GRP
0    0.719580  0.359790  0.102004
1    0.454824  0.227412  0.034060

UPDATE 1:

Because the aggregate function works on Series, references to the other column names are lost. To get around this, you can reference the full dataframe and index it using the group indices within the lambda function.

Here's a hacky workaround:

In [67]: f = {'A':['sum','mean'], 'B':['prod'], 'D': lambda g: df.loc[g.index].E.sum()}

In [69]: df.groupby('GRP').agg(f)
Out[69]:
            A                   B         D
          sum      mean      prod  <lambda>
GRP
0    0.719580  0.359790  0.102004  1.170219
1    0.454824  0.227412  0.034060  1.182901

Here, the resultant 'D' column is made up of the summed 'E' values.

UPDATE 2:

Here's a method that I think will do everything you ask. First make a custom lambda function. Below, g references the group. When aggregating, g will be a Series. Passing g.index to df.ix[] selects the current group from df. I then test if column C is less than 0.5. The returned boolean series is passed to g[] which selects only those rows meeting the criteria.

In [95]: cust = lambda g: g[df.loc[g.index]['C'] < 0.5].sum()

In [96]: f = {'A':['sum','mean'], 'B':['prod'], 'D': {'my name': cust}}

In [97]: df.groupby('GRP').agg(f)
Out[97]:
            A                   B         D
          sum      mean      prod   my name
GRP
0    0.719580  0.359790  0.102004  0.204072
1    0.454824  0.227412  0.034060  0.570441

How to clear the canvas for redrawing

Context.clearRect(starting width, starting height, ending width, ending height);

Example: context.clearRect(0, 0, canvas.width, canvas.height);

CodeIgniter Active Record not equal

Try this code. This seems working in my case.

$this->db->where(array('id !='=> $id))

Matplotlib (pyplot) savefig outputs blank image

let's me give a more detail example:

import numpy as np
import matplotlib.pyplot as plt


def draw_result(lst_iter, lst_loss, lst_acc, title):
    plt.plot(lst_iter, lst_loss, '-b', label='loss')
    plt.plot(lst_iter, lst_acc, '-r', label='accuracy')

    plt.xlabel("n iteration")
    plt.legend(loc='upper left')
    plt.title(title)
    plt.savefig(title+".png")  # should before plt.show method

    plt.show()


def test_draw():
    lst_iter = range(100)
    lst_loss = [0.01 * i + 0.01 * i ** 2 for i in xrange(100)]
    # lst_loss = np.random.randn(1, 100).reshape((100, ))
    lst_acc = [0.01 * i - 0.01 * i ** 2 for i in xrange(100)]
    # lst_acc = np.random.randn(1, 100).reshape((100, ))
    draw_result(lst_iter, lst_loss, lst_acc, "sgd_method")


if __name__ == '__main__':
    test_draw()

enter image description here

Safest way to convert float to integer in python?

All integers that can be represented by floating point numbers have an exact representation. So you can safely use int on the result. Inexact representations occur only if you are trying to represent a rational number with a denominator that is not a power of two.

That this works is not trivial at all! It's a property of the IEEE floating point representation that int°floor = ?·? if the magnitude of the numbers in question is small enough, but different representations are possible where int(floor(2.3)) might be 1.

To quote from Wikipedia,

Any integer with absolute value less than or equal to 224 can be exactly represented in the single precision format, and any integer with absolute value less than or equal to 253 can be exactly represented in the double precision format.

How to run only one task in ansible playbook?

I would love the ability to use a role as a collection of tasks such that, in my playbook, I can choose which subset of tasks to run. Unfortunately, the playbook can only load them all in and then you have to use the --tags option on the cmdline to choose which tasks to run. The problem with this is that all of the tasks will run unless you remember to set --tags or --skip-tags.

I have set up some tasks, however, with a when: clause that will only fire if a var is set.

e.g.

# role/stuff/tasks/main.yml
- name: do stuff
  when: stuff|default(false)

Now, this task will not fire by default, but only if I set the stuff=true

$ ansible-playbook -e '{"stuff":true}'

or in a playbook:

roles:
- {"role":"stuff", "stuff":true}

How to check if input date is equal to today's date?

Try using moment.js

moment('dd/mm/yyyy').isSame(Date.now(), 'day');

You can replace 'day' string with 'year, month, minute' if you want.

Programmatically change input type of the EditText from PASSWORD to NORMAL & vice versa

some dynamic situation holder.edit_pin.setInputType(InputType.TYPE_CLASS_NUMBER); will not work so better use both like that

holder.edit_pin.setInputType(InputType.TYPE_CLASS_NUMBER);
holder.edit_pin.setTransformationMethod(PasswordTransformationMethod.getInstance());

Note : this is suitable for when you are using dynamic controls like using arrayaapter

Singleton with Arguments in Java

This is not quite a singleton, but may be something that could fix your problem.

public class KamilManager {

  private static KamilManager sharedInstance;

  /**
   * This method cannot be called before calling KamilManager constructor or else
   * it will bomb out.
   * @return
   */
  public static KamilManager getInstanceAfterInitialized() {
    if(sharedInstance == null)
        throw new RuntimeException("You must instantiate KamilManager once, before calling this method");

    return sharedInstance;
}

  public KamilManager(Context context, KamilConfig KamilConfig) {
    //Set whatever you need to set here then call:
  s  haredInstance = this;
  }
}

JavaScript: client-side vs. server-side validation

The benefit of doing server side validation over client side validation is that client side validation can be bypassed/manipulated:

  • The end user could have javascript switched off
  • The data could be sent directly to your server by someone who's not even using your site, with a custom app designed to do so
  • A Javascript error on your page (caused by any number of things) could result in some, but not all, of your validation running

In short - always, always validate server-side and then consider client-side validation as an added "extra" to enhance the end user experience.

How to define two fields "unique" as couple

Django 2.2+

Using the constraints features UniqueConstraint is preferred over unique_together.

From the Django documentation for unique_together:

Use UniqueConstraint with the constraints option instead.
UniqueConstraint provides more functionality than unique_together.
unique_together may be deprecated in the future.

For example:

class Volume(models.Model):
    id = models.AutoField(primary_key=True)
    journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name="Journal")
    volume_number = models.CharField('Volume Number', max_length=100)
    comments = models.TextField('Comments', max_length=4000, blank=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['journal_id', 'volume_number'], name='name of constraint')
        ]

Access elements of parent window from iframe

You can access elements of parent window from within an iframe by using window.parent like this:

// using jquery    
window.parent.$("#element_id");

Which is the same as:

// pure javascript
window.parent.document.getElementById("element_id");

And if you have more than one nested iframes and you want to access the topmost iframe, then you can use window.top like this:

// using jquery
window.top.$("#element_id");

Which is the same as:

// pure javascript
window.top.document.getElementById("element_id");

How to display pdf in php

easy if its pdf or img use

return (in_Array($file['content-type'], ['image/jpg', 'application/pdf']));

Split a string by another string in C#

Regex.Split(string, "xx")

is the way I do it usually.


Of course you'll need:

using System.Text.RegularExpressions;

or :

System.Text.RegularExpressions.Regex.Split(string, "xx")

but then again I need that library all the time.

How to delete an SMS from the inbox in Android programmatically?

"As of Android 1.6, incoming SMS message broadcasts (android.provider.Telephony.SMS_RECEIVED) are delivered as an "ordered broadcast" — meaning that you can tell the system which components should receive the broadcast first."

This means that you can intercept incoming message and abort broadcasting of it further on.

In your AndroidManifest.xml file, make sure to have priority set to highest:

<receiver android:name=".receiver.SMSReceiver" android:enabled="true">
    <intent-filter android:priority="1000">
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

In your BroadcastReceiver, in onReceive() method, before performing anything with your message, simply call abortBroadcast();

EDIT: As of KitKat, this doesn't work anymore apparently.

EDIT2: More info on how to do it on KitKat here:

Delete SMS from android on 4.4.4 (Affected rows = 0(Zero), after deleted)

Counting the number of option tags in a select tag in jQuery

In a multi-select option box, you can use $('#input1 :selected').length; to get the number of selected options. This can be useful to disable buttons if a certain minimum number of options aren't met.

function refreshButtons () {
    if ($('#input :selected').length == 0)
    {
        $('#submit').attr ('disabled', 'disabled');
    }
    else
    {
        $('#submit').removeAttr ('disabled');
    }
}

how to implement login auth in node.js

Why not disecting a bare minimum authentication module?

SweetAuth

A lightweight, zero-configuration user authentication module which doesn't depend on a database.

https://www.npmjs.com/package/sweet-auth

It's simple as:

app.get('/private-page', (req, res) => {

    if (req.user.isAuthorized) {
        // user is logged in! send the requested page
        // you can access req.user.email
    }
    else {
        // user not logged in. redirect to login page
    }
})

Multiline string literal in C#

You can use @ and "".

        string sourse = @"{
        ""items"":[
        {
            ""itemId"":0,
            ""name"":""item0""
        },
        {
            ""itemId"":1,
            ""name"":""item1""
        }
        ]
    }";

How to read a configuration file in Java

Create a configuration file and put your entries there.

SERVER_PORT=10000     
THREAD_POOL_COUNT=3     
ROOT_DIR=/home/   

You can load this file using Properties.load(fileName) and retrieved values you get(key);

Edittext change border color with shape.xml

Check below code may will help you, Using stroke can make border in edit text and change it's color too as shown below...

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="10dp"
android:shape="rectangle">
<stroke
    android:width="2dp"
    android:color="@color/secondary" />
<corners
    android:bottomLeftRadius="10dp"
    android:bottomRightRadius="10dp"
    android:topLeftRadius="10dp"
    android:topRightRadius="10dp" />

Add this as background in to edit text. Thanks!

How to use nanosleep() in C? What are `tim.tv_sec` and `tim.tv_nsec`?

POSIX 7

First find the function: http://pubs.opengroup.org/onlinepubs/9699919799/functions/nanosleep.html

That contains a link to a time.h, which as a header should be where structs are defined:

The header shall declare the timespec structure, which shall > include at least the following members:

time_t  tv_sec    Seconds. 
long    tv_nsec   Nanoseconds.

man 2 nanosleep

Pseudo-official glibc docs which you should always check for syscalls:

struct timespec {
    time_t tv_sec;        /* seconds */
    long   tv_nsec;       /* nanoseconds */
};

Apply .gitignore on an existing repository already tracking large number of files

  1. Create a .gitignore file, so to do that, you just create any blank .txt file.

  2. Then you have to change its name writing the following line on the cmd (where git.txt is the name of the file you've just created):

    rename git.txt .gitignore

  3. Then you can open the file and write all the untracked files you want to ignore for good. For example, mine looks like this:

```

OS junk files
[Tt]humbs.db
*.DS_Store

#Visual Studio files
*.[Oo]bj
*.user
*.aps
*.pch
*.vspscc
*.vssscc
*_i.c
*_p.c
*.ncb
*.suo
*.tlb
*.tlh
*.bak
*.[Cc]ache
*.ilk
*.log
*.lib
*.sbr
*.sdf
*.pyc
*.xml
ipch/
obj/
[Bb]in
[Dd]ebug*/
[Rr]elease*/
Ankh.NoLoad

#Tooling
_ReSharper*/
*.resharper
[Tt]est[Rr]esult*

#Project files
[Bb]uild/

#Subversion files
.svn

# Office Temp Files
~$*

There's a whole collection of useful .gitignore files by GitHub

  1. Once you have this, you need to add it to your git repository just like any other file, only it has to be in the root of the repository.

  2. Then in your terminal you have to write the following line:

    git config --global core.excludesfile ~/.gitignore_global

From oficial doc:

You can also create a global .gitignore file, which is a list of rules for ignoring files in every Git repository on your computer. For example, you might create the file at ~/.gitignore_global and add some rules to it.

Open Terminal. Run the following command in your terminal: git config --global core.excludesfile ~/.gitignore_global

If the respository already exists then you have to run these commands:

git rm -r --cached .
git add .
git commit -m ".gitignore is now working"

If the step 2 doesn´t work then you should write the hole route of the files that you would like to add.

How to compare two JSON have the same properties without order?

lodash will work, tested even for angular 5, http://jsfiddle.net/L5qrfx3x/

var remoteJSON = {"allowExternalMembers": "false", "whoCanJoin": 
   "CAN_REQUEST_TO_JOIN"};
var localJSON = {"whoCanJoin": "CAN_REQUEST_TO_JOIN", 
  "allowExternalMembers": "false"};

 if(_.isEqual(remoteJSON, localJSON)){
     //TODO
    }

it works, for installation in angular, follow this

What is the best free SQL GUI for Linux for various DBMS systems

For Oracle, I highly recommend the free Oracle SQL Developer

http://www.oracle.com/technology/products/database/sql_developer/index.html

The doucmentation states it also works with non-oracle databases - i've never tried that feature myself, but I do know that it works really well with Oracle