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.
This answer outlines two ways to workaround APIs that don't support CORS:
One workaround is to use a CORS PROXY:
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_
For more information, see
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
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."
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
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.
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();
});
Simple :
npm install *GithubUrl*.git --save
example :
npm install https://github.com/visionmedia/express.git --save
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);
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.
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:
months_of_service=6
).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.
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.
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.
If you are looking for a difference expressed as a combination of years, months, and days, I would suggest this function:
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_
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).
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]))
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.
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='')
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.
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
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>
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")
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">×</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 -->
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>
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
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
To center it both vertically and horizontally do this:
div#thing {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
The probably shortest answer is
val==null || val==''
if you change rigth side to val===''
then empty array will give false. Proof
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_
More details about ==
(source here)
BONUS: Reason why ===
is more clear than ==
To write clear and easy understandable code, use explicite list of accepted values
val===undefined || val===null || val===''|| (Array.isArray(val) && val.length===0)
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_
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>
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
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.
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"
.
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 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.
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);
}
}
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
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
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.
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.
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.
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;
}
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 ""
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!
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.
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.)
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_
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_
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.
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.
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.
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);
}
}
Just put some CSS into the stylesheet like this
form {
text-align: center;
}
then you're done!
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]);
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.
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
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!
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', [...])
Yes. ArrayList
has a toArray()
method.
http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html
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)).
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);
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().
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"?>
You can use Jquery's on method and listen for the scroll
event.
This worked for me with 5 images in diferent sizes.
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>
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", "");
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
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 ) ) )
:
" & < >
swift
view.frame = view.frame.offsetBy(dx: offsetX, dy: offsetY)
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.
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 ...
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
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.
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]
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.
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();
You can use .change()
function too
E.g.:
$('form input[type=checkbox]').change(function() { console.log('hello') });
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 :
Difference between ViewBag & ViewData:
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.
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.
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);
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);
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:
We have to uninstall manually for all users!, then we can install our compiled application with no problems.
Remove the old application and install again.
Use Android Debug Bridge command:
adb uninstall [PACKAGE NAME]
Use the formatting pattern 'dd-MM-yyyy HH:mm:ss aa' to get date as 21-10-2020 20:53:42 pm
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.
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
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
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);
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>
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.
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.
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)...}
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.
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
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.
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);
});
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]
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']]
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.
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;
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.
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
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;
};
With SimpleDateFormat
. And steps are -
SimpleDateFormat
ObjectDate
Object.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());
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 withx!
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 forunowned(safe)
currently, but the intent is that it will be optimized tounowned(unsafe)
in-Ofast
builds when runtime checks are disabled.
unowned
vs weak
unowned
actually uses a much simpler implementation thanweak
. Native Swift objects carry two reference counts, andunowned
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 whenunowned
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
.
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?
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");
Very simple to override the method in the fragment:
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser){
actionView();
}
else{
//no
}
}
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
...
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)
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
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>
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');
...
}
Instead of if-else condition use if in both conditions. it will work that way but not sure why.
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_id
s. 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_id
s 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
.
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;
}
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.
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
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.
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.
if the file containing that link tag is in the root dir of the project, then the correct path would be "css/styles.css"
df <- data.frame(x=rnorm(10), y=rnorm(10))
rownames(df) <- letters[1:10]
df[c('a','b'),]
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.
You should be able to set the className property of the element. You could do a += to append it.
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'));
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.
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]
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)
})
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 :
<string name="notyet">Website %1$s isn\'t yet available, I\'m working on it, please wait %2$s more days</string>
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();
Here is a simple solution. This is a late answer but may be simple one-
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_
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";
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.
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.
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:
Use SimpleDateFormat
class. Take a look on its javadoc: it explains how to use format switches.
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');
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.
You can try with this code (Same case)
chaine1 + chaine2;
I suggest you also (I prefer this) the string.concat method
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.
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)
}
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
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
.
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
.
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.
The Replace string function will do that.
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
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);
};
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.
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).
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.
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
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
The easiest way to convert a byte array to a stream is using the MemoryStream
class:
Stream stream = new MemoryStream(byteArray);
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.
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).
We can use lodash here. _.merge works as you expected. It works with the common key present.
_.merge(array1, array2)
1- Count the number of <div
in notepad++ (Ctrl + F)
2- Count the number of </div
Compare the two numbers!
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.
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");
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
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_
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.
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.
No, but you could have something like:
bool b;
b = b.YourExtensionMethod();
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";
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."
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.
$(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_
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.
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/"
}
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
{
//
}
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.
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:
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).
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.
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.
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);
}
}
Add below in app gradle file implementation project(path: ':project name')
- 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.
Where the Android-SDK is installed depends on how you installed it.
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).
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}
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
echo $ANDROID_HOME
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
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.
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.
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.
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>
}
You're very close. Use same type on both sides, and include ()
.
ArrayList<Class> myArray = new ArrayList<Class>();
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
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
Context.clearRect(starting width, starting height, ending width, ending height);
Example: context.clearRect(0, 0, canvas.width, canvas.height);
Try this code. This seems working in my case.
$this->db->where(array('id !='=> $id))
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()
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.
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}
Try using moment.js
moment('dd/mm/yyyy').isSame(Date.now(), 'day');
You can replace 'day' string with 'year, month, minute' if you want.
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
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;
}
}
The benefit of doing server side validation over client side validation is that client side validation can be bypassed/manipulated:
In short - always, always validate server-side and then consider client-side validation as an added "extra" to enhance the end user experience.
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')
]
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");
easy if its pdf or img use
return (in_Array($file['content-type'], ['image/jpg', 'application/pdf']));
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.
"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)
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');
}
}
Why not disecting a bare minimum authentication module?
SweetAuth
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
}
})
You can use @ and "".
string sourse = @"{
""items"":[
{
""itemId"":0,
""name"":""item0""
},
{
""itemId"":1,
""name"":""item1""
}
]
}";
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)
;
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!
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 */
};
Create a .gitignore file, so to do that, you just create any blank .txt file.
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
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
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.
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.
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
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