Another approach to test just for a JSON response (not that the content within contains an expected value), is to parse the response using ActiveSupport:
ActiveSupport::JSON.decode(response.body).should_not be_nil
If the response is not parsable JSON an exception will be thrown and the test will fail.
The tel:
scheme was used in the late 1990s and documented in early 2000 with RFC 2806 (which was obsoleted by the more-thorough RFC 3966 in 2004) and continues to be improved. Supporting tel:
on the iPhone was not an arbitrary decision.
callto:
, while supported by Skype, is not a standard and should be avoided unless specifically targeting Skype users.
Me? I'd just start including properly-formed tel:
URIs on your pages (without sniffing the user agent) and wait for the rest of the world's phones to catch up :) .
Example:
<a href="tel:+18475555555">1-847-555-5555</a>
_x000D_
As well as setting global defaults for ajax events, you can set behaviour for specific elements. Perhaps just changing their class would be enough?
$('#myForm').ajaxSend( function() {
$(this).addClass('loading');
});
$('#myForm').ajaxComplete( function(){
$(this).removeClass('loading');
});
Example CSS, to hide #myForm with a spinner:
.loading {
display: block;
background: url(spinner.gif) no-repeat center middle;
width: 124px;
height: 124px;
margin: 0 auto;
}
/* Hide all the children of the 'loading' element */
.loading * {
display: none;
}
To print 'item1' , 'item2', this code would work.
var myarray = ['hello', ' hello again'];
for (var item in myarray) {
console.log(myarray[item])
}
LinearLayout : A layout that organizes its children into a single horizontal or vertical row. It creates a scrollbar if the length of the window exceeds the length of the screen.It means you can align views one by one (vertically/ horizontally).
RelativeLayout : This enables you to specify the location of child objects relative to each other (child A to the left of child B) or to the parent (aligned to the top of the parent). It is based on relation of views from its parents and other views.
WebView : to load html, static or dynamic pages.
For more information refer this link:http://developer.android.com/guide/topics/ui/layout-objects.html
Just multiply the number by 100, round, and divide the resulting number by 100.
Expanded solution (takes table schema into account):
-- Drop default contstraint for SchemaName.TableName.ColumnName
DECLARE @schema_name NVARCHAR(256)
DECLARE @table_name NVARCHAR(256)
DECLARE @col_name NVARCHAR(256)
DECLARE @Command NVARCHAR(1000)
set @schema_name = N'SchemaName'
set @table_name = N'TableName'
set @col_name = N'ColumnName'
SELECT @Command = 'ALTER TABLE [' + @schema_name + '].[' + @table_name + '] DROP CONSTRAINT ' + d.name
FROM sys.tables t
JOIN sys.default_constraints d
ON d.parent_object_id = t.object_id
JOIN sys.schemas s
ON s.schema_id = t.schema_id
JOIN sys.columns c
ON c.object_id = t.object_id
AND c.column_id = d.parent_column_id
WHERE t.name = @table_name
AND s.name = @schema_name
AND c.name = @col_name
EXECUTE (@Command)
The answer comes from the javadoc of ZoneId
(emphasis mine) ...
A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:
- Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
- Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply
Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.
... and from the javadoc of ZoneId#of
(emphasis mine):
This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.
The argument id is specified as "UTC"
, therefore it will return a ZoneId
with an offset, which also presented in the string form:
System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));
Outputs:
2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]
As you use the equals
method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false
.
When the normalized()
method is used as proposed in the documentation, the comparison using equals
will return true
, as normalized()
will return the corresponding ZoneOffset
:
Normalizes the time-zone ID, returning a ZoneOffset where possible.
now.withZoneSameInstant(ZoneOffset.UTC)
.equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true
As the documentation states, if you use "Z"
or "+0"
as input id, of
will return the ZoneOffset
directly and there is no need to call normalized()
:
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true
To check if they store the same date time, you can use the isEqual
method instead:
now.withZoneSameInstant(ZoneOffset.UTC)
.isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true
Sample
System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
.equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
.isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));
Output:
equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true
You can use, for example:
words = [word.replace('[br]','<br />') for word in words]
Update @angular-devkit/build-angular to "^0.13.9" . Then run npm install
and after that, run npm serve
.
Specs:
Angular: 7.2.15
Angular CLI: 7.3.9
Node: 11.2.0
OS: darwin x64
HTML provides no way to generate JSON from form data.
If you really want to handle it from the client, then you would have to resort to using JavaScript to:
You'd probably be better off sticking to application/x-www-form-urlencoded
data and processing that on the server instead of JSON. Your form doesn't have any complicated hierarchy that would benefit from a JSON data structure.
Update in response to major rewrite of the question…
readystatechange
handler, so you do nothing with the responseThe datetime class has a method strftime. The Python docs documents the different formats it accepts:
For this specific example, it would look something like:
my_datetime.strftime("%B %d, %Y")
Simply:
$("#tabs_div").tabs();
$("#tabs_div").on("click", "a.tab_a", function(){
console.log("selected tab id: " + $(this).attr("href"));
console.log("selected tab name: " + $(this).find("span").text());
});
But you have to add class name to your anchors named "tab_a":
<div id="tabs">
<UL>
<LI><A class="tab_a" href="#fragment-1"><SPAN>Tab1</SPAN></A></LI>
<LI><A class="tab_a" href="#fragment-2"><SPAN>Tab2</SPAN></A></LI>
<LI><A class="tab_a" href="#fragment-3"><SPAN>Tab3</SPAN></A></LI>
<LI><A class="tab_a" href="#fragment-4"><SPAN>Tab4</SPAN></A></LI>
</UL>
<DIV id=fragment-1>
<UL>
<LI><A class="tab_a" href="#fragment-1a"><SPAN>Sub-Tab1</SPAN></A></LI>
<LI><A class="tab_a" href="#fragment-1b"><SPAN>Sub-Tab2</SPAN></A></LI>
<LI><A class="tab_a" href="#fragment-1c"><SPAN>Sub-Tab3</SPAN></A></LI>
</UL>
</DIV>
.
.
</DIV>
Here's a working example, which is a fork of this answer:
$(document).ready(function(){
FB.login(function(response) {
if (response.status == 'connected') {
var user_id = response.authResponse.userID;
var page_id = "40796308305"; // coca cola page https://www.facebook.com/cocacola
var fql_query = "SELECT uid FROM page_fan WHERE page_id="+page_id+" and uid="+user_id;
FB.api({
method: 'fql.query',
query: fql_query
},
function(response){
if (response[0]) {
$("#container_like").show();
} else {
$("#container_notlike").show();
}
}
);
} else {
// user is not logged in
}
});
});
I used the FB.api method (JavaScript SDK), instead of FB.Data.query, which is deprecated. Or you can use the Graph API like with this example:
$(document).ready(function() {
FB.login(function(response) {
if (response.status == 'connected') {
var user_id = response.authResponse.userID;
var page_id = "40796308305"; // coca cola page https://www.facebook.com/cocacola
var fql_query = "SELECT uid FROM page_fan WHERE page_id=" + page_id + " and uid=" + user_id;
FB.api('/me/likes/'+page_id, function(response) {
if (response.data[0]) {
$("#container_like").show();
} else {
$("#container_notlike").show();
}
});
} else {
// user is not logged in
}
});
});?
enum Constants
{
Abc = 1,
Def = 2,
Ghi = 3
}
...
int i = (int)Enum.Parse(typeof(Constants), "Def");
I just wanted to add these from TLDP:
~:$ echo $SHELL
/bin/bash
~:$ echo ${#SHELL}
9
~:$ ARRAY=(one two three)
~:$ echo ${#ARRAY}
3
~:$ echo ${TEST:-test}
test
~:$ echo $TEST
~:$ export TEST=a_string
~:$ echo ${TEST:-test}
a_string
~:$ echo ${TEST2:-$TEST}
a_string
~:$ echo $TEST2
~:$ echo ${TEST2:=$TEST}
a_string
~:$ echo $TEST2
a_string
~:$ export STRING="thisisaverylongname"
~:$ echo ${STRING:4}
isaverylongname
~:$ echo ${STRING:6:5}
avery
~:$ echo ${ARRAY[*]}
one two one three one four
~:$ echo ${ARRAY[*]#one}
two three four
~:$ echo ${ARRAY[*]#t}
one wo one hree one four
~:$ echo ${ARRAY[*]#t*}
one wo one hree one four
~:$ echo ${ARRAY[*]##t*}
one one one four
~:$ echo $STRING
thisisaverylongname
~:$ echo ${STRING%name}
thisisaverylong
~:$ echo ${STRING/name/string}
thisisaverylongstring
git reset --hard
This command will completely remove all the local changes from your local repository. This is the best way to avoid conflicts during pull command, only if you don't want to keep your local changes at all.
If you want to pull the new changes from remote and want to ignore the local changes during this pull then,
git stash
It will stash all the local changes, now you can pull the remote changes,
git pull
Now, you can bring back your local changes by,
git stash pop
If you are getting the user input with Scanner
, you can do:
if(yourScanner.hasNextInt()) {
yourNumber = yourScanner.nextInt();
}
If you are not, you'll have to convert it to int
and catch a NumberFormatException
:
try{
yourNumber = Integer.parseInt(yourInput);
}catch (NumberFormatException ex) {
//handle exception here
}
Run these three commands to make sure that you have all the relevant packages installed:
pip install bs4
pip install html5lib
pip install lxml
Then restart your Python IDE, if needed.
That should take care of anything related to this issue.
Watch this.
The video says that you need to just add self.view.layoutIfNeeded()
like the following:
UIView.animate(withDuration: 1.0, animations: {
self.centerX.constant -= 75
self.view.layoutIfNeeded()
}, completion: nil)
hex --> decimal then decimal --> binary
#decimal to binary
def d2b(n):
bStr = ''
if n < 0: raise ValueError, "must be a positive integer"
if n == 0: return '0'
while n > 0:
bStr = str(n % 2) + bStr
n = n >> 1
return bStr
#hex to binary
def h2b(hex):
return d2b(int(hex,16))
if (condition){ // where condition evaluates to true
return false
}
see similar question asked 3 days ago.
This task can be accomplished using one of the android's main building block named as Intents and One of the methods public void startActivity (Intent intent)
which belongs to your Activity class.
An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.
An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed.
Refer the official docs -- http://developer.android.com/reference/android/content/Intent.html
public void startActivity (Intent intent)
-- Used to launch a new activity.
So suppose you have two Activity class --
PresentActivity -- This is your current activity from which you want to go the second activity.
NextActivity -- This is your next Activity on which you want to move.
So the Intent would be like this
Intent(PresentActivity.this, NextActivity.class)
Finally this will be the complete code
public class PresentActivity extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.content_layout_id);
final Button button = (Button) findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Intent activityChangeIntent = new Intent(PresentActivity.this, NextActivity.class);
// currentContext.startActivity(activityChangeIntent);
PresentActivity.this.startActivity(activityChangeIntent);
}
});
}
}
At last i did it Thanks alot friends, and a special thanks to Mr https://stackoverflow.com/users/87015/salman-a because of his code i was able to solve it properly. finally my code is looking like this as i am using groovy grails i hope this will help somebody there.. Thanks alot
html code looks like this in my gsp page
<input id="populate-dropdown" name="nameofClient" type="text">
<input id="wilhaveid" name="idofclient" type="text">
script Function is like this in my gsp page
<script>
$( "#populate-dropdown").on('input', function() {
$.ajax({
url:'autoCOmp',
data: {inputField: $("#populate-dropdown").val()},
success: function(resp){
$('#populate-dropdown').autocomplete({
source:resp,
select: function (event, ui) {
$("#populate-dropdown").val(ui.item.label);
$("#wilhaveid").val(ui.item.value);
return false;
}
})
}
});
});
</script>
And my controller code is like this
def autoCOmp(){
println(params)
def c = Client.createCriteria()
def results = c.list {
like("nameOfClient", params.inputField+"%")
}
def itemList = []
results.each{
itemList << [value:it.id,label:it.nameOfClient]
}
println(itemList)
render itemList as JSON
}
One more thing i have not set id field hidden because at first i was checking that i am getting the exact id , you can keep it hidden just put type=hidden instead of text for second input item in html
Thanks !
Try this:
data=pd.read_csv('C:\Users\Desktop\Data Exploration.csv')
data.head(5)
first=data['1st Gift']
last=data['Last Gift']
maxi=data['Largest Gift']
l_1=np.mean(first)-3*np.std(first)
u_1=np.mean(first)+3*np.std(first)
m=np.abs(data['1st Gift']-np.mean(data['1st Gift']))>3*np.std(data['1st Gift'])
pd.value_counts(m)
l=first[m]
data.loc[:,'1st Gift'][m==True]=np.mean(data['1st Gift'])+3*np.std(data['1st Gift'])
data['1st Gift'].head()
m=np.abs(data['Last Gift']-np.mean(data['Last Gift']))>3*np.std(data['Last Gift'])
pd.value_counts(m)
l=last[m]
data.loc[:,'Last Gift'][m==True]=np.mean(data['Last Gift'])+3*np.std(data['Last Gift'])
data['Last Gift'].head()
Beware that calling Sleep() will freeze the service, so if the service is requested to stop, it won't react for the duration of the Sleep() call.
I tried the first solution and it works but the end user can easily identify that the div's are refreshing as it is fadeIn(), without fade in i tried .toggle().toggle() and it works perfect. you can try like this
$("#panel").toggle().toggle();
_x000D_
it works perfectly for me as i'm developing a messenger and need to minimize and maximize the chat box's and this does it best rather than the above code.
As a general rule, there is not a specific 'uninstall' mechanism that comes with CPAN modules. But you might try make uninstall
in the original directory the module unpacked into (this is often under /root/.cpan
or ~/.cpan
), as some packages do contain this directive in their install script. (However, since you've installed modules into a local (non-root) library directory, you also have the option of blowing away this entire directory and reinstalling everything else that you want to keep.)
A lot of the time you can simply get away with removing the A/B.pm
file (for the A::B
module) from your perllib -- that will at least render the module unusable. Most modules also contain a list of files to be installed (called a "manifest"), so if you can find that, you'll know which files you can delete.
However, none of these approaches will address any modules that were installed as dependencies. There's no good (automated) way of knowing if something else is dependent on that module, so you'll have to uninstall it manually as well once you're sure.
The difficulty in uninstalling modules is one reason why many Perl developers are moving towards using a revision control system to keep track of installations -- e.g. see the article by brian d foy as a supplement to his upcoming book that discusses using git for package management.
I use ".hpp" for C++ headers and ".h" for C language headers. The ".hpp" reminds me that the file contains statements for the C++ language which are not valid for the C language, such as "class" declarations.
Swift 5.
To convert a String
to a URL
:
let stringToURL = URL(string: "your-string")
To convert a URL
to a String
:
let urlToString = stringToURL?.absoluteString
Suppose you have one stored procedure like this
First stored procedure:
Create PROCEDURE LoginId
@UserName nvarchar(200),
@Password nvarchar(200)
AS
BEGIN
DECLARE @loginID int
SELECT @loginID = LoginId
FROM UserLogin
WHERE UserName = @UserName AND Password = @Password
return @loginID
END
Now you want to call this procedure from another stored procedure like as below
Second stored procedure
Create PROCEDURE Emprecord
@UserName nvarchar(200),
@Password nvarchar(200),
@Email nvarchar(200),
@IsAdmin bit,
@EmpName nvarchar(200),
@EmpLastName nvarchar(200),
@EmpAddress nvarchar(200),
@EmpContactNo nvarchar(150),
@EmpCompanyName nvarchar(200)
AS
BEGIN
INSERT INTO UserLogin VALUES(@UserName,@Password,@Email,@IsAdmin)
DECLARE @EmpLoginid int
**exec @EmpLoginid= LoginId @UserName,@Password**
INSERT INTO tblEmployee VALUES(@EmpName,@EmpLastName,@EmpAddress,@EmpContactNo,@EmpCompanyName,@EmpLoginid)
END
As you seen above, we can call one stored procedure from another
Yes, you can... If a then a, else if b then if c then c(b), else b, else null
a ? a : (b ? (c ? c(b) : b) : null)
a
? a
: b
? c
? c(b)
: b
: null
Ternary operator ?:
used as inline if-else is right associative. In short this means that the rightmost ?
gets fed first and it takes exactly one closest operand on the left and two, with a :
, on the right.
Practically speaking, consider the following statement (same as above):
a ? a : b ? c ? c(b) : b : null
The rightmost ?
gets fed first, so find it and its surrounding three arguments and consecutively expand to the left to another ?
.
a ? a : b ? c ? c(b) : b : null
^ <---- RTL
1. |1-?-2----:-3|
^ <-
2. |1-?|--2---------|:-3---|
^ <-
3.|1-?-2-:|--3--------------------|
result: a ? a : (b ? (c ? c(b) : b) : null)
- Term
a
is read.
Node:a
- Nonterminal
?
is read.
Node:a ?
- Term
a
is read.
Node:a ? a
- Nonterminal
:
is read.
Node:a ? a :
- Term
b
is read.
Node:a ? a : b
- Nonterminal
?
is read, triggering the right-associativity rule. Associativity decides:
node:a ? a : (b ?
- Term
c
is read.
Node:a ? a : (b ? c
- Nonterminal
?
is read, re-applying the right-associativity rule.
Node:a ? a : (b ? (c ?
- Term
c(b)
is read.
Node:a ? a : (b ? (c ? c(b)
- Nonterminal
:
is read.
Node:a ? a : (b ? (c ? c(b) :
- Term
b
is read.
Node:a ? a : (b ? (c ? c(b) : b
- Nonterminal
:
is read. The ternary operator?:
from previous scope is satisfied and the scope is closed.
Node:a ? a : (b ? (c ? c(b) : b) :
- Term
null
is read.
Node:a ? a : (b ? (c ? c(b) : b) : null
- No tokens to read. Close remaining open parenthesis.
#Result is:a ? a : (b ? (c ? c(b) : b) : null)
The ugly oneliner from above could (and should) be rewritten for readability as:
(Note that the indentation does not implicitly define correct closures as brackets () do.)
a
? a
: b
? c
? c(b)
: b
: null
for example
return a + some_lengthy_variable_name > another_variable
? "yep"
: "nop"
Mozilla: JavaScript Conditional Operator
Wiki: Operator Associativity
var a = 0 // 1
var b = 20
var c = null // x=> {console.log('b is', x); return true} // return true here!
a
&& a
|| b
&& c
&& c(b) // if this returns false, || b is processed
|| b
|| null
Using logical operators as in this example is ugly and wrong, but this is where they shine...
This approach comes with subtle limitations as explained in the link below. For proper solution, see Nullish coalescing in Bonus2.
function f(mayBeNullOrFalsy) {
var cantBeNull = mayBeNullOrFalsy || 42 // "default" value
var alsoCantBe = mayBeNullOrFalsy ? mayBeNullOrFalsy : 42 // ugly...
..
}
false && (anything) // is short-circuit evaluated to false.
true || (anything) // is short-circuit evaluated to true.
Logical operators
Null coalescence
Short-circuit evaluation
developer.mozilla.org~Nullish_coalescing_operator
function f(mayBeNullOrUndefined, another) {
var cantBeNullOrUndefined = mayBeNullOrUndefined ?? 42
another ??= 37 // nullish coalescing self-assignment
another = another ?? 37 // same effect
..
}
Stage 4 finished proposal https://github.com/tc39/proposal-optional-chaining https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
// before
var street = user.address && user.address.street
// after
var street = user.address?.street
// combined with Nullish coalescing
// before
var street = user.address
? user.address.street
: "N/A"
// after
var street = user.address?.street ?? "N/A"
// arrays
obj.someArray?.[index]
// functions
obj.someMethod?.(args)
Contrary to what pointy says, the blur()
method does exist and is a part of the w3c standard. The following exaple will work in every modern browser (including IE):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Javascript test</title>
<script type="text/javascript" language="javascript">
window.onload = function()
{
var field = document.getElementById("field");
var link = document.getElementById("link");
var output = document.getElementById("output");
field.onfocus = function() { output.innerHTML += "<br/>field.onfocus()"; };
field.onblur = function() { output.innerHTML += "<br/>field.onblur()"; };
link.onmouseover = function() { field.blur(); };
};
</script>
</head>
<body>
<form name="MyForm">
<input type="text" name="field" id="field" />
<a href="javascript:void(0);" id="link">Blur field on hover</a>
<div id="output"></div>
</form>
</body>
</html>
Note that I used link.onmouseover
instead of link.onclick
, because otherwise the click itself would have removed the focus.
Simple way to count is,
$currentdate = date('Y-m-d H:i:s');
$after1yrdate = date("Y-m-d H:i:s", strtotime("+1 year", strtotime($data)));
$diff = (strtotime($after1yrdate) - strtotime($currentdate)) / (60 * 60 * 24);
echo "<p style='color:red'>The difference is ".round($diff)." Days</p>";
This can now be achieve through the css method :focus-within
as examplified in this post: http://www.scottohara.me/blog/2017/05/14/focus-within.html
/*_x000D_
A normal (though ugly) focus_x000D_
pseudo-class. Any element that_x000D_
can receive focus within the_x000D_
.my-element parent will receive_x000D_
a yellow background._x000D_
*/_x000D_
.my-element *:focus {_x000D_
background: yellow !important;_x000D_
color: #000;_x000D_
}_x000D_
_x000D_
/*_x000D_
The :focus-within pseudo-class_x000D_
will NOT style the elements within_x000D_
the .my-element selector, like the_x000D_
normal :focus above, but will_x000D_
style the .my-element container_x000D_
when its focusable children_x000D_
receive focus._x000D_
*/_x000D_
.my-element:focus-within {_x000D_
outline: 3px solid #333;_x000D_
}
_x000D_
<div class="my-element">_x000D_
<p>A paragraph</p>_x000D_
<p>_x000D_
<a href="http://scottohara.me">_x000D_
My Website_x000D_
</a>_x000D_
</p>_x000D_
_x000D_
<label for="wut_email">_x000D_
Your email:_x000D_
</label>_x000D_
<input type="email" id="wut_email" />_x000D_
</div>
_x000D_
Rather than getting lost amongst the random selection of formulae mentioned here, I suggest you go for the formula recommended by W3C standards.
Here's a straightforward but exact PHP implementation of the WCAG 2.0 SC 1.4.3 relative luminance and contrast ratio formulae. It produces values that are appropriate for evaluating the ratios required for WCAG compliance, as on this page, and as such is suitable and appropriate for any web app. This is trivial to port to other languages.
/**
* Calculate relative luminance in sRGB colour space for use in WCAG 2.0 compliance
* @link http://www.w3.org/TR/WCAG20/#relativeluminancedef
* @param string $col A 3 or 6-digit hex colour string
* @return float
* @author Marcus Bointon <[email protected]>
*/
function relativeluminance($col) {
//Remove any leading #
$col = trim($col, '#');
//Convert 3-digit to 6-digit
if (strlen($col) == 3) {
$col = $col[0] . $col[0] . $col[1] . $col[1] . $col[2] . $col[2];
}
//Convert hex to 0-1 scale
$components = array(
'r' => hexdec(substr($col, 0, 2)) / 255,
'g' => hexdec(substr($col, 2, 2)) / 255,
'b' => hexdec(substr($col, 4, 2)) / 255
);
//Correct for sRGB
foreach($components as $c => $v) {
if ($v <= 0.04045) {
$components[$c] = $v / 12.92;
} else {
$components[$c] = pow((($v + 0.055) / 1.055), 2.4);
}
}
//Calculate relative luminance using ITU-R BT. 709 coefficients
return ($components['r'] * 0.2126) + ($components['g'] * 0.7152) + ($components['b'] * 0.0722);
}
/**
* Calculate contrast ratio acording to WCAG 2.0 formula
* Will return a value between 1 (no contrast) and 21 (max contrast)
* @link http://www.w3.org/TR/WCAG20/#contrast-ratiodef
* @param string $c1 A 3 or 6-digit hex colour string
* @param string $c2 A 3 or 6-digit hex colour string
* @return float
* @author Marcus Bointon <[email protected]>
*/
function contrastratio($c1, $c2) {
$y1 = relativeluminance($c1);
$y2 = relativeluminance($c2);
//Arrange so $y1 is lightest
if ($y1 < $y2) {
$y3 = $y1;
$y1 = $y2;
$y2 = $y3;
}
return ($y1 + 0.05) / ($y2 + 0.05);
}
I ended up getting the answer from AngularJS forum. See this thread for details
The link is to a Google Groups thread, which is difficult to read and doesn't provide a clear answer. To remove URL parameters use
$location.url($location.path());
This way worked for me when adding random data to MySql table using a python script.
First install the following packages using the below commands
pip install mysql-connector-python<br>
pip install random
import mysql.connector
import random
from datetime import date
start_dt = date.today().replace(day=1, month=1).toordinal()
end_dt = date.today().toordinal()
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="your_db_name"
)
mycursor = mydb.cursor()
sql_insertion = "INSERT INTO customer (name,email,address,dateJoined) VALUES (%s, %s,%s, %s)"
#insert 10 records(rows)
for x in range(1,11):
#generate a random date
random_day = date.fromordinal(random.randint(start_dt, end_dt))
value = ("customer" + str(x),"customer_email" + str(x),"customer_address" + str(x),random_day)
mycursor.execute(sql_insertion , value)
mydb.commit()
print("customer records inserted!")
Following is a sample output of the insertion
cid | name | email | address | dateJoined |
1 | customer1 | customer_email1 | customer_address1 | 2020-11-15 |
2 | customer2 | customer_email2 | customer_address2 | 2020-10-11 |
3 | customer3 | customer_email3 | customer_address3 | 2020-11-17 |
4 | customer4 | customer_email4 | customer_address4 | 2020-09-20 |
5 | customer5 | customer_email5 | customer_address5 | 2020-02-18 |
6 | customer6 | customer_email6 | customer_address6 | 2020-01-11 |
7 | customer7 | customer_email7 | customer_address7 | 2020-05-30 |
8 | customer8 | customer_email8 | customer_address8 | 2020-04-22 |
9 | customer9 | customer_email9 | customer_address9 | 2020-01-05 |
10 | customer10 | customer_email10| customer_address10| 2020-11-12 |
MOV can do same thing as LEA [label], but MOV instruction contain the effective address inside the instruction itself as an immediate constant (calculated in advance by the assembler). LEA uses PC-relative to calculate the effective address during the execution of the instruction.
With lombok it's easy to declare a Pair
class:
@Data(staticConstructor = "of")
public class Pair<A, B> {
private final A left;
private final B right;
}
This will generates getters, static constructor named "of", equals()
, hashcode()
and toString()
.
see @Data
documentation for more information
In this world of flashy new native functions, we sometimes forget the basics.
for (let i = 0; i < arr.length; i++) {
console.log('index:', i, 'element:', arr[i]);
}
Clean, efficient, and you can still break
the loop. Bonus! You can also start from the end and go backwards with i--
!
Additional note: If you're using the value a lot within the loop, you may wish to do const value = arr[i];
at the top of the loop for an easy, readable reference.
In JavaScript 1.8.5, Object.getOwnPropertyNames
returns an array of all properties found directly upon a given object.
Object.getOwnPropertyNames ( obj )
and another method Object.keys
, which returns an array containing the names of all of the given object's own enumerable properties.
Object.keys( obj )
I used forEach
to list values and keys in obj, same as for (var key in obj) ..
Object.keys(obj).forEach(function (key) {
console.log( key , obj[key] );
});
This all are new features in ECMAScript , the mothods getOwnPropertyNames
, keys
won't supports old browser's.
@Override
protected Dialog onCreateDialog(int id)
{
switch(id)
{
case 0:
{
return new AlertDialog.Builder(this)
.setMessage("text here")
.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface arg0, int arg1)
{
try
{
}//end try
catch(Exception e)
{
Toast.makeText(getBaseContext(), "", Toast.LENGTH_LONG).show();
}//end catch
}//end onClick()
}).create();
}//end case
}//end switch
return null;
}//end onCreateDialog
Your problem is that all chapters, whether they're in the appendix or not, default to starting on an odd-numbered page when you're in two-sided layout mode. A few possible solutions:
The simplest solution is to use the openany
option to your document class, which makes chapters start on the next page, irrespective of whether it's an odd or even numbered page. This is supported in the standard book documentclass, eg \documentclass[openany]{book}
. (memoir
also supports using this as a declaration \openany
which can be used in the middle of a document to change the behavior for subsequent pages.)
Another option is to try the \let\cleardoublepage\clearpage
command before your appendices to avoid the behavior.
Or, if you don't care using a two-sided layout, using the option oneside
to your documentclass
(eg \documentclass[oneside]{book}
) will switch to using a one-sided layout.
const {Builder, By, Key, util} = require('selenium-webdriver')
// FUNÇÃO PARA PAUSA
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function example() {
// chrome
let driver = await new Builder().forBrowser("firefox").build()
await driver.get('https://www.google.com.br')
// await driver.findElement(By.name('q')).sendKeys('Selenium' ,Key.RETURN)
await sleep(2000)
await driver.findElement(By.name('q')).sendKeys('Selenium')
await sleep(2000)
// CLICAR
driver.findElement(By.name('btnK')).click()
}
example()
Com essas últimas linhas, você pode clicar !
$result = mysql_query($query) or die("Data not found.");
$rows=array();
while($r=mysql_fetch_assoc($result))
{
$rows[]=$r;
}
header("Content-type:application/json");
echo json_encode($rows);
I am really OCD about maintaining strict column limits, and not a fan of "\" line continuation because you can't put a comment after it, so here is my method.
//|¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯|//
#ifdef CONDITION_01 //| |//
#define TEMP_MACRO //| |//
#endif //| |//
#ifdef CONDITION_02 //| |//
#define TEMP_MACRO //| |//
#endif //| |//
#ifdef CONDITION_03 //| |//
#define TEMP_MACRO //| |//
#endif //| |//
#ifdef TEMP_MACRO //| |//
//|- -- -- -- -- -- -- -- -- -- -|//
printf("[IF_CONDITION:(1|2|3)]\n");
//|- -- -- -- -- -- -- -- -- -- -|//
#endif //| |//
#undef TEMP_MACRO //| |//
//|________________________________________|//
Any applications that require CPU usage such as transcoding, display performance and media rendering, whether it be audio or visual, will certainly require (at this point) and benefit from using 64 bit versus 32 bit due to the CPU's ability to deal with the sheer amount of data being thrown at it. It's not so much a question of address space as it is the way the data is being dealt with. A 64 bit processor, given 64 bit code, is going to perform better, especially with mathematically difficult things like transcoding and VoIP data - in fact, any sort of 'math' applications should benefit by the usage of 64 bit CPUs and operating systems. Prove me wrong.
FIRST OF ALL KNOW THE REASON WHY ECLIPSE IS DOING SO.
Date has only one constructor Date(long date) which asks for date in long data type.
The constructor you are using
Date(String s) Deprecated. As of JDK version 1.1, replaced by DateFormat.parse(String s).
Thats why eclipse tells that this function is not good.
See this official docs
http://docs.oracle.com/javase/6/docs/api/java/util/Date.html
Deprecated methods from your context -- Source -- http://www.coderanch.com/t/378728/java/java/Deprecated-methods
There are a number of reasons why a method or class may become deprecated. An API may not be easily extensible without breaking backwards compatibility, and thus be superseded by a more powerful API (e.g., java.util.Date has been deprecated in favor of Calendar, or the Java 1.0 event model). It may also simply not work or produce incorrect results under certain circumstances (e.g., some of the java.io stream classes do not work properly with some encodings). Sometimes an API is just ill-conceived (SingleThreadModel in the servlet API), and gets replaced by nothing. And some of the early calls have been replaced by "Java Bean"-compatible methods (size by getSize, bounds by getBounds etc.)
SEVRAL SOLUTIONS ARE THERE JUST GOOGLE IT--
You can use date(long date) By converting your date String into long milliseconds and stackoverflow has so many post for that purpose.
In SQL server, a cursor is used when you need Instead of the T-SQL commands that operate on all the rows in the result set one at a time, we use a cursor when we need to update records in a database table in a singleton fashion, in other words row by row.to fetch one row at a time or row by row.
Working with cursors consists of several steps:
Declare - Declare is used to define a new cursor. Open - A Cursor is opened and populated by executing the SQL statement defined by the cursor. Fetch - When the cursor is opened, rows can be retrieved from the cursor one by one. Close - After data operations, we should close the cursor explicitly. Deallocate - Finally, we need to delete the cursor definition and release all the system resources associated with the cursor. Syntax
DECLARE cursor_name CURSOR [ LOCAL | GLOBAL ] [ FORWARD_ONLY | SCROLL ] [ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ] [ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ] [ TYPE_WARNING] FOR select_statement [FOR UPDATE [ OF column_name [ ,...n ] ] ] [;]
You can also try this, if this is what you need:
<style type="text/css">
....
table td div {height:20px;overflow-y:hidden;}
table td.col1 div {width:100px;}
table td.col2 div {width:300px;}
</style>
<table>
<tbody>
<tr><td class="col1"><div>test</div></td></tr>
<tr><td class="col2"><div>test</div></td></tr>
</tbody>
</table>
In your comment to max's answer, you say that what you really wanted to get is the key in, and not the index of, the KeyValuePair that contains a certain value. You could edit your question to make it more clear.
It is worth pointing out (EricM has touched upon this in his answer) that a value might appear more than once in the dictionary, in which case one would have to think which key he would like to get: e.g. the first that comes up, the last, all of them?
If you are sure that each key has a unique value, you could have another dictionary, with the values from the first acting as keys and the previous keys acting as values. Otherwise, this second dictionary idea (suggested by Jon Skeet) will not work, as you would again have to think which of all the possible keys to use as value in the new dictionary.
If you were asking about the index, though, EricM's answer would be OK. Then you could get the KeyValuePair in question by using:
yourDictionary.ElementAt(theIndexYouFound);
provided that you do not add/remove things in yourDictionary
.
PS: I know it's been almost 7 years now, but what the heck. I thought it best to formulate my answer as addressing the OP, but of course by now one can say it is an answer for just about anyone else but the OP. Fully aware of that, thank you.
Assume you stored that dictionary in a variable called values. To get id
in to a variable, do:
idValue = values['criteria'][0]['id']
If that json is in a file, do the following to load it:
import json
jsonFile = open('your_filename.json', 'r')
values = json.load(jsonFile)
jsonFile.close()
If that json is from a URL, do the following to load it:
import urllib, json
f = urllib.urlopen("http://domain/path/jsonPage")
values = json.load(f)
f.close()
To print ALL of the criteria, you could:
for criteria in values['criteria']:
for key, value in criteria.iteritems():
print key, 'is:', value
print ''
If you know the array index, you can delete() it. The difference between splice() and delete() is that delete() does not renumber the remaining elements of the array.
I think you can change your query and try it like :
$res=User::where('id',$id)->delete();
If you want the latest file in the directory and you are using only the LastWriteTime
to determine the latest file, you can do something like below:
gci path | sort LastWriteTime | select -last 1
On the other hand, if you want to only rely on the names that have the dates in them, you should be able to something similar
gci path | select -last 1
Also, if there are directories in the directory, you might want to add a ?{-not $_.PsIsContainer}
This query stands good for fetching the values between current date and its next 3 dates
SELECT * FROM tableName
WHERE columName BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 3 DAY)
This will eventually add extra 3 days of buffer to the current date.
I don't know a way to do what you want exactly, but a workaround might be:
run: ./prog
./prog $(ARGS)
Then:
make ARGS="asdf" run
# or
make run ARGS="asdf"
This is the tiny limitation of Mysql in older version , actually after version 5.6 and later multiple timestamps works...
This worked for me.
$('.nav-pills > li > a').click( function() {
$('.nav-pills > li.active').removeClass('active');
$(this).parent().addClass('active');
} );
Use this extension, it generates xpaths based on id or class, which is probably what you want to use.
Click on the browser icon, the panel is shown on the right corner of the page, then click start inspect, then click on any element to get your xpath.
Structure in C
First you need to declare your structure:
struct mystruct{
char element_1,
char element_2
};
Instantiate C structure
Once you declared your structure , you can instantiate a variable that has as type your structure using either:
mystruct struct_example;
or :
mystruct* struct_example;
For the first use case you can access the varaiable eleemnet using the following syntax: struct_example.element_1 = 5;
For the second use case which is having a pointer to variable of type your structure, to be able to access the variable structure you need an arrow:
struct_example->element_1 = 5;
See O'Reilly "Java Cookbook", Ian Darwin - recipe 17.4 Handling Multiple Clients.
Pay attention that accept()
is not thread safe, so the call is wrapped within synchronized
.
64: synchronized(servSock) {
65: clientSocket = servSock.accept();
66: }
I came up with this method because while on the CLI, it's not possible to use the methods provided in the other answers here and it had always bugged me.
Basic Example
FOR /L %L IN (0,0,1) DO @(
ECHO. Counter always 0, See "%L" = "0" - Waiting a split second&ping -n 1 127.0.0.1>NUL )
This is truly an infinite loop!
This is useful for monitoring something in a CMD
window, and allows you to use CTRL
+C
to break it when you're done.
Want to Have a counter?
Either use SET /A
OR You can modify the FOR /L
Loop to do the counting and still be infinite (Note, BOTH of these methods have a 32bit integer overflow)
SET /A
Method:
FOR /L %L IN (0,0,1) DO @(
SET /A "#+=1"&ECHO. L Still equals 0, See "%L = 0"! - Waiting a split second &ping -n 1 127.0.0.1>NUL )
Native FOR /L
Counter:
FOR /L %L IN (-2147483648,1,2147483648) DO @(
ECHO.Current value of L: %L - Waiting a split second &ping -n 1 127.0.0.1>NUL )
Counting Sets of 4294967295 and Showing Current Value of L:
FOR /L %L IN (1,1,2147483648) DO @(
(
IF %L EQU 0 SET /A "#+=1">NUL
)&SET /A "#+=0"&ECHO. Sets of 4294967295 - Current value of L: %L - Waiting a split second &ping -n 1 127.0.0.1>NUL )
However, what if:
For this, I determined how to use a couple methods to break the FOR
Loop prematurely effectively turning it into a "DO WHILE
" or "DO UNTIL
" Loop, which is otherwise sorely lacking in CMD.
NOTE: Most of the time a loop will continue to iterate past the condition you checked for, often this is a wanted behavior, but not in our case.
DO WHILE
" / "DO UNTIL
" LoopUPDATE: Due to wanting to use this code in CMD Scripts (and have them persist!) as well as CLI, and on thinking if there might be a "more Correct" method to achieve this I recommend using the New method!
New Method (Can be used inside CMD Scripts without exiting the script):
FOR /F %%A IN ('
CMD /C "FOR /L %%L IN (0,1,2147483648) DO @( ECHO.%%L & IF /I %%L EQU 10 ( exit /b ) )"
') DO @(
ECHO %%~A
)
At CLI:
FOR /F %A IN ('
CMD /C "FOR /L %L IN (0,1,2147483648) DO @( ECHO.%L & IF /I %L EQU 10 ( exit /b ) )"
') DO @(
ECHO %~A
)
Original Method (Will work on CLI just fine, but will kill a script.)
FOR /L %L IN (0,1,2147483648) DO @(
ECHO.Current value of L: %L - Waiting a split second &ping -n 1 127.0.0.1>NUL&(
IF /I %L EQU 10 (
ECHO.Breaking the Loop! Because We have matched the condition!&DIR >&0
)
)
) 2>NUL
Through chance I had hit upon some ways to exit loops prematurely that did not close the CMD prompt when trying to do other things which gave me this Idea.
While ECHO.>&3 >NUL
had worked for me in some scenarios, I have played with this off and on over the years and found that DIR >&0 >NUL
was much more consistent.
I am re-writing this answer from here forward to use that method instead as I recently found the old note to myself to use this method instead.
DIR >&0 >NUL
The >NUL is optional, I just prefer not to have it output the error.
I prefer to match inLine when possible, as you can see in this sanitized example of a Command I use to monitor LUN Migrations on our VNX.
for /l %L IN (0,0,1) DO @(
ECHO.& ECHO.===========================================& (
[VNX CMD] | FINDSTR /R /C:"Source LU Name" /C:"State:" /C:"Time " || DIR >&0 >NUL
) & Ping -n 10 1.1.1.1 -w 1000>NUL )
Also, I have another method I found in that note to myself which I just re-tested to confirm works just as well at the CLI as the other method.
Apparently, when I first posted here I posted an older iteration I was playing with instead of the two newer ones which work better:
In this method, we use EXIT /B
to exit the For Loop, but we don't want to exit the CLI so we wrap it in a CMD session:
FOR /F %A IN ('CMD /C "FOR /L %L IN (0,1,10000000) DO @( ECHO.%L & IF /I %L EQU 10 ( exit /b ) )" ') DO @(ECHO %~A)
Because the loop itself happens in the CMD session, we can use EXIT /B to exit the iteration of the loop without losing our CMD Session, and without waiting for the loop to complete, much the same as with the other method.
I would go so far as to say that this method is likely the "intended" method for the sort of scenario where you want to break a for loop at the CLI, as using CMD session is also the only way to get Delayed expansion working at the CLI for your loops, and the behavior and such behavior is clearly an intended workflow to leave a CMD session.
IE: Microsoft clearly made an intentional effort to have CMD Exit /B For loops behave this way, while the "Intended" way of doing this, as my other method, relies on having accidentally created just the right error to kick you out of the loop without letting the loop finish processing, which I only happenstantially discovered, and seems to only reliably work when using the DIR command which is fairly strange.
So that said, I think it's probably a better practice to use Method 2:
FOR /F %A IN ('CMD /C "FOR /L %L IN (0,1,10000000) DO @( ECHO.%L & IF /I %L EQU 10 ( exit /b ) )" ') DO @(ECHO %~A)
Although I suspect Method 1 is going to be slightly faster:
FOR /L %L IN (0,1,10000000) DO @( ECHO.%L & IF /I %L EQU 10 ( DIR >&) >NUL ) )
And in either case, both should allow DO-While loops as you need for your purposes.
If you want to be sure that these files are properly refreshed by Chrome for all users, then you need to have must-revalidate
in the Cache-Control
header. This will make Chrome re-check files to see if they need to be re-fetched.
Recommend the following response header:
Cache-Control: must-validate
This tells Chrome to check with the server, and see if there is a newer file. If there is a newer file, it will receive it in the response. If not, it will receive a 304 response, and the assurance that the one in the cache is up to date.
If you do NOT set this header, then in the absence of any other setting that invalidates the file, Chrome will never check with the server to see if there is a newer version.
Here is a blog post that discusses the issue further.
There are some great answers, but many use functions that are flagged as not cryptographically secure. If you want a random 6 digit number that is cryptographically secure you can use something like this:
$key = random_int(0, 9999999);
$key = str_pad($key, 6, 0, STR_PAD_LEFT);
return $key;
This will also include numbers like 000182 and others that would otherwise be excluded from the other examples.
I came up with my own basic method which seems to work fine (so far). There's probably a dozen things some of the popular scripts address that I haven't thought of.
Note - This solution is fast and easy to implement but of course not great for performance. Definitely look into the new Intersection Observer as mentioned by Apoorv and explained by developers.google if performance is an issue.
The JQuery
$(window).scroll(function() {
$.each($('img'), function() {
if ( $(this).attr('data-src') && $(this).offset().top < ($(window).scrollTop() + $(window).height() + 100) ) {
var source = $(this).data('src');
$(this).attr('src', source);
$(this).removeAttr('data-src');
}
})
})
Sample html code
<div>
<img src="" data-src="pathtoyour/image1.jpg">
<img src="" data-src="pathtoyour/image2.jpg">
<img src="" data-src="pathtoyour/image3.jpg">
</div>
Explained
When the page is scrolled each image on the page is checked..
$(this).attr('data-src')
- if the image has the attribute data-src
and how far those images are from the bottom of the window..
$(this).offset().top < ($(window).scrollTop() + $(window).height() + 100)
adjust the + 100 to whatever you like (- 100 for example)
var source = $(this).data('src');
- gets the value of data-src=
aka the image url
$(this).attr('src', source);
- puts that value into the src=
$(this).removeAttr('data-src');
- removes the data-src attribute (so your browser doesn't waste resources messing with the images that have already loaded)
Adding To Existing Code
To convert your html, in an editor just search and replace src="
with src="" data-src="
Just to complete the example with a full implementation of ClientHttpRequestInterceptor
to trace request and response:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
public class LoggingRequestInterceptor implements ClientHttpRequestInterceptor {
final static Logger log = LoggerFactory.getLogger(LoggingRequestInterceptor.class);
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
traceRequest(request, body);
ClientHttpResponse response = execution.execute(request, body);
traceResponse(response);
return response;
}
private void traceRequest(HttpRequest request, byte[] body) throws IOException {
log.info("===========================request begin================================================");
log.debug("URI : {}", request.getURI());
log.debug("Method : {}", request.getMethod());
log.debug("Headers : {}", request.getHeaders() );
log.debug("Request body: {}", new String(body, "UTF-8"));
log.info("==========================request end================================================");
}
private void traceResponse(ClientHttpResponse response) throws IOException {
StringBuilder inputStringBuilder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), "UTF-8"));
String line = bufferedReader.readLine();
while (line != null) {
inputStringBuilder.append(line);
inputStringBuilder.append('\n');
line = bufferedReader.readLine();
}
log.info("============================response begin==========================================");
log.debug("Status code : {}", response.getStatusCode());
log.debug("Status text : {}", response.getStatusText());
log.debug("Headers : {}", response.getHeaders());
log.debug("Response body: {}", inputStringBuilder.toString());
log.info("=======================response end=================================================");
}
}
Then instantiate RestTemplate
using a BufferingClientHttpRequestFactory
and the LoggingRequestInterceptor
:
RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new LoggingRequestInterceptor());
restTemplate.setInterceptors(interceptors);
The BufferingClientHttpRequestFactory
is required as we want to use the response body both in the interceptor and for the initial calling code. The default implementation allows to read the response body only once.
You should probably be looking to the configuration that controls the underlying platform TLS implementation via -Djdk.tls.client.protocols=TLSv1.2
.
I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.
To answer the question in the header: To install make in ubuntu you have to install build-essentials
sudo apt-get install build-essential
In Java 8 you can use the Stream interface:
return dvdList.stream().anyMatch(d -> d.getTitle().equalsIgnoreCase("SomeTitle"));
No, you can specify the list as a keyword argument to your function.
alist = []
def fn(alist=alist):
alist.append(1)
fn()
print alist # [1]
I'd say it's bad practice though. Kind of too hackish. If you really need to use a globally available singleton-like data structure, I'd use the module level variable approach, i.e. put 'alist' in a module and then in your other modules import that variable:
In file foomodule.py:
alist = []
In file barmodule.py:
import foomodule
def fn():
foomodule.alist.append(1)
print foomodule.alist # [1]
console.log(document.getElementById('xx') ) evaluates to null.
document.getElementById('xx') !=null evaluates to false
You should use document.getElementById('xx') !== null
as it is a stronger equality check.
I know this has been answered before but I know a lot of people get tripped up on this, so I'm going to add a comment.
I had this exact same problem happen on my Nexus One. This was from the file not existing on the disk before the camera app started. Therefore, I made sure that the file existing before started the camera app. Here's some sample code that I used:
String storageState = Environment.getExternalStorageState();
if(storageState.equals(Environment.MEDIA_MOUNTED)) {
String path = Environment.getExternalStorageDirectory().getName() + File.separatorChar + "Android/data/" + MainActivity.this.getPackageName() + "/files/" + md5(upc) + ".jpg";
_photoFile = new File(path);
try {
if(_photoFile.exists() == false) {
_photoFile.getParentFile().mkdirs();
_photoFile.createNewFile();
}
} catch (IOException e) {
Log.e(TAG, "Could not create file.", e);
}
Log.i(TAG, path);
_fileUri = Uri.fromFile(_photoFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE );
intent.putExtra( MediaStore.EXTRA_OUTPUT, _fileUri);
startActivityForResult(intent, TAKE_PICTURE);
} else {
new AlertDialog.Builder(MainActivity.this)
.setMessage("External Storeage (SD Card) is required.\n\nCurrent state: " + storageState)
.setCancelable(true).create().show();
}
I first create a unique (somewhat) file name using an MD5 hash and put it into the appropriate folder. I then check to see if it exists (shouldn't, but its good practice to check anyway). If it does not exist, I get the parent dir (a folder) and create the folder hierarchy up to it (therefore if the folders leading up to the location of the file don't exist, they will after this line. Then after that I create the file. Once the file is created I get the Uri and pass it to the intent and then the OK button works as expected and all is golden.
Now,when the Ok button is pressed on the camera app, the file will be present in the given location. In this example it would be /sdcard/Android/data/com.example.myapp/files/234asdioue23498ad.jpg
There is no need to copy the file in the "onActivityResult" as posted above.
Scolp is a new library that lets you pretty print streaming columnar data easily while auto-adjusting column width.
(Disclaimer: I am the author)
Strict Contextual Escaping can be disabled entirely, allowing you to inject html using ng-html-bind
. This is an unsafe option, but helpful when testing.
Example from the AngularJS documentation on $sce
:
angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
// Completely disable SCE. For demonstration purposes only!
// Do not use in new projects.
$sceProvider.enabled(false);
});
Attaching the above config section to your app will allow you inject html into ng-html-bind
, but as the doc remarks:
SCE gives you a lot of security benefits for little coding overhead. It will be much harder to take an SCE disabled application and either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE for cases where you have a lot of existing code that was written before SCE was introduced and you're migrating them a module at a time.
The "if" expression tests for truthiness, while the double-equal tests for type-independent equivalency. A string is always truthy, as others here have pointed out. If the double-equal were testing both of its operands for truthiness and then comparing the results, then you'd get the outcome you were intuitively assuming, i.e. ("0" == true) === true
. As Doug Crockford says in his excellent JavaScript: the Good Parts, "the rules by which [== coerces the types of its operands] are complicated and unmemorable.... The lack of transitivity is alarming." It suffices to say that one of the operands is type-coerced to match the other, and that "0" ends up being interpreted as a numeric zero, which is in turn equivalent to false when coerced to boolean (or false is equivalent to zero when coerced to a number).
Use a div #overlay
with your loading info / .gif that will cover all your page:
<div id="overlay">
<img src="loading.gif" alt="Loading" />
Loading...
</div>
jQuery:
$(window).load(function(){
// PAGE IS FULLY LOADED
// FADE OUT YOUR OVERLAYING DIV
$('#overlay').fadeOut();
});
Here's an example with a Loading bar:
<div id="overlay">
<div id="progstat"></div>
<div id="progress"></div>
</div>
<div id="container">
<img src="http://placehold.it/3000x3000/cf5">
</div>
CSS:
*{margin:0;}
body{ font: 200 16px/1 sans-serif; }
img{ width:32.2%; }
#overlay{
position:fixed;
z-index:99999;
top:0;
left:0;
bottom:0;
right:0;
background:rgba(0,0,0,0.9);
transition: 1s 0.4s;
}
#progress{
height:1px;
background:#fff;
position:absolute;
width:0; /* will be increased by JS */
top:50%;
}
#progstat{
font-size:0.7em;
letter-spacing: 3px;
position:absolute;
top:50%;
margin-top:-40px;
width:100%;
text-align:center;
color:#fff;
}
JavaScript:
;(function(){
function id(v){ return document.getElementById(v); }
function loadbar() {
var ovrl = id("overlay"),
prog = id("progress"),
stat = id("progstat"),
img = document.images,
c = 0,
tot = img.length;
if(tot == 0) return doneLoading();
function imgLoaded(){
c += 1;
var perc = ((100/tot*c) << 0) +"%";
prog.style.width = perc;
stat.innerHTML = "Loading "+ perc;
if(c===tot) return doneLoading();
}
function doneLoading(){
ovrl.style.opacity = 0;
setTimeout(function(){
ovrl.style.display = "none";
}, 1200);
}
for(var i=0; i<tot; i++) {
var tImg = new Image();
tImg.onload = imgLoaded;
tImg.onerror = imgLoaded;
tImg.src = img[i].src;
}
}
document.addEventListener('DOMContentLoaded', loadbar, false);
}());
So I had this exact same issue and lost about 6 hours of my life searching, I had the
withCredentials: true
But the browser still didn't save the cookie until for some weird reason I had the idea to shuffle the configuration setting:
Axios.post(GlobalVariables.API_URL + 'api/login', {
email,
password,
honeyPot
}, {
withCredentials: true,
headers: {'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json'
}});
Seems like you should always send the 'withCredentials' Key first.
I am not sure if you got this resolved. To follow up on "CommonsWare's" comment.
That is not a valid string representation of a Uri. A Uri has a scheme, and "/external/images/media/470939" does not have a scheme.
Change
Uri uri=Uri.parse("/external/images/media/470939");
to
Uri uri=Uri.parse("content://external/images/media/470939");
in my case
Uri uri = Uri.parse("content://media/external/images/media/6562");
Unix will only run commands if they are available on the system path, as you can view by the $PATH variable
echo $PATH
Executables located in directories that are not on the path cannot be run unless you specify their full location. So in your case, assuming the executable is in the current directory you are working with, then you can execute it as such
./my-exec
Where my-exec
is the name of your program.
Use:
SELECT t1.Notes,
t2.Name
FROM Table1 t1
JOIN Table2 t2 ON t1.Notes LIKE CONCAT('%', t2.Name ,'%')
I couldn't used android:anyDensity="true" because objects in my game would be positioned completely different... seems this also does the trick:
// creating locale Locale locale2 = new Locale(loc); Locale.setDefault(locale2); Configuration config2 = new Configuration(); config2.locale = locale2; // updating locale mContext.getResources().updateConfiguration(config2, null);
$domain = "domain.local"
$password = "Passw@rd" | ConvertTo-SecureString -asPlainText -Force
$username = "$domain\Administrator"
$hostname=hostname
$credential = New-Object System.Management.Automation.PSCredential($username,$password)
Add-Computer -DomainName $domain -ComputerName $hostname -NewName alrootca -Credential $credential -Restart
Works for me ^^
@Eric
I was actually hoping to see a C wizard post something really cool, sort of like what I did but less verbose, while still doing it "manually".
Well, I'm no C guru, but here's what I came up with:
unsigned int parseHex(const char * str)
{
unsigned int val = 0;
char c;
while(c = *str++)
{
val <<= 4;
if (c >= '0' && c <= '9')
{
val += c & 0x0F;
continue;
}
c &= 0xDF;
if (c >= 'A' && c <= 'F')
{
val += (c & 0x07) + 9;
continue;
}
errno = EINVAL;
return 0;
}
return val;
}
I originally had more bitmasking going on instead of comparisons, but I seriously doubt bitmasking is any faster than comparison on modern hardware.
f-string formatting:
This was new in Python 3.6 - the string is placed in quotation marks as usual, prepended with f'...
in the same way you would r'...
for a raw string. Then you place whatever you want to put within your string, variables, numbers, inside braces f'some string text with a {variable} or {number} within that text'
- and Python evaluates as with previous string formatting methods, except that this method is much more readable.
>>> foobar = 3.141592
>>> print(f'My number is {foobar:.2f} - look at the nice rounding!')
My number is 3.14 - look at the nice rounding!
You can see in this example we format with decimal places in similar fashion to previous string formatting methods.
NB foobar
can be an number, variable, or even an expression eg f'{3*my_func(3.14):02f}'
.
Going forward, with new code I prefer f-strings over common %s or str.format() methods as f-strings can be far more readable, and are often much faster.
Just adding so you don't have to click-through:
curl --user name:password http://www.example.com
or if you're trying to do send authentication for OAuth 2:
curl -H "Authorization: OAuth <ACCESS_TOKEN>" http://www.example.com
You could add a method to String to make it more semantic:
String.metaClass.getNotBlank = { !delegate.allWhitespace }
which let's you do:
groovy:000> foo = ''
===>
groovy:000> foo.notBlank
===> false
groovy:000> foo = 'foo'
===> foo
groovy:000> foo.notBlank
===> true
The following numpy implementation should be approx. 2x the speed of the given answer:
def cartesian2(arrays):
arrays = [np.asarray(a) for a in arrays]
shape = (len(x) for x in arrays)
ix = np.indices(shape, dtype=int)
ix = ix.reshape(len(arrays), -1).T
for n, arr in enumerate(arrays):
ix[:, n] = arrays[n][ix[:, n]]
return ix
The comma expression takes on the value of the last (eg. right-most) expression.
So in your first loop, the only controlling expression is i<=5
; and j>=0
is ignored.
In the second loop, j>=0
controls the loop, and i<=5
is ignored.
As for a reason... there is no reason. This code is just wrong. The first part of the comma-expressions does nothing except confuse programmers. If a serious programmer wrote this, they should be ashamed of themselves and have their keyboard revoked.
set ORACLE_SID=<YOUR_SID>
sqlplus "/as sysdba"
alter system disable restricted session;
or maybe
shutdown abort;
or maybe
lsnrctl stop
lsnrctl start
It may be easiest to create a fake date so you can use the date function.
Excellent reference here: http://php.net/manual/en/function.date.php
Example:
<?
$month = 7;
$tempDate = mktime(0, 0, 0, $month, 1, 1900);
echo date("m",$tempDate);
?>
The following are tried, tested and proven methods to check if a row exists.
(Some of which I use myself, or have used in the past).
Edit: I made an previous error in my syntax where I used mysqli_query()
twice. Please consult the revision(s).
I.e.:
if (!mysqli_query($con,$query))
which should have simply read as if (!$query)
.
Side note: Both '".$var."'
and '$var'
do the same thing. You can use either one, both are valid syntax.
Here are the two edited queries:
$query = mysqli_query($con, "SELECT * FROM emails WHERE email='".$email."'");
if (!$query)
{
die('Error: ' . mysqli_error($con));
}
if(mysqli_num_rows($query) > 0){
echo "email already exists";
}else{
// do something
}
and in your case:
$query = mysqli_query($dbl, "SELECT * FROM `tblUser` WHERE email='".$email."'");
if (!$query)
{
die('Error: ' . mysqli_error($dbl));
}
if(mysqli_num_rows($query) > 0){
echo "email already exists";
}else{
// do something
}
You can also use mysqli_
with a prepared statement method:
$query = "SELECT `email` FROM `tblUser` WHERE email=?";
if ($stmt = $dbl->prepare($query)){
$stmt->bind_param("s", $email);
if($stmt->execute()){
$stmt->store_result();
$email_check= "";
$stmt->bind_result($email_check);
$stmt->fetch();
if ($stmt->num_rows == 1){
echo "That Email already exists.";
exit;
}
}
}
Or a PDO method with a prepared statement:
<?php
$email = $_POST['email'];
$mysql_hostname = 'xxx';
$mysql_username = 'xxx';
$mysql_password = 'xxx';
$mysql_dbname = 'xxx';
try {
$conn= new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
exit( $e->getMessage() );
}
// assuming a named submit button
if(isset($_POST['submit']))
{
try {
$stmt = $conn->prepare('SELECT `email` FROM `tblUser` WHERE email = ?');
$stmt->bindParam(1, $_POST['email']);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
}
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
if($stmt->rowCount() > 0){
echo "The record exists!";
} else {
echo "The record is non-existant.";
}
}
?>
N.B.:
When dealing with forms and POST arrays as used/outlined above, make sure that the POST arrays contain values, that a POST method is used for the form and matching named attributes for the inputs.
Note: <input type = "text" name = "var">
- $_POST['var']
match. $_POST['Var']
no match.
Consult:
Error checking references:
Please note that MySQL APIs do not intermix, in case you may be visiting this Q&A and you're using mysql_
to connect with (and querying with).
Consult the following about this:
If you are using the mysql_
API and have no choice to work with it, then consult the following Q&A on Stack:
The mysql_*
functions are deprecated and will be removed from future PHP releases.
You can also add a UNIQUE constraint to (a) row(s).
References:
@Schildmeijer is largely right, however port 7001 is still used when using TLS Encrypted Internode communication
So my complete list would be for current versions of Cassandra:
As example (DEMO):
HTML:
<div class="header">
<img src="img/logo.png" alt="logo" />
<h1>My website name</h1>
</div>
CSS:
.header img {
float: left;
width: 100px;
height: 100px;
background: #555;
}
.header h1 {
position: relative;
top: 18px;
left: 10px;
}
this error occur when you change your php version: it's very simple to suppress this error message
To suppress the DEPRECATED Error message, just add below code into your index.php file:
init_set('display_errors',False);
This should work. No more gray areas at the top or bottom:)
<script type="text/javascript">
function blockMove() {
event.preventDefault() ;
}
</script>
<body ontouchmove="blockMove()">
But this also disables any scrollable areas. If you want to keep your scrollable areas and still remove the rubber band effect at the top and bottom, see here: https://github.com/joelambert/ScrollFix.
In newer version of git (2.23+) you can use:
git switch -C master origin/master
-C
is same as --force-create
. Related Reference Docs
Use -A and -B switches (mean lines-after and lines-before):
grep -A 1 -B 1 FAILED file.txt
After making your corrections listed in the top answer, change the default settings of your server.
In your "/etc/my.cnf.d/server.cnf" or where ever it's located add the defaults to the [mysqld] section so it looks like this:
[mysqld]
character-set-server=utf8
collation-server=utf8_general_ci
Source: https://dev.mysql.com/doc/refman/5.7/en/charset-applications.html
The benefits of super()
in single-inheritance are minimal -- mostly, you don't have to hard-code the name of the base class into every method that uses its parent methods.
However, it's almost impossible to use multiple-inheritance without super()
. This includes common idioms like mixins, interfaces, abstract classes, etc. This extends to code that later extends yours. If somebody later wanted to write a class that extended Child
and a mixin, their code would not work properly.
set ansi_nulls off go select * from table t inner join otherTable o on t.statusid = o.statusid go set ansi_nulls on go
std::map::find
returns an iterator to the found element (or to the end()
if the element was not found). So long as the map
is not const, you can modify the element pointed to by the iterator:
std::map<char, int> m;
m.insert(std::make_pair('c', 0)); // c is for cookie
std::map<char, int>::iterator it = m.find('c');
if (it != m.end())
it->second = 42;
The default parser can parse your input. So you don't need a custom formatter and
String dateTime = "2012-02-22T02:06:58.147Z";
ZonedDateTime d = ZonedDateTime.parse(dateTime);
works as expected.
My fix for this on Mountain Lion was: -
npm install -g grunt-cli
Saw it on http://gruntjs.com/getting-started
I didn't use it myself but heard of a simple tool (not a text editor) for this so it is definitely possible without setting up a programming environment (by installing octave or python).
A quick search hints that it was possible with total commander. (A lightweight tool with an easy point and click interface)
I would not be surprised if this still works, but I can't guarantee it.
Don't forget about spaces:
source=""
samples=("")
if [ $1 = "country" ]; then
source="country"
samples="US Canada Mexico..."
else
echo "try again"
fi
Linux: who am i | awk '{print $5}' | sed 's/[()]//g'
AIX: who am i | awk '{print $6}' | sed 's/[()]//g'
Answer for Elasticsearch inside Docker:
Just stop the docker container. It seems to stop gracefully because it logs:
[INFO ][o.e.n.Node ] [elastic] stopping ...
I had a similar problem:
module cv2 has no attribute "cv2.TrackerCSRT_create"
My Python version is 3.8.0 under Windows 10. The problem was the opencv version installation.
So I fixed this way (cmd prompt with administrator privileges):
pip uninstall opencv-python
pip install opencv-contrib-python
Anyway you can read the following guide:
Go to File > Sync Project with Gradles Files.
To complete @cpu-100 answer,
in case you don't want to enable/use web interface, you can create a new credentials using command line like below and use it in your code to connect to RabbitMQ.
$ rabbitmqctl add_user YOUR_USERNAME YOUR_PASSWORD
$ rabbitmqctl set_user_tags YOUR_USERNAME administrator
$ rabbitmqctl set_permissions -p / YOUR_USERNAME ".*" ".*" ".*"
Your Print method likely needs to wait for the continuation to finish (ContinueWith returns a task which you can wait on). Otherwise the second ReadAsStringAsync finishes, the method returns (before result is assigned in the continuation). Same problem exists in your send method. Both need to wait on the continuation to consistently get the results you want. Similar to below
private static string Send(int id)
{
Task<HttpResponseMessage> responseTask = client.GetAsync("aaaaa");
string result = string.Empty;
Task continuation = responseTask.ContinueWith(x => result = Print(x));
continuation.Wait();
return result;
}
private static string Print(Task<HttpResponseMessage> httpTask)
{
Task<string> task = httpTask.Result.Content.ReadAsStringAsync();
string result = string.Empty;
Task continuation = task.ContinueWith(t =>
{
Console.WriteLine("Result: " + t.Result);
result = t.Result;
});
continuation.Wait();
return result;
}
Info regarding .NET / C#:
Decimal digit character: \d \d matches any decimal digit. It is equivalent to the \p{Nd} regular expression pattern, which includes the standard decimal digits 0-9 as well as the decimal digits of a number of other character sets.
If ECMAScript-compliant behavior is specified, \d is equivalent to [0-9]. For information on ECMAScript regular expressions, see the "ECMAScript Matching Behavior" section in Regular Expression Options.
As part of the solution that Larry K suggested, registering your own protocol might be a possible solution. The web page could contain a simple link to download and install the application - which would then register its own protocol in the Windows registry.
The web page would then contain links with parameters that would result in the registerd program being opened and any parameters specified in the link being passed to it. There's a good description of how to do this on MSDN
If you have a menu then changing ShortcutKeys
property of the ToolStripMenuItem
should do the trick.
If not, you could create one and set its visible
property to false.
You have to use show()
methode when you done all initialisations in your code in order to see the complet version of plot:
import matplotlib.pyplot as plt
plt.plot(x, y)
................
................
plot.show()
Python does support "method overloading" as you present it. In fact, what you just describe is trivial to implement in Python, in so many different ways, but I would go with:
class Character(object):
# your character __init__ and other methods go here
def add_bullet(self, sprite=default, start=default,
direction=default, speed=default, accel=default,
curve=default):
# do stuff with your arguments
In the above code, default
is a plausible default value for those arguments, or None
. You can then call the method with only the arguments you are interested in, and Python will use the default values.
You could also do something like this:
class Character(object):
# your character __init__ and other methods go here
def add_bullet(self, **kwargs):
# here you can unpack kwargs as (key, values) and
# do stuff with them, and use some global dictionary
# to provide default values and ensure that ``key``
# is a valid argument...
# do stuff with your arguments
Another alternative is to directly hook the desired function directly to the class or instance:
def some_implementation(self, arg1, arg2, arg3):
# implementation
my_class.add_bullet = some_implementation_of_add_bullet
Yet another way is to use an abstract factory pattern:
class Character(object):
def __init__(self, bfactory, *args, **kwargs):
self.bfactory = bfactory
def add_bullet(self):
sprite = self.bfactory.sprite()
speed = self.bfactory.speed()
# do stuff with your sprite and speed
class pretty_and_fast_factory(object):
def sprite(self):
return pretty_sprite
def speed(self):
return 10000000000.0
my_character = Character(pretty_and_fast_factory(), a1, a2, kw1=v1, kw2=v2)
my_character.add_bullet() # uses pretty_and_fast_factory
# now, if you have another factory called "ugly_and_slow_factory"
# you can change it at runtime in python by issuing
my_character.bfactory = ugly_and_slow_factory()
# In the last example you can see abstract factory and "method
# overloading" (as you call it) in action
Try starting with the Percona wizard and comparing their recommendations against your current settings one by one. Don't worry there aren't as many applicable settings as you might think.
https://tools.percona.com/wizard
Update circa 2020: Sorry, this tool reached it's end of life: https://www.percona.com/blog/2019/04/22/end-of-life-query-analyzer-and-mysql-configuration-generator/
Everyone points to key_buffer_size
first which you have addressed. With 96GB memory I'd be wary of any tiny default value (likely to be only 96M!).
If the command that you are trying to execute fails, it would write the output onto the error stream and would then be printed out to the console.
To avoid it, you must redirect the error stream:
result=$(ls -l something_that_does_not_exist 2>&1)
There is an indexOf
method that all arrays have (except Internet Explorer 8 and below) that will return the index of an element in the array, or -1 if it's not in the array:
if (yourArray.indexOf("someString") > -1) {
//In the array!
} else {
//Not in the array
}
If you need to support old IE browsers, you can polyfill this method using the code in the MDN article.
just type the below command in terminal
ps -ef |grep 'catalina'
copy the value of process id then type the following command and paste process id
kill -9 processid
Since Spring 3.0 you also can throw an Exception declared with @ResponseStatus
annotation:
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
...
}
@Controller
public class SomeController {
@RequestMapping.....
public void handleCall() {
if (isFound()) {
// whatever
}
else {
throw new ResourceNotFoundException();
}
}
}
Place the below lines in your <EditText>
:
android:digits="0123456789"
android:inputType="phone"
MVW stands for Model-View-Whatever.
For completeness, here are all the acronyms mentioned:
MVC - Model-View-Controller
MVP - Model-View-Presenter
MVVM - Model-View-ViewModel
MVW / MV* / MVx - Model-View-Whatever
And some more:
HMVC - Hierarchical Model-View-Controller
MMV - Multiuse Model View
MVA - Model-View-Adapter
MVI - Model-View-Intent
Another way;
alert( "JanFebMarAprMayJunJulAugSepOctNovDec".indexOf("Jun") / 3 + 1 );
There is contextlib.redirect_stdout()
function in Python 3.4+:
from contextlib import redirect_stdout
with open('help.txt', 'w') as f:
with redirect_stdout(f):
print('it now prints to `help.text`')
It is similar to:
import sys
from contextlib import contextmanager
@contextmanager
def redirect_stdout(new_target):
old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
try:
yield new_target # run some code with the replaced stdout
finally:
sys.stdout = old_target # restore to the previous value
that can be used on earlier Python versions. The latter version is not reusable. It can be made one if desired.
It doesn't redirect the stdout at the file descriptors level e.g.:
import os
from contextlib import redirect_stdout
stdout_fd = sys.stdout.fileno()
with open('output.txt', 'w') as f, redirect_stdout(f):
print('redirected to a file')
os.write(stdout_fd, b'not redirected')
os.system('echo this also is not redirected')
b'not redirected'
and 'echo this also is not redirected'
are not redirected to the output.txt
file.
To redirect at the file descriptor level, os.dup2()
could be used:
import os
import sys
from contextlib import contextmanager
def fileno(file_or_fd):
fd = getattr(file_or_fd, 'fileno', lambda: file_or_fd)()
if not isinstance(fd, int):
raise ValueError("Expected a file (`.fileno()`) or a file descriptor")
return fd
@contextmanager
def stdout_redirected(to=os.devnull, stdout=None):
if stdout is None:
stdout = sys.stdout
stdout_fd = fileno(stdout)
# copy stdout_fd before it is overwritten
#NOTE: `copied` is inheritable on Windows when duplicating a standard stream
with os.fdopen(os.dup(stdout_fd), 'wb') as copied:
stdout.flush() # flush library buffers that dup2 knows nothing about
try:
os.dup2(fileno(to), stdout_fd) # $ exec >&to
except ValueError: # filename
with open(to, 'wb') as to_file:
os.dup2(to_file.fileno(), stdout_fd) # $ exec > to
try:
yield stdout # allow code to be run with the redirected stdout
finally:
# restore stdout to its previous value
#NOTE: dup2 makes stdout_fd inheritable unconditionally
stdout.flush()
os.dup2(copied.fileno(), stdout_fd) # $ exec >&copied
The same example works now if stdout_redirected()
is used instead of redirect_stdout()
:
import os
import sys
stdout_fd = sys.stdout.fileno()
with open('output.txt', 'w') as f, stdout_redirected(f):
print('redirected to a file')
os.write(stdout_fd, b'it is redirected now\n')
os.system('echo this is also redirected')
print('this is goes back to stdout')
The output that previously was printed on stdout now goes to output.txt
as long as stdout_redirected()
context manager is active.
Note: stdout.flush()
does not flush
C stdio buffers on Python 3 where I/O is implemented directly on read()
/write()
system calls. To flush all open C stdio output streams, you could call libc.fflush(None)
explicitly if some C extension uses stdio-based I/O:
try:
import ctypes
from ctypes.util import find_library
except ImportError:
libc = None
else:
try:
libc = ctypes.cdll.msvcrt # Windows
except OSError:
libc = ctypes.cdll.LoadLibrary(find_library('c'))
def flush(stream):
try:
libc.fflush(None)
stream.flush()
except (AttributeError, ValueError, IOError):
pass # unsupported
You could use stdout
parameter to redirect other streams, not only sys.stdout
e.g., to merge sys.stderr
and sys.stdout
:
def merged_stderr_stdout(): # $ exec 2>&1
return stdout_redirected(to=sys.stdout, stdout=sys.stderr)
Example:
from __future__ import print_function
import sys
with merged_stderr_stdout():
print('this is printed on stdout')
print('this is also printed on stdout', file=sys.stderr)
Note: stdout_redirected()
mixes buffered I/O (sys.stdout
usually) and unbuffered I/O (operations on file descriptors directly). Beware, there could be buffering issues.
To answer, your edit: you could use python-daemon
to daemonize your script and use logging
module (as @erikb85 suggested) instead of print
statements and merely redirecting stdout for your long-running Python script that you run using nohup
now.
how can you be pythonic without lambdas! .. not to be taken seriously .. but this way works too:
orig_array = [ ..... ]
test_array = [ ... ]
filter(lambda x:x in test_array, orig_array) == test_array
leave out the end part if you want to test if any of the values are in the array:
filter(lambda x:x in test_array, orig_array)
I found this brilliant solution here, it uses the simple logic NAN!=NAN. https://www.codespeedy.com/check-if-a-given-string-is-nan-in-python/
Using above example you can simply do the following. This should work on different type of objects as it simply utilize the fact that NAN is not equal to NAN.
import numpy as np
s = pd.Series(['apple', np.nan, 'banana'])
s.apply(lambda x: x!=x)
out[252]
0 False
1 True
2 False
dtype: bool
List.toArray()
necessarily returns an array of Object. To get an array of String, you need to use the casting syntax:
String[] strarray = strlist.toArray(new String[0]);
See the javadoc for java.util.List for more.
Why not downloading the python installer here ? It make the work for you when you check the path installation
"How do I create an initial database ?"
You created a database when you installed XE. At some point the installation process prompted you to enter a password for the SYSTEM account. Use that to connect to the XE database using the SQL commandline on the application menu.
The XE documentation is online and pretty helpful. Find it here.
It's worth mentioning that 11g XE has several limitations, one of which is only one database per server. So using the pre-installed database is the sensible option.
We should access the website using the name given in the certificate.
This is works. Kind of.
public static Object[] toArray(List<?> a) {
Object[] arr = new Object[a.size()];
for (int i = 0; i < a.size(); i++)
arr[i] = a.get(i);
return arr;
}
Then the main method.
public static void main(String[] args) {
List<String> list = new ArrayList<String>() {{
add("hello");
add("world");
}};
Object[] arr = toArray(list);
System.out.println(arr[0]);
}
Unfortunately, there's no way to do that with CSS.
It's not very difficult with JavaScript though:
// JavaScript code:
document.getElementsByClassName("active")[0].parentNode;
// jQuery code:
$('.active').parent().get(0); // This would be the <a>'s parent <li>.
Simple INNER JOIN VIEW code....
CREATE VIEW room_view
AS SELECT a.*,b.*
FROM j4_booking a INNER JOIN j4_scheduling b
on a.room_id = b.room_id;
In regards to the answer provided by Fuzzy:
I actually had to do something slightly different.
Project -> Properties -> C/C++ Build -> Settings -> GCC C Linker -> Libraries
Click the little green add icon, type m and hit ok. Everything in this window automatically has -l applied to it since it is a library.
it's a pure PHP setting. The alternative is to increase the execution time limit only for specific php scripts, by inserting on top of that php file, the following:
ini_set('max_execution_time', 180); //3 minutes
There are at least three different types of logging:
The logging BEFORE the program is executed, which only logs IF the cronjob TRIED to execute the command. That one is located in /var/log/syslog, as already mentioned by @Matthew Lock.
The logging of errors AFTER the program tried to execute, which can be sent to an email or to a file, as mentioned by @Spliffster. I prefer logging to a file, because with email THEN you have a NEW source of problems, and its checking if email sending and reception is working perfectly. Sometimes it is, sometimes it's not. For example, in a simple common desktop machine in which you are not interested in configuring an smtp, sometimes you will prefer logging to a file:
* * * * COMMAND_ABSOLUTE_PATH > /ABSOLUTE_PATH_TO_LOG 2>&1
There are some common sources of problems with cronjobs: * The ABSOLUTE PATH of the binary to be executed. When you run it from your shell, it might work, but the cron process seems to use another environment, and hence it doesn't always find binaries if you don't use the absolute path. * The LIBRARIES used by a binary. It's more or less the same previous point, but make sure that, if simply putting the NAME of the command, is referring to exactly the binary which uses the very same library, or better, check if the binary you are referring with the absolute path is the very same you refer when you use the console directly. The binaries can be found using the locate command, for example:
$locate python
Be sure that the binary you will refer, is the very same the binary you are calling in your shell, or simply test again in your shell using the absolute path that you plan to put in the cronjob.
If you just need sampling without replacement:
>>> import random
>>> random.sample(range(1, 100), 3)
[77, 52, 45]
random.sample takes a population and a sample size k
and returns k
random members of the population.
If you have to control for the case where k
is larger than len(population)
, you need to be prepared to catch a ValueError
:
>>> try:
... random.sample(range(1, 2), 3)
... except ValueError:
... print('Sample size exceeded population size.')
...
Sample size exceeded population size
This answer is counting that the second parameter is useless when calling removeAttr! (as it was when this answer was posted) Do not use this otherwise!
Can't beat RienNeVaPlus's clean answer, but it does the job as well, it's basically a more compressed way to do the ternary operation:
$('.list-sort')[$('.list-sort').hasAttr('colspan') ?
'removeAttr' : 'attr']('colspan', 6);
an extra variable can be used in these cases, when you need to use the reference more than once:
var $listSort = $('.list-sort');
$listSort[$listSort.hasAttr('colspan') ? 'removeAttr' : 'attr']('colspan', 6);
As previous people have answered npm --save ../location-of-your-packages-root-directory
.
The ../location-of-your-packages-root-directory
however must have two things in order for it to work.
1) package.json
in that directory pointed towards
2) main
property in the package.json
must be set and working i.g. "main": "src/index.js",
if the entry file for ../location-of-your-packages-root-directory
is ../location-of-your-packages-root-directory/src/index.js
I faced the same issue and fixed it by making a small change in the httpd.conf
file which can be obtained by clicking the config button along with the Apache option.
The change I made was to replace listen 80 with listen 8080.
I did something really stupid (and maybe you did too).
I was trying to call System.Web.Mvc.Html.Partial("<Partial Page>")
System.Web.Mvc.Html is a namespace and not a class and I didn't read my error message so well, so I interpreted my error as the class Html
does not exist in the namespace System.Web.Mvc and that's how I ended up here (stupid I know).
All I needed to do was add a using statement @using System.Web.Mvc.Html
to my page and then @Html.Partial
worked as expected.
My solution is add css "display: inline-block" to img tag.
<img style="display: inline-block; height: 30px; margin-top: -5px">
DEMO: jsfiddle
The abstract.xml.gz
dump sounds like the one you want.
Drifting a bit, but it would be relatively easy to autofill the US City/State or CA City/Provence when the user enters her postal code using a lookup table.
Here's how you could do it if you could force people to bend to your will:
User enters: postal (zip) code
You fill: state, city (province, for Canada)
User starts to enter: streetname
You: autofill
You display: a range of allowed address numbers
User: enters the number
Done.
Here's how it is natural for people to do it:
User enters: address number
You: do nothing
User starts to enter: street name
You: autofill, drawing from a massive list of every street in the country
User enters: city
You: autofill
User enters: state/provence
You: is it worth autofilling a few chars?
You: autofill postal (zip) code, if you can (because some codes straddle cities).
Now you know why people charge $$$ to do this. :)
For the street address, consider there are two parts: numeric and streetname. If you have the zip code, then you can narrow down the available streets, but most people enter the numeric part first, which is backwa
I ran into this and added the following to my datetime property:
[Column(TypeName = "datetime2")]
public DateTime? NullableDateTimePropUtc { get; set; }
#firstDropContainer{
float: left;
width: 40%;
margin-right: 1.5em;
}
#secondDropContainer{
float: left;
width: 40%;
margin-bottom: 1em;
}
<div id="mainDrop">
<div id="firstDropContainer"></div>
<div id="secondDropContainer"></div>
</div>
Note: Adjust the width of the divs based on your req.
os.pardir
is a better way for ../
and more readable.
import os
print os.path.abspath(os.path.join(given_path, os.pardir))
This will return the parent path of the given_path
If you use the rule :focus { outline: none; }
to remove outlines, the link or control will be focusable but with no indication of focus for keyboard users. Methods to remove it such with JS like onfocus="blur()"
are even worse and will result in keyboard users being unable to interact with the control.
The hacks you can use, that are sort of OK, includes adding :focus { outline: none; }
rules when users interacts with the mouse and remove them again if keyboard interaction is detected. Lindsay Evans has made a lib for this: https://github.com/lindsayevans/outline.js
But i would prefer to setting a class on the html or body tag. And have control in the CSS file of when to use this.
For example (inline event handlers is for demonstration purposes only):
<html>
<head>
<style>
a:focus, button:focus {
outline: 3px solid #000;
}
.no-focus a, .no-focus button {
outline: none;
}
</style>
</head>
<body id="thebody"
onmousedown="document.getElementById('thebody').classList.add('no-focus');"
onkeydown="document.getElementById('thebody').classList.remove('no-focus');">
<p>This her is <a href="#">a link</a></p>
<button>Click me</button>
</body>
</html>
I did put togheter a Pen: http://codepen.io/snobojohan/pen/RWXXmp
But beware there are performance issues. This forces repaint every time the user switches between mouse and keyboard. More about Avoiding Unnecessary Paints http://www.html5rocks.com/en/tutorials/speed/unnecessary-paints/
I'm running Git version 2.6.1.windows.1 on Windows 10, so I needed a slight modification to Nevik's answer (tilde instead of caret):
git diff COMMIT~ COMMIT
Another option is to quote the caret:
git diff "COMMIT^" COMMIT
At first, the problem is because you did't put any parameter for mysqli_error. I can see that it has been solved based on the post here. Most probably, the next problem is cause by wrong file path for the included file.. .
Are you sure this code
$myConnection = mysqli_connect("$db_host","$db_username","$db_pass","$db_name") or die ("could not connect to mysql");
is in the 'scripts' folder and your main code file is on the same level as the script folder?
While googling I find a good explanation about usage and compression of SVG and Canvas at http://teropa.info/blog/2016/12/12/graphics-in-angular-2.html
Hope it helps:
- SVG, like HTML, uses retained rendering: When we want to draw a rectangle on the screen, we declaratively use a element in our DOM. The browser will then draw a rectangle, but it will also create an in-memory SVGRectElement object that represents the rectangle. This object is something that sticks around for us to manipulate – it is retained. We can assign different positions and sizes to it over time. We can also attach event listeners to make it interactive.
- Canvas uses immediate rendering: When we draw a rectangle, the browser immediately renders a rectangle on the screen, but there is never going to be any "rectangle object" that represents it. There's just a bunch of pixels in the canvas buffer. We can't move the rectangle. We can only draw another rectangle. We can't respond to clicks or other events on the rectangle. We can only respond to events on the whole canvas.
So canvas is a more low-level, restrictive API than SVG. But there's a flipside to that, which is that with canvas you can do more with the same amount of resources. Because the browser does not have to create and maintain the in-memory object graph of all the things we have drawn, it needs less memory and computation resources to draw the same visual scene. If you have a very large and complex visualization to draw, Canvas may be your ticket.
This seems to me the most simple and readable way of doing so:
let options = {name:"James"}
const default_options = {name:"John", surname:"Doe"}
options = Object.assign({}, default_options, options)
Windows 7 has the arp command within it. arp -a should show you the static and dynamic type interfaces connected to your system.
Your FMAT.h requires a definition of std::string in order to complete the definition of class FMAT. In FMAT.cpp, you've done this by #include <string>
before #include "FMAT.h"
. You haven't done that in your main file.
Your attempt to forward declare string
was incorrect on two levels. First you need a fully qualified name, std::string
. Second this works only for pointers and references, not for variables of the declared type; a forward declaration doesn't give the compiler enough information about what to embed in the class you're defining.
I got the same error and the cause was the directory:
U:.....WEB\WebRoot\WEB-INF\classes\com\yourcompany\cc\dao
was corrupted(directory or file not readable or damaged).. solved with
This seems to be the cleanest way to do
if (foo === 1) {
} else if (bar === 99) {
} else if (foo === 2) {
} else {
}
in the template:
<ng-container *ngIf="foo === 1; else elseif1">foo === 1</ng-container>
<ng-template #elseif1>
<ng-container *ngIf="bar === 99; else elseif2">bar === 99</ng-container>
</ng-template>
<ng-template #elseif2>
<ng-container *ngIf="foo === 2; else else1">foo === 2</ng-container>
</ng-template>
<ng-template #else1>else</ng-template>
Notice that it works like a proper else if
statement should when the conditions involve different variables (only 1 case is true at a time). Some of the other answers don't work right in such a case.
aside: gosh angular, that's some really ugly else if
template code...
The best way to skip the first item(s) is:
from itertools import islice
for car in islice(cars, 1, None):
# do something
islice in this case is invoked with a start-point of 1, and an end point of None, signifying the end of the iterator.
To be able to skip items from the end of an iterable, you need to know its length (always possible for a list, but not necessarily for everything you can iterate on). for example, islice(cars, 1, len(cars)-1) will skip the first and last items in the cars list.
Why not put some junk in your .htaccess file and try to reload apache. If apache fails to start you know its working. Remove the junk then reload apache if it loads congrats you configured .htaccess correctly.
<script src="jquery.min.js"></script>
<table border="1" id="ReportTable" class="myClass">
<tr bgcolor="#CCC">
<td width="100">xxxxx</td>
<td width="700">xxxxxx</td>
<td width="170">xxxxxx</td>
<td width="30">xxxxxx</td>
</tr>
<tr bgcolor="#FFFFFF">
<td><?php
$date = date_create($row_Recordset3['fecha']);
echo date_format($date, 'd-m-Y');
?></td>
<td><?php echo $row_Recordset3['descripcion']; ?></td>
<td><?php echo $row_Recordset3['producto']; ?></td>
<td><img src="borrar.png" width="14" height="14" class="clickable" onClick="eliminarSeguimiento(<?php echo $row_Recordset3['idSeguimiento']; ?>)" title="borrar"></td>
</tr>
</table>
<input type="hidden" id="datatodisplay" name="datatodisplay">
<input type="submit" value="Export to Excel">
exporttable.php
<?php
header('Content-Type: application/force-download');
header('Content-disposition: attachment; filename=export.xls');
// Fix for crappy IE bug in download.
header("Pragma: ");
header("Cache-Control: ");
echo $_REQUEST['datatodisplay'];
?>
you can use linq :) using :
System.linq;
var newList = people.OrderBy(x=>x.Name).ToList();
To help newbies navigate through the manual fog, it might be helpful to see the [[ ... ]]
notation as a collapsing function - in other words, it is when you just want to 'get the data' from a named vector, list or data frame. It is good to do this if you want to use data from these objects for calculations. These simple examples will illustrate.
(x <- c(x=1, y=2)); x[1]; x[[1]]
(x <- list(x=1, y=2, z=3)); x[1]; x[[1]]
(x <- data.frame(x=1, y=2, z=3)); x[1]; x[[1]]
So from the third example:
> 2 * x[1]
x
1 2
> 2 * x[[1]]
[1] 2
from http://www.vmware.com/products/player/faqs.html:
How does VMware Player compare to VMware Workstation? VMware Player enables you to quickly and easily create and run virtual machines. However, VMware Player lacks many powerful features, remote connections to vSphere, drag and drop upload to vSphere, multiple Snapshots and Clones, and much more.
Not being able to revert snapshots it's a big no for me.
ALTER TABLE MyTable MODIFY Col3 varchar(20) NULL;
git reset
and git clean
can be overkill in some situations (and be a huge waste of time).
If you simply have a message like "The following untracked files would be overwritten..." and you want the remote/origin/upstream to overwrite those conflicting untracked files, then git checkout -f <branch>
is the best option.
If you're like me, your other option was to clean and perform a --hard reset
then recompile your project.
Since the request
module that other answers use has been deprecated, may I suggest switching to node-fetch
:
const fetch = require("node-fetch")
const url = "https://www.googleapis.com/urlshortener/v1/url"
const payload = { longUrl: "http://www.google.com/" }
const res = await fetch(url, {
method: "post",
body: JSON.stringify(payload),
headers: { "Content-Type": "application/json" },
})
const { id } = await res.json()
The absolute easiest method if all you want to run is a simple script, (or anything) is if you have a gui to use system > preferences then startup apps.
just browse to the script you want and there you go. (make script executable)
if you have some codes in your Page_Load method and you don't want that those execute after button click use if(!IsPostBack) on Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// put codes here
}
}
asp:Button is a server control and for send request to server and get response need page refresh. You can use JQuery and Ajax to prevent full Page refresh
As Dave Webb mentions, the Android Developer Blog has an article that covers this. Their preferred solution is to track app installs rather than devices, and that will work well for most use cases. The blog post will show you the necessary code to make that work, and I recommend you check it out.
However, the blog post goes on to discuss solutions if you need a device identifier rather than an app installation identifier. I spoke with someone at Google to get some additional clarification on a few items in the event that you need to do so. Here's what I discovered about device identifiers that's NOT mentioned in the aforementioned blog post:
Based on Google's recommendations, I implemented a class that will generate a unique UUID for each device, using ANDROID_ID as the seed where appropriate, falling back on TelephonyManager.getDeviceId() as necessary, and if that fails, resorting to a randomly generated unique UUID that is persisted across app restarts (but not app re-installations).
Note that for devices that have to fallback on the device ID, the unique ID WILL persist across factory resets. This is something to be aware of. If you need to ensure that a factory reset will reset your unique ID, you may want to consider falling back directly to the random UUID instead of the device ID.
Again, this code is for a device ID, not an app installation ID. For most situations, an app installation ID is probably what you're looking for. But if you do need a device ID, then the following code will probably work for you.
import android.content.Context;
import android.content.SharedPreferences;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import java.io.UnsupportedEncodingException;
import java.util.UUID;
public class DeviceUuidFactory {
protected static final String PREFS_FILE = "device_id.xml";
protected static final String PREFS_DEVICE_ID = "device_id";
protected static UUID uuid;
public DeviceUuidFactory(Context context) {
if( uuid ==null ) {
synchronized (DeviceUuidFactory.class) {
if( uuid == null) {
final SharedPreferences prefs = context.getSharedPreferences( PREFS_FILE, 0);
final String id = prefs.getString(PREFS_DEVICE_ID, null );
if (id != null) {
// Use the ids previously computed and stored in the prefs file
uuid = UUID.fromString(id);
} else {
final String androidId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
// Use the Android ID unless it's broken, in which case fallback on deviceId,
// unless it's not available, then fallback on a random number which we store
// to a prefs file
try {
if (!"9774d56d682e549c".equals(androidId)) {
uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8"));
} else {
final String deviceId = ((TelephonyManager) context.getSystemService( Context.TELEPHONY_SERVICE )).getDeviceId();
uuid = deviceId!=null ? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8")) : UUID.randomUUID();
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
// Write the value out to the prefs file
prefs.edit().putString(PREFS_DEVICE_ID, uuid.toString() ).commit();
}
}
}
}
}
/**
* Returns a unique UUID for the current android device. As with all UUIDs, this unique ID is "very highly likely"
* to be unique across all Android devices. Much more so than ANDROID_ID is.
*
* The UUID is generated by using ANDROID_ID as the base key if appropriate, falling back on
* TelephonyManager.getDeviceID() if ANDROID_ID is known to be incorrect, and finally falling back
* on a random UUID that's persisted to SharedPreferences if getDeviceID() does not return a
* usable value.
*
* In some rare circumstances, this ID may change. In particular, if the device is factory reset a new device ID
* may be generated. In addition, if a user upgrades their phone from certain buggy implementations of Android 2.2
* to a newer, non-buggy version of Android, the device ID may change. Or, if a user uninstalls your app on
* a device that has neither a proper Android ID nor a Device ID, this ID may change on reinstallation.
*
* Note that if the code falls back on using TelephonyManager.getDeviceId(), the resulting ID will NOT
* change after a factory reset. Something to be aware of.
*
* Works around a bug in Android 2.2 for many devices when using ANDROID_ID directly.
*
* @see http://code.google.com/p/android/issues/detail?id=10603
*
* @return a UUID that may be used to uniquely identify your device for most purposes.
*/
public UUID getDeviceUuid() {
return uuid;
}
}
If you have access to the iframed page you could use something like easyXDM to make function calls in the iframe and return the data.
If you don't have access to the iframed page you will have to use a server side solution. With PHP you could do something quick and dirty like:
<?php echo file_get_contents('http://url_of_the_iframe/content.php'); ?>
There are several issues:
getElementsByClassName()
.Example (untested):
<script type="text/javascript">
function hideTd(className){
var elements = document.getElementsByClassName(className);
for(var i = 0, length = elements.length; i < length; i++) {
if( elements[i].textContent == ''){
elements[i].style.display = 'none';
}
}
}
</script>
</head>
<body onload="hideTd('td');">
<table border="1">
<tr>
<td class="td">not empty</td>
</tr>
<tr>
<td class="td"></td>
</tr>
<tr>
<td class="td"></td>
</tr>
</table>
</body>
Note that getElementsByClassName()
is not available up to and including IE8.
Update:
Alternatively you can give the table an ID and use:
var elements = document.getElementById('tableID').getElementsByTagName('td');
to get all td
elements.
To hide the parent row, use the parentNode
property of the element:
elements[i].parentNode.style.display = "none";
JScript is Microsoft's equivalent of JavaScript.
Java is an Oracle product and used to be a Sun product.
Oracle bought Sun.
JavaScript + Microsoft = JScript
Key elements of a zero-downtime migration is:
CONFIG SET slave-read-only no
)In short:
Additionally redis have options which allows to disable a source redis to accept writes right after detaching a target:
min-slaves-to-write
min-slaves-max-lag
This topic covered by
Very good explanation from RedisLabs team https://redislabs.com/blog/real-time-synchronization-tool-for-redis-migration (use web.archive.org)
And even their interactive tool for migrate: https://github.com/RedisLabs/redis-migrate
Short answer: You can't.
You will have to use border-image
property and a few images.
You could use a try...catch block like the following:
var status = 'Variable exists'
try {
myVar
} catch (ReferenceError) {
status = 'Variable does not exist'
}
console.log(status)
_x000D_
A disadvantage is you cannot put it in a function as it would throw a ReferenceError
function variableExists(x) {
var status = true
try {
x
} catch (ReferenceError) {
status = false
}
return status
}
console.log(variableExists(x))
_x000D_
Edit:
If you were working in front-end Javascript and you needed to check if a variable was not initialized (var x = undefined
would count as not initialized), you could use:
function globalVariableExists(variable) {
if (window[variable] != undefined) {
return true
}
return false
}
var x = undefined
console.log(globalVariableExists("x"))
console.log(globalVariableExists("y"))
var z = 123
console.log(globalVariableExists("z"))
_x000D_
Edit 2:
If you needed to check if a variable existed in the current scope, you could simply pass this
to the function, along with the name of the variable contained in a string:
function variableExists(variable, thisObj) {
if (thisObj[variable] !== undefined) {
return true
}
return false
}
class someClass {
constructor(name) {
this.x = 99
this.y = 99
this.z = 99
this.v = 99
console.log(variableExists(name, this))
}
}
new someClass('x')
new someClass('y')
new someClass('z')
new someClass('v')
new someClass('doesNotExist')
_x000D_
you can using fxFlex
from "@angular/flex-layout" in th
and td
like this:
<ng-container matColumnDef="value">
<th mat-header-cell fxFlex="15%" *matHeaderCellDef>Value</th>
<td mat-cell *matCellDef="let element" fxFlex="15%" fxLayoutAlign="start center">
{{'value'}}
</td>
</th>
</ng-container>
First thing first, button()
is a jQuery ui function to create a button widget which has nothing to do with jQuery core, it just styles the button.
So if you want to use the widget add jQuery ui's javascript and CSS files or alternatively remove it, like this:
$("#filter").click(function(){
alert('clicked!');
});
Another thing that might have caused you the problem is if you didn't wait for the input to be rendered and wrote the code before the input. jQuery has the ready function, or it's alias $(func)
which execute the callback once the DOM is ready.
Usage:
$(function(){
$("#filter").click(function(){
alert('clicked!');
});
});
So even if the order is this it will work:
$(function(){
$("#filter").click(function(){
alert('clicked!');
});
});
<input type="button" id="filter" name="filter" value="Filter" />
None/Null is a data type of the class NoneType in pyspark/python so, Below will not work as you are trying to compare NoneType object with string object
Wrong way of filretingdf[df.dt_mvmt == None].count() 0 df[df.dt_mvmt != None].count() 0
df=df.where(col("dt_mvmt").isNotNull()) returns all records with dt_mvmt as None/Null
use 'any'
dict = {}
if any(dict) :
# true
# dictionary is not empty
else :
# false
# dictionary is empty
On Excel for Mac 2011, the newline had to be a \r
instead of an \n
So
"\"first line\rsecond line\""
would show up as a cell with 2 lines
You can create an extension for UIView to access these values in the design editor
extension UIView{
@IBInspectable var shadowOffset: CGSize{
get{
return self.layer.shadowOffset
}
set{
self.layer.shadowOffset = newValue
}
}
@IBInspectable var shadowColor: UIColor{
get{
return UIColor(cgColor: self.layer.shadowColor!)
}
set{
self.layer.shadowColor = newValue.cgColor
}
}
@IBInspectable var shadowRadius: CGFloat{
get{
return self.layer.shadowRadius
}
set{
self.layer.shadowRadius = newValue
}
}
@IBInspectable var shadowOpacity: Float{
get{
return self.layer.shadowOpacity
}
set{
self.layer.shadowOpacity = newValue
}
}
}
The issue in my case was I included a constructor taking parameters but not an empty constructor with the Inject annotation, like so.
@Inject public VisitorBean() {}
I just tested it without any constructor and this appears to work also.
For a more modern solution, and if there is no need to support legacy browsers, you can do this:
.frame {_x000D_
display: flex;_x000D_
/**_x000D_
Uncomment 'justify-content' below to center horizontally._x000D_
? Read below for a better way to center vertically and horizontally._x000D_
**/_x000D_
_x000D_
/* justify-content: center; */_x000D_
align-items: center;_x000D_
}_x000D_
_x000D_
img {_x000D_
height: auto;_x000D_
_x000D_
/**_x000D_
? To center this image both vertically and horizontally,_x000D_
in the .frame rule above comment the 'justify-content'_x000D_
and 'align-items' declarations,_x000D_
then uncomment 'margin: auto;' below._x000D_
**/_x000D_
_x000D_
/* margin: auto; */_x000D_
}_x000D_
_x000D_
/* Styling stuff not needed for demo */_x000D_
.frame {_x000D_
max-width: 900px;_x000D_
height: 200px;_x000D_
margin: auto;_x000D_
background: #222;_x000D_
}_x000D_
p {_x000D_
max-width: 900px;_x000D_
margin: 20px auto 0;_x000D_
}_x000D_
img {_x000D_
width: 150px;_x000D_
}
_x000D_
<div class="frame">_x000D_
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/9988/hand-pointing.png">_x000D_
</div>
_x000D_
Here's a Pen: http://codepen.io/ricardozea/pen/aa0ee8e6021087b6e2460664a0fa3f3e
Make sure you don't have any undefined classpath variables (like M2_REPO).
This works fine for Swift 5 in case you want to fit your TextView once user write text on the fly.
Just implement UITextViewDelegate with:
func textViewDidChange(_ textView: UITextView) {
let newSize = textView.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))
textView.frame.size = CGSize(width: newSize.width, height: newSize.height)
}
Why not just use something based on a timestamp..?
Use the which function:
A <- c('a','a','b','b','b')
B <- c(1,0,1,1,0)
d <- data.frame(A, B)
r <- with(d, which(B==0, arr.ind=TRUE))
newd <- d[-r, ]
This blog post explains very well:
(just replace 9.X by your version. e.g: 9.6)
A. If installed PostgreSQL with homebrew, enter brew uninstall postgresql
B. If you used the EnterpriseDB installer, follow the following step.
Run the uninstaller on terminal window: sudo /Library/PostgreSQL/9.X/uninstall-postgresql.app/Contents/MacOS/installbuilder.sh
C. If installed with Postgres Installer, do:
open /Library/PostgreSQL/9.X/uninstall-postgresql.app
Remove the PostgreSQL and data folders. The Wizard will notify you that these were not removed.
sudo rm -rf /Library/PostgreSQL
Remove the ini file:
sudo rm /etc/postgres-reg.ini
Remove the PostgreSQL user using System Preferences -> Users & Groups.
Unlock the settings panel by clicking on the padlock and entering your password.
Select the PostgreSQL user and click on the minus button.
Restore your shared memory settings: sudo rm /etc/sysctl.conf
This Error can also occur if you slice a negative point and pass it to the array. So check if you did
There are two ways to tackle this based on what you want:
Solution 1: Remove purple commits, preserving history (incase you want to roll back)
git revert -m 1 <SHA of merge>
-m 1
specifies which parent line to choose
Purple commits will still be there in history but since you have reverted, you will not see code from those commits.
Solution 2: Completely remove purple commits (disruptive change if repo is shared)
git rebase -i <SHA before branching out>
and delete (remove lines) corresponding to purple commits.
This would be less tricky if commits were not made after merge. Additional commits increase the chance of conflicts during revert/rebase
.
I had the same problem. This work fine for me:
str(objdata).encode('utf-8')
Encoding options for SHA256's 256 bits:
CHAR(44)
including padding characterCHAR(64)
BINARY(32)
Use the following code to float the items and make sure they are displayed inline.
ul.myclass li{float:left;display:inline}
Also make sure that the container you put them in is floated with width 100% or some other technique to ensure the floated items are contained within it and following items below it.
According to this site add
CONFIG += c++11
to your .pro file (see at the bottom of that web page). It requires Qt 5.
The other answers, suggesting
QMAKE_CXXFLAGS += -std=c++11
(or QMAKE_CXXFLAGS += -std=c++0x
)
also work with Qt 4.8 and gcc / clang.
equals()
(javadoc) must define an equivalence relation (it must be reflexive, symmetric, and transitive). In addition, it must be consistent (if the objects are not modified, then it must keep returning the same value). Furthermore, o.equals(null)
must always return false.
hashCode()
(javadoc) must also be consistent (if the object is not modified in terms of equals()
, it must keep returning the same value).
The relation between the two methods is:
Whenever
a.equals(b)
, thena.hashCode()
must be same asb.hashCode()
.
If you override one, then you should override the other.
Use the same set of fields that you use to compute equals()
to compute hashCode()
.
Use the excellent helper classes EqualsBuilder and HashCodeBuilder from the Apache Commons Lang library. An example:
public class Person {
private String name;
private int age;
// ...
@Override
public int hashCode() {
return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
// if deriving: appendSuper(super.hashCode()).
append(name).
append(age).
toHashCode();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Person))
return false;
if (obj == this)
return true;
Person rhs = (Person) obj;
return new EqualsBuilder().
// if deriving: appendSuper(super.equals(obj)).
append(name, rhs.name).
append(age, rhs.age).
isEquals();
}
}
When using a hash-based Collection or Map such as HashSet, LinkedHashSet, HashMap, Hashtable, or WeakHashMap, make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable, which has also other benefits.
I found your question looking for a solution to the same problem; and what other answers fail to point is a way to use a variable to change the name of the table for every execution of your procedure in a permanent form, not temporary.
So far what I do is concatenate the entire SQL code with the variables to use. Like this:
declare @table_name as varchar(30)
select @table_name = CONVERT(varchar(30), getdate(), 112)
set @table_name = 'DAILY_SNAPSHOT_' + @table_name
EXEC('
SELECT var1, var2, var3
INTO '+@table_name+'
FROM my_view
WHERE string = ''Strings must use double apostrophe''
');
I hope it helps, but it could be cumbersome if the code is too large, so if you've found a better way, please share!