If you want to do something like the following example, you'd have to use nested if
s.
If percentage is greater than or equal to 93%, then corresponding value in B should be 4 and if the percentage is greater than or equal to 90% and less than 92%, then corresponding value in B to be 3.7, etc.
Here's how you'd do it:
=IF(A2>=93%, 4, IF(A2>=90%, 3.7,IF(A2>=87%,3.3,0)))
For handling errors from ajax calls on the client side, you assign a function to the error
option of the ajax call.
To set a default globally, you can use the function described here: http://api.jquery.com/jQuery.ajaxSetup.
In PHP 5+ objects are passed by reference. In PHP 4 they are passed by value (that's why it had runtime pass by reference, which became deprecated).
You can use the 'clone' operator in PHP5 to copy objects:
$objectB = clone $objectA;
Also, it's just objects that are passed by reference, not everything as you've said in your question...
Using PostgreSQL like
(see accepted answer above) somehow didn't work for me although cases matched, but ilike
(case insensisitive like) does.
usually i don't use for loop in R, but here is my solution using for loops and two packages : plyr and dostats
plyr is on cran and you can download dostats on https://github.com/halpo/dostats (may be using install_github from Hadley devtools package)
Assuming that i have your first two data.frame (Df.1 and Df.2) in csv files, you can do something like this.
require(plyr)
require(dostats)
files <- list.files(pattern = ".csv")
for (i in seq_along(files)) {
assign(paste("Df", i, sep = "."), read.csv(files[i]))
assign(paste(paste("Df", i, sep = ""), "summary", sep = "."),
ldply(get(paste("Df", i, sep = ".")), dostats, sum, min, mean, median, max))
}
Here is the output
R> Df1.summary
.id sum min mean median max
1 A 34 4 5.6667 5.5 8
2 B 22 1 3.6667 3.0 9
R> Df2.summary
.id sum min mean median max
1 A 21 1 3.5000 3.5 6
2 B 16 1 2.6667 2.5 5
I was facing the same issue then i made my key 16 byte and it's working properly now. Create your key exactly 16 byte. It will surely work.
X-Frame-Options
is a header included in the response to the request to state if the domain requested will allow itself to be displayed within a frame. It has nothing to do with javascript or HTML, and cannot be changed by the originator of the request.
This website has set this header to disallow it to be displayed in an iframe
. There is nothing a client can do to stop this behaviour.
I have python 2.7.3 and this solved my problem:
pip install pysqlite
I made a solution for this.
$(function () {_x000D_
var dropZoneId = "drop-zone";_x000D_
var buttonId = "clickHere";_x000D_
var mouseOverClass = "mouse-over";_x000D_
_x000D_
var dropZone = $("#" + dropZoneId);_x000D_
var ooleft = dropZone.offset().left;_x000D_
var ooright = dropZone.outerWidth() + ooleft;_x000D_
var ootop = dropZone.offset().top;_x000D_
var oobottom = dropZone.outerHeight() + ootop;_x000D_
var inputFile = dropZone.find("input");_x000D_
document.getElementById(dropZoneId).addEventListener("dragover", function (e) {_x000D_
e.preventDefault();_x000D_
e.stopPropagation();_x000D_
dropZone.addClass(mouseOverClass);_x000D_
var x = e.pageX;_x000D_
var y = e.pageY;_x000D_
_x000D_
if (!(x < ooleft || x > ooright || y < ootop || y > oobottom)) {_x000D_
inputFile.offset({ top: y - 15, left: x - 100 });_x000D_
} else {_x000D_
inputFile.offset({ top: -400, left: -400 });_x000D_
}_x000D_
_x000D_
}, true);_x000D_
_x000D_
if (buttonId != "") {_x000D_
var clickZone = $("#" + buttonId);_x000D_
_x000D_
var oleft = clickZone.offset().left;_x000D_
var oright = clickZone.outerWidth() + oleft;_x000D_
var otop = clickZone.offset().top;_x000D_
var obottom = clickZone.outerHeight() + otop;_x000D_
_x000D_
$("#" + buttonId).mousemove(function (e) {_x000D_
var x = e.pageX;_x000D_
var y = e.pageY;_x000D_
if (!(x < oleft || x > oright || y < otop || y > obottom)) {_x000D_
inputFile.offset({ top: y - 15, left: x - 160 });_x000D_
} else {_x000D_
inputFile.offset({ top: -400, left: -400 });_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
document.getElementById(dropZoneId).addEventListener("drop", function (e) {_x000D_
$("#" + dropZoneId).removeClass(mouseOverClass);_x000D_
}, true);_x000D_
_x000D_
})
_x000D_
#drop-zone {_x000D_
/*Sort of important*/_x000D_
width: 300px;_x000D_
/*Sort of important*/_x000D_
height: 200px;_x000D_
position:absolute;_x000D_
left:50%;_x000D_
top:100px;_x000D_
margin-left:-150px;_x000D_
border: 2px dashed rgba(0,0,0,.3);_x000D_
border-radius: 20px;_x000D_
font-family: Arial;_x000D_
text-align: center;_x000D_
position: relative;_x000D_
line-height: 180px;_x000D_
font-size: 20px;_x000D_
color: rgba(0,0,0,.3);_x000D_
}_x000D_
_x000D_
#drop-zone input {_x000D_
/*Important*/_x000D_
position: absolute;_x000D_
/*Important*/_x000D_
cursor: pointer;_x000D_
left: 0px;_x000D_
top: 0px;_x000D_
/*Important This is only comment out for demonstration purposes._x000D_
opacity:0; */_x000D_
}_x000D_
_x000D_
/*Important*/_x000D_
#drop-zone.mouse-over {_x000D_
border: 2px dashed rgba(0,0,0,.5);_x000D_
color: rgba(0,0,0,.5);_x000D_
}_x000D_
_x000D_
_x000D_
/*If you dont want the button*/_x000D_
#clickHere {_x000D_
position: absolute;_x000D_
cursor: pointer;_x000D_
left: 50%;_x000D_
top: 50%;_x000D_
margin-left: -50px;_x000D_
margin-top: 20px;_x000D_
line-height: 26px;_x000D_
color: white;_x000D_
font-size: 12px;_x000D_
width: 100px;_x000D_
height: 26px;_x000D_
border-radius: 4px;_x000D_
background-color: #3b85c3;_x000D_
_x000D_
}_x000D_
_x000D_
#clickHere:hover {_x000D_
background-color: #4499DD;_x000D_
_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="drop-zone">_x000D_
Drop files here..._x000D_
<div id="clickHere">_x000D_
or click here.._x000D_
<input type="file" name="file" id="file" />_x000D_
</div>_x000D_
</div>
_x000D_
The Drag and Drop functionality for this method only works with Chrome, Firefox and Safari. (Don't know if it works with IE10), but for other browsers, the "Or click here" button works fine.
The input field simply follow your mouse when dragging a file over an area, and I've added a button as well..
Uncomment opacity:0; the file input is only visible so you can see what's going on.
==
and ===
The difference between the loosely ==
equal operator and the strict ===
identical operator is exactly explained in the manual:
Comparison Operators
+----------------------------------------------------------------------------------+ ¦ Example ¦ Name ¦ Result ¦ +----------+-----------+-----------------------------------------------------------¦ ¦$a == $b ¦ Equal ¦ TRUE if $a is equal to $b after type juggling. ¦ ¦$a === $b ¦ Identical ¦ TRUE if $a is equal to $b, and they are of the same type. ¦ +----------------------------------------------------------------------------------+
==
equal comparisonIf you are using the ==
operator, or any other comparison operator which uses loosely comparison such as !=
, <>
or ==
, you always have to look at the context to see what, where and why something gets converted to understand what is going on.
As reference and example you can see the comparison table in the manual:
Loose comparisons with
==
+-----------------------------------------------------------------------------------------------------------+ ¦ ¦ TRUE ¦ FALSE ¦ 1 ¦ 0 ¦ -1 ¦ "1" ¦ "0" ¦ "-1" ¦ NULL ¦ array() ¦ "php" ¦ "" ¦ +---------+-------+-------+-------+-------+-------+-------+-------+-------+-------+---------+-------+-------¦ ¦ TRUE ¦ TRUE ¦ FALSE ¦ TRUE ¦ FALSE ¦ TRUE ¦ TRUE ¦ FALSE ¦ TRUE ¦ FALSE ¦ FALSE ¦ TRUE ¦ FALSE ¦ ¦ FALSE ¦ FALSE ¦ TRUE ¦ FALSE ¦ TRUE ¦ FALSE ¦ FALSE ¦ TRUE ¦ FALSE ¦ TRUE ¦ TRUE ¦ FALSE ¦ TRUE ¦ ¦ 1 ¦ TRUE ¦ FALSE ¦ TRUE ¦ FALSE ¦ FALSE ¦ TRUE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ ¦ 0 ¦ FALSE ¦ TRUE ¦ FALSE ¦ TRUE ¦ FALSE ¦ FALSE ¦ TRUE ¦ FALSE ¦ TRUE ¦ FALSE ¦ TRUE ¦ TRUE ¦ ¦ -1 ¦ TRUE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE ¦ FALSE ¦ FALSE ¦ TRUE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ ¦ "1" ¦ TRUE ¦ FALSE ¦ TRUE ¦ FALSE ¦ FALSE ¦ TRUE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ ¦ "0" ¦ FALSE ¦ TRUE ¦ FALSE ¦ TRUE ¦ FALSE ¦ FALSE ¦ TRUE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ ¦ "-1" ¦ TRUE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE ¦ FALSE ¦ FALSE ¦ TRUE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ ¦ NULL ¦ FALSE ¦ TRUE ¦ FALSE ¦ TRUE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE ¦ TRUE ¦ FALSE ¦ TRUE ¦ ¦ array() ¦ FALSE ¦ TRUE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE ¦ TRUE ¦ FALSE ¦ FALSE ¦ ¦ "php" ¦ TRUE ¦ FALSE ¦ FALSE ¦ TRUE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE ¦ FALSE ¦ ¦ "" ¦ FALSE ¦ TRUE ¦ FALSE ¦ TRUE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE ¦ FALSE ¦ FALSE ¦ TRUE ¦ +-----------------------------------------------------------------------------------------------------------+
===
identical comparisonIf you are using the ===
operator, or any other comparison operator which uses strict comparison such as !==
or ===
, then you can always be sure that the types won't magically change, because there will be no converting going on. So with strict comparison the type and value have to be the same, not only the value.
As reference and example you can see the comparison table in the manual:
Strict comparisons with
===
+-----------------------------------------------------------------------------------------------------------+ ¦ ¦ TRUE ¦ FALSE ¦ 1 ¦ 0 ¦ -1 ¦ "1" ¦ "0" ¦ "-1" ¦ NULL ¦ array() ¦ "php" ¦ "" ¦ +---------+-------+-------+-------+-------+-------+-------+-------+-------+-------+---------+-------+-------¦ ¦ TRUE ¦ TRUE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ ¦ FALSE ¦ FALSE ¦ TRUE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ ¦ 1 ¦ FALSE ¦ FALSE ¦ TRUE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ ¦ 0 ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ ¦ -1 ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ ¦ "1" ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ ¦ "0" ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ ¦ "-1" ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ ¦ NULL ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE ¦ FALSE ¦ FALSE ¦ FALSE ¦ ¦ array() ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE ¦ FALSE ¦ FALSE ¦ ¦ "php" ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE ¦ FALSE ¦ ¦ "" ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE ¦ +-----------------------------------------------------------------------------------------------------------+
When you want a flex item to occupy an entire row, set it to width: 100%
or flex-basis: 100%
, and enable wrap
on the container.
The item now consumes all available space. Siblings are forced on to other rows.
.parent {
display: flex;
flex-wrap: wrap;
}
#range, #text {
flex: 1;
}
.error {
flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
border: 1px dashed black;
}
_x000D_
<div class="parent">
<input type="range" id="range">
<input type="text" id="text">
<label class="error">Error message (takes full width)</label>
</div>
_x000D_
More info: The initial value of the flex-wrap
property is nowrap
, which means that all items will line up in a row. MDN
<input type="checkbox" @( Model.Checked == true ? "checked" : "" ) />
Have a look at the AlertDialog docs. As it states, to add a custom view to your alert dialog you need to find the frameLayout and add your view to that like so:
FrameLayout fl = (FrameLayout) findViewById(android.R.id.custom);
fl.addView(myView, new LayoutParams(MATCH_PARENT, WRAP_CONTENT));
Most likely you are going to want to create a layout xml file for your view, and inflate it:
LayoutInflater inflater = getLayoutInflater();
View twoEdits = inflater.inflate(R.layout.my_layout, f1, false);
I have solved that problem. The only I do is:
private int num_rows;
And then in your method using the resultset put this code
while (this.rs.next())
{
this.num_rows++;
}
That's all
See answer from Gary Makin. And you need change the format or data. Because the data that you have do not fit under the chosen format. For example this code works correct:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let dateObj = dateFormatter.dateFromString("10 10 2001")
print("Dateobj: \(dateObj)")
InputStream is=getResources().openRawResource(R.raw.name);
BufferedReader reader=new BufferedReader(new InputStreamReader(is));
StringBuffer data=new StringBuffer();
String line=reader.readLine();
while(line!=null)
{
data.append(line+"\n");
}
tvDetails.seTtext(data.toString());
Instead of flex: 1 0 auto
just use flex: 1
main, aside, article {_x000D_
margin: 10px;_x000D_
border: solid 1px #000;_x000D_
border-bottom: 0;_x000D_
height: 50px;_x000D_
}_x000D_
main {_x000D_
display: flex;_x000D_
}_x000D_
aside {_x000D_
flex: 0 0 200px;_x000D_
}_x000D_
article {_x000D_
flex: 1;_x000D_
}
_x000D_
<main>_x000D_
<aside>x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x </aside>_x000D_
<article>don't let flex item overflow container.... y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y </article>_x000D_
</main>
_x000D_
The getPosts()
function seems to be expecting $con
to be global, but you're not declaring it as such.
A lot of programmers regard bald global variables as a "code smell". The alternative at the other end of the scale is to always pass around the connection resource. Partway between the two is a singleton call that always returns the same resource handle.
It's a kludge, but assuming there's a minimum length for SEARCHSTRING
, for example 2 characters, substring
the SEARCHSTRING
parameter at the second character and pass it as two parameters instead: SEARCHSTRING1 ("Nu")
and SEARCHSTRING2 ("ll").
Concatenate
them back together when executing the query to the database.
You've obviously considered lots of ways to write the SQL such that it prints out okay, but how about changing the 'print' statement you use for debug logging, rather than writing your SQL in ways you don't like? Using your favourite option above, how about a logging function such as this:
def debugLogSQL(sql):
print ' '.join([line.strip() for line in sql.splitlines()]).strip()
sql = """
select field1, field2, field3, field4
from table"""
if debug:
debugLogSQL(sql)
This would also make it trivial to add additional logic to split the logged string across multiple lines if the line is longer than your desired length.
I created a function in VBA for you, so you can do this now in an easy way.
Create a VBA code module (macro) as you can see in this tutorial.
Module
in Insert
.Excel Macro-Enabled
in Save As
.Function listUnique(rng As Range) As Variant
Dim row As Range
Dim elements() As String
Dim elementSize As Integer
Dim newElement As Boolean
Dim i As Integer
Dim distance As Integer
Dim result As String
elementSize = 0
newElement = True
For Each row In rng.Rows
If row.Value <> "" Then
newElement = True
For i = 1 To elementSize Step 1
If elements(i - 1) = row.Value Then
newElement = False
End If
Next i
If newElement Then
elementSize = elementSize + 1
ReDim Preserve elements(elementSize - 1)
elements(elementSize - 1) = row.Value
End If
End If
Next
distance = Range(Application.Caller.Address).row - rng.row
If distance < elementSize Then
result = elements(distance)
listUnique = result
Else
listUnique = ""
End If
End Function
Just enter =listUnique(range)
to a cell. The only parameter is range
that is an ordinary Excel range. For example: A$1:A$28
or H$8:H$30
.
range
must be a column.range
starts.It works in columns that have empty cells in them. Also the function outputs nothing (not errors) if you overwind the cells (calling the function) into places where should be no output, as I did it in the previous example's "2. Grow it" part.
var classes = $('html')[0].className;
if (classes.indexOf('m320') != -1 || classes.indexOf('m768') != -1) {
//do something
}
This has always worked for me:
SET CurrentDir="%~dp0"
ECHO The current file path this bat file is executing in is the following:
ECHO %CurrentDir%
Pause
You can use the markup below, but note that if you set the textAllCaps
to true
the underline effect would be removed.
<resource>
<string name="my_string_value">I am <u>underlined</u>.</string>
</resources>
Note
Using textAllCaps with a string (login_change_settings) that contains markup; the markup will be dropped by the caps conversion
The textAllCaps text transform will end up calling toString on the CharSequence, which has the net effect of removing any markup such as . This check looks for usages of strings containing markup that also specify textAllCaps=true.
For me , it was related to setting the "User Setting.xml" inside
Window > preferences > Maven > User Settings > and then browsing to the user Settings inside the { maven unarchived directory / }/apache-maven-2.2.1/conf/settings.xml .
Here is specifically what worked for me only when the Excel file being queried was not open and when running the SQL Server Service as me [as a user that has access to the file system]. I see pieces of my answer already given elsewhere, so I apologize for any redundancy, but for the sake of a more succinct answer:
USE [master]
GO
EXEC sp_configure 'Show Advanced Options', 1
RECONFIGURE
GO
EXEC sp_configure 'Ad Hoc Distributed Queries', 1
RECONFIGURE
GO
EXEC sp_MSSet_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
GO
EXEC sp_MSSet_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1
GO
SELECT *
FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0',
'Excel 12.0;Database=C:\MyExcelFile.xlsx',
'SELECT * FROM [MyExcelSheetName$]')
$(document).keyup(function(e) {
if(e.key === 'Enter') {
//Do the stuff
}
});
It will give consistent behavior for add/remove operations. But while iterating you have to explicitly synchronized. Refer this link
Updates you make to the CTE will be cascaded to the source table.
I have had to guess at your schema slightly, but something like this should work.
;WITH T AS
( SELECT InvoiceNumber,
DocTotal,
SUM(Sale + VAT) OVER(PARTITION BY InvoiceNumber) AS NewDocTotal
FROM PEDI_InvoiceDetail
)
UPDATE T
SET DocTotal = NewDocTotal
As you have noticed, xscale
and yscale
does not support a simple linear re-scaling (unfortunately). As an alternative to Hooked's answer, instead of messing with the data, you can trick the labels like so:
ticks = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x*scale))
ax.xaxis.set_major_formatter(ticks)
A complete example showing both x and y scaling:
import numpy as np
import pylab as plt
import matplotlib.ticker as ticker
# Generate data
x = np.linspace(0, 1e-9)
y = 1e3*np.sin(2*np.pi*x/1e-9) # one period, 1k amplitude
# setup figures
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
# plot two identical plots
ax1.plot(x, y)
ax2.plot(x, y)
# Change only ax2
scale_x = 1e-9
scale_y = 1e3
ticks_x = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_x))
ax2.xaxis.set_major_formatter(ticks_x)
ticks_y = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_y))
ax2.yaxis.set_major_formatter(ticks_y)
ax1.set_xlabel("meters")
ax1.set_ylabel('volt')
ax2.set_xlabel("nanometers")
ax2.set_ylabel('kilovolt')
plt.show()
And finally I have the credits for a picture:
Note that, if you have text.usetex: true
as I have, you may want to enclose the labels in $
, like so: '${0:g}$'
.
The main (very interesting) difference for me is that:
"string" & Null
-> "string"
while
"string" + Null
-> Null
But that's probably more useful in database apps like Access.
Do both in a single pass with:
find -type f ... -o -type d ...
As in, find type f OR type d, and do the first ... for files and the second ... for dirs. Specifically:
find -type f -exec chmod --changes 644 {} + -o -type d -exec chmod --changes 755 {} +
Leave off the --changes
if you want it to work silently.
In addition to other answers which helped me, you can also add to surrounding div. In my case this was for sign on with user Name/Password fields.
<div (keyup.enter)="login()" class="container-fluid">
Here is answer to your question.
By default maven looks in ../pom.xml
for relativePath
. Use empty <relativePath/>
tag instead.
I had the same symptom. For me it turned out that another thread was modifying the compared objects while the sorting was happening in a Stream. To resolve the issue, I mapped the objects to immutable temporary objects, collected the Stream to a temporary Collection and did the sorting on that.
It seems that in VBA macro code for an ActiveX checkbox control you use
If (ActiveSheet.OLEObjects("CheckBox1").Object.Value = True)
and for a Form checkbox control you use
If (ActiveSheet.Shapes("CheckBox1").OLEFormat.Object.Value = 1)
Can you try this?
SELECT [Title], [Firstname], [Surname], [Company_name], [Interest]
FROM [dbo].[EXTRANET_users]
WHERE CAST(Submission_date AS DATE) = CAST(GETDATE() AS DATE)
T-SQL doesn't really have the "implied" casting like C# does - you need to explicitly use CAST
(or CONVERT
).
Also, use GETDATE()
or CURRENT_TIMESTAMP
to get the "now" date and time.
Update: since you're working against SQL Server 2000 - none of those approaches so far work. Try this instead:
SELECT [Title], [Firstname], [Surname], [Company_name], [Interest]
FROM [dbo].[EXTRANET_users]
WHERE DATEADD(dd, 0, DATEDIFF(dd, 0, submission_date)) = DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
You can set ignorecase
by default, run this in shell
echo "set ic" >> ~/.vimrc
There is a very simple answer and without pass context
public static int getScreenWidth() {
return Resources.getSystem().getDisplayMetrics().widthPixels;
}
public static int getScreenHeight() {
return Resources.getSystem().getDisplayMetrics().heightPixels;
}
Note: if you want the height include navigation bar, use method below
WindowManager windowManager =
(WindowManager) BaseApplication.getApplication().getSystemService(Context.WINDOW_SERVICE);
final Display display = windowManager.getDefaultDisplay();
Point outPoint = new Point();
if (Build.VERSION.SDK_INT >= 19) {
// include navigation bar
display.getRealSize(outPoint);
} else {
// exclude navigation bar
display.getSize(outPoint);
}
if (outPoint.y > outPoint.x) {
mRealSizeHeight = outPoint.y;
mRealSizeWidth = outPoint.x;
} else {
mRealSizeHeight = outPoint.x;
mRealSizeWidth = outPoint.y;
}
You can pass any number of arguments to the function that apply
is calling through either unnamed arguments, passed as a tuple to the args
parameter, or through other keyword arguments internally captured as a dictionary by the kwds
parameter.
For instance, let's build a function that returns True for values between 3 and 6, and False otherwise.
s = pd.Series(np.random.randint(0,10, 10))
s
0 5
1 3
2 1
3 1
4 6
5 0
6 3
7 4
8 9
9 6
dtype: int64
s.apply(lambda x: x >= 3 and x <= 6)
0 True
1 True
2 False
3 False
4 True
5 False
6 True
7 True
8 False
9 True
dtype: bool
This anonymous function isn't very flexible. Let's create a normal function with two arguments to control the min and max values we want in our Series.
def between(x, low, high):
return x >= low and x =< high
We can replicate the output of the first function by passing unnamed arguments to args
:
s.apply(between, args=(3,6))
Or we can use the named arguments
s.apply(between, low=3, high=6)
Or even a combination of both
s.apply(between, args=(3,), high=6)
Looking at the implementation differences, I see that:
[-a-zA-Z0-9._*~'()!]
Java 1.5.0 documentation on URLEncoder
:
[-a-zA-Z0-9._*]
" "
is converted into a plus sign "+"
. So basically, to get the desired result, use URLEncoder.encode(s, "UTF-8")
and then do some post-processing:
"+"
with "%20"
"%xx"
representing any of [~'()!]
back to their literal counter-parts<TextView
android:id="@+id/txtTitlevalue"
android:text="Line1: \r\n-Line2\r\n-Line3"
android:layout_width="54dip"
android:layout_height="fill_parent"
android:textSize="11px" />
I think this will work.
Try setting android:background="#00000000"
in TextView. Setting alpha of colour 00 will make the background transparent.
I haven't tried this, but it should work.
Try this:
It looks like you are looping for every product each time, now this is looping for each product that has the same category ID as the current category being looped
<div id="accordion1" style="text-align:justify">
@using (Html.BeginForm())
{
foreach (var category in Model.Categories)
{
<h3><u>@category.Name</u></h3>
<div>
<ul>
@foreach (var product in Model.Product.Where(m=> m.CategoryID= category.CategoryID)
{
<li>
@product.Title
@if (System.Web.Security.UrlAuthorizationModule.CheckUrlAccessForPrincipal("/admin", User, "GET"))
{
@Html.Raw(" - ")
@Html.ActionLink("Edit", "Edit", new { id = product.ID })
}
<ul>
<li>
@product.Description
</li>
</ul>
</li>
}
</ul>
</div>
}
}
I solved this error with clearing cache and restarting chrome. Hope they will fix it in ver 40.
Just use the *args
parameter, which allows you to pass as many arguments as you want after your a,b,c
. You would have to add some logic to map args
->c,d,e,f
but its a "way" of overloading.
def myfunc(a,b, *args, **kwargs):
for ar in args:
print ar
myfunc(a,b,c,d,e,f)
And it will print values of c,d,e,f
Similarly you could use the kwargs
argument and then you could name your parameters.
def myfunc(a,b, *args, **kwargs):
c = kwargs.get('c', None)
d = kwargs.get('d', None)
#etc
myfunc(a,b, c='nick', d='dog', ...)
And then kwargs
would have a dictionary of all the parameters that are key valued after a,b
You can submit the first form using AJAX, otherwise the submission of one will prevent the other from being submitted.
The following code performs a HEAD
request to check whether the website is available or not.
public static boolean isReachable(String targetUrl) throws IOException
{
HttpURLConnection httpUrlConnection = (HttpURLConnection) new URL(
targetUrl).openConnection();
httpUrlConnection.setRequestMethod("HEAD");
try
{
int responseCode = httpUrlConnection.getResponseCode();
return responseCode == HttpURLConnection.HTTP_OK;
} catch (UnknownHostException noInternetConnection)
{
return false;
}
}
Converting both strings to lower-case is usually not a big deal but it would be slow if some of the strings is long. And if you do this in a loop then it would be really bad. For this reason, I would recommend indexOfIgnoreCase
.
These are known errors from libGL and libstdc++
You can quick fix this by change to use Software
for Emulated Performance Graphics
option, in the AVD settings.
Or try to use the libstdc++.so.6
(which is available in your system) instead of the one bundled inside Android SDK. There are 2 ways to replace it:
The emulator has a switch -use-system-libs
. You can found it here: ~/Android/Sdk/tools/emulator -avd Nexus_5_API_23 -use-system-libs
.
This option force Linux emulator to load the system libstdc++
(but not Qt libraries),
in cases where the bundled ones (from Android SDK) prevent it from loading or
working correctly. See this commit
Alternatively you can set the ANDROID_EMULATOR_USE_SYSTEM_LIBS
environment variable to 1
for your user/system
.
This has the benefit of making sure that the emulator will work even if you launched it from within Android Studio.
See: libGL error and libstdc++: Cannot launch AVD in emulator - Issue Tracker
I took Crystalonics' answer and turned them into extension methods. I hope someone else will find them useful:
public static byte[] SerializeToByteArray(this object obj)
{
if (obj == null)
{
return null;
}
var bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, obj);
return ms.ToArray();
}
}
public static T Deserialize<T>(this byte[] byteArray) where T : class
{
if (byteArray == null)
{
return null;
}
using (var memStream = new MemoryStream())
{
var binForm = new BinaryFormatter();
memStream.Write(byteArray, 0, byteArray.Length);
memStream.Seek(0, SeekOrigin.Begin);
var obj = (T)binForm.Deserialize(memStream);
return obj;
}
}
normally I extract the embedded image with 'pdfimages' at the native resolution, then use ImageMagick's convert to the needed format:
$ pdfimages -list fileName.pdf
$ pdfimages fileName.pdf fileName # save in .ppm format
$ convert fileName-000.ppm fileName-000.png
this generate the best and smallest result file.
Note: For lossy JPG embedded images, you had to use -j:
$ pdfimages -j fileName.pdf fileName # save in .jpg format
With recent poppler you can use -all that save lossy as jpg and lossless as png
On little provided Win platform you had to download a recent (0.37 2015) 'poppler-util' binary from: http://blog.alivate.com.au/poppler-windows/
curl
sends POST requests with the default content type of application/x-www-form-urlencoded
. If you want to send a JSON request, you will have to specify the correct content type header:
$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"
But that will only work if the server accepts json input. The .json
at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.
The reason you get a 401
and not some other error is probably because the server can't extract the auth_token
from your request.
You can use jQuery's attr()
function, like $("#id").attr('src',"source")
.
Using following commands to uninstall :
npm uninstall -g @angular/cli
npm cache clean --force
To verify: ng --version /* You will get the error message, then u have uninstalled */
Using following commands to re-install :
npm install -g @angular/cli
Notes :
- Using --force for clean all the caches
- On Windows run this using administrator
- On Mac use sudo ($ sudo <command>
)
npm>5
you may need to use cache verify instead. ($ npm cache verify
)With vim from command line:
vim -c "set encoding=utf8" -c "set fileencoding=utf8" -c "wq" filename
I was also getting this error. The problem for me turned out to be that I had two separate websites on the machine, and I had not designated which address went to which website. To resolve this, go to IIS Manager -> Select Web Site -> Bindings -> Add... -> Enter the host name that you want to resolve for this website. Repeat for any other websites on the machine.
HTH. Rick
push
does not return the array, but the length of it (docs), so what you are doing is replacing the array with its length, losing the only reference to it that you had. Try this:
import {ADD_ITEM} from '../Actions/UserActions'
const initialUserState = {
arr:[]
}
export default function userState(state = initialUserState, action){
console.log(arr);
switch (action.type){
case ADD_ITEM :
return {
...state,
arr:[...state.arr, action.newItem]
}
default:return state
}
}
I'm going to begin this answer with an illustration:
var colours = ['red', 'green', 'blue'];
document.getElementById('element').addEventListener('click', function() {
// this is a reference to the element clicked on
var that = this;
colours.forEach(function() {
// this is undefined
// that is a reference to the element clicked on
});
});
My answer originally demonstrated this with jQuery, which is only very slightly different:
$('#element').click(function(){
// this is a reference to the element clicked on
var that = this;
$('.elements').each(function(){
// this is a reference to the current element in the loop
// that is still a reference to the element clicked on
});
});
Because this
frequently changes when you change the scope by calling a new function, you can't access the original value by using it. Aliasing it to that
allows you still to access the original value of this
.
Personally, I dislike the use of that
as the alias. It is rarely obvious what it is referring to, especially if the functions are longer than a couple of lines. I always use a more descriptive alias. In my examples above, I'd probably use clickedEl
.
This query should work for you:
SELECT *
FROM table
WHERE MONTH(columnName) = MONTH(CURRENT_DATE())
AND YEAR(columnName) = YEAR(CURRENT_DATE())
Make sure you pip version matches your python version.
to get your python version use:
python -V
then install the correct pip. You might already have intall in that case try to use:
pip-2.5 install ...
pip-2.7 install ...
or for those of you using macports make sure your version match using.
port select --list pip
then change to the same python version you are using.
sudo port select --set pip pip27
Hope this helps. It work on my end.
A view is a virtual table, which provides access to a subset of column from one or more table. A view can derive its data from one or more table. An output of query can be stored as a view. View act like small a table but it does not physically take any space. View is good way to present data in particular users from accessing the table directly. A view in oracle is nothing but a stored sql scripts. Views itself contain no data.
Just use the following command if you wanna set configuration in system level:
$ sudo git config --system user.name "my_name"
You need just to follow those steps:
After which, if the build fails when you do Maven Install, it means there is no web.xml file under WEB-INF or some problem associated with it. it really works
Check if have not set a open_basedir in php.ini or .htaccess of domain what you use. That will jail you in directory of your domain and php will get only access to execute inside this directory.
For the more inexperienced, I have decided to add an example to demonstrate how to input and output an ArrayList of Integer arrays based on this question here.
ArrayList<Integer[]> arrayList = new ArrayList<Integer[]>();
while(n > 0)
{
int d = scan.nextInt();
Integer temp[] = new Integer[d];
for (int i = 0 ; i < d ; i++)
{
int t = scan.nextInt();
temp[i]=Integer.valueOf(t);
}
arrayList.add(temp);
n--;
}//n is the size of the ArrayList that has been taken as a user input & d is the size
//of each individual array.
//to print something out from this ArrayList, we take in two
// values,index and index1 which is the number of the line we want and
// and the position of the element within that line (since the question
// followed a 1-based numbering scheme, I did not change it here)
System.out.println(Integer.valueOf(arrayList.get(index-1)[index1-1]));
Thanks to this answer on this question here, I got the correct answer. I believe this satisfactorily answers OP's question, albeit a little late and can serve as an explanation for those with less experience.
You can always use the DATALENGTH Function to determine if you have extra white space characters in text fields. This won't make the text visible but will show you where there are extra white space characters.
SELECT DATALENGTH('MyTextData ') AS BinaryLength, LEN('MyTextData ') AS TextLength
This will produce 11 for BinaryLength and 10 for TextLength.
In a table your SQL would like this:
SELECT *
FROM tblA
WHERE DATALENGTH(MyTextField) > LEN(MyTextField)
This function is usable in all versions of SQL Server beginning with 2005.
You can also use a while loop:
while (true) {
//your code
}
var owl = $('.owl-carousel');
owl.owlCarousel();
// Go to the next item
$('.customNextBtn').click(function() {
owl.trigger('owl.prev');
})
// Go to the previous item
$('.customPrevBtn').click(function() {
owl.trigger('owl.next');
})
var owl = $('.owl-carousel');
owl.owlCarousel();
// Go to the next item
$('.customNextBtn').click(function() {
owl.trigger('next.owl.carousel');
})
// Go to the previous item
$('.customPrevBtn').click(function() {
// With optional speed parameter
// Parameters has to be in square bracket '[]'
owl.trigger('prev.owl.carousel', [300]);
})
update-alternatives
is problematic in this case as it forces you to update all the elements depending on the JDK.
For this specific purpose, the package java-common
contains a tool called update-java-alternatives
.
It's straightforward to use it. First list the JDK installs available on your machine:
root@mylaptop:~# update-java-alternatives -l
java-1.7.0-openjdk-amd64 1071 /usr/lib/jvm/java-1.7.0-openjdk-amd64
java-1.8.0-openjdk-amd64 1069 /usr/lib/jvm/java-1.8.0-openjdk-amd64
And then pick one up:
root@mylaptop:~# update-java-alternatives -s java-1.7.0-openjdk-amd64
The easiest way to solve this in pure HTML is to use the <base href="…">
element like so:
<base href="http://localhost/mywebsite/" />
Then all of the URLs in your HTML can just be this:
<a href="images/example.png">Link To Image</a>
Just change the <base href="…">
to match your server. The rest of the HTML paths will just fall in line and will be appended to that.
Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.
In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:
CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
one int;
two int;
BEGIN
one := 1;
two := 2;
RETURN one + two;
END
$$;
SELECT somefuncname();
The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.
First, revert the working copy to 1943.
> svn merge -c -1943 .
Second, check what is about to be commited.
> svn status
Third, commit version 1945.
> svn commit -m "Fix bad commit."
Fourth, look at the new log.
> svn log -l 4
------------------------------------------------------------------------
1945 | myname | 2015-04-20 19:20:51 -0700 (Mon, 20 Apr 2015) | 1 line
Fix bad commit.
------------------------------------------------------------------------
1944 | myname | 2015-04-20 19:09:58 -0700 (Mon, 20 Apr 2015) | 1 line
This is the bad commit that I made.
------------------------------------------------------------------------
1943 | myname | 2015-04-20 18:36:45 -0700 (Mon, 20 Apr 2015) | 1 line
This was a good commit.
------------------------------------------------------------------------
For iPhone it works if you add also playsinline so:
<video width="320" height="240" autoplay loop muted playsinline>
<source src="movie.mp4" type="video/mp4" />
</video>
private void Add_Click(object sender, EventArgs e) {
OleDbConnection con = new OleDbConnection(@ "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\HP\Desktop\DS Project.mdb");
OleDbCommand cmd = con.CreateCommand();
con.Open();
cmd.CommandText = "Insert into DSPro (Playlist) values('" + textBox1.Text + "')";
cmd.ExecuteNonQuery();
MessageBox.Show("Record Submitted", "Congrats");
con.Close();
}
If you are using angular ui-router this will be the best solution.
$scope.myLoadingFunction = function() {
$state.reload();
};
Implement the HandlerInterceptor
interface, and then inject the UserDetails
into each request that has a Model, as follows:
@Component
public class UserInterceptor implements HandlerInterceptor {
....other methods not shown....
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
if(modelAndView != null){
modelAndView.addObject("user", (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal());
}
}
Google shrinks their css classes etc., so it is not easy to identify everything.
Also you have the problem that you have to "wait" until the site shows the result. I would do it like this:
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
WebElement element = driver.findElement(By.name("q"));
element.sendKeys("Cheese!\n"); // send also a "\n"
element.submit();
// wait until the google page shows the result
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("resultStats")));
List<WebElement> findElements = driver.findElements(By.xpath("//*[@id='rso']//h3/a"));
// this are all the links you like to visit
for (WebElement webElement : findElements)
{
System.out.println(webElement.getAttribute("href"));
}
}
This will print you:
-- Change the starting value of the sequence
ALTER SEQUENCE project_id_seq RESTART 3000;
Same but dynamic :
SELECT SETVAL('project_id_seq', (SELECT MAX(id) + 1 FROM project));
I agree the use of a SELECT
is disturbing but it works.
Source: https://kylewbanks.com/blog/Adding-or-Modifying-a-PostgreSQL-Sequence-Auto-Increment
Using Search bar
Shift
/editor /appearance/
and thenShow line numbers
toggle buttonFor Windows and Linux
File | Settings | Editor | General | Appearance
For macOS
IntelliJ IDEA | Preferences | Editor | General | Appearance
Using shortcut
Ctrl+Alt+S
Then
Editor > General > Appearance
Click on Show line numbers toggle button.
There is a nice package called mat4py
which can easily be installed using
pip install mat4py
It is straightforward to use (from the website):
Load data from a MAT-file
The function loadmat
loads all variables stored in the MAT-file into a simple Python data structure, using only Python’s dict
and list
objects. Numeric and cell arrays are converted to row-ordered nested lists. Arrays are squeezed to eliminate arrays with only one element. The resulting data structure is composed of simple types that are compatible with the JSON format.
Example: Load a MAT-file into a Python data structure:
from mat4py import loadmat
data = loadmat('datafile.mat')
The variable data
is a dict
with the variables and values contained in the MAT-file.
Save a Python data structure to a MAT-file
Python data can be saved to a MAT-file, with the function savemat
. Data has to be structured in the same way as for loadmat
, i.e. it should be composed of simple data types, like dict
, list
, str
, int
, and float
.
Example: Save a Python data structure to a MAT-file:
from mat4py import savemat
savemat('datafile.mat', data)
The parameter data
shall be a dict
with the variables.
I like this very simple definition: (source)
A loop invariant is a condition [among program variables] that is necessarily true immediately before and immediately after each iteration of a loop. (Note that this says nothing about its truth or falsity part way through an iteration.)
By itself, a loop invariant doesn't do much. However, given an appropriate invariant, it can be used to help prove the correctness of an algorithm. The simple example in CLRS probably has to do with sorting. For example, let your loop invariant be something like, at the start of the loop, the first i
entries of this array are sorted. If you can prove that this is indeed a loop invariant (i.e. that it holds before and after every loop iteration), you can use this to prove the correctness of a sorting algorithm: at the termination of the loop, the loop invariant is still satisfied, and the counter i
is the length of the array. Therefore, the first i
entries are sorted means the entire array is sorted.
An even simpler example: Loops Invariants, Correctness, and Program Derivation.
The way I understand a loop invariant is as a systematic, formal tool to reason about programs. We make a single statement that we focus on proving true, and we call it the loop invariant. This organizes our logic. While we can just as well argue informally about the correctness of some algorithm, using a loop invariant forces us to think very carefully and ensures our reasoning is airtight.
You can simply cast to List and then check if every element can be casted to T.
public <T> List<T> asList(final Class<T> clazz) {
List<T> values = (List<T>) this.value;
values.forEach(clazz::cast);
return values;
}
While adding a AutoRun entry to HKEY_CURRENT_USER\Software\Microsoft\Command Processor
like Shinnok's answer is the way to go it can also really mess things up, you really should try to detect a simple cmd.exe startup vs a script/program using cmd.exe as a child process:
IF /I x"%COMSPEC%"==x%CMDCMDLINE% (cd /D c:\)
Would √ (square root symbol, √) suffice?
Alternatively, ensure you're setting the Content-Type:
header before sending data to the browser. Merely specifying the <meta>
content-type tag may not be enough to encourage browsers to use the correct character set.
Another reply to your questions (assuming you are on master and already did "git fetch origin" to make you repo aware about remote changes):
1) Commits on remote branch since when local branch was created:
git diff HEAD...origin/master
2) I assume by "working copy" you mean your local branch with some local commits that are not yet on remote. To see the differences of what you have on your local branch but that does not exist on remote branch run:
git diff origin/master...HEAD
3) See the answer by dbyrne.
Neither code is always better. They do different things, so they are good at different things.
InvariantCultureIgnoreCase
uses comparison rules based on english, but without any regional variations. This is good for a neutral comparison that still takes into account some linguistic aspects.
OrdinalIgnoreCase
compares the character codes without cultural aspects. This is good for exact comparisons, like login names, but not for sorting strings with unusual characters like é
or ö
. This is also faster because there are no extra rules to apply before comparing.
The const
and let
are part of ECMAScript 2015 (a.k.a. ES6 and Harmony), and was not enabled by default in Node.js 0.10 or 0.12. Since Node.js 4.x, “All shipping [ES2015] features, which V8 considers stable, are turned on by default on Node.js and do NOT require any kind of runtime flag.”. Node.js docs has an overview of what ES2015 features are enabled by default, and which who require a runtime flag. So by upgrading to Node.js 4.x or newer the error should disappear.
To enable some of the ECMAScript 2015 features (including const
and let
) in Node.js 0.10 and 0.12; start your node program with a harmony flag, otherwise you will get a syntax error. For example:
node --harmony app.js
It all depends on which side your strict js is located. I would recommend using strict mode with const
declarations on your server side and start the server with the harmony flag. For the client side, you should use Babel or similar tool to convert ES2015 to ES5, since not all client browsers support the const
declarations.
Here is updated Fiddle
Simply remove </br>
between input radio's
<div class="clearBoth"></div>
<input type="radio" name="editList" value="always">Always
<input type="radio" name="editList" value="never">Never
<input type="radio" name="editList" value="costChange">Cost Change
<div class="clearBoth"></div>
[^\x00-\x7F]
and [^[:ascii:]]
miss some control bytes so strings can be the better option sometimes. For example cat test.torrent | perl -pe 's/[^[:ascii:]]+/\n/g'
will do odd things to your terminal, where as strings test.torrent
will behave.
The usual pattern is EXISTS(subselect)
:
BEGIN
IF EXISTS(SELECT name
FROM test_table t
WHERE t.id = x
AND t.name = 'test')
THEN
---
ELSE
---
END IF;
This pattern is used in PL/SQL, PL/pgSQL, SQL/PSM, ...
> myMatrix <- matrix(1:10, nrow=2)
> rownames(myMatrix) <- c("A", "B")
> colnames(myMatrix) <- c("A", "B", "C", "D", "E")
> myMatrix
A B C D E
A 1 3 5 7 9
B 2 4 6 8 10
> myMatrix["A", "A"]
[1] 1
> myMatrix["A", ]
A B C D E
1 3 5 7 9
> myMatrix[, "A"]
A B
1 2
This is based on Jim's answer,
SELECT
@field_text + SPACE(@pad_length - LEN(@field_text)) AS RightPad
,SPACE(@pad_length - LEN(@field_text)) + @field_text AS LeftPad
Advantages
Disadvantages
In my case, I use Symfony2.3.x and the minimum-stability parameter is by default "stable" (which is good). I wanted to import a repo not in packagist but had the same issue "Your requirements could not be resolved to an installable set of packages.". It appeared that the composer.json in the repo I tried to import use a minimum-stability "dev".
So to resolve this issue, don't forget to verify the minimum-stability
. I solved it by requiring a dev-master
version instead of master
as stated in this post.
How do I emulate the ISNULL() functionality ?
SELECT (Field IS NULL) FROM ...
Nowadays, code to do this should look something like:
document.getElementById('foo').addEventListener('keydown', function (event) {
if (event.keyCode == 8) {
console.log('BACKSPACE was pressed');
// Call event.preventDefault() to stop the character before the cursor
// from being deleted. Remove this line if you don't want to do that.
event.preventDefault();
}
if (event.keyCode == 46) {
console.log('DELETE was pressed');
// Call event.preventDefault() to stop the character after the cursor
// from being deleted. Remove this line if you don't want to do that.
event.preventDefault();
}
});
although in the future, once they are broadly supported in browsers, you may want to use the .key
or .code
attributes of the KeyboardEvent
instead of the deprecated .keyCode
.
Details worth knowing:
Calling event.preventDefault()
in the handler of a keydown event will prevent the default effects of the keypress. When pressing a character, this stops it from being typed into the active text field. When pressing backspace or delete in a text field, it prevents a character from being deleted. When pressing backspace without an active text field, in a browser like Chrome where backspace takes you back to the previous page, it prevents that behaviour (as long as you catch the event by adding your event listener to document
instead of a text field).
Documentation on how the value of the keyCode
attribute is determined can be found in section B.2.1 How to determine keyCode
for keydown
and keyup
events in the W3's UI Events Specification. In particular, the codes for Backspace and Delete are listed in B.2.3 Fixed virtual key codes.
There is an effort underway to deprecate the .keyCode
attribute in favour of .key
and .code
. The W3 describe the .keyCode
property as "legacy", and MDN as "deprecated".
One benefit of the change to .key
and .code
is having more powerful and programmer-friendly handling of non-ASCII keys - see the specification that lists all the possible key values, which are human-readable strings like "Backspace"
and "Delete"
and include values for everything from modifier keys specific to Japanese keyboards to obscure media keys. Another, which is highly relevant to this question, is distinguishing between the meaning of a modified keypress and the physical key that was pressed.
On small Mac keyboards, there is no Delete key, only a Backspace key. However, pressing Fn+Backspace is equivalent to pressing Delete on a normal keyboard - that is, it deletes the character after the text cursor instead of the one before it. Depending upon your use case, in code you might want to handle a press of Backspace with Fn held down as either Backspace or Delete. That's why the new key model lets you choose.
The .key
attribute gives you the meaning of the keypress, so Fn+Backspace will yield the string "Delete"
. The .code
attribute gives you the physical key, so Fn+Backspace will still yield the string "Backspace"
.
Unfortunately, as of writing this answer, they're only supported in 18% of browsers, so if you need broad compatibility you're stuck with the "legacy" .keyCode
attribute for the time being. But if you're a reader from the future, or if you're targeting a specific platform and know it supports the new interface, then you could write code that looked something like this:
document.getElementById('foo').addEventListener('keydown', function (event) {
if (event.code == 'Delete') {
console.log('The physical key pressed was the DELETE key');
}
if (event.code == 'Backspace') {
console.log('The physical key pressed was the BACKSPACE key');
}
if (event.key == 'Delete') {
console.log('The keypress meant the same as pressing DELETE');
// This can happen for one of two reasons:
// 1. The user pressed the DELETE key
// 2. The user pressed FN+BACKSPACE on a small Mac keyboard where
// FN+BACKSPACE deletes the character in front of the text cursor,
// instead of the one behind it.
}
if (event.key == 'Backspace') {
console.log('The keypress meant the same as pressing BACKSPACE');
}
});
<>
is standard ANSI SQL and stands for not equal or !=
.
You can use: <xsl:text> </xsl:text>
see the example
<xsl:variable name="module-info">
<xsl:value-of select="@name" /> = <xsl:value-of select="@rev" />
<xsl:text> </xsl:text>
</xsl:variable>
if you write this in file e.g.
<redirect:write file="temp.prop" append="true">
<xsl:value-of select="$module-info" />
</redirect:write>
this variable will produce a new line infile as:
commons-dbcp_commons-dbcp = 1.2.2
junit_junit = 4.4
org.easymock_easymock = 2.4
Both Python dict
(before Python 3.7) and JSON object are unordered collections. You could pass sort_keys
parameter, to sort the keys:
>>> import json
>>> json.dumps({'a': 1, 'b': 2})
'{"b": 2, "a": 1}'
>>> json.dumps({'a': 1, 'b': 2}, sort_keys=True)
'{"a": 1, "b": 2}'
If you need a particular order; you could use collections.OrderedDict
:
>>> from collections import OrderedDict
>>> json.dumps(OrderedDict([("a", 1), ("b", 2)]))
'{"a": 1, "b": 2}'
>>> json.dumps(OrderedDict([("b", 2), ("a", 1)]))
'{"b": 2, "a": 1}'
Since Python 3.6, the keyword argument order is preserved and the above can be rewritten using a nicer syntax:
>>> json.dumps(OrderedDict(a=1, b=2))
'{"a": 1, "b": 2}'
>>> json.dumps(OrderedDict(b=2, a=1))
'{"b": 2, "a": 1}'
See PEP 468 – Preserving Keyword Argument Order.
If your input is given as JSON then to preserve the order (to get OrderedDict
), you could pass object_pair_hook
, as suggested by @Fred Yankowski:
>>> json.loads('{"a": 1, "b": 2}', object_pairs_hook=OrderedDict)
OrderedDict([('a', 1), ('b', 2)])
>>> json.loads('{"b": 2, "a": 1}', object_pairs_hook=OrderedDict)
OrderedDict([('b', 2), ('a', 1)])
Make sure branch "master" exists! It's not just a name apparently.
I got this error after creating a blank bare repo, pushing a branch named "dev" to it, and trying to use git log in the bare repo. Interestingly, git branch knows that dev is the only branch existing (so I think this is a git bug).
Solution: I repeated the procedure, this time having renamed "dev" to "master" on the working repo before pushing to the bare repo. Success!
It reads Hello World
(cat
), replaces all (g
) occurrences of %
by $
and (over)writes it to /etc/init.d/dropbox
as root.
You can add float:none; margin:auto;
styling to centerize column content.
git ls-files
lists the files in the current directory. If you want to list untracked files from anywhere in the tree, this might work better:
git ls-files -o --exclude-standard $(git rev-parse --show-toplevel)
To add all untracked files in the tree:
git ls-files -o --exclude-standard $(git rev-parse --show-toplevel) | xargs git add
An abstract class cannot be instantiated by definition. In order to use this class, you must create a concrete subclass which implements all virtual functions of the class. In this case, you most likely have not implemented all the virtual functions declared in Light
. This means that AmbientOccluder
defaults to an abstract class. For us to further help you, you should include the details of the Light
class.
Tensorflow 2.2.0 supports Python3.8
First, make sure to install Python 3.8 64bit. For some reason, the official site defaults to 32bit. Verify this using python -VV
(two capital V
, not W
). Then continue as usual:
python -m pip install --upgrade pip
python -m pip install wheel # not necessary
python -m pip install tensorflow
As usual, make sure you have CUDA 10.1 and CuDNN installed.
Note to other people finding this: The heart of the solution to make nginx not manipulate the URL, is to remove the slash at the end of the Copy: proxy_pass directive. http://my_app_upstream vs http://my_app_upstream/ – Hugo Josefson
I found this above in the comments but I think it really should be an answer.
If only to 0 then you can use memset
:
int* a = new int[6];
memset(a, 0, 6*sizeof(int));
Actually, ojdbc14.jar doesn't really say anything about the real version of the driver (see JDBC Driver Downloads), except that it predates Oracle 11g. In such situation, you should provide the exact version.
Anyway, I think you'll find some explanation in What is going on with DATE and TIMESTAMP? In short, they changed the behavior in 9.2 drivers and then again in 11.1 drivers.
This might explain the differences you're experiencing (and I suggest using the most recent version i.e. the 11.2 drivers).
Maven plugin uses a settings file where the configuration can be set. Its path is available in Eclipse at Window|Preferences|Maven|User Settings
. If the file doesn't exist, create it and put on something like this:
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository/>
<interactiveMode/>
<usePluginRegistry/>
<offline/>
<pluginGroups/>
<servers/>
<mirrors/>
<proxies>
<proxy>
<id>myproxy</id>
<active>true</active>
<protocol>http</protocol>
<host>192.168.1.100</host>
<port>6666</port>
<username></username>
<password></password>
<nonProxyHosts>localhost|127.0.0.1</nonProxyHosts>
</proxy>
</proxies>
<profiles/>
<activeProfiles/>
</settings>
After editing the file, it's just a matter of clicking on Update Settings
button and it's done. I've just done it and it worked :)
You could make a recursive function do the work
L = size(M)
idx = zeros(L,1)
length(L)
as the maximum depthfor idx(depth) = 1:L(depth)
length(L)
, do the element operation, else call the function again with depth+1
Not as fast as vectorized methods if you want to check all the points, but if you don't need to evaluate most of them it can be quite a time saver.
A Bin file is a pure binary file with no memory fix-ups or relocations, more than likely it has explicit instructions to be loaded at a specific memory address. Whereas....
ELF files are Executable Linkable Format which consists of a symbol look-ups and relocatable table, that is, it can be loaded at any memory address by the kernel and automatically, all symbols used, are adjusted to the offset from that memory address where it was loaded into. Usually ELF files have a number of sections, such as 'data', 'text', 'bss', to name but a few...it is within those sections where the run-time can calculate where to adjust the symbol's memory references dynamically at run-time.
select DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-0, -1) LastDate
What @Nilsi mentioned is perfectly correct. However, adminclass and user class need to be wrapped in single quotes as this might fail due to Thymeleaf looking for adminClass or userclass variables which should be strings. That said,
it should be: -
<a href="" class="baseclass" th:classappend="${isAdmin} ? 'adminclass' :
'userclass'">
</a>
or just:
<a href="" th:class="${isAdmin} ? 'newclass' :
'baseclass'">
</a>
RDBMS focus more on relationship and NoSQL focus more on storage.
You can consider using NoSQL when your RDBMS reaches bottlenecks. NoSQL makes RDBMS more flexible.
select format(convert(float,@your_column),'0.0#########')
Advantage: This solution is irrespective of the source datatype (float, scientific, varchar, date etc)
String
is limited to 10 digits, bigInt
gets rid of decimal values
It's common when you want to implement a singleton. The class can have a static "factory method" that checks if the class has already been instantiated, and calls the constructor if it hasn't.
On the Eclipse toolbar, select Window ? Preferences, set the font size (General ? Appearance ? Colors and Fonts ? Basic ? Text Font).
Save the preferences.
Our team uses dropbox for ad-hoc distribution which uses https but still our app was failing to install. After much trouble-shooting we realized that the title field is required too. Whenever we sent out a link without this field safari ignored the link and did not prompt the user to install. Sometimes for quick development tests we skipped over the title node in the xml and not populate it. In case this is helpful for anyone having this issue make sure that your .plist contains the following nodes populated:
....
<string>software</string>
<key>title</key>
<string>Your App Name</string>
...
In my case, I tried to first use port 88 instead, and even then the httpd won't start.
I used the below command, i.e. modify instead of add, as suggested by one of users, and was able to run httpd.
semanage port -a -t http_port_t -p tcp 88
resultList = results.Where(x=>x.Id != 2).ToList();
There's a little Linq helper I like that's easy to implement and can make queries with "where not" conditions a little easier to read:
public static IEnumerable<T> ExceptWhere<T>(this IEnumerable<T> source, Predicate<T> predicate)
{
return source.Where(x=>!predicate(x));
}
//usage in above situation
resultList = results.ExceptWhere(x=>x.Id == 2).ToList();
(The answer was heavily modified after clarifications to the original question)
After clarifications:
This cannot be done in xml only. It is not possible to scale both the image and the ImageView
so that image's one dimension would always be 250dp and the ImageView
would have the same dimensions as the image.
This code scales Drawable
of an ImageView
to stay in a square like 250dp x 250dp with one dimension exactly 250dp and keeping the aspect ratio. Then the ImageView
is resized to match the dimensions of the scaled image. The code is used in an activity. I tested it via button click handler.
Enjoy. :)
private void scaleImage(ImageView view) throws NoSuchElementException {
// Get bitmap from the the ImageView.
Bitmap bitmap = null;
try {
Drawable drawing = view.getDrawable();
bitmap = ((BitmapDrawable) drawing).getBitmap();
} catch (NullPointerException e) {
throw new NoSuchElementException("No drawable on given view");
} catch (ClassCastException e) {
// Check bitmap is Ion drawable
bitmap = Ion.with(view).getBitmap();
}
// Get current dimensions AND the desired bounding box
int width = 0;
try {
width = bitmap.getWidth();
} catch (NullPointerException e) {
throw new NoSuchElementException("Can't find bitmap on given view/drawable");
}
int height = bitmap.getHeight();
int bounding = dpToPx(250);
Log.i("Test", "original width = " + Integer.toString(width));
Log.i("Test", "original height = " + Integer.toString(height));
Log.i("Test", "bounding = " + Integer.toString(bounding));
// Determine how much to scale: the dimension requiring less scaling is
// closer to the its side. This way the image always stays inside your
// bounding box AND either x/y axis touches it.
float xScale = ((float) bounding) / width;
float yScale = ((float) bounding) / height;
float scale = (xScale <= yScale) ? xScale : yScale;
Log.i("Test", "xScale = " + Float.toString(xScale));
Log.i("Test", "yScale = " + Float.toString(yScale));
Log.i("Test", "scale = " + Float.toString(scale));
// Create a matrix for the scaling and add the scaling data
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
// Create a new bitmap and convert it to a format understood by the ImageView
Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
width = scaledBitmap.getWidth(); // re-use
height = scaledBitmap.getHeight(); // re-use
BitmapDrawable result = new BitmapDrawable(scaledBitmap);
Log.i("Test", "scaled width = " + Integer.toString(width));
Log.i("Test", "scaled height = " + Integer.toString(height));
// Apply the scaled bitmap
view.setImageDrawable(result);
// Now change ImageView's dimensions to match the scaled image
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
params.width = width;
params.height = height;
view.setLayoutParams(params);
Log.i("Test", "done");
}
private int dpToPx(int dp) {
float density = getApplicationContext().getResources().getDisplayMetrics().density;
return Math.round((float)dp * density);
}
The xml code for the ImageView
:
<ImageView a:id="@+id/image_box"
a:background="#ff0000"
a:src="@drawable/star"
a:layout_width="wrap_content"
a:layout_height="wrap_content"
a:layout_marginTop="20dp"
a:layout_gravity="center_horizontal"/>
Thanks to this discussion for the scaling code:
http://www.anddev.org/resize_and_rotate_image_-_example-t621.html
UPDATE 7th, November 2012:
Added null pointer check as suggested in comments
You may find this query useful:
SELECT *
FROM sys.dm_exec_requests
WHERE DB_NAME(database_id) = 'YourDBName'
AND blocking_session_id <> 0
Simply use FractionallySizedBox
, where widthFactor
& heightFactor
define the percentage of app/parent size.
FractionallySizedBox(
widthFactor: 0.8, //means 80% of app width
child: RaisedButton(
onPressed: () {},
child: Text(
"Your Text",
style: TextStyle(color: Colors.white),
),
color: Colors.red,
)),
Global variables and static variables are automatically initialized to zero. If you have simply
char ZEROARRAY[1024];
at global scope it will be all zeros at runtime. But actually there is a shorthand syntax if you had a local array. If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type. You could write:
char ZEROARRAY[1024] = {0};
The compiler would fill the unwritten entries with zeros. Alternatively you could use memset
to initialize the array at program startup:
memset(ZEROARRAY, 0, 1024);
That would be useful if you had changed it and wanted to reset it back to all zeros.
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
//more views
</androidx.constraintlayout.widget.ConstraintLayout>
In the above code, the basic need of tools:context is to tell which activity or fragment the layout file is associated with by default. So, you can specify the activity class name using the same dot prefix as used in Manifest file.
By doing so, the Android Studio will choose the necessary theme for the preview automatically and you don’t have to do the preview settings manually. As we all know that a layout file can be associated with several activities but the themes are defined in the Manifest file and these themes are associated with your activity. So, by adding tools:context in your layout file, the Android Studio preview will automatically choose the necessary theme for you.
I also met this problem when I've made ListView for android app:
Map<String, Object> m;
for(int i=0; i < dates.length; i++){
m = new HashMap<String, Object>();
m.put(ATTR_DATES, dates[i]);
m.put(ATTR_SQUATS, squats[i]);
m.put(ATTR_BP, benchpress[i]);
m.put(ATTR_ROW, row[i]);
data.add(m);
}
The problem was that I've forgotten to use the [i]
index inside the loop
Updated answer of Jesse Crossen for Swift 4:
extension UIButton {
func alignVertical(spacing: CGFloat = 6.0) {
guard let imageSize = self.imageView?.image?.size,
let text = self.titleLabel?.text,
let font = self.titleLabel?.font
else { return }
self.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: -imageSize.width, bottom: -(imageSize.height + spacing), right: 0.0)
let labelString = NSString(string: text)
let titleSize = labelString.size(withAttributes: [kCTFontAttributeName as NSAttributedStringKey: font])
self.imageEdgeInsets = UIEdgeInsets(top: -(titleSize.height + spacing), left: 0.0, bottom: 0.0, right: -titleSize.width)
let edgeOffset = abs(titleSize.height - imageSize.height) / 2.0;
self.contentEdgeInsets = UIEdgeInsets(top: edgeOffset, left: 0.0, bottom: edgeOffset, right: 0.0)
}
}
Use this way:
override func viewDidLayoutSubviews() {
button.alignVertical()
}
The trick here is to use the -C (comment) parameter to specify your GCE userid. It looks like Google introduced this change last in 2018.
If the Google user who owns the GCE instance is [email protected] (which you will use as your login userid), then generate the key pair with (for example)
ssh-keygen -b521 -t ecdsa -C myname -f mykeypair
When you paste mykeypair.pub into the instance's public key list, you should see "myname" appear as the userid of the key.
Setting this up will let you use ssh, scp, etc from your command line.
As per the other answers, set the output logging level to detailed and search there for conflicts, that will tell you where to look next.
In my case, it sent me off in a few directions looking for the source of the references, but in the end it turned out that the problem was one of my portable class library projects, it was targeting the wrong version and was pulling its own version of the references in, hence the conflicts. A quick re-target and the problem was solved.
Shorter version:
$('#multiselect1').multiselect({
...
onChange: function() {
console.log($('#multiselect1').val());
}
});
or shorter
function sortBy(field) {_x000D_
return function(a, b) {_x000D_
return (a[field] > b[field]) - (a[field] < b[field])_x000D_
};_x000D_
}_x000D_
_x000D_
let myArray = [_x000D_
{tabid: 6237, url: 'https://reddit.com/r/znation'},_x000D_
{tabid: 8430, url: 'https://reddit.com/r/soccer'},_x000D_
{tabid: 1400, url: 'https://reddit.com/r/askreddit'},_x000D_
{tabid: 3620, url: 'https://reddit.com/r/tacobell'},_x000D_
{tabid: 5753, url: 'https://reddit.com/r/reddevils'},_x000D_
]_x000D_
_x000D_
myArray.sort(sortBy('url'));_x000D_
console.log(myArray);
_x000D_
Which one of those is indexable?
This one is definitely btree-indexable:
WHERE title >= '0' AND title < ':'
Note that ':' comes after '9' in ASCII.
You normally define your connection strings in Web.config. After generating the edmx the connection string will get stored in the App.Config. If you want to change the connection string go to the app.config and remove all the connection strings. Now go to the edmx, right click on the designer surface, select Update model from database, choose the connection string from the dropdown, Click next, Add or Refresh (select what you want) and finish.
In the output window it will show something like this,
Generated model file: UpostDataModel.edmx. Loading metadata from the database took 00:00:00.4258157. Generating the model took 00:00:01.5623765. Added the connection string to the App.Config file.
If you are using Twig as a standalone component here's some example of how to enable debugging as it's unlikely the dump(variable) function will work straight out of the box
This was found on the link provided by icode4food
$twig = new Twig_Environment($loader, array(
'debug' => true,
// ...
));
$twig->addExtension(new Twig_Extension_Debug());
$app->register(new \Silex\Provider\TwigServiceProvider(), array(
'debug' => true,
'twig.path' => __DIR__.'/views'
));
you can do so by using the :before
or :after
pseudo. read more about it here http://astronautweb.co/snippet/font-awesome/
change your code to this
.lb-prev:hover {
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100);
opacity: 1;
text-decoration: none;
}
.lb-prev:before {
font-family: FontAwesome;
content: "\f053";
font-size: 30px;
}
do the same for the other icons. you might want to adjust the color and height of the icons too. anyway here is the fiddle hope this helps
Nothing wrong with straight up recursion for this task, and if you need a version that works with strings, this might fit your needs:
combinations = []
def combine(terms, accum):
last = (len(terms) == 1)
n = len(terms[0])
for i in range(n):
item = accum + terms[0][i]
if last:
combinations.append(item)
else:
combine(terms[1:], item)
>>> a = [['ab','cd','ef'],['12','34','56']]
>>> combine(a, '')
>>> print(combinations)
['ab12', 'ab34', 'ab56', 'cd12', 'cd34', 'cd56', 'ef12', 'ef34', 'ef56']
Try this
Option Explicit
Sub UniqueValues()
Dim ws As Worksheet
Dim uniqueRng As Range
Dim myCol As Long
myCol = 5 '<== set it as per your needs
Set ws = ThisWorkbook.Worksheets("unique") '<== set it as per your needs
Set uniqueRng = GetUniqueValues(ws, myCol)
End Sub
Function GetUniqueValues(ws As Worksheet, col As Long) As Range
Dim firstRow As Long
With ws
.Columns(col).RemoveDuplicates Columns:=Array(1), header:=xlNo
firstRow = 1
If IsEmpty(.Cells(1, col)) Then firstRow = .Cells(1, col).End(xlDown).row
Set GetUniqueValues = Range(.Cells(firstRow, col), .Cells(.Rows.Count, col).End(xlUp))
End With
End Function
it should be quite fast and without the drawback NeepNeepNeep told about
A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. It is an "interface" that allows access to application specific resources and class and information about application environment. Your activities and services also extend Context to they inherit all those methods to access the environment information in which the application is running.
This means you must have to pass context to the specific class if you want to get/modify some specific information about the resources. You can pass context in the constructor like
public classname(Context context, String s1)
{
...
}
I know this question is old. Other answers here suggesting Html.fromHtml()
method. I suggest you to use HtmlCompat.fromHtml()
from androidx.core.text.HtmlCompat
package. As this is backward compatible version of Html
class.
Sample code:
import androidx.core.text.HtmlCompat;
import android.text.Spanned;
import android.widget.TextView;
String htmlString = "<h1>Hello World!</h1>";
Spanned spanned = HtmlCompat.fromHtml(htmlString, HtmlCompat.FROM_HTML_MODE_COMPACT);
TextView tvOutput = (TextView) findViewById(R.id.text_view_id);
tvOutput.setText(spanned);
By this way you can avoid Android API version check and it's easy to use (single line solution).
You could try using Insight a graphical front-end for gdb written by Red Hat Or if you use GNOME desktop environment, you can also try Nemiver.
For elementwise multiplication of matrix
objects, you can use numpy.multiply
:
import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
np.multiply(a,b)
Result
array([[ 5, 12],
[21, 32]])
However, you should really use array
instead of matrix
. matrix
objects have all sorts of horrible incompatibilities with regular ndarrays. With ndarrays, you can just use *
for elementwise multiplication:
a * b
If you're on Python 3.5+, you don't even lose the ability to perform matrix multiplication with an operator, because @
does matrix multiplication now:
a @ b # matrix multiplication
I'm surprised no one mentioned the possibility to use an API to do the work.
Granted, if you want to stay secure, converting HTML to PDF directly from within the browser using javascript is not a good idea.
But here's what you can do:
When your user hit the "Print" (for example) button, you:
For a user point of view, they will receive a PDF by clicking on a button.
There are many available API that does the job, some better than others (that's not why I'm here) and a Google search will give you a lot of answers.
Depending on what is written your backend, you might be interested in PDFShift (Truth: I work there).
They offer ready to work packages for PHP, Python and Node.js. All you have to do is install the package, create an account, indicate your API key and you are all set!
The advantage of the API is that they work well in all languages. All you have to do is a request (generally POST) containing the data you want to be converted and get a PDF back. And depending on your usage, it's generally free, except if you are a heavy user.
string.split("=", 2);
As String.split(java.lang.String regex, int limit)
explains:
The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.
The
limit
parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.The string
boo:and:foo
, for example, yields the following results with these parameters:Regex Limit Result : 2 { "boo", "and:foo" } : 5 { "boo", "and", "foo" } : -2 { "boo", "and", "foo" } o 5 { "b", "", ":and:f", "", "" } o -2 { "b", "", ":and:f", "", "" } o 0 { "b", "", ":and:f" }
...is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called
While "Easier to ask for forgiveness than permission" is certainly the Pythonic way, you may be looking for:
d={'foo':'bar', 'spam':'eggs'}
if 'get' in dir(d):
d.get('foo')
# OUT: 'bar'
You need to set your local branch to track the remote branch, which it won't do automatically if they have different capitalizations.
Try:
git branch --set-upstream downloadmanager origin/DownloadManager
git pull
UPDATE:
'--set-upstream' option is no longer supported.
git branch --set-upstream-to downloadmanager origin/DownloadManager
git pull
You can Use both disabled or readonly attribute of input . Using disable attribute will omit that value at form submit, so if you want that values at submit event make them readonly instead of disable.
<input type="text" readonly>
or
<input type="text" disabled>
You can refer to the following article: http://www.wellho.net/mouth/3934_Multiple-identical-keys-in-a-Python-dict-yes-you-can-.html
In a dict, if a key is an object, there are no duplicate problems.
For example:
class p(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
def __str__(self):
return self.name
d = {p('k'): 1, p('k'): 2}
This is what I'm teaching my students tomorrow. After years of looking at this stuff... ie all of the documentation above http://www.cpearson.com/excel/errorhandling.htm comes to mind as an excellent one...
I hope this summarizes it for others. There is an Err
object and an active (or inactive) ErrorHandler
. Both need to be handled and reset for new errors.
Paste this into a workbook and step through it with F8.
Sub ErrorHandlingDemonstration()
On Error GoTo ErrorHandler
'this will error
Debug.Print (1 / 0)
'this will also error
dummy = Application.WorksheetFunction.VLookup("not gonna find me", Range("A1:B2"), 2, True)
'silly error
Dummy2 = "string" * 50
Exit Sub
zeroDivisionErrorBlock:
maybeWe = "did some cleanup on variables that shouldnt have been divided!"
' moves the code execution to the line AFTER the one that errored
Resume Next
vlookupFailedErrorBlock:
maybeThisTime = "we made sure the value we were looking for was in the range!"
' moves the code execution to the line AFTER the one that errored
Resume Next
catchAllUnhandledErrors:
MsgBox(thisErrorsDescription)
Exit Sub
ErrorHandler:
thisErrorsNumberBeforeReset = Err.Number
thisErrorsDescription = Err.Description
'this will reset the error object and error handling
On Error GoTo 0
'this will tell vba where to go for new errors, ie the new ErrorHandler that was previous just reset!
On Error GoTo ErrorHandler
' 11 is the err.number for division by 0
If thisErrorsNumberBeforeReset = 11 Then
GoTo zeroDivisionErrorBlock
' 1004 is the err.number for vlookup failing
ElseIf thisErrorsNumberBeforeReset = 1004 Then
GoTo vlookupFailedErrorBlock
Else
GoTo catchAllUnhandledErrors
End If
End Sub
If you are going to do it in pure CSS (using scss) but you have different elements/classes inside the same parent class you can use this version!!
&:first-of-type:nth-last-of-type(1) {
max-width: 100%;
}
@for $i from 2 through 10 {
&:first-of-type:nth-last-of-type(#{$i}),
&:first-of-type:nth-last-of-type(#{$i}) ~ & {
max-width: (100% / #{$i});
}
}
macOS:
I have found that the best approach is to convert the "moment" of interest to a utc-timezone-aware datetime object (in python, the timezone component is not required for datetime objects).
Then you can use astimezone to convert to the timezone of interest (reference).
from datetime import datetime
import pytz
utcmoment_naive = datetime.utcnow()
utcmoment = utcmoment_naive.replace(tzinfo=pytz.utc)
# print "utcmoment_naive: {0}".format(utcmoment_naive) # python 2
print("utcmoment_naive: {0}".format(utcmoment_naive))
print("utcmoment: {0}".format(utcmoment))
localFormat = "%Y-%m-%d %H:%M:%S"
timezones = ['America/Los_Angeles', 'Europe/Madrid', 'America/Puerto_Rico']
for tz in timezones:
localDatetime = utcmoment.astimezone(pytz.timezone(tz))
print(localDatetime.strftime(localFormat))
# utcmoment_naive: 2017-05-11 17:43:30.802644
# utcmoment: 2017-05-11 17:43:30.802644+00:00
# 2017-05-11 10:43:30
# 2017-05-11 19:43:30
# 2017-05-11 13:43:30
So, with the moment of interest in the local timezone (a time that exists), you convert it to utc like this (reference).
localmoment_naive = datetime.strptime('2013-09-06 14:05:10', localFormat)
localtimezone = pytz.timezone('Australia/Adelaide')
try:
localmoment = localtimezone.localize(localmoment_naive, is_dst=None)
print("Time exists")
utcmoment = localmoment.astimezone(pytz.utc)
except pytz.exceptions.NonExistentTimeError as e:
print("NonExistentTimeError")
If installed Django using python setup.py install
python -c "import sys; sys.path = sys.path[1:]; import django; print(django.__path__)"
find the directory you need to remove, delete it
Here is the Primary key Column Name
SELECT k.column_name
FROM information_schema.table_constraints t
JOIN information_schema.key_column_usage k
USING(constraint_name,table_schema,table_name)
WHERE t.constraint_type='PRIMARY KEY'
AND t.table_schema='YourDatabase'
AND t.table_name='YourTable';
You missed the second statement: 1) NOT LIKE A, AND 2) NOT LIKE B
SELECT word FROM table WHERE word NOT LIKE '%a%' AND word NOT LIKE '%b%'
jquery provides val()
function and not value()
. You can check empty string using jquery
if($('#person_data[document_type]').val() != ''){}
A friend was having issues in Internet Explorer 8 and showed me what he did. I told him it was wrong, and he told me he got the answer here. The current top answer will not work in all browsers (Internet Explorer 8 for example), and it will only remove the first occurrence of the item.
function array_remove_index_by_value(arr, item)
{
for (var i = arr.length; i--;)
{
if (arr[i] === item) {arr.splice(i, 1);}
}
}
It loops through the array backwards (since indices and length will change as items are removed) and removes the item if it's found. It works in all browsers.
If you're using Emacs, you can type C-x v ~
to see a different revision of the file you're currently editing (tags, branches and hashes all work).
FIX 1:
Step1: Go to settings > then select the following configuration(Disable Floppy)
Alternatively, you can press F12 while booting the Guest OS and select CD from there, this is a one time setting, good enough for the installation.
Step 2: Place your Existing Guest OS bootable CD in the Disk Drive and start the Guest OS.
FIX 2:
Go to Settings > And Perform the following:
FIX 3:
Try Fix 1 & 2 together..
driver.find_element_by_id('foo').clear()
Try this code my friend...
#include<stdio.h>
int main(){
char *s1, *s2;
char str[10];
printf("type a string: ");
scanf("%s", str);
s1 = &str[0];
s2 = &str[2];
printf("%c\n", *s1); //use %c instead of %s and *s1 which is the content of position 1
printf("%c\n", *s2); //use %c instead of %s and *s3 which is the content of position 1
return 0;
}
I just change the type of input to the text and back to the file :D
I took another approach inspired by @john-rees above - especially when his approach started to fail for me at some point. Basically recurse the subtree and sort files by their path-length - delete from longest to the shortest
Get-ChildItem $tfsLocalPath -Recurse | #Find all children
Select-Object FullName,@{Name='PathLength';Expression={($_.FullName.Length)}} | #Calculate the length of their path
Sort-Object PathLength -Descending | #sort by path length descending
%{ Get-Item -LiteralPath $_.FullName } |
Remove-Item -Force
Regarding the -LiteralPath magic, here's another gotchya that may be hitting you: https://superuser.com/q/212808
Escape the | character using a backtick
get-content c:\new\temp_*.txt | select-string -pattern 'H`|159' -notmatch | Out-File c:\new\newfile.txt
java 1.6.0_21 or later, or so...
$ java -XX:+PrintFlagsFinal -version 2>&1 | grep MaxHeapSize
uintx MaxHeapSize := 12660904960 {product}
It looks like the min(1G) has been removed.
Or on Windows using findstr
C:\>java -XX:+PrintFlagsFinal -version 2>&1 | findstr MaxHeapSize
Method A is recommended by httpclient developer community.
Please refer http://www.mail-archive.com/[email protected]/msg02455.html for more details.
One simpler way to include a class file of one project in another projects is by Adding the project in existing solution and then Adding the DLL reference of the new project in the existing project. Finally, you can use the methods of the added class by decalring using directive at the top of the any class.
C (ISO/IEC 9899:1999, 6.4.6/3) and C++ (ISO/IEC 14882:2003, 2.5) have a feature that is rarely used, called "digraphs" by C and "alternative tokens" by C++. These differ from trigraphs mainly because string literals containing them will never be interpreted differently.
%:include <stdio.h>
int main() <%
int a<:10:> = <%0%>;
printf("Here's the 5th element of 'a': %d\n", a<:4:>);
puts("Evil, eh? %:>");
return 0;
%>
C++ has many more, including and, or, and not which are required to behave as &&
, ||
, and !
. C has these too, but requires that <iso646.h> be included to use them, treating them as macros rather than tokens. The C++ header <ciso646> is literally an empty file.
It's worth noting that GCC implements support for this weird language feature, but lots of other compilers choke and die when trying to compile the above segment of code.
By some reason sql server save some identity columns in different tables, the code that work for me, is the following:
select TABLE_NAME tabla,COLUMN_NAME columna
from INFORMATION_SCHEMA.COLUMNS
where COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
union all
select o.name tabla, c.name columna
from sys.objects o
inner join sys.columns c on o.object_id = c.object_id
where c.is_identity = 1
You can use the Tomcat manager app to find out which JRE and OS versions Tomcat is using. Given a user tomcat
with password password
with a role of manager
:
Tomcat 6:
curl http://tomcat:password@localhost:8080/manager/serverinfo
Tomcat 7/8:
curl http://tomcat:password@localhost:8080/manager/text/serverinfo
You will have to make a new static method where you iterate PcapLinkType.values() and compare:
public static PcapLinkType forCode(int code) {
for (PcapLinkType typ? : PcapLinkType.values()) {
if (type.getValue() == code) {
return type;
}
}
return null;
}
That would be fine if it is called rarely. If it is called frequently, then look at the Map
optimization suggested by others.
Could do this, but then the user has to separate the numbers by a space:
#include "stdio.h"
int main()
{
int minx, x, y, z;
printf("Enter four ints: ");
scanf( "%i %i %i %i", &minx, &x, &y, &z);
printf("You wrote: %i %i %i %i", minx, x, y, z);
}
Use the following methods
1: Method one
var count = 123;
var message = $"Rows count is: {count}";
2: Method two
var count = 123;
var message = "Rows count is:" + count;
3: Method three
var count = 123;
var message = string.Format("Rows count is:{0}", count);
4: Method four
var count = 123;
var message = @"Rows
count
is:{0}" + count;
5: Method five
var count = 123;
var message = $@"Rows
count
is: {count}";
The <p>
paragraph tag is meant for specifying paragraphs of text. If you don't want the text to start on a new line, I would suggest you're using the <p>
tag incorrectly. Perhaps the <span>
tag more closely fits what you want to achieve...?
The problems were:
The solution based on omerkirk's answer involves:
autoOpen: false, width: "auto", height: "auto"
Here is a rough outline of code:
<div class="thumb">
<a href="http://jsfiddle.net/yBNVr/show/" data-title="Std 4:3 ratio video" data-width="512" data-height="384"><img src="http://dummyimage.com/120x90/000/f00&text=Std+4-3+ratio+video" /></a></li>
<a href="http://jsfiddle.net/yBNVr/1/show/" data-title="HD 16:9 ratio video" data-width="512" data-height="288"><img src="http://dummyimage.com/120x90/000/f00&text=HD+16-9+ratio+video" /></a></li>
</div>
$(function () {
var iframe = $('<iframe frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>');
var dialog = $("<div></div>").append(iframe).appendTo("body").dialog({
autoOpen: false,
modal: true,
resizable: false,
width: "auto",
height: "auto",
close: function () {
iframe.attr("src", "");
}
});
$(".thumb a").on("click", function (e) {
e.preventDefault();
var src = $(this).attr("href");
var title = $(this).attr("data-title");
var width = $(this).attr("data-width");
var height = $(this).attr("data-height");
iframe.attr({
width: +width,
height: +height,
src: src
});
dialog.dialog("option", "title", title).dialog("open");
});
});
Demo here and code here. And another example along similar lines
For JavaScript arrays, you use Both push() and concat() function.
var array = [1, 2, 3];
array.push(4, 5); //use push for appending a single array.
var array1 = [1, 2, 3];
var array2 = [4, 5, 6];
var array3 = array1.concat(array2); //It is better use concat for appending more then one array.
Something like this?
if so, type the HTML ✔
And ✓
gives a lighter one:
✓
In C++, you can use a such function:
template <typename T>
T to(const std::string & s)
{
std::istringstream stm(s);
T result;
stm >> result;
if(stm.tellg() != s.size())
throw error;
return result;
}
This can help you to convert any string to any type such as float, int, double...
this may not be accurate but its close enough for me
long size = 0;
object o = new object();
using (Stream s = new MemoryStream()) {
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(s, o);
size = s.Length;
}
BeatifulSoup's own parser can be slow. It might be more feasible to use lxml which is capable of parsing directly from a URL (with some limitations mentioned below).
import lxml.html
doc = lxml.html.parse(url)
links = doc.xpath('//a[@href]')
for link in links:
print link.attrib['href']
The code above will return the links as is, and in most cases they would be relative links or absolute from the site root. Since my use case was to only extract a certain type of links, below is a version that converts the links to full URLs and which optionally accepts a glob pattern like *.mp3
. It won't handle single and double dots in the relative paths though, but so far I didn't have the need for it. If you need to parse URL fragments containing ../
or ./
then urlparse.urljoin might come in handy.
NOTE: Direct lxml url parsing doesn't handle loading from https
and doesn't do redirects, so for this reason the version below is using urllib2
+ lxml
.
#!/usr/bin/env python
import sys
import urllib2
import urlparse
import lxml.html
import fnmatch
try:
import urltools as urltools
except ImportError:
sys.stderr.write('To normalize URLs run: `pip install urltools --user`')
urltools = None
def get_host(url):
p = urlparse.urlparse(url)
return "{}://{}".format(p.scheme, p.netloc)
if __name__ == '__main__':
url = sys.argv[1]
host = get_host(url)
glob_patt = len(sys.argv) > 2 and sys.argv[2] or '*'
doc = lxml.html.parse(urllib2.urlopen(url))
links = doc.xpath('//a[@href]')
for link in links:
href = link.attrib['href']
if fnmatch.fnmatch(href, glob_patt):
if not href.startswith(('http://', 'https://' 'ftp://')):
if href.startswith('/'):
href = host + href
else:
parent_url = url.rsplit('/', 1)[0]
href = urlparse.urljoin(parent_url, href)
if urltools:
href = urltools.normalize(href)
print href
The usage is as follows:
getlinks.py http://stackoverflow.com/a/37758066/191246
getlinks.py http://stackoverflow.com/a/37758066/191246 "*users*"
getlinks.py http://fakedomain.mu/somepage.html "*.mp3"
The Simplest Way is:
In Swift 3:
var textViewString:String = "HelloWorld2016"
guard let index = textViewString.characters.index(of: "W") else { return }
let mentionPosition = textViewString.distance(from: index, to: textViewString.endIndex)
print(mentionPosition)
For windows
please follow these steps
Goto - > File -> preferences -> settings
OR
press CTRL + , (for windows only)
you'll see settings page there find text editor option tab on left side then click on ' Font ' then add any valid font family name there which you want to apply to vscode.
To set a FOREIGN KEY in Table B you must set a KEY in the table A.
In table A:
INDEX id
(id
)
And then in the table B,
CONSTRAINT `FK_id` FOREIGN KEY (`id`) REFERENCES `table-A` (`id`)
This is the right way to execute a .jar
, and whatever one class in that .jar
should have main()
and the following are the parameters to it :
java -DLB="uk" -DType="CLIENT_IND" -jar com.fbi.rrm.rrm-batchy-1.5.jar
You can use a RelativeLayout
and align it to the bottom with android:layout_alignParentBottom="true"
I will suggest you to use ClientID of HiddenField. first Register its client Id in any Javascript Variable from codebehind, then use it in clientside script. as:
.cs file code:
ClientScript.RegisterStartupScript(this.GetType(), "clientids", "var hdntxtbxTaksit=" + hdntxtbxTaksit.ClientID, true);
and then use following code in JS:
document.getElementById(hdntxtbxTaksit).value= "";
@model AdventureWork.CRUD.WebApp4.Models.EmployeeViewModel
@{
ViewBag.Title = "Detalle";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Ingresar Usuario</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Employee.PersonType, labelText: "Tipo de Persona", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Employee.PersonType, new List<SelectListItem>
{
new SelectListItem{ Text= "SC", Value = "SC" },
new SelectListItem{ Text= "VC", Value = "VC" },
new SelectListItem{ Text= "IN", Value = "IN" },
new SelectListItem{ Text= "EM", Value = "EM" },
new SelectListItem{ Text= "SP", Value = "SP" },
}, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Employee.PersonType, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeGender, labelText: "Genero", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Employee.EmployeeGender, new List<SelectListItem>
{
new SelectListItem{ Text= "Masculino", Value = "M" },
new SelectListItem{ Text= "Femenino", Value = "F" }
}, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Employee.EmployeeGender, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.PersonTitle, labelText: "Titulo", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.PersonTitle, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.PersonTitle, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.PersonFirstName, labelText: "Primer Nombre", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.PersonFirstName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.PersonFirstName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.PersonMiddleName, labelText: "Segundo Nombre", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.PersonMiddleName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.PersonMiddleName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.PersonLastName, labelText: "Apellido", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.PersonLastName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.PersonLastName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.PersonSuffix, labelText: "Sufijo", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.PersonSuffix, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.PersonSuffix, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.DepartmentID, labelText: "Departamento", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Employee.DepartmentID, new SelectList(Model.ListDepartment, "DepartmentID", "DepartmentName"), htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Employee.DepartmentID, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeMaritalStatus, labelText: "Estado Civil", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Employee.EmployeeMaritalStatus, new List<SelectListItem>
{
new SelectListItem{ Text= "Soltero", Value = "S" },
new SelectListItem{ Text= "Casado", Value = "M" }
}, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Employee.EmployeeMaritalStatus, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.ShiftId, labelText: "Turno", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Employee.ShiftId, new SelectList(Model.ListShift, "ShiftId", "ShiftName"), htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Employee.ShiftId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeLoginId, labelText: "Login", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.EmployeeLoginId, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.EmployeeLoginId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeNationalIDNumber, labelText: "Identificacion Nacional", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.EmployeeNationalIDNumber, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.EmployeeNationalIDNumber, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeJobTitle, labelText: "Cargo", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.EmployeeJobTitle, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.EmployeeJobTitle, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeBirthDate, labelText: "Fecha Nacimiento", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.EmployeeBirthDate, new { htmlAttributes = new { @class = "form-control datepicker" } })
@Html.ValidationMessageFor(model => model.Employee.EmployeeBirthDate, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Employee.EmployeeSalariedFlag, labelText: "Asalariado", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Employee.EmployeeSalariedFlag, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Employee.EmployeeSalariedFlag, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Guardar" class="btn btn-default" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10" style="color:green">
@ViewBag.Message
</div>
<div class="col-md-offset-2 col-md-10" style="color:red">
@ViewBag.ErrorMessage
</div>
</div>
</div>
}
Do you have Zend, IonCube, or xDebug installed? If so, that is probably where you are getting this error from.
I ran into this a few years ago, and it ended up being Zend putting that limit there, not PHP. Of course removing it will let you go past the 100 iterations, but you will eventually hit the memory limits.
i didn't solve the problem, sadly. but managed to make to codes work (almost all of my codes have this probelm btw) the local issuer certificate problem happens under python3.7 so i changed back to python2.7 QAQ and all that needed to change including "from urllib2 import urlopen" instead of "from urllib.request import urlopen" so sad...
I don't know how exactly the bottom sheet of the new Maps app, responds to user interactions. But you can create a custom view that looks like the one in the screenshots and add it to the main view.
I assume you know how to:
1- create view controllers either by storyboards or using xib files.
2- use googleMaps or Apple's MapKit.
1- Create 2 view controllers e.g, MapViewController and BottomSheetViewController. The first controller will host the map and the second is the bottom sheet itself.
Create a method to add the bottom sheet view.
func addBottomSheetView() {
// 1- Init bottomSheetVC
let bottomSheetVC = BottomSheetViewController()
// 2- Add bottomSheetVC as a child view
self.addChildViewController(bottomSheetVC)
self.view.addSubview(bottomSheetVC.view)
bottomSheetVC.didMoveToParentViewController(self)
// 3- Adjust bottomSheet frame and initial position.
let height = view.frame.height
let width = view.frame.width
bottomSheetVC.view.frame = CGRectMake(0, self.view.frame.maxY, width, height)
}
And call it in viewDidAppear method:
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
addBottomSheetView()
}
Create a method to add blur and vibrancy effects
func prepareBackgroundView(){
let blurEffect = UIBlurEffect.init(style: .Dark)
let visualEffect = UIVisualEffectView.init(effect: blurEffect)
let bluredView = UIVisualEffectView.init(effect: blurEffect)
bluredView.contentView.addSubview(visualEffect)
visualEffect.frame = UIScreen.mainScreen().bounds
bluredView.frame = UIScreen.mainScreen().bounds
view.insertSubview(bluredView, atIndex: 0)
}
call this method in your viewWillAppear
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
prepareBackgroundView()
}
Make sure that your controller's view background color is clearColor.
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
UIView.animateWithDuration(0.3) { [weak self] in
let frame = self?.view.frame
let yComponent = UIScreen.mainScreen().bounds.height - 200
self?.view.frame = CGRectMake(0, yComponent, frame!.width, frame!.height)
}
}
In your viewDidLoad method add UIPanGestureRecognizer.
override func viewDidLoad() {
super.viewDidLoad()
let gesture = UIPanGestureRecognizer.init(target: self, action: #selector(BottomSheetViewController.panGesture))
view.addGestureRecognizer(gesture)
}
And implement your gesture behaviour:
func panGesture(recognizer: UIPanGestureRecognizer) {
let translation = recognizer.translationInView(self.view)
let y = self.view.frame.minY
self.view.frame = CGRectMake(0, y + translation.y, view.frame.width, view.frame.height)
recognizer.setTranslation(CGPointZero, inView: self.view)
}
If your custom view is a scroll view or any other view that inherits from, so you have two options:
First:
Design the view with a header view and add the panGesture to the header. (bad user experience).
Second:
1 - Add the panGesture to the bottom sheet view.
2 - Implement the UIGestureRecognizerDelegate and set the panGesture delegate to the controller.
3- Implement shouldRecognizeSimultaneouslyWith delegate function and disable the scrollView isScrollEnabled property in two case:
Otherwise enable scrolling.
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
let gesture = (gestureRecognizer as! UIPanGestureRecognizer)
let direction = gesture.velocity(in: view).y
let y = view.frame.minY
if (y == fullView && tableView.contentOffset.y == 0 && direction > 0) || (y == partialView) {
tableView.isScrollEnabled = false
} else {
tableView.isScrollEnabled = true
}
return false
}
NOTE
In case you set .allowUserInteraction as an animation option, like in the sample project, so you need to enable scrolling on the animation completion closure if the user is scrolling up.
I created a sample project with more options on this repo which may give you better insights about how to customise the flow.
In the demo, addBottomSheetView() function controls which view should be used as a bottom sheet.
Here is what I learned: PYTHONPATH is a directory to add to the Python import search path "sys.path", which is made up of current dir. CWD, PYTHONPATH, standard and shared library, and customer library. For example:
% python3 -c "import sys;print(sys.path)"
['',
'/home/username/Documents/DjangoTutorial/mySite',
'/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']
where the first path '' denotes the current dir., the 2nd path is via
%export PYTHONPATH=/home/username/Documents/DjangoTutorial/mySite
which can be added to ~/.bashrc to make it permanent, and the rest are Python standard and dynamic shared library plus third-party library such as django.
As said not to mess with PYTHONHOME, even setting it to '' or 'None' will cause python3 shell to stop working:
% export PYTHONHOME=''
% python3
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ModuleNotFoundError: No module named 'encodings'
Current thread 0x00007f18a44ff740 (most recent call first):
Aborted (core dumped)
Note that if you start a Python script, the CWD will be the script's directory. For example:
username@bud:~/Documents/DjangoTutorial% python3 mySite/manage.py runserver
==== Printing sys.path ====
/home/username/Documents/DjangoTutorial/mySite # CWD is where manage.py resides
/usr/lib/python3.6
/usr/lib/python3.6/lib-dynload
/usr/local/lib/python3.6/dist-packages
/usr/lib/python3/dist-packages
You can also append a path to sys.path at run-time: Suppose you have a file Fibonacci.py in ~/Documents/Python directory:
username@bud:~/Documents/DjangoTutorial% python3
>>> sys.path.append("/home/username/Documents")
>>> print(sys.path)
['', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages',
'/home/username/Documents']
>>> from Python import Fibonacci as fibo
or via
% PYTHONPATH=/home/username/Documents:$PYTHONPATH
% python3
>>> print(sys.path)
['',
'/home/username/Documents', '/home/username/Documents/DjangoTutorial/mySite',
'/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']
>>> from Python import Fibonacci as fibo
You don't have to do this locally either. You can do it through a remote repository, for example:
svn export http://<repo>/process/test.txt /path/to/code/
img {
-webkit-filter: drop-shadow(5px 5px 5px #222222);
filter: drop-shadow(5px 5px 5px #222222);
}
That worked great for me. One thing to note tho in IE you need the full color (#222222) three characters don't work.
Using a static const is like using any other const variables in your code. This means you can trace wherever the information comes from, as opposed to a #define that will simply be replaced in the code in the pre-compilation process.
You might want to take a look at the C++ FAQ Lite for this question: http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.7
I had this issue myself, and I wanted to both be able to set the width, and have it update on rotate and allow the user to scale and zoom the page (the current answer provides the first but prevents the later as a side-effect).. so I came up with a fix that keeps the view width correct for the orientation, but still allows for zooming, though it is not super straight forward.
First, add the following Javascript to the webpage you are displaying:
<script type='text/javascript'>
function setViewPortWidth(width) {
var metatags = document.getElementsByTagName('meta');
for(cnt = 0; cnt < metatags.length; cnt++) {
var element = metatags[cnt];
if(element.getAttribute('name') == 'viewport') {
element.setAttribute('content','width = '+width+'; maximum-scale = 5; user-scalable = yes');
document.body.style['max-width'] = width+'px';
}
}
}
</script>
Then in your - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation method, add:
float availableWidth = [EmailVC webViewWidth];
NSString *stringJS;
stringJS = [NSString stringWithFormat:@"document.body.offsetWidth"];
float documentWidth = [[_webView stringByEvaluatingJavaScriptFromString:stringJS] floatValue];
if(documentWidth > availableWidth) return; // Don't perform if the document width is larger then available (allow auto-scale)
// Function setViewPortWidth defined in EmailBodyProtocolHandler prepend
stringJS = [NSString stringWithFormat:@"setViewPortWidth(%f);",availableWidth];
[_webView stringByEvaluatingJavaScriptFromString:stringJS];
Additional Tweaking can be done by modifying more of the viewportal content settings:
Also, I understand you can put a JS listener for onresize or something like to trigger the rescaling, but this worked for me as I'm doing it from Cocoa Touch UI frameworks.
Hope this helps someone :)
This thing is empty nested list from which ne will append data to empty dict
ls = [['a','a1','a2','a3'],['b','b1','b2','b3'],['c','c1','c2','c3'],
['d','d1','d2','d3']]
this means to create four empty dict inside data_dict
data_dict = {f'dict{i}':{} for i in range(4)}
for i in range(4):
upd_dict = {'val' : ls[i][0], 'val1' : ls[i][1],'val2' : ls[i][2],'val3' : ls[i][3]}
data_dict[f'dict{i}'].update(upd_dict)
print(data_dict)
The output
{'dict0': {'val': 'a', 'val1': 'a1', 'val2': 'a2', 'val3': 'a3'}, 'dict1': {'val': 'b', 'val1': 'b1', 'val2': 'b2', 'val3': 'b3'},'dict2': {'val': 'c', 'val1': 'c1', 'val2': 'c2', 'val3': 'c3'}, 'dict3': {'val': 'd', 'val1': 'd1', 'val2': 'd2', 'val3': 'd3'}}
Just adding here that [[
also is equipped for recursive indexing.
This was hinted at in the answer by @JijoMatthew but not explored.
As noted in ?"[["
, syntax like x[[y]]
, where length(y) > 1
, is interpreted as:
x[[ y[1] ]][[ y[2] ]][[ y[3] ]] ... [[ y[length(y)] ]]
Note that this doesn't change what should be your main takeaway on the difference between [
and [[
-- namely, that the former is used for subsetting, and the latter is used for extracting single list elements.
For example,
x <- list(list(list(1), 2), list(list(list(3), 4), 5), 6)
x
# [[1]]
# [[1]][[1]]
# [[1]][[1]][[1]]
# [1] 1
#
# [[1]][[2]]
# [1] 2
#
# [[2]]
# [[2]][[1]]
# [[2]][[1]][[1]]
# [[2]][[1]][[1]][[1]]
# [1] 3
#
# [[2]][[1]][[2]]
# [1] 4
#
# [[2]][[2]]
# [1] 5
#
# [[3]]
# [1] 6
To get the value 3, we can do:
x[[c(2, 1, 1, 1)]]
# [1] 3
Getting back to @JijoMatthew's answer above, recall r
:
r <- list(1:10, foo=1, far=2)
In particular, this explains the errors we tend to get when mis-using [[
, namely:
r[[1:3]]
Error in
r[[1:3]]
: recursive indexing failed at level 2
Since this code actually tried to evaluate r[[1]][[2]][[3]]
, and the nesting of r
stops at level one, the attempt to extract through recursive indexing failed at [[2]]
, i.e., at level 2.
Error in
r[[c("foo", "far")]]
: subscript out of bounds
Here, R was looking for r[["foo"]][["far"]]
, which doesn't exist, so we get the subscript out of bounds error.
It probably would be a bit more helpful/consistent if both of these errors gave the same message.
Using Enum.TryParse you don't need the Exception handling:
baseKey e;
if ( Enum.TryParse(s, out e) )
{
...
}