It is standard matplotlib.pyplot:
...
import matplotlib.pyplot as plt
plt.ylim(10, 40)
Or simpler, as mwaskom comments below:
ax.set(ylim=(10, 40))
You should get your data in a specific format by melting your data (see below for how melted data looks like) before you plot. Otherwise, what you have done seems to be okay.
require(reshape2)
df <- read.csv("TestData.csv", header=T)
# melting by "Label". `melt is from the reshape2 package.
# do ?melt to see what other things it can do (you will surely need it)
df.m <- melt(df, id.var = "Label")
> df.m # pasting some rows of the melted data.frame
# Label variable value
# 1 Good F1 0.64778924
# 2 Good F1 0.54608791
# 3 Good F1 0.46134200
# 4 Good F1 0.79421221
# 5 Good F1 0.56919951
# 6 Good F1 0.73568570
# 7 Good F1 0.65094207
# 8 Good F1 0.45749702
# 9 Good F1 0.80861929
# 10 Good F1 0.67310067
# 11 Good F1 0.68781739
# 12 Good F1 0.47009455
# 13 Good F1 0.95859182
# 14 Good F1 1.00000000
# 15 Good F1 0.46908343
# 16 Bad F1 0.57875528
# 17 Bad F1 0.28938046
# 18 Bad F1 0.68511766
require(ggplot2)
ggplot(data = df.m, aes(x=variable, y=value)) + geom_boxplot(aes(fill=Label))
Edit: I realise that you might need to facet. Here's an implementation of that as well:
p <- ggplot(data = df.m, aes(x=variable, y=value)) +
geom_boxplot(aes(fill=Label))
p + facet_wrap( ~ variable, scales="free")
Edit 2: How to add x-labels
, y-labels
, title
, change legend heading
, add a jitter
?
p <- ggplot(data = df.m, aes(x=variable, y=value))
p <- p + geom_boxplot(aes(fill=Label))
p <- p + geom_jitter()
p <- p + facet_wrap( ~ variable, scales="free")
p <- p + xlab("x-axis") + ylab("y-axis") + ggtitle("Title")
p <- p + guides(fill=guide_legend(title="Legend_Title"))
p
Edit 3: How to align geom_point()
points to the center of box-plot? It could be done using position_dodge
. This should work.
require(ggplot2)
p <- ggplot(data = df.m, aes(x=variable, y=value))
p <- p + geom_boxplot(aes(fill = Label))
# if you want color for points replace group with colour=Label
p <- p + geom_point(aes(y=value, group=Label), position = position_dodge(width=0.75))
p <- p + facet_wrap( ~ variable, scales="free")
p <- p + xlab("x-axis") + ylab("y-axis") + ggtitle("Title")
p <- p + guides(fill=guide_legend(title="Legend_Title"))
p
The simplest is to just give the 'trans' (formerly 'formatter' argument the name of the log function:
m + geom_boxplot() + scale_y_continuous(trans='log10')
EDIT: Or if you don't like that, then either of these appears to give different but useful results:
m <- ggplot(diamonds, aes(y = price, x = color), log="y")
m + geom_boxplot()
m <- ggplot(diamonds, aes(y = price, x = color), log10="y")
m + geom_boxplot()
EDIT2 & 3: Further experiments (after discarding the one that attempted successfully to put "$" signs in front of logged values):
fmtExpLg10 <- function(x) paste(round_any(10^x/1000, 0.01) , "K $", sep="")
ggplot(diamonds, aes(color, log10(price))) +
geom_boxplot() +
scale_y_continuous("Price, log10-scaling", trans = fmtExpLg10)
Note added mid 2017 in comment about package syntax change:
scale_y_continuous(formatter = 'log10') is now scale_y_continuous(trans = 'log10') (ggplot2 v2.2.1)
See ?boxplot
for all the help you need.
outline: if ‘outline’ is not true, the outliers are not drawn (as
points whereas S+ uses lines).
boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)
And for extending the range of the whiskers and suppressing the outliers inside this range:
range: this determines how far the plot whiskers extend out from the
box. If ‘range’ is positive, the whiskers extend to the most
extreme data point which is no more than ‘range’ times the
interquartile range from the box. A value of zero causes the
whiskers to extend to the data extremes.
# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)
Just to add to the conversation, I have found a more elegant way to change the color of the box plot by iterating over the dictionary of the object itself
import numpy as np
import matplotlib.pyplot as plt
def color_box(bp, color):
# Define the elements to color. You can also add medians, fliers and means
elements = ['boxes','caps','whiskers']
# Iterate over each of the elements changing the color
for elem in elements:
[plt.setp(bp[elem][idx], color=color) for idx in xrange(len(bp[elem]))]
return
a = np.random.uniform(0,10,[100,5])
bp = plt.boxplot(a)
color_box(bp, 'red')
Cheers!
I also think chart.Boxplot is the best option, it gives you the position of the mean but if you have a matrix with returns all you need is one line of code to get all the boxplots in one graph.
Here is a small ETF portfolio example.
library(zoo)
library(PerformanceAnalytics)
library(tseries)
library(xts)
VTI.prices = get.hist.quote(instrument = "VTI", start= "2007-03-01", end="2013-03-01",
quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
compression = "m", retclass = c("zoo"))
VEU.prices = get.hist.quote(instrument = "VEU", start= "2007-03-01", end="2013-03-01",
quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
compression = "m", retclass = c("zoo"))
VWO.prices = get.hist.quote(instrument = "VWO", start= "2007-03-01", end="2013-03-01",
quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
compression = "m", retclass = c("zoo"))
VNQ.prices = get.hist.quote(instrument = "VNQ", start= "2007-03-01", end="2013-03-01",
quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
compression = "m", retclass = c("zoo"))
TLT.prices = get.hist.quote(instrument = "TLT", start= "2007-03-01", end="2013-03-01",
quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
compression = "m", retclass = c("zoo"))
TIP.prices = get.hist.quote(instrument = "TIP", start= "2007-03-01", end="2013-03-01",
quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
compression = "m", retclass = c("zoo"))
index(VTI.prices) = as.yearmon(index(VTI.prices))
index(VEU.prices) = as.yearmon(index(VEU.prices))
index(VWO.prices) = as.yearmon(index(VWO.prices))
index(VNQ.prices) = as.yearmon(index(VNQ.prices))
index(TLT.prices) = as.yearmon(index(TLT.prices))
index(TIP.prices) = as.yearmon(index(TIP.prices))
Prices.z=merge(VTI.prices, VEU.prices, VWO.prices, VNQ.prices,
TLT.prices, TIP.prices)
colnames(Prices.z) = c("VTI", "VEU", "VWO" , "VNQ", "TLT", "TIP")
returnscc.z = diff(log(Prices.z))
start(returnscc.z)
end(returnscc.z)
colnames(returnscc.z)
head(returnscc.z)
Return Matrix
ret.mat = coredata(returnscc.z)
class(ret.mat)
colnames(ret.mat)
head(ret.mat)
Box Plot of Return Matrix
chart.Boxplot(returnscc.z, names=T, horizontal=TRUE, colorset="darkgreen", as.Tufte =F,
mean.symbol = 20, median.symbol="|", main="Return Distributions Comparison",
element.color = "darkgray", outlier.symbol = 20,
xlab="Continuously Compounded Returns", sort.ascending=F)
You can try changing the mean.symbol, and remove or change the median.symbol. Hope it helped. :)
instead of trying to catch both POST and GET responses - you can have everything you want in the POST.
Your code:
<form method="POST" action="index.php?action=contact_agent&agent_id=">
<select>
<option value="1">Agent Homer</option>
<option value="2">Agent Lenny</option>
<option value="3">Agent Carl</option>
</select>
</form>
can easily become:
<form method="POST" action="index.php">
<input type="hidden" name="action" value="contact_agent">
<select name="agent_id">
<option value="1">Agent Homer</option>
<option value="2">Agent Lenny</option>
<option value="3">Agent Carl</option>
</select>
<button type="submit">Submit POST Data</button>
</form>
then in index.php - these values will be populated
$_POST['action'] // "contact_agent"
$_POST['agent_id'] // 1, 2 or 3 based on selection in form...
for (i>0; i--;)
is probably wrong and should be
for (; i>0; i--)
instead. Note where I put the semicolons. The condition goes in the middle, not at the start.
import os
def count_files(in_directory):
joiner= (in_directory + os.path.sep).__add__
return sum(
os.path.isfile(filename)
for filename
in map(joiner, os.listdir(in_directory))
)
>>> count_files("/usr/lib")
1797
>>> len(os.listdir("/usr/lib"))
2049
The various overloads of Runtime.getRuntime().exec(...)
take either an array of strings or a single string. The single-string overloads of exec()
will tokenise the string into an array of arguments, before passing the string array onto one of the exec()
overloads that takes a string array. The ProcessBuilder
constructors, on the other hand, only take a varargs array of strings or a List
of strings, where each string in the array or list is assumed to be an individual argument. Either way, the arguments obtained are then joined up into a string that is passed to the OS to execute.
So, for example, on Windows,
Runtime.getRuntime().exec("C:\DoStuff.exe -arg1 -arg2");
will run a DoStuff.exe
program with the two given arguments. In this case, the command-line gets tokenised and put back together. However,
ProcessBuilder b = new ProcessBuilder("C:\DoStuff.exe -arg1 -arg2");
will fail, unless there happens to be a program whose name is DoStuff.exe -arg1 -arg2
in C:\
. This is because there's no tokenisation: the command to run is assumed to have already been tokenised. Instead, you should use
ProcessBuilder b = new ProcessBuilder("C:\DoStuff.exe", "-arg1", "-arg2");
or alternatively
List<String> params = java.util.Arrays.asList("C:\DoStuff.exe", "-arg1", "-arg2");
ProcessBuilder b = new ProcessBuilder(params);
I think that you need to import this:
import 'rxjs/add/operator/map'
Or more generally this if you want to have more methods for observables. WARNING: This will import all 50+ operators and add them to your application, thus affecting your bundle size and load times.
import 'rxjs/Rx';
See this issue for more details.
Just use:
assert cmp(dict1, dict2) == 0
.style1 {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Works in:
In addition you can try this for an ie solution
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";
zoom:1;
Credit to this article by Chris Coyier http://css-tricks.com/perfect-full-page-background-image/
You can use combination of C preprocessor functions with varargs, compound literals and designated initializers for maximum convenience:
typedef struct {
int id;
char* name;
} employee;
#define EMPLOYEE(...) ((employee) { .id = 0, .name = "none", ##__VA_ARGS__ })
employee john = EMPLOYEE(.name="John"); // no id initialization
employee jane = EMPLOYEE(.id=5); // no name initialization
Don't drop, just take the rows where EPS is not NA:
df = df[df['EPS'].notna()]
Regarding “thought leaders”: Linus emphatically advocates line wrapping for the full commit message:
[…] we use 72-character columns for word-wrapping, except for quoted material that has a specific line format.
The exceptions refers mainly to “non-prose” text, that is, text that was not typed by a human for the commit — for example, compiler error messages.
class name:
def __init__(self, name):
self.name = name
print("name: "+name)
Somewhere else:
john = name("john")
Output:
name: john
It doesn't seem possible with SQL Server 2008 alone. You're going to need a third-party tool's help.
It will help you make your .bak act like a live database:
I would not advice you to use built in font-awesome styling like the fa-5x etc; for fear they may change it and you would have to keep chainging your application code to meet up with the latest standard. You simply avoid this by giving each font-awesome class you want to style uniformly the same class say:
<i class="fa fa-facebook-square fa-sabi-social-icons" aria-hidden="true"></i>
<i class="fa fa-twitter-square fa-sabi-social-icons" aria-hidden="true"></i>
<i class="fa fa-google-plus-square fa-sabi-social-icons" aria-hidden="true"></i>
Here the class is fa-sabi-social-icons
Then in your css you can the style the fonts using the same css rules you would style a normal font with. e.g
.fa-sabi-social-icons {
color: //your color;
font-size: // your font-size in px, em or %;
text-shadow: 2px 2px #FF0000;
}
That should get your font-awesome fonts styled
On iOS there is the switch UI component instead of a checkbox, look into the UISwitch
class.
The property on
(boolean) can be used to determine the state of the slider and about the saving of its state: That depends on how you save your other stuff already, its just saving a boolean value.
Look here for a description of the statusVar variable.
You can do something like below, where the "status" variable contains the current status of the iteration. This is very useful if you need special annotations for the first and last iteraton. In the case below I want to ommit the comma behind the last tag. Of course you can replace status.last
with status.first
to do something special on the first itteration:
<td>
<c:forEach var="tag" items="${idea.tags}" varStatus="status">
<span>${tag.name not status.last ? ', ' : ''}</span>
</c:forEach>
</td>
Possible options are: current, index, count, first, last, begin, step,
and end
This is a more versatile solution (that can do a little more than the question asks), and can be used in a query window without having to create a new stored proc - useful in production databases for instance where you don't have write access.
To use the code, please modify according to the in line comments which explain its usage. You can then just run this query in a query window and it will print the INSERT statements you require.
SET NOCOUNT ON
-- Set the ID you wish to filter on here
DECLARE @id AS INT = 123
DECLARE @tables TABLE (Name NVARCHAR(128), IdField NVARCHAR(128), IdInsert BIT, Excluded NVARCHAR(128))
-- Add any tables you wish to generate INSERT statements for here. The fields are as thus:
-- Name: Your table name
-- IdField: The field on which to filter the dataset
-- IdInsert: If the primary key field is to be included in the INSERT statement
-- Excluded: Any fields you do not wish to include in the INSERT statement
INSERT INTO @tables (Name, IdField, IdInsert, Excluded) VALUES ('MyTable1', 'Id', 0, 'Created,Modified')
INSERT INTO @tables (Name, IdField, IdInsert, Excluded) VALUES ('MyTable2', 'Id', 1, 'Created,Modified')
DECLARE @numberTypes TABLE (sysId TINYINT)
-- This will ensure INT and BIT types are not surrounded with quotes in the
-- resultant INSERT statement, but you may need to add more (from sys.types)
INSERT @numberTypes(SysId) VALUES(56),(104)
DECLARE @rows INT = (SELECT COUNT(*) FROM @tables)
DECLARE @cnt INT = 1
DECLARE @results TABLE (Sql NVARCHAR(4000))
WHILE @cnt <= @rows
BEGIN
DECLARE @tablename AS NVARCHAR(128)
DECLARE @idField AS NVARCHAR(128)
DECLARE @idInsert AS BIT
DECLARE @excluded AS NVARCHAR(128)
SELECT
@tablename = Name,
@idField = IdField,
@idInsert = IdInsert,
@excluded = Excluded
FROM (SELECT *, ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS RowId FROM @tables) t WHERE t.RowId = @cnt
DECLARE @excludedFields TABLE (FieldName NVARCHAR(128))
DECLARE @xml AS XML = CAST(('<X>' + REPLACE(@excluded, ',', '</X><X>') + '</X>') AS XML)
INSERT INTO @excludedFields SELECT N.value('.', 'NVARCHAR(128)') FROM @xml.nodes('X') AS T(N)
DECLARE @setIdentity NVARCHAR(128) = 'SET IDENTITY_INSERT ' + @tablename
DECLARE @execsql AS NVARCHAR(4000) = 'SELECT ''' + CASE WHEN @idInsert = 1 THEN @setIdentity + ' ON' + CHAR(13) ELSE '' END + 'INSERT INTO ' + @tablename + ' ('
SELECT @execsql = @execsql +
STUFF
(
(
SELECT CASE WHEN NOT EXISTS(SELECT * FROM @excludedFields WHERE FieldName = name) THEN ', ' + name ELSE '' END
FROM sys.columns
WHERE object_id = OBJECT_ID('dbo.' + @tablename)
FOR XML PATH('')
), 1, 2, ''
) +
')' + CHAR(13) + 'VALUES (' +
STUFF
(
(
SELECT
CASE WHEN NOT EXISTS(SELECT * FROM @excludedFields WHERE FieldName = name) THEN
''', '' + ISNULL(' +
CASE WHEN EXISTS(SELECT * FROM @numberTypes WHERE SysId = system_type_id) THEN '' ELSE ''''''''' + ' END +
'CAST(' + name + ' AS VARCHAR)' +
CASE WHEN EXISTS(SELECT * FROM @numberTypes WHERE SysId = system_type_id) THEN '' ELSE ' + ''''''''' END +
', ''NULL'') + '
ELSE ''
END
FROM sys.columns
WHERE object_id = OBJECT_ID('dbo.' + @tablename)
FOR XML PATH('')
), 1, 3, ''
) +
''')' + CASE WHEN @idInsert = 1 THEN CHAR(13) + @setIdentity + ' OFF' ELSE '' END +
''' FROM ' + @tablename + ' WHERE ' + @idField + ' = ' + CAST(@id AS VARCHAR)
INSERT @results EXEC (@execsql)
DELETE @excludedFields
SET @cnt = @cnt + 1
END
DECLARE cur CURSOR FOR SELECT Sql FROM @results
OPEN cur
DECLARE @sql NVARCHAR(4000)
FETCH NEXT FROM cur INTO @sql
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @sql
FETCH NEXT FROM cur INTO @sql
END
CLOSE cur
DEALLOCATE cur
Super simple Kotlin approach
with(AlertDialog.Builder(this)) {
setTitle("Title")
setView(R.layout.dialog_name)
setPositiveButton("Ok", null)
setNegativeButton("Cancel") { _, _ -> }
create().apply {
setOnShowListener {
getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
//Validate and dismiss
dismiss()
}
}
}
}.show()
You can 'learn' the size of the array automatically:
template<typename T, size_t N>
void set_data(const T (&w)[N]){
w_.assign(w, w+N);
}
Hopefully, you can change the interface to set_data as above. It still accepts a C-style array as its first argument. It just happens to take it by reference.
How it works
[ Update: See here for a more comprehensive discussion on learning the size ]
Here is a more general solution:
template<typename T, size_t N>
void copy_from_array(vector<T> &target_vector, const T (&source_array)[N]) {
target_vector.assign(source_array, source_array+N);
}
This works because the array is being passed as a reference-to-an-array. In C/C++, you cannot pass an array as a function, instead it will decay to a pointer and you lose the size. But in C++, you can pass a reference to the array.
Passing an array by reference requires the types to match up exactly. The size of an array is part of its type. This means we can use the template parameter N to learn the size for us.
It might be even simpler to have this function which returns a vector. With appropriate compiler optimizations in effect, this should be faster than it looks.
template<typename T, size_t N>
vector<T> convert_array_to_vector(const T (&source_array)[N]) {
return vector<T>(source_array, source_array+N);
}
One thing you can do is ask your users to disable saving the password for your site. This can be done browser wide or origin wide.
Something else you can do is to force the inputs to be empty after the page is loaded (and after the browser auto completed the fields). Put this script at the end of the <body>
element.
userIdInputElement.value = "";
userPasswordInputElement.value = "";
Use this app : Servers Ultimate
With this app can run any server you can imagine on your android device (php, mysql, ftp, dhcp, ...) your phone will be a real server, just install the app click on (+) sign to add server, if the server is not installed the app will ask to download the package.
You can access your server via LAN or WAN easily.
Here's a library that really helps: https://cdn.rawgit.com/ccampbell/mousetrap/2e5c2a8adbe80a89050aaf4e02c45f02f1cc12d4/tests/libs/key-event.js
I don't know from where did it came from, but it is helpful. It adds a .simulate()
method to window.KeyEvent
, so you use it simply with KeyEvent.simulate(0, 13)
for simulating an enter
or KeyEvent.simulate(81, 81)
for a 'Q'
.
I got it at https://github.com/ccampbell/mousetrap/tree/master/tests.
I almost always just use overflow:hidden on my text-elements in those situations, it often works like a charm ;)
.post-container {
margin: 20px 20px 0 0;
border:5px solid #333;
}
.post-thumb img {
float: left;
}
.post-content {
overflow:hidden;
}
This helped me get to my answer. There are two php.ini
files located, in my case, for wamp. One is under the php folder and the other one is in the C:\wamp\bin\apache\Apachex.x.x\bin
folder. When connecting to SQL through sqlsrv_connect
function, we are referring to the php.ini
file in the apache
folder. Add the following (as per your version) to this file:
extension=c:/wamp/bin/php/php5.4.16/ext/php_sqlsrv_53_ts.dll
Python 3 does not allow deletion while iterating (using for loop above) dictionary. There are various alternatives to do; one simple way is the to change following line
for i in x.keys():
With
for i in list(x)
You can paste your code into LINQPad. Then copy from LINQPad into MS Word. LINQPad supports following programming languages: C#, VB, SQL, ESQL and F#
Try this one:
h1 {
text-align: center;
background-color: green;
visibility: hidden;
}
h1:after {
content:'The Last Will and Testament of Eric Jones';
visibility: visible;
display: block;
position: absolute;
background-color: inherit;
padding: 5px;
top: 10px;
left: calc(30% - 5px);
}
Please note that calc is not compatible to all browsers :) Just want to be consistent with the alignment in the original post.
I strongly suspect that's because of the network connection or the web server you're talking to - it's not BufferedReader
's fault. Try measuring this:
InputStream stream = conn.getInputStream();
byte[] buffer = new byte[1000];
// Start timing
while (stream.read(buffer) > 0)
{
}
// End timing
I think you'll find it's almost exactly the same time as when you're parsing the text.
Note that you should also give InputStreamReader
an appropriate encoding - the platform default encoding is almost certainly not what you should be using.
Similar to other answers I had miss typed the query.
I had -
SELECT t.id FROM t.table LEFT JOIN table2 AS t2 ON t.id = t2.table_id
Should have been
SELECT t.id FROM table AS t LEFT JOIN table2 AS t2 ON t.id = t2.table_id
Mysql was trying to find a database called t which the user didn't have permission for.
I like this a lot better. reduces the if/switch, just do.
private enum Alignment { LEFT, RIGHT;
void process() {
//Process it...
}
};
String drawCellValue (int maxCellLength, String cellValue, Alignment align){
align.process();
}
of course, it can be:
String process(...) {
//Process it...
}
I would use
like 'Express Edition%'
Example:
DECLARE @edition varchar(50);
set @edition = cast((select SERVERPROPERTY ('edition')) as varchar)
DECLARE @isExpress bit
if @edition like 'Express Edition%'
set @isExpress = 1;
else
set @isExpress = 0;
print @isExpress
You can use groupingBy
collector:
persons.collect(Collectors.groupingBy(p -> p.getName())).values().forEach(t -> System.out.println(t.get(0).getId()));
If you want to have another stream you can use this:
persons.collect(Collectors.groupingBy(p -> p.getName())).values().stream().map(l -> (l.get(0)));
You could also use INDEX MATCH
, which is more "powerful" than vlookup. This would give you exactly what you are looking for:
Just an alternative:
ls -lAR | grep -v '^d' | awk '{total += $5} END {print "Total:", total}'
grep -v '^d'
will exclude the directories.
You can use https://github.com/musclesoft/jquery-connections. This allows you connect block elements in DOM.
To simply list the commits waiting to be pushed: (this is the one you will remember)
git cherry -v
Show the commit subjects next to the SHA1s.
Have a look at C++11 Features (Modern C++)
and section "Quick Reference Guide to Visual C++ Version Numbers" ...
For selecting only specific columns out of multiple columns for a given value in Pandas:
select col_name1, col_name2 from table where column_name = some_value.
Options:
df.loc[df['column_name'] == some_value][[col_name1, col_name2]]
or
df.query['column_name' == 'some_value'][[col_name1, col_name2]]
There are 2 steps to resolve this:
Add UseAccessibleHeader="true"
to Gridview tag:
<asp:GridView ID="MyGridView" runat="server" UseAccessibleHeader="true">
Add the following Code to the PreRender
event:
Protected Sub MyGridView_PreRender(sender As Object, e As EventArgs) Handles MyGridView.PreRender
Try
MyGridView.HeaderRow.TableSection = TableRowSection.TableHeader
Catch ex As Exception
End Try
End Sub
Note setting Header Row in DataBound()
works only when the object is databound, any other postback that doesn't databind the gridview will result in the gridview header row style reverting to a standard row again. PreRender works everytime, just make sure you have an error catch for when the gridview is empty.
It shouldn't be HTTP headers if the file has been downloaded successfully and it's the same file that you can open from OI.
A shot in the dark, but could it be that you are not allowing installation from unknown sources, and that OI is somehow bypassing that?
Settings > Applications > Unknown sources...
Edit
Answer extracted from comments which worked. Ensure the Content-Type is set to application/vnd.android.package-archive
It adds beauty to your code by removing all the basic looping clutter. It gives a clean look to your code, justified below.
Normal for
loop:
void cancelAll(Collection<TimerTask> list) {
for (Iterator<TimerTask> i = list.iterator(); i.hasNext();)
i.next().cancel();
}
Using for-each:
void cancelAll(Collection<TimerTask> list) {
for (TimerTask t : list)
t.cancel();
}
for-each is a construct over a collection that implements Iterator. Remember that, your collection should implement Iterator; otherwise you can't use it with for-each.
The following line is read as "for each TimerTask t in list."
for (TimerTask t : list)
There is less chance for errors in case of for-each. You don't have to worry about initializing the iterator or initializing the loop counter and terminating it (where there is scope for errors).
You can can call a function which will calculate the iframe's body hieght when the iframe is loaded:
<script type="text/javascript">
function iframeloaded(){
var lastHeight = 0, curHeight = 0, $frame = $('iframe:eq(0)');
curHeight = $frame.contents().find('body').height();
if ( curHeight != lastHeight ) {
$frame.css('height', (lastHeight = curHeight) + 'px' );
}
}
</script>
<iframe onload="iframeloaded()" src=...>
These are really two questions.
The first one is answered here: Calling a Sub in VBA
To the second one, protip: there is no main subroutine in VBA. Forget procedural, general-purpose languages. VBA subs are "macros" - you can run them by hitting Alt+F8 or by adding a button to your worksheet and calling up the sub you want from the automatically generated "ButtonX_Click" sub.
After doing all steps like enable debug, ... I had to put a sim card and reboot the phone
Suppose you have following lines of code
MyUrl = "www.google.com" #Your url goes here
urllib.urlretrieve(MyUrl)
If you are receiving following error message
AttributeError: module 'urllib' has no attribute 'urlretrieve'
Then you should try following code to fix the issue:
import urllib.request
MyUrl = "www.google.com" #Your url goes here
urllib.request.urlretrieve(MyUrl)
Otro example, custom Data Pagination for JOIN
CODE in Controller CakePHP 2.6 is OK:
$this->SenasaPedidosFacturadosSds->recursive = -1;
// Filtro
$where = array(
'joins' => array(
array(
'table' => 'usuarios',
'alias' => 'Usuarios',
'type' => 'INNER',
'conditions' => array(
'Usuarios.usuario_id = SenasaPedidosFacturadosSds.usuarios_id'
)
),
array(
'table' => 'senasa_pedidos',
'alias' => 'SenasaPedidos',
'type' => 'INNER',
'conditions' => array(
'SenasaPedidos.id = SenasaPedidosFacturadosSds.senasa_pedidos_id'
)
),
array(
'table' => 'clientes',
'alias' => 'Clientes',
'type' => 'INNER',
'conditions' => array(
'Clientes.id_cliente = SenasaPedidos.clientes_id'
)
),
),
'fields'=>array(
'SenasaPedidosFacturadosSds.*',
'Usuarios.usuario_id',
'Usuarios.apellido_nombre',
'Usuarios.senasa_establecimientos_id',
'Clientes.id_cliente',
'Clientes.consolida_doc_sanitaria',
'Clientes.requiere_senasa',
'Clientes.razon_social',
'SenasaPedidos.id',
'SenasaPedidos.domicilio_entrega',
'SenasaPedidos.sds',
'SenasaPedidos.pt_ptr'
),
'conditions'=>array(
'Clientes.requiere_senasa'=>1
),
'order' => 'SenasaPedidosFacturadosSds.created DESC',
'limit'=>100
);
$this->paginate = $where;
// Get datos
$data = $this->Paginator->paginate();
exit(debug($data));
OR Example 2, NOT active conditions:
$this->SenasaPedidosFacturadosSds->recursive = -1;
// Filtro
$where = array(
'joins' => array(
array(
'table' => 'usuarios',
'alias' => 'Usuarios',
'type' => 'INNER',
'conditions' => array(
'Usuarios.usuario_id = SenasaPedidosFacturadosSds.usuarios_id'
)
),
array(
'table' => 'senasa_pedidos',
'alias' => 'SenasaPedidos',
'type' => 'INNER',
'conditions' => array(
'SenasaPedidos.id = SenasaPedidosFacturadosSds.senasa_pedidos_id'
)
),
array(
'table' => 'clientes',
'alias' => 'Clientes',
'type' => 'INNER',
'conditions' => array(
'Clientes.id_cliente = SenasaPedidos.clientes_id',
'Clientes.requiere_senasa = 1'
)
),
),
'fields'=>array(
'SenasaPedidosFacturadosSds.*',
'Usuarios.usuario_id',
'Usuarios.apellido_nombre',
'Usuarios.senasa_establecimientos_id',
'Clientes.id_cliente',
'Clientes.consolida_doc_sanitaria',
'Clientes.requiere_senasa',
'Clientes.razon_social',
'SenasaPedidos.id',
'SenasaPedidos.domicilio_entrega',
'SenasaPedidos.sds',
'SenasaPedidos.pt_ptr'
),
//'conditions'=>array(
// 'Clientes.requiere_senasa'=>1
//),
'order' => 'SenasaPedidosFacturadosSds.created DESC',
'limit'=>100
);
$this->paginate = $where;
// Get datos
$data = $this->Paginator->paginate();
exit(debug($data));
var result = string.Join("", input.Select(c => ((int)c).ToString("X2")));
OR
var result =string.Join("",
input.Select(c=> String.Format("{0:X2}", Convert.ToInt32(c))));
Full combo of build/ clean project + build/ rebuild project + file/ Invalidate caches / restart works for me!
There is a pairwise()
function example in the itertools
document:
from itertools import tee, izip
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return izip(a, b)
import pandas as pd
df = pd.DataFrame(['AA', 'BB', 'CC'], columns = ['value'])
for (i1, row1), (i2, row2) in pairwise(df.iterrows()):
print i1, i2, row1["value"], row2["value"]
Here is the output:
0 1 AA BB
1 2 BB CC
But, I think iter rows in a DataFrame
is slow, if you can explain what's the problem you want to solve, maybe I can suggest some better method.
I found your question because I was also fighting with NSAttributedString.
For me, the beginEditing
and endEditing
methods did the trick, like stated in Changing an Attributed String.
Apart from that, the lineSpacing is set with setLineSpacing
on the paragraphStyle.
So you might want to try changing your code to:
NSString *string = @" Hello \n world";
attrString = [[NSMutableAttributedString alloc] initWithString:string];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
[paragraphStyle setLineSpacing:20] // Or whatever (positive) value you like...
[attrSting beginEditing];
[attrString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:20] range:NSMakeRange(0, string.length)];
[attrString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, string.length)];
[attrString endEditing];
mainTextView.attributedText = attrString;
Didn't test this exact code though, btw, but mine looks nearly the same.
Meanwhile, I've tested it, and, correct me if I'm wrong, the - beginEditing
and - endEditing
calls seem to be of quite an importance.
just recap:
$(document).ready(function() {_x000D_
_x000D_
$('button').on( "click", function() {_x000D_
_x000D_
showAlert( "OK", "alert-success" );_x000D_
_x000D_
} );_x000D_
_x000D_
});_x000D_
_x000D_
function showAlert( message, alerttype ) {_x000D_
_x000D_
$('#alert_placeholder').append( $('#alert_placeholder').append(_x000D_
'<div id="alertdiv" class="alert alert-dismissible fade in ' + alerttype + '">' +_x000D_
'<a class="close" data-dismiss="alert" aria-label="close" >×</a>' +_x000D_
'<span>' + message + '</span>' + _x000D_
'</div>' )_x000D_
);_x000D_
_x000D_
// close it in 3 secs_x000D_
setTimeout( function() {_x000D_
$("#alertdiv").remove();_x000D_
}, 3000 );_x000D_
_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" />_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
<button onClick="" >Show Alert</button>_x000D_
_x000D_
<div id="alert_placeholder" class="container" ></div>
_x000D_
Basically there are four logical steps.
Create a new Identity column. Turn on Insert Identity for this new column.
Insert the data from the source column (the column you wished to convert to Identity) to this new column.
Turn off the Insert Identity for the new column.
Drop your source column & rename the new column to the name of the source column.
There may be some more complexities like working across multiple servers etc.
Please refer the following article for the steps (using ssms & T-sql). These steps are intended for beginners with less grip on T-SQL.
A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.
If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).
Create Common Method to Convert String to Date format
public static void main(String[] args) throws Exception {
long test = ConvertStringToDate("May 26 10:41:23", "MMM dd hh:mm:ss");
long test2 = ConvertStringToDate("Tue, Jun 06 2017, 12:30 AM", "EEE, MMM dd yyyy, hh:mm a");
long test3 = ConvertStringToDate("Jun 13 2003 23:11:52.454 UTC", "MMM dd yyyy HH:mm:ss.SSS zzz");
}
private static long ConvertStringToDate(String dateString, String format) {
try {
return new SimpleDateFormat(format).parse(dateString).getTime();
} catch (ParseException e) {}
return 0;
}
Excellent solutions Xuan, Theller.
For it to work with python 3 make the following changes
import sys, urllib.request
def reporthook(a, b, c):
print ("% 3.1f%% of %d bytes\r" % (min(100, float(a * b) / c * 100), c))
sys.stdout.flush()
for url in sys.argv[1:]:
i = url.rfind("/")
file = url[i+1:]
print (url, "->", file)
urllib.request.urlretrieve(url, file, reporthook)
print
Also, the URL you enter should be preceded by a "http://", otherwise it returns a unknown url type error.
The only real answer, if you don't control the headers on your source you want in your iframe, is to proxy it. Have a server act as a client, receive the source, strip the problematic headers, add CORS if needed, and then ping your own server.
There is one other answer explaining how to write such a proxy. It isn't difficult, but I was sure someone had to have done this before. It was just difficult to find it, for some reason.
I finally did find some sources:
https://github.com/Rob--W/cors-anywhere/#documentation
^ preferred. If you need rare usage, I think you can just use his heroku app. Otherwise, it's code to run it yourself on your own server. Note sure what the limits are.
whateverorigin.org
^ second choice, but quite old. supposedly newer choice in python: https://github.com/Eiledon/alloworigin
then there's the third choice:
Which seems to allow a little free usage, but will put you on a public shame list if you don't pay and use some unspecified amount, which you can only be removed from if you pay the fee...
You could iterate on a copy (clone) of your original list:
List<String> copy = new ArrayList<String>(list);
for (String s : copy) {
// And if you have to add an element to the list, add it to the original one:
list.add("some element");
}
Note that it is not even possible to add a new element to a list while iterating on it, because it will result in a ConcurrentModificationException
.
You have to do this to echo it:
echo $row['note'];
(The data is coming as an array)
A better solution is to set the doc width/height using the aspect ratio of your image.
var ExportModule = {_x000D_
// Member method to convert pixels to mm._x000D_
pxTomm: function(px) {_x000D_
return Math.floor(px / $('#my_mm').height());_x000D_
},_x000D_
ExportToPDF: function() {_x000D_
var myCanvas = document.getElementById("exportToPDF");_x000D_
_x000D_
html2canvas(myCanvas, {_x000D_
onrendered: function(canvas) {_x000D_
var imgData = canvas.toDataURL(_x000D_
'image/jpeg', 1.0);_x000D_
//Get the original size of canvas/image_x000D_
var img_w = canvas.width;_x000D_
var img_h = canvas.height;_x000D_
_x000D_
//Convert to mm_x000D_
var doc_w = ExportModule.pxTomm(img_w);_x000D_
var doc_h = ExportModule.pxTomm(img_h);_x000D_
//Set doc size_x000D_
var doc = new jsPDF('l', 'mm', [doc_w, doc_h]);_x000D_
_x000D_
//set image height similar to doc size_x000D_
doc.addImage(imgData, 'JPG', 0, 0, doc_w, doc_h);_x000D_
var currentTime = new Date();_x000D_
doc.save('Dashboard_' + currentTime + '.pdf');_x000D_
_x000D_
}_x000D_
});_x000D_
},_x000D_
}
_x000D_
<script src="Scripts/html2canvas.js"></script>_x000D_
<script src="Scripts/jsPDF/jsPDF.js"></script>_x000D_
<script src="Scripts/jsPDF/plugins/canvas.js"></script>_x000D_
<script src="Scripts/jsPDF/plugins/addimage.js"></script>_x000D_
<script src="Scripts/jsPDF/plugins/fileSaver.js"></script>_x000D_
<div id="my_mm" style="height: 1mm; display: none"></div>_x000D_
_x000D_
<div id="exportToPDF">_x000D_
Your html here._x000D_
</div>_x000D_
_x000D_
<button id="export_btn" onclick="ExportModule.ExportToPDF();">Export</button>
_x000D_
There is no such thing as associative array in Java. Its closest relative is a Map
, which is strongly typed, however has less elegant syntax/API.
This is the closest you can get based on your example:
Map<Integer, Map<String, String>> arr =
org.apache.commons.collections.map.LazyMap.decorate(
new HashMap(), new InstantiateFactory(HashMap.class));
//$arr[0]['name'] = 'demo';
arr.get(0).put("name", "demo");
System.out.println(arr.get(0).get("name"));
System.out.println(arr.get(1).get("name")); //yields null
May be useful:
The code that calls the Trigger should go after the event is called.
For example, I have some code that I want to be executed when #expense_tickets value is changed, and also, when page is reload
$(function() {
$("#expense_tickets").change(function() {
// code that I want to be executed when #expense_tickets value is changed, and also, when page is reload
});
// now we trigger the change event
$("#expense_tickets").trigger("change");
})
Try this:
body {
min-height:100%;
background:red;
}
#some_div {
min-height:100%;
background:black;
}
IE6 and earlier versions do not support the min-height property.
I think the problem is that when you tell the body to have a height of 100%, it's background can only be as tall as the hieght of one browser "viewport" (the viewing area that excludes the browsers toolbars & statusbars & menubars and the window edges). If the content is taller than one viewport, it will overflow the height devoted to the background.
This min-height property on the body should FORCE the background to be at least as tall as one viewport if your content does not fill one whole page down to the bottom, yet it should also let it grow downwards to encompass more interior content.
The following steps can be used:
sudo apt-get -y update
---------
sudo apt-get install python3.7
--------------
python3.7
-------------
curl -O https://bootstrap.pypa.io/get-pip.py
-----------------
sudo apt install python3-pip
-----------------
sudo apt install python3.7-venv
-----------------
python3.7 -m venv /home/ubuntu/app
-------------
cd app
----------------
source bin/activate
you might also want to change your font size for other parts of the IDE (other than the code).
Just add the parameter --fontsize <size>
(default size is 11) to the startup command.
You can put it into the command line when launching IDE. You can also put it into the netbeans.conf
file, which is in the /etc
subdirectory of NetBeans installation.
Just place it as a last parameter into the netbeans_default_options
parameter.
You can solve this problem in different way.
If you use Row/Column then you have to use mainAxisAlignment: MainAxisAlignment.spaceEvenly
If you use Wrap Widget you have to use runSpacing: 5, spacing: 10,
In anywhere you can use SizeBox()
Like @wesley says, you have not closed your first <td>
. You opened it two times.
<table class="list1">
<tr>
<td>1</td><td>a</td>
</tr>
<tr>
<td>2</td><td>b</td>
</tr>
<tr>
<td>3</td><td>c</td>
</tr>
</table>
CSS:
.list1 tr:hover{
background-color:#fefefe;
}
There is no JavaScript needed, just complete your HTML code
If you installed the system image and still get this error, it might be that the Android SDK manager did not put the files in the right folder for the AVD manager. See an answer to Stack Overflow question How to create an AVD for Android 4.0.3? (Unable to find a 'userdata.img').
You could make your service completely unaware of the scope, but in your controller allow the scope to be updated asynchronously.
The problem you're having is because you're unaware that http calls are made asynchronously, which means you don't get a value immediately as you might. For instance,
var students = $http.get(path).then(function (resp) {
return resp.data;
}); // then() returns a promise object, not resp.data
There's a simple way to get around this and it's to supply a callback function.
.service('StudentService', [ '$http',
function ($http) {
// get some data via the $http
var path = '/students';
//save method create a new student if not already exists
//else update the existing object
this.save = function (student, doneCallback) {
$http.post(
path,
{
params: {
student: student
}
}
)
.then(function (resp) {
doneCallback(resp.data); // when the async http call is done, execute the callback
});
}
.controller('StudentSaveController', ['$scope', 'StudentService', function ($scope, StudentService) {
$scope.saveUser = function (user) {
StudentService.save(user, function (data) {
$scope.message = data; // I'm assuming data is a string error returned from your REST API
})
}
}]);
The form:
<div class="form-message">{{message}}</div>
<div ng-controller="StudentSaveController">
<form novalidate class="simple-form">
Name: <input type="text" ng-model="user.name" /><br />
E-mail: <input type="email" ng-model="user.email" /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<input type="button" ng-click="reset()" value="Reset" />
<input type="submit" ng-click="saveUser(user)" value="Save" />
</form>
</div>
This removed some of your business logic for brevity and I haven't actually tested the code, but something like this would work. The main concept is passing a callback from the controller to the service which gets called later in the future. If you're familiar with NodeJS this is the same concept.
The accepted answer doesn't create a name-only attribute anymore (as of September 2017).
You should use JQuery prop() method to create name-only attributes.
$(body).prop('data-body', true)
In my exprience I added two Jquery libraries in my file.The versions were jquery 1.11.1 and 2.1.Suddenly I took out 2.1 Jquery from my code. Then ran it and was working for me well. After trying out the first answer. please check out your file like I said above.
Refer to the below link,
https://angular.io/api/common/DatePipe
**Code Sample**
@Component({
selector: 'date-pipe',
template: `<div>
<p>Today is {{today | date}}</p>
<p>Or if you prefer, {{today | date:'fullDate'}}</p>
<p>The time is {{today | date:'h:mm a z'}}</p>
</div>`
})
// Get the current date and time as a date-time value.
export class DatePipeComponent {
today: number = Date.now();
}
{{today | date:'MM/dd/yyyy'}} output: 17/09/2019
or
{{today | date:'shortDate'}} output: 17/9/19
public class MyPdfViewActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView mWebView=new WebView(MyPdfViewActivity.this);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginsEnabled(true);
mWebView.loadUrl("https://docs.google.com/gview?embedded=true&url="+LinkTo);
setContentView(mWebView);
}
}
You should always give an argument to your maven command. Normally this is one of the lifecycles. For example:
mvn package
Package will create jars, wars, ears etc.
For more phases and their meaning, see: http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html
Make it simply use: PDO::lastInsertId
Well, first, you need to actually define a function before you can run it (and it doesn't need to be called main
). For instance:
class Example(object):
def run(self):
print "Hello, world!"
if __name__ == '__main__':
Example().run()
You don't need to use a class, though - if all you want to do is run some code, just put it inside a function and call the function, or just put it in the if
block:
def main():
print "Hello, world!"
if __name__ == '__main__':
main()
or
if __name__ == '__main__':
print "Hello, world!"
Here is a code-example of how you can do it:
Intent intent = getIntent(getApplicationContext(), A.class)
This will make sure that you only have one instance of an activity on the stack.
private static Intent getIntent(Context context, Class<?> cls) {
Intent intent = new Intent(context, cls);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
return intent;
}
I was having same error In ReactJS statless function while using ReactJs Hook useState. I wanted to set state of an object array , so if I use the following way
const [items , setItems] = useState([]);
and update the state like this:
const item = { id : new Date().getTime() , text : 'New Text' };
setItems([ item , ...items ]);
I was getting error:
Argument of type '{ id: number; text: any }' is not assignable to parameter of type 'never'
but if do it like this,
const [items , setItems] = useState([{}]);
Error is gone but there is an item at 0 index which don't have any data(don't want that).
so the solution I found is:
const [items , setItems] = useState([] as any);
We have one more option to do order by
public Cursor getlistbyrank(String rank) {
try {
//This can be used
return db.`query("tablename", null, null, null, null, null, rank +"DESC",null );
OR
return db.rawQuery("SELECT * FROM table order by rank", null);
} catch (SQLException sqle) {
Log.e("Exception on query:-", "" + sqle.getMessage());
return null;
}
}
You can use this two method for order
Vanilla JavaScript solution:-
document.querySelectorAll('.a.b')
answering to your question:
How can I destroy or unset the value of the session?
I can help you by this:
$this->session->unset_userdata('some_name');
and for multiple data you can:
$array_items = array('username' => '', 'email' => '');
$this->session->unset_userdata($array_items);
and to destroy the session:
$this->session->sess_destroy();
Now for the on page change part (on the top of my mind):
you can set the config "anchor_class" of the paginator equal to the classname you want.
after that just check it with jquery onclick for that class which will send a head up to the controller function that will unset the user session.
hi you can try doing this
link_to image_tag("Search.png", border: 0), {action: 'search', controller: 'pages'}, {class: 'dock-item'}
or even
link_to image_tag("Search.png", border: 0), {action: 'search', controller: 'pages'}, class: 'dock-item'
note that the position of the curly braces is very important, because if you miss them out, rails will assume they form a single hash parameters (read more about this here)
and according to the api for link_to:
link_to(name, options = {}, html_options = nil)
hope it helps! =)
Given the string foobarbarfoo
:
bar(?=bar) finds the 1st bar ("bar" which has "bar" after it)
bar(?!bar) finds the 2nd bar ("bar" which does not have "bar" after it)
(?<=foo)bar finds the 1st bar ("bar" which has "foo" before it)
(?<!foo)bar finds the 2nd bar ("bar" which does not have "foo" before it)
You can also combine them:
(?<=foo)bar(?=bar) finds the 1st bar ("bar" with "foo" before it and "bar" after it)
(?=)
Find expression A where expression B follows:
A(?=B)
(?!)
Find expression A where expression B does not follow:
A(?!B)
(?<=)
Find expression A where expression B precedes:
(?<=B)A
(?<!)
Find expression A where expression B does not precede:
(?<!B)A
(?>)
An atomic group exits a group and throws away alternative patterns after the first matched pattern inside the group (backtracking is disabled).
(?>foo|foot)s
applied to foots
will match its 1st alternative foo
, then fail as s
does not immediately follow, and stop as backtracking is disabledA non-atomic group will allow backtracking; if subsequent matching ahead fails, it will backtrack and use alternative patterns until a match for the entire expression is found or all possibilities are exhausted.
(foo|foot)s
applied to foots
will:
foo
, then fail as s
does not immediately follow in foots
, and backtrack to its 2nd alternative;foot
, then succeed as s
immediately follows in foots
, and stop.It may not be IIS!
I went through all of the answers on this page, as well as several more. None of them solved our issue, BUT they are good things to check and WILL cause problems. SO check those first. If you're still pulling your hair out, and you're using PHP, check your PHP settings.
What fixed it for me was to edit our php.ini file and specify:
display_errors: On
I also set:
display_startup_errors: On
just for good measure.
That fixed the problem, and our real issue turned out to be a missed comma that was missed during dev to stage migration.
I realize this page was linked to asp.net, which we were ALSO using, and this is not an asp.net issue, but when you search for these errors, this page comes up and has some good info for fixing most common problems; just not our specific issue. The config changes did fix it, and then we could concentrate on our asp.net files!
You can try this
decimal(18,1)
The length of numbers should be totally 18. The length of numbers after the decimal point should be 1 only and not more than that.
add style="clear:both;"
to the "adm" div
.
I found to delete this section from the project file fix the problem.
<ItemGroup>
<Reference Include="Newtonsoft.Json">
<HintPath>..\packages\Newtonsoft.Json.6.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
Use This method very simple easy to use
HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getNativeRequest();
request.getSession().setAttribute("errorMsg", "your massage");
in jsp once use then remove
<c:remove var="errorMsg" scope="session"/>
A thread dump is a dump of the stacks of all live threads. Thus useful for analysing what an app is up to at some point in time, and if done at intervals handy in diagnosing some kinds of 'execution' problems (e.g. thread deadlock).
A heap dump is a dump of the state of the Java heap memory. Thus useful for analysing what use of memory an app is making at some point in time so handy in diagnosing some memory issues, and if done at intervals handy in diagnosing memory leaks.
This is what they are in 'raw' terms, and could be provided in many ways. In general used to describe dumped files from JVMs and app servers, and in this form they are a low level tool. Useful if for some reason you can't get anything else, but you will find life easier using decent profiling tool to get similar but easier to dissect info.
With respect to WebSphere a javacore file is a thread dump, albeit with a lot of other info such as locks and loaded classes and some limited memory usage info, and a PHD file is a heap dump.
If you want to read a javacore file you can do so by hand, but there is an IBM tool (BM Thread and Monitor Dump Analyzer) which makes it simpler. If you want to read a heap dump file you need one of many IBM tools: MDD4J or Heap Analyzer.
Implementations are free to set limits on JSON documents, including the size, so choose your parser wisely. See RFC 7159, Section 9. Parsers:
"An implementation may set limits on the size of texts that it accepts. An implementation may set limits on the maximum depth of nesting. An implementation may set limits on the range and precision of numbers. An implementation may set limits on the length and character contents of strings."
You can use the Positioned.fill
with Align
inside a Stack
:
Stack(
children: <Widget>[
Positioned.fill(
child: Align(
alignment: Alignment.centerRight,
child: ....
),
),
],
),
This code work fine for me, Here i contvert array to string with ~ sign
<input type="checkbox" value="created" name="today_check"><strong> Created </strong>
<input type="checkbox" value="modified" name="today_check"><strong> Modified </strong>
<a class="get_tody_btn">Submit</a>
<script type="text/javascript">
$('.get_tody_btn').click(function(){
var ck_string = "";
$.each($("input[name='today_check']:checked"), function(){
ck_string += "~"+$(this).val();
});
if (ck_string ){
ck_string = ck_string .substring(1);
}else{
alert('Please choose atleast one value.');
}
});
</script>
None of the above responses are working for error that has no body but still has some describing text. For me, it was SSL certificate problem: unable to get local issuer certificate
error. So I looked right into the code, because doc does't really say much, and did this (in Guzzle 7.1):
try {
// call here
} catch (\GuzzleHttp\Exception\RequestException $e) {
if ($e->hasResponse()) {
$response = $e->getResponse();
// message is in $response->getReasonPhrase()
} else {
$response = $e->getHandlerContext();
if (isset($response['error'])) {
// message is in $response['error']
} else {
// Unknown error occured!
}
}
}
Python(the interpreter) is compiled.
Proof: It won't even compile your code if it contains syntax error.
Example 1:
print("This should print")
a = 9/0
Output:
This should print
Traceback (most recent call last):
File "p.py", line 2, in <module>
a = 9/0
ZeroDivisionError: integer division or modulo by zero
Code gets compiled successfully. First line gets executed (
ZeroDivisionError
(run time error) .
Example 2:
print("This should not print")
/0
Output:
File "p.py", line 2
/0
^
SyntaxError: invalid syntax
Conclusion: If your code file contains
SyntaxError
nothing will execute as compilation fails.
I personally like to do it this way:
<input type="checkbox" name="option" value="1" disabled="disabled" />
<input type="hidden" name="option" value="1">
I think this is better for two reasons:
Here is some old code I had laying around to do WebDAV. I think it was written against Exchange 2003, but I don't remember any more. Feel free to borrow it if its helpful...
class MailUtil
{
private CredentialCache creds = new CredentialCache();
public MailUtil()
{
// set up webdav connection to exchange
this.creds = new CredentialCache();
this.creds.Add(new Uri("http://mail.domain.com/Exchange/[email protected]/Inbox/"), "Basic", new NetworkCredential("myUserName", "myPassword", "WINDOWSDOMAIN"));
}
/// <summary>
/// Gets all unread emails in a user's Inbox
/// </summary>
/// <returns>A list of unread mail messages</returns>
public List<model.Mail> GetUnreadMail()
{
List<model.Mail> unreadMail = new List<model.Mail>();
string reqStr =
@"<?xml version=""1.0""?>
<g:searchrequest xmlns:g=""DAV:"">
<g:sql>
SELECT
""urn:schemas:mailheader:from"", ""urn:schemas:httpmail:textdescription""
FROM
""http://mail.domain.com/Exchange/[email protected]/Inbox/""
WHERE
""urn:schemas:httpmail:read"" = FALSE
AND ""urn:schemas:httpmail:subject"" = 'tbintg'
AND ""DAV:contentclass"" = 'urn:content-classes:message'
</g:sql>
</g:searchrequest>";
byte[] reqBytes = Encoding.UTF8.GetBytes(reqStr);
// set up web request
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://mail.domain.com/Exchange/[email protected]/Inbox/");
request.Credentials = this.creds;
request.Method = "SEARCH";
request.ContentLength = reqBytes.Length;
request.ContentType = "text/xml";
request.Timeout = 300000;
using (Stream requestStream = request.GetRequestStream())
{
try
{
requestStream.Write(reqBytes, 0, reqBytes.Length);
}
catch
{
}
finally
{
requestStream.Close();
}
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
try
{
XmlDocument document = new XmlDocument();
document.Load(responseStream);
// set up namespaces
XmlNamespaceManager nsmgr = new XmlNamespaceManager(document.NameTable);
nsmgr.AddNamespace("a", "DAV:");
nsmgr.AddNamespace("b", "urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/");
nsmgr.AddNamespace("c", "xml:");
nsmgr.AddNamespace("d", "urn:schemas:mailheader:");
nsmgr.AddNamespace("e", "urn:schemas:httpmail:");
// Load each response (each mail item) into an object
XmlNodeList responseNodes = document.GetElementsByTagName("a:response");
foreach (XmlNode responseNode in responseNodes)
{
// get the <propstat> node that contains valid HTTP responses
XmlNode uriNode = responseNode.SelectSingleNode("child::a:href", nsmgr);
XmlNode propstatNode = responseNode.SelectSingleNode("descendant::a:propstat[a:status='HTTP/1.1 200 OK']", nsmgr);
if (propstatNode != null)
{
// read properties of this response, and load into a data object
XmlNode fromNode = propstatNode.SelectSingleNode("descendant::d:from", nsmgr);
XmlNode descNode = propstatNode.SelectSingleNode("descendant::e:textdescription", nsmgr);
// make new data object
model.Mail mail = new model.Mail();
if (uriNode != null)
mail.Uri = uriNode.InnerText;
if (fromNode != null)
mail.From = fromNode.InnerText;
if (descNode != null)
mail.Body = descNode.InnerText;
unreadMail.Add(mail);
}
}
}
catch (Exception e)
{
string msg = e.Message;
}
finally
{
responseStream.Close();
}
}
return unreadMail;
}
}
And model.Mail:
class Mail
{
private string uri;
private string from;
private string body;
public string Uri
{
get { return this.uri; }
set { this.uri = value; }
}
public string From
{
get { return this.from; }
set { this.from = value; }
}
public string Body
{
get { return this.body; }
set { this.body = value; }
}
}
I think in this case you want something like this:
$(window).resize(resize=function resize(){ some code...}
Now u can call resize() within some other nested functions:
$(window).scroll(function(){ resize();}
For the substition impaired here is a real example from GitHub.com to a local directory:
svn ls https://github.com/rdcarp/playing-cards/trunk/PumpkinSoup.PlayingCards.Interfaces
svn export https://github.com/rdcarp/playing-cards/trunk/PumpkinSoup.PlayingCards.Interfaces /temp/SvnExport/Washburn
See: Download a single folder or directory from a GitHub repo for more details.
In bash, you can construct a command line like the following:
$ z=10
$ echo $z
10
$ Rscript -e "args<-commandArgs(TRUE);x=args[1]:args[2];x;mean(x);sd(x)" 1 $z
[1] 1 2 3 4 5 6 7 8 9 10
[1] 5.5
[1] 3.027650
$
You can see that the variable $z
is substituted by bash shell with "10" and this value is picked up by commandArgs
and fed into args[2]
, and the range command x=1:10
executed by R successfully, etc etc.
Create an Ant file and tell Eclipse to build it. There are only two steps and each is easy with the step-by-step instructions below.
Step 1 Create a build.xml file and add to package explorer:
<?xml version="1.0" ?>
<!-- Configuration of the Ant build system to generate a Jar file -->
<project name="TestMain" default="CreateJar">
<target name="CreateJar" description="Create Jar file">
<jar jarfile="Test.jar" basedir="." includes="*.class" />
</target>
</project>
Eclipse should looks something like the screenshot below. Note the Ant icon on build.xml.
Step 2 Right-click on the root node in the project. - Select Properties - Select Builders - Select New - Select Ant Build - In the Main tab, complete the path to the build.xml file in the bin folder.
Check the Output
The Eclipse output window (named Console) should show the following after a build:
Buildfile: /home/<user>/src/Test/build.xml
CreateJar:
[jar] Building jar: /home/<user>/src/Test/Test.jar
BUILD SUCCESSFUL
Total time: 152 milliseconds
EDIT: Some helpful comments by @yeoman and @betlista
@yeoman I think the correct include would be /.class, not *.class, as most people use packages and thus recursive search for class files makes more sense than flat inclusion
@betlista I would recomment to not to have build.xml in src folder
Prikrutil, I think we're on the same boat. I also come to Scala from Erlang. I like Nitrogen a lot so I decided to created a Scala web framework inspired by it.
Take a look at Xitrum. Its doc is quite extensive. From README:
Xitrum is an async and clustered Scala web framework and web server on top of Netty and Hazelcast:
Hazelcast also gives:
Follow the tutorial for a quick start.
To check a number is positive, negative or negative zero. Check its sign using Math.sign() method it will provide you -1,-0,0 and 1 on the basis of positive negative and negative zero or zero numbers
Math.sign(-3) // -1
Math.sign(3) // 1
Math.sign(-0) // -0
Math.sign(0) // 0
For future searchers, if none of the above worked, for me, python was trying to open a folder as a file.
* "For example, say you'd declared a List at the beginning of a method which grew in size to be very large, but was only required until half-way through the method. You could at this point set the List reference to null to allow the garbage collector to potentially reclaim this object before the method completes (and the reference falls out of scope anyway)." *
This is correct, but this solution may not be generalizable. While setting a List object reference to null -will- make memory available for garbage collection, this is only true for a List object of primitive types. If the List object instead contains reference types, setting the List object = null will not dereference -any- of the reference types contained -in- the list. In this case, setting the List object = null will orphan the contained reference types whose objects will not be available for garbage collection unless the garbage collection algorithm is smart enough to determine that the objects have been orphaned.
If you are using ng-show to limit the values, the {{$last ? '' : ', '}}
won`t work since it will still take into consideration all the values.Example
<div ng-repeat="x in records" ng-show="x.email == 1">{{x}}{{$last ? '' : ', '}}</div>
var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function($scope) {
$scope.records = [
{"email": "1"},
{"email": "1"},
{"email": "2"},
{"email": "3"}
]
});
Results in adding a comma after the "last" value,since with ng-show it still takes into consideration all 4 values
{"email":"1"},
{"email":"1"},
One solution is to add a filter directly into ng-repeat
<div ng-repeat="x in records | filter: { email : '1' } ">{{x}}{{$last ? '' : ', '}}</div>
Results
{"email":"1"},
{"email":"1"}
I know this is an old one, but I wanted to post a variation of the accepted answer that will work in IE without removing lines:
function multiLineHtmlEncode(value) {
var lines = value.split(/\r\n|\r|\n/);
for (var i = 0; i < lines.length; i++) {
lines[i] = htmlEncode(lines[i]);
}
return lines.join('\r\n');
}
function htmlEncode(value) {
return $('<div/>').text(value).html();
}
In more recent versions of SQL Server Management studio, you can now right click on a database and 'Take Database Offline'. This gives you the option to Drop All Active Connections to the database.
for some applications, for example google chrome, they store it under /opt. you can follow the above instruction using dpkg -l to get the correct naming then dpkg -L to get the detail.
hope it helps
A sort of block comment uses an if statement:
if(FALSE) {
all your code
}
It works, but I almost always use the block comment options of my editors (RStudio, Kate, Kwrite).
It sounds like you want to use this web application as a remote control for your robot, and a core issue is that you won't want a page reload every time you perform an action, in which case, the last link you posted answers your problem.
I think you may be misunderstanding a few things about Flask. For one, you can't nest multiple functions in a single route. You're not making a set of functions available for a particular route, you're defining the one specific thing the server will do when that route is called.
With that in mind, you would be able to solve your problem with a page reload by changing your app.py to look more like this:
from flask import Flask, render_template, Response, request, redirect, url_for
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html')
@app.route("/forward/", methods=['POST'])
def move_forward():
#Moving forward code
forward_message = "Moving Forward..."
return render_template('index.html', forward_message=forward_message);
Then in your html, use this:
<form action="/forward/" method="post">
<button name="forwardBtn" type="submit">Forward</button>
</form>
...To execute your moving forward code. And include this:
{{ forward_message }}
... where you want the moving forward message to appear on your template.
This will cause your page to reload, which is inevitable without using AJAX and Javascript.
You can nest your queries:
select * from (
select bla
from bla
where bla
order by finaldate desc
)
where rownum < 2
Actually there is no any cancel()
or dismiss()
method from AlertDialog.Builder Class.
So Instead of AlertDialog.Builder optionDialog
use AlertDialog
instance.
Like,
AlertDialog optionDialog = new AlertDialog.Builder(this).create();
Now, Just call optionDialog.dismiss();
background.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SetBackground();
// here I want to dismiss it after SetBackground() method
optionDialog.dismiss();
}
});
Like @Venkatramanan and others I found INFORMATION_SCHEMA.TABLES unreliable (using InnoDB, MySQL 5.1.44), giving different row counts each time I run it even on quiesced tables. Here's a relatively hacky (but flexible/adaptable) way of generating a big SQL statement you can paste into a new query, without installing Ruby gems and stuff.
SELECT CONCAT(
'SELECT "',
table_name,
'" AS table_name, COUNT(*) AS exact_row_count FROM `',
table_schema,
'`.`',
table_name,
'` UNION '
)
FROM INFORMATION_SCHEMA.TABLES
WHERE table_schema = '**my_schema**';
It produces output like this:
SELECT "func" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.func UNION
SELECT "general_log" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.general_log UNION
SELECT "help_category" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.help_category UNION
SELECT "help_keyword" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.help_keyword UNION
SELECT "help_relation" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.help_relation UNION
SELECT "help_topic" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.help_topic UNION
SELECT "host" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.host UNION
SELECT "ndb_binlog_index" AS table_name, COUNT(*) AS exact_row_count FROM my_schema.ndb_binlog_index UNION
Copy and paste except for the last UNION to get nice output like,
+------------------+-----------------+
| table_name | exact_row_count |
+------------------+-----------------+
| func | 0 |
| general_log | 0 |
| help_category | 37 |
| help_keyword | 450 |
| help_relation | 990 |
| help_topic | 504 |
| host | 0 |
| ndb_binlog_index | 0 |
+------------------+-----------------+
8 rows in set (0.01 sec)
Usage:
//Searches file names (start with "temp" and extension ".txt")
//in the current directory and subdirectories recursively
Path initialPath = Paths.get(".");
PathUtils.searchRegularFilesStartsWith(initialPath, "temp", ".txt").
stream().forEach(System.out::println);
Source:
public final class PathUtils {
private static final String startsWithRegex = "(?<![_ \\-\\p{L}\\d\\[\\]\\(\\) ])";
private static final String endsWithRegex = "(?=[\\.\\n])";
private static final String containsRegex = "%s(?:[^\\/\\\\]*(?=((?i)%s(?!.))))";
public static List<Path> searchRegularFilesStartsWith(final Path initialPath,
final String fileName, final String fileExt) throws IOException {
return searchRegularFiles(initialPath, startsWithRegex + fileName, fileExt);
}
public static List<Path> searchRegularFilesEndsWith(final Path initialPath,
final String fileName, final String fileExt) throws IOException {
return searchRegularFiles(initialPath, fileName + endsWithRegex, fileExt);
}
public static List<Path> searchRegularFilesAll(final Path initialPath) throws IOException {
return searchRegularFiles(initialPath, "", "");
}
public static List<Path> searchRegularFiles(final Path initialPath,
final String fileName, final String fileExt)
throws IOException {
final String regex = String.format(containsRegex, fileName, fileExt);
final Pattern pattern = Pattern.compile(regex);
try (Stream<Path> walk = Files.walk(initialPath.toRealPath())) {
return walk.filter(path -> Files.isRegularFile(path) &&
pattern.matcher(path.toString()).find())
.collect(Collectors.toList());
}
}
private PathUtils() {
}
}
Try startsWith regex for \txt\temp\tempZERO0.txt:
(?<![_ \-\p{L}\d\[\]\(\) ])temp(?:[^\/\\]*(?=((?i)\.txt(?!.))))
Try endsWith regex for \txt\temp\ZERO0temp.txt:
temp(?=[\\.\\n])(?:[^\/\\]*(?=((?i)\.txt(?!.))))
Try contains regex for \txt\temp\tempZERO0tempZERO0temp.txt:
temp(?:[^\/\\]*(?=((?i)\.txt(?!.))))
for everything related to Python's style guide: i'd recommend you read PEP8.
To answer your question:
Function names should be lowercase, with words separated by underscores as necessary to improve readability.
Since AngularJS does not have directive DOM manipulations as jQuery does, a proper way to modify attributes of one element will be using directive. Through link function of a directive, you have access to both element and its attributes.
Wrapping you whole input inside one directive, you can still introduce ng-model's methods through controller property.
This method will help to decouple the logic of ngmodel with placeholder from controller. If there is no logic between them, you can definitely go as Wagner Francisco said.
you can (sort of) return an array
instead of
int m1[5] = {1, 2, 3, 4, 5};
int m2[5] = {6, 7, 8, 9, 10};
int* m3 = test(m1, m2);
write
struct mystruct
{
int arr[5];
};
int m1[5] = {1, 2, 3, 4, 5};
int m2[5] = {6, 7, 8, 9, 10};
mystruct m3 = test(m1,m2);
where test looks like
struct mystruct test(int m1[5], int m2[5])
{
struct mystruct s;
for (int i = 0; i < 5; ++i ) s.arr[i]=m1[i]+m2[i];
return s;
}
not very efficient since one is copying it delivers a copy of the array
Just Close The Android Studio and Restart it and Sysnc. Gradle Files Again......And Run The Project Again
But it would be possible if one were used in place of the variable in @html.Hidden field. As in this example.
@Html.Hidden("myVar", 0);
set the field per script:
<script>
function setMyValue(value) {
$('#myVar').val(value);
}
</script>
I hope I can at least offer no small Workaround.
You can't find a consistent reference because it seems to go by at least six different names!
You can use LINQ for this
var list = new List<int>();
var sum = list.Sum();
and for a List of strings like Roy Dictus said you have to convert
list.Sum(str => Convert.ToInt32(str));
The git command
git count-objects -v
will give you a good estimate of the git repository's size. Without the -v flag, it only tells you the size of your unpacked files. This command may not be in your $PATH, you may have to track it down (on Ubuntu I found it in /usr/lib/git-core/, for instance).
From the Git man-page:
-v, --verbose
In addition to the number of loose objects and disk space consumed, it reports the number of in-pack objects, number of packs, disk space consumed by those packs, and number of objects that can be removed by running git prune-packed.
Your output will look similar to the following:
count: 1910
size: 19764
in-pack: 41814
packs: 3
size-pack: 1066963
prune-packable: 1
garbage: 0
The line you're looking for is size-pack
. That is the size of all the packed commit objects, or the smallest possible size for the new cloned repository.
Sample of the Recursive Level:
DECLARE @VALUE_CODE AS VARCHAR(5);
--SET @VALUE_CODE = 'A' -- Specify a level
WITH ViewValue AS
(
SELECT ValueCode
, ValueDesc
, PrecedingValueCode
FROM ValuesTable
WHERE PrecedingValueCode IS NULL
UNION ALL
SELECT A.ValueCode
, A.ValueDesc
, A.PrecedingValueCode
FROM ValuesTable A
INNER JOIN ViewValue V ON
V.ValueCode = A.PrecedingValueCode
)
SELECT ValueCode, ValueDesc, PrecedingValueCode
FROM ViewValue
--WHERE PrecedingValueCode = @VALUE_CODE -- Specific level
--WHERE PrecedingValueCode IS NULL -- Root
Try:
String str = "my string \n my other string";
When printed you will get:
my string
my other string
There's now an EMPTY
constant and an empty
function.
import { Observable, empty, of } from 'rxjs';
var delay = empty().pipe(delay(1000));
var delay2 = EMPTY.pipe(delay(1000));
Observable.empty()
doesn't exist anymore.
I would recommend you using the Conditional Attribute!
Update: 3.5 years later
You can use #if
like this (example copied from MSDN):
// preprocessor_if.cs
#define DEBUG
#define VC_V7
using System;
public class MyClass
{
static void Main()
{
#if (DEBUG && !VC_V7)
Console.WriteLine("DEBUG is defined");
#elif (!DEBUG && VC_V7)
Console.WriteLine("VC_V7 is defined");
#elif (DEBUG && VC_V7)
Console.WriteLine("DEBUG and VC_V7 are defined");
#else
Console.WriteLine("DEBUG and VC_V7 are not defined");
#endif
}
}
Only useful for excluding parts of methods.
If you use #if
to exclude some method from compilation then you will have to exclude from compilation all pieces of code which call that method as well (sometimes you may load some classes at runtime and you cannot find the caller with "Find all references"). Otherwise there will be errors.
If you use conditional compilation on the other hand you can still leave all pieces of code that call the method. All parameters will still be validated by the compiler. The method just won't be called at runtime. I think that it is way better to hide the method just once and not have to remove all the code that calls it as well. You are not allowed to use the conditional attribute on methods which return value - only on void methods. But I don't think this is a big limitation because if you use #if
with a method that returns a value you have to hide all pieces of code that call it too.
Here is an example:
// calling Class1.ConditionalMethod() will be ignored at runtime // unless the DEBUG constant is defined using System.Diagnostics; class Class1 { [Conditional("DEBUG")] public static void ConditionalMethod() { Console.WriteLine("Executed Class1.ConditionalMethod"); } }
Summary:
I would use #ifdef
in C++ but with C#/VB I would use Conditional attribute. This way you hide the method definition without having to hide the pieces of code that call it. The calling code is still compiled and validated by the compiler, the method is not called at runtime though.
You may want to use #if
to avoid dependencies because with Conditional attribute your code is still compiled.
You can also add underscore.js to your project and will be able to do it in one line:
_.map($("input[name='category_ids[]']:checked"), function(el){return $(el).val()})
include <string>
For Validating Doubles:
bool validateDouble(const std::string & input) {
int decimals = std::count(input.begin(), input.end(), '.'); // The number of decimals in the string
int negativeSigns = std::count(input.begin(), input.end(), '-'); // The number of negative signs in the string
if (input.size() == decimals + negativeSigns) // Consists of only decimals and negatives or is empty
return false;
else if (1 < decimals || 1 < negativeSigns) // More than 1 decimal or negative sign
return false;
else if (1 == negativeSigns && input[0] != '-') // The negative sign (if there is one) is not the first character
return false;
else if (strspn(input.c_str(), "-.0123456789") != input.size()) // The string contains a character that isn't in "-.0123456789"
return false;
return true;
}
For Validating Ints (With Negatives)
bool validateInt(const std::string & input) {
int negativeSigns = std::count(input.begin(), input.end(), '-'); // The number of negative signs in the string
if (input.size() == negativeSigns) // Consists of only negatives or is empty
return false;
else if (1 < negativeSigns) // More than 1 negative sign
return false;
else if (1 == negativeSigns && input[0] != '-') // The negative sign (if there is one) is not the first character
return false;
else if (strspn(input.c_str(), "-0123456789") != input.size()) // The string contains a character that isn't in "-0123456789"
return false;
return true;
}
For Validating Unsigned Ints
bool validateUnsignedInt(const std::string & input) {
return (input.size() != 0 && strspn(input.c_str(), "0123456789") == input.size()); // The string is not empty and contains characters only in "0123456789"
}
Schema says what tables are in database, what columns they have and how they are related. Each database has its own schema.
This problem drives me crazy as well but I know what the cause of it is. The problem is that eclipse is not smart enough to create a folder with the same name of your project within your workspace folder if it is custom.
The way to solve this is to make sure all of your projects are in a folder with the name that matches your Project Name, otherwise it will dump all of your project files straight into the directory. The reason why you end up seeing that error is because it thinks you are putting a project inside another project (probably reads the project config file).
I noticed this is especially a problem when not using the default workspace path. The way I solve this problem is to just add the Project Name to the end of location. So let's say you are putting a project named "HelloWorld" into /Users/name/Documents/projects/android/, you would want to manually add "HelloWorld" to the end of it, like this: /Users/name/Documents/projects/android/HelloWorld. This would ensure that the project is put in it's own folder called "HelloWorld" and not inside some other project. Be sure that if there are any projects not within folders into a folder of the same name as the project to solve the errors.
jqXHR.done(function( data, textStatus, jqXHR ) {});
An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.
The point it is just an alternative for success callback option, and jqXHR.success()
is deprecated.
LOAD DATA INFILE 'D:\CertificationInputFile.csv' INTO TABLE CERT_EXCLUSION_LIST FIELDS TERMINATED BY "|" OPTIONALLY ENCLOSED BY '"' ( CERTIFICATIONNAME, CERTIFICATIONVERSION )
Change the query to
"INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) VALUES(@na,@occ); SELECT SCOPE_IDENTITY()"
This will return the last inserted ID which you can then get with ExecuteScalar
This also works with np.reshape.
def softmax( scores):
"""
Compute softmax scores given the raw output from the model
:param scores: raw scores from the model (N, num_classes)
:return:
prob: softmax probabilities (N, num_classes)
"""
prob = None
exponential = np.exp(
scores - np.max(scores, axis=1).reshape(-1, 1)
) # subract the largest number https://jamesmccaffrey.wordpress.com/2016/03/04/the-max-trick-when-computing-softmax/
prob = exponential / exponential.sum(axis=1).reshape(-1, 1)
return prob
As long as your tests are passing you are good, hit alt + enter
by taking the cursor over the error and inside the submenu of the first item you will find Disable Inspection
select that
First, you should take a look to appCompat lib article there and to different attributs you can set:
colorPrimary: The primary branding color for the app. By default, this is the color applied to the action bar background.
colorPrimaryDark: Dark variant of the primary branding color. By default, this is the color applied to the status bar (via statusBarColor) and navigation bar (via navigationBarColor).
colorAccent: Bright complement to the primary branding color. By default, this is the color applied to framework controls (via colorControlActivated).
colorControlNormal: The color applied to framework controls in their normal state.
colorControlActivated: The color applied to framework controls in their activated (ex. checked, switch on) state.
colorControlHighlight: The color applied to framework control highlights (ex. ripples, list selectors).
colorButtonNormal: The color applied to framework buttons in their normal state.
colorSwitchThumbNormal: The color applied to framework switch thumbs in their normal state. (switch off)
With previous attributes you can define your own theme for each activity:
<style name="Theme.MyActivityTheme" parent="Theme.AppCompat.Light">
<!-- colorPrimary is used for the default action bar background -->
<item name="colorPrimary">@color/my_awesome_color</item>
<!-- colorPrimaryDark is used for the status bar -->
<item name="colorPrimaryDark">@color/my_awesome_darker_color</item>
<!-- colorAccent is used as the default value for colorControlActivated,
which is used to tint widgets -->
<item name="colorAccent">@color/accent</item>
<!-- You can also set colorControlNormal, colorControlActivated
colorControlHighlight, and colorSwitchThumbNormal. -->
</style>
and :
<manifest>
...
<activity
android:name=".MainActivity"
android:theme="@style/Theme.MyActivityTheme">
</activity>
...
</manifest>
As widget tinting in appcompat works by intercepting any layout inflation and inserting a special tint-aware version of the widget in its place (See Chris Banes post about it) you can not apply a custom style to each switch of your layout xml file. You have to set a custom Context that will tint switch with right colors.
--
To do so for pre-5.0 you need to create a Context that overlays global theme with customs attributs and then create your switches programmatically:
ContextThemeWrapper ctw = ContextThemeWrapper(getActivity(), R.style.Color1SwitchStyle);
SwitchCompat sc = new SwitchCompat(ctw)
As of AppCompat v22.1
you can use the following XML
to apply a theme to the switch widget:
<RelativeLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
...>
<android.support.v7.widget.SwitchCompat
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:theme="@style/Color1SwitchStyle"/>
Your custom switch theme:
<style name="Color1SwitchStyle">
<item name="colorControlActivated">@color/my_awesome_color</item>
</style>
--
On Android 5.0 it looks like a new view attribut comes to life : android:theme
(same as one use for activity declaration in manifest). Based on another Chris Banes post, with the latter you should be able to define a custom theme directly on a view from your layout xml:
<android.support.v7.widget.SwitchCompat
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:theme="@style/Color1SwitchStyle"/>
Thanks to vine'th I complete my answer with a link to SO answer that explains how to specify the Foreground of the Track when Switch is Off, it's there.
So the rules are that the first UTF-8 octlet has the high bit set as a marker, and then 1 to 4 bits to indicate how many additional octlets; then each of the additional octlets must have the high two bits set to 10.
The pseudo-python would be:
newstring = ''
cont = 0
for each ch in string:
if cont:
if (ch >> 6) != 2: # high 2 bits are 10
# do whatever, e.g. skip it, or skip whole point, or?
else:
# acceptable continuation of multi-octlet char
newstring += ch
cont -= 1
else:
if (ch >> 7): # high bit set?
c = (ch << 1) # strip the high bit marker
while (c & 1): # while the high bit indicates another octlet
c <<= 1
cont += 1
if cont > 4:
# more than 4 octels not allowed; cope with error
if !cont:
# illegal, do something sensible
newstring += ch # or whatever
if cont:
# last utf-8 was not terminated, cope
This same logic should be translatable to php. However, its not clear what kind of stripping is to be done once you get a malformed character.
use this, it won't effect height:
<input type="text" style="border:1px solid #ff0000" />
It looks like two of your lines are out of order. You start the process before setting up an event handler to capture the output. It's possible the process is just finishing before the event handler is added.
Switch the lines like so.
p.OutputDataReceived += ...
p.Start();
Even though I had been developing apps for a few years now, this was my first time debugging a binary and I felt like a complete NOOB figuring out where all the files were i.e. where is *.app *.dSYM and crash logs? I had to read multiple posts in order to figure it out. Picture is worth a thousand words and I hope this post helps anyone else in future.
1- First go to itunesconnect and download your crash logs. NOTE: Is most cases you may get something like "Too few reports have been submitted for a report to be shown." Basically not enough users have submitted crash log reports to Apple in which case you can't do much of anything at that point.
2- Now if you had not changed your code since you had submitted your binary it to Apple then Launch Xcode for that project and do Product --> Archive again. Otherwise just find your latest submitted binary and right click on it.
Zcron is available free for personal use.
Imagine you are in a bank, trying to get some money out of your account. But it's dark; the bank is pitch black: there's no light and you can't see your hand in front of your face. You are surrounded by another 20 people. They all look the same. And everybody has the same voice. And everyone is a potential bad guy. In other words, HTTP is stateless.
This bank is a funny type of bank - for the sake of argument here's how things work:
The teller can't see or readily recognise you, remember, because the lights are all out. What if your teller gives your $10,000 withdrawal to someone else - the wrong person?! It's absolutely vital that the teller can recognise you as the one who made the withdrawal, so that you can get the money (or resource) that you asked for.
Solution:
When you first appear to the teller, he or she tells you something in secret:
"When ever you are talking to me," says the teller, "you should first identify yourlself as GNASHEU329 - that way I know it's you".
Nobody else knows the secret passcode.
So I decide to go to and chill out for 20 minutes and then later i go to the teller and say "I'd like to collect my withdrawal"
The teller asks me: "who are you??!"
"It's me, Mr George Banks!"
"Prove it!"
And then I tell them my passcode: GNASHEU329
"Certainly Mr Banks!"
That basically is how a session works. It allows one to be uniquely identified in a sea of millions of people. You need to identify yourself every time you deal with the teller.
If you got any questions or are unclear - please post comment and i will try to clear it up for you. The following is not strictly speaking, completely accurate in its terminology, but I hope it's helpful to you in understanding concepts.
Use the write()-Method of the Popup's document to put your markup there:
$.post(url, function (data) {
var w = window.open('about:blank');
w.document.open();
w.document.write(data);
w.document.close();
});
As @FelixKling pointed out, the most likely scenario is that the nodes you are looking for do not exist (yet).
However, modern development practices can often manipulate document elements outside of the document tree either with DocumentFragments or simply detaching/reattaching current elements directly. Such techniques may be used as part of JavaScript templating or to avoid excessive repaint/reflow operations while the elements in question are being heavily altered.
Similarly, the new "Shadow DOM" functionality being rolled out across modern browsers allows elements to be part of the document, but not query-able by document.getElementById and all of its sibling methods (querySelector, etc.). This is done to encapsulate functionality and specifically hide it.
Again, though, it is most likely that the element you are looking for simply is not (yet) in the document, and you should do as Felix suggests. However, you should also be aware that that is increasingly not the only reason that an element might be unfindable (either temporarily or permanently).
Or you can just create your own MediaTypeFormatter
. I use this for text/html
. If you add text/plain
to it, it'll work for you too:
public class TextMediaTypeFormatter : MediaTypeFormatter
{
public TextMediaTypeFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
return ReadFromStreamAsync(type, readStream, content, formatterLogger, CancellationToken.None);
}
public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger, CancellationToken cancellationToken)
{
using (var streamReader = new StreamReader(readStream))
{
return await streamReader.ReadToEndAsync();
}
}
public override bool CanReadType(Type type)
{
return type == typeof(string);
}
public override bool CanWriteType(Type type)
{
return false;
}
}
Finally you have to assign this to the HttpMethodContext.ResponseFormatter
property.
Anyone could potentially use this command to rename a field from the collection (By not using any _id):
dbName.collectionName.update({}, {$rename:{"oldFieldName":"newFieldName"}}, false, true);
see FYI
There are two things I think you could try to develop iPhone applications.
You can try the Aptana mobile wep app plugin for eclipse which is nice, although still in early stage. It comes with a emulator for running the applications so this could be helpful
You can try cocoa
(Extra) Here is a nice guide I found of guy who managed to get the iPhone SDK running in ubuntu, hope this help -_-. iPhone on Ubuntu
if your date format is like this : 14/02/1989 ----> you may find some problems
you need to use ISOdate like this :
var start_date = new Date(2012, 07, x, x, x);
-----> the result ------>ISODate("2012-07-14T08:14:00.201Z")
now just use the query like this :
collection.find( { query : query ,$orderby :{start_date : -1}} ,function (err, cursor) {...}
that's it :)
The only half-way proper way to do this is
<p>
<span style="float: right">Text on the right</span>
<span style="float: left">Text on the left</span>
</p>
however, this will get you into trouble if the text overflows. If you can, use div
s (block level elements) and give them a fixed width
.
A table (or a number of div
s with the according display: table / table-row / table-cell
properties) would in fact be the safest solution for this - it will be impossible to break, even if you have lots of difficult content.
Use a public static class and access it from anywhere.
public static class MyGlobals {
public const string Prefix = "ID_"; // cannot change
public static int Total = 5; // can change because not const
}
used like so, from master page or anywhere:
string strStuff = MyGlobals.Prefix + "something";
textBox1.Text = "total of " + MyGlobals.Total.ToString();
You don't need to make an instance of the class; in fact you can't because it's static. Just use it directly. All members inside a static class must also be static. The string Prefix isn't marked static because new
const
is implicitly static by nature.
The static class can be anywhere in your project. It doesn't have to be part of Global.asax or any particular page because it's "global" (or at least as close as we can get to that concept in object-oriented terms.)
You can make as many static classes as you like and name them whatever you want.
Sometimes programmers like to group their constants by using nested static classes. For example,
public static class Globals {
public static class DbProcedures {
public const string Sp_Get_Addresses = "dbo.[Get_Addresses]";
public const string Sp_Get_Names = "dbo.[Get_First_Names]";
}
public static class Commands {
public const string Go = "go";
public const string SubmitPage = "submit_now";
}
}
and access them like so:
MyDbCommand proc = new MyDbCommand( Globals.DbProcedures.Sp_Get_Addresses );
proc.Execute();
//or
string strCommand = Globals.Commands.Go;
Here is an elegant way to do similar thing. But why do partly JSON unmarshal? That doesn't make sense.
Look below at the working code. Copy and paste it.
import (
"bytes"
"encoding/json" // Encoding and Decoding Package
"fmt"
)
var messeging = `{
"say":"Hello",
"sendMsg":{
"user":"ANisus",
"msg":"Trying to send a message"
}
}`
type SendMsg struct {
User string `json:"user"`
Msg string `json:"msg"`
}
type Chat struct {
Say string `json:"say"`
SendMsg *SendMsg `json:"sendMsg"`
}
func main() {
/** Clean way to solve Json Decoding in Go */
/** Excellent solution */
var chat Chat
r := bytes.NewReader([]byte(messeging))
chatErr := json.NewDecoder(r).Decode(&chat)
errHandler(chatErr)
fmt.Println(chat.Say)
fmt.Println(chat.SendMsg.User)
fmt.Println(chat.SendMsg.Msg)
}
func errHandler(err error) {
if err != nil {
fmt.Println(err)
return
}
}
Possibly somewhat faster than Jaime Soriano's answer, and without the multi-byte encoding problems of Adrian's answer, I suggest:
File file = new File("/tmp/myfile");
try {
FileInputStream stream = new FileInputStream(file);
int count;
byte[] buffer = new byte[1024];
ByteArrayOutputStream byteStream =
new ByteArrayOutputStream(stream.available());
while (true) {
count = stream.read(buffer);
if (count <= 0)
break;
byteStream.write(buffer, 0, count);
}
String string = byteStream.toString();
System.out.format("%d bytes: \"%s\"%n", string.length(), string);
} catch (IOException e) {
e.printStackTrace();
}
domContentLoaded: marks the point when both the DOM is ready and there are no stylesheets that are blocking JavaScript execution - meaning we can now (potentially) construct the render tree. Many JavaScript frameworks wait for this event before they start executing their own logic. For this reason the browser captures the EventStart and EventEnd timestamps to allow us to track how long this execution took.
loadEvent: as a final step in every page load the browser fires an “onload” event which can trigger additional application logic.
Use this html to get the clicked element:
<div class="row" style="padding-left:21px;">
<ul class="nav nav-tabs" style="padding-left:40px;">
<li class="active filter"><a href="#month" onclick="Data('month', this)">This Month</a></li>
<li class="filter"><a href="#year" onclick="Data('year', this)">Year</a></li>
<li class="filter"><a href="#last60" onclick="Data('last60', this)">60 Days</a></li>
<li class="filter"><a href="#last90" onclick="Data('last90', this)">90 Days</a></li>
</ul>
</div>
Script:
function Data(string, el)
{
$('.filter').removeClass('active');
$(el).parent().addClass('active');
}
The following is equivalent to your second code block:
var f = function () {
//Some logic here...
};
var fr = f;
fr(pars);
If you want to actually pass a reference to a function to some other function, you can do something like this:
function fiz(x, y, z) {
return x + y + z;
}
// elsewhere...
function foo(fn, p, q, r) {
return function () {
return fn(p, q, r);
}
}
// finally...
f = foo(fiz, 1, 2, 3);
f(); // returns 6
You're almost certainly better off using a framework for this sort of thing, though.
Ok so I was having this issue where I tried several different options.
The font i'm using is Ubuntu-LI , I created a font folder in my working directory. under the folder fonts
I was able to apply it... eventually here is my working code
I wanted this to apply to my entire website so I put it at the top of the css doc. above all of the Div tags (not that it matters, just know that any individual fonts you assign post your script will take precedence)
@font-face{
font-family: "Ubuntu-LI";
src: url("/fonts/Ubuntu/(Ubuntu-LI.ttf"),
url("../fonts/Ubuntu/Ubuntu-LI.ttf");
}
*{
font-family:"Ubuntu-LI";
}
If i then wanted all of my H1 tags to be something else lets say sans sarif I would do something like
h1{
font-family: Sans-sarif;
}
From which case only my H1 tags would be the sans-sarif font and the rest of my page would be the Ubuntu-LI font
Simple but usefull way:
$query = $this->db->distinct()->select('order_id')->get_where('tbl_order_details', array('seller_id' => $seller_id));
return $query;
There's elegant solution:
Just mount not whole directory, but only app directory. This way you'll you won't have troubles with npm_modules
.
Example:
frontend:
build:
context: ./ui_frontend
dockerfile: Dockerfile.dev
ports:
- 3000:3000
volumes:
- ./ui_frontend/src:/frontend/src
Dockerfile.dev:
FROM node:7.2.0
#Show colors in docker terminal
ENV COMPOSE_HTTP_TIMEOUT=50000
ENV TERM="xterm-256color"
COPY . /frontend
WORKDIR /frontend
RUN npm install update
RUN npm install --global typescript
RUN npm install --global webpack
RUN npm install --global webpack-dev-server
RUN npm install --global karma protractor
RUN npm install
CMD npm run server:dev
We can use geobytes.com to get the location using user IP address
$user_ip = getIP();
$meta_tags = get_meta_tags('http://www.geobytes.com/IPLocator.htm?GetLocation&template=php3.txt&IPAddress=' . $user_ip);
echo '<pre>';
print_r($meta_tags);
it will return data like this
Array(
[known] => true
[locationcode] => USCALANG
[fips104] => US
[iso2] => US
[iso3] => USA
[ison] => 840
[internet] => US
[countryid] => 254
[country] => United States
[regionid] => 126
[region] => California
[regioncode] => CA
[adm1code] =>
[cityid] => 7275
[city] => Los Angeles
[latitude] => 34.0452
[longitude] => -118.2840
[timezone] => -08:00
[certainty] => 53
[mapbytesremaining] => Free
)
Function to get user IP
function getIP(){
if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
$pattern = "/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/";
if(preg_match($pattern, $_SERVER["HTTP_X_FORWARDED_FOR"])){
$userIP = $_SERVER["HTTP_X_FORWARDED_FOR"];
}else{
$userIP = $_SERVER["REMOTE_ADDR"];
}
}
else{
$userIP = $_SERVER["REMOTE_ADDR"];
}
return $userIP;
}
If you are simply trying to stop people clicking and are not horrifically worried about security - I have found an absolute placed div with a z-index of 99999 sorts it fine. You can't click or access any of the content because the div is placed over it. Might be a bit simpler and is a CSS only solution until you need to remove it.
The topic is 'Embed image in a button element', and the question using plain HTML. I do this using the span tag in the same way that glyphicons are used in bootstrap. My image is 16 x 16px and can be any format.
Here's the plain HTML that answers the question:
<button type="button"><span><img src="images/xxx.png" /></span> Click Me</button>
use this code to redirect the page
echo "<script>alert('There are no fields to generate a report');document.location='admin/ahm/panel'</script>";
I discovered that the accepted answer actually doesn't always work, because \\Z
may occur in the file. Another problem is that if you don't have the correct charset a whole bunch of unexpected things may happen which may cause the scanner to read only a part of the file.
The solution is to use a delimiter which you are certain will never occur in the file. However, this is theoretically impossible. What we CAN do, is use a delimiter that has such a small chance to occur in the file that it is negligible: such a delimiter is a UUID, which is natively supported in Java.
String content = new Scanner(file, "UTF-8")
.useDelimiter(UUID.randomUUID().toString()).next();
You can do get id value by using
test_alert = $('#myDiv').val();_x000D_
alert(test_alert);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="myDiv"><p>Some Text</p></div>
_x000D_
Use replace method of string like the following way:
String x="\"abcd";
String z=x.replace("\"", "");
System.out.println(z);
Output:
abcd
The Revert command in the context menu ignores your edits and returns the working copy to its previous state. You may also select the desired revision other than the "Head" when you "CheckOut" from the repository.
You can try it simply like this:
$length = 5;
$randomletter = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, $length);
more details: http://forum.arnlweb.com/viewtopic.php?f=7&t=25
Tested for version: jdk-7u60-windows-x64.exe, jdk-7u60-windows-x64.exe
Tested for version: jdk-7u55-windows-x64.exe
You can do this in Python using simple function:
def get_cosine(text1, text2):
vec1 = text1
vec2 = text2
intersection = set(vec1.keys()) & set(vec2.keys())
numerator = sum([vec1[x] * vec2[x] for x in intersection])
sum1 = sum([vec1[x]**2 for x in vec1.keys()])
sum2 = sum([vec2[x]**2 for x in vec2.keys()])
denominator = math.sqrt(sum1) * math.sqrt(sum2)
if not denominator:
return 0.0
else:
return round(float(numerator) / denominator, 3)
dataSet1 = [3, 45, 7, 2]
dataSet2 = [2, 54, 13, 15]
get_cosine(dataSet1, dataSet2)
There is no need to keep calling .ToString()
as getValue
is already a string.
Aside that, this line could possibly be your problem:
string getValue = cmd.ExecuteScalar().ToString();
If there are no rows .ExecuteScalar
will return null
so you need to do some checking.
For instance:
var firstColumn = cmd.ExecuteScalar();
if (firstColumn != null) {
result = firstColumn.ToString();
}
If you want to inspect html, css or maybe you need js console in your mobile browser . You can use excelent tool eruda Using it you have the same Developer Tools on your mobile browser like in your desctop device. Dont forget to upvote :) Here is a link https://github.com/liriliri/eruda
Python lists have no built-in pre-allocation. If you really need to make a list, and need to avoid the overhead of appending (and you should verify that you do), you can do this:
l = [None] * 1000 # Make a list of 1000 None's
for i in xrange(1000):
# baz
l[i] = bar
# qux
Perhaps you could avoid the list by using a generator instead:
def my_things():
while foo:
#baz
yield bar
#qux
for thing in my_things():
# do something with thing
This way, the list isn't every stored all in memory at all, merely generated as needed.
Console.OutputEncoding Property
https://docs.microsoft.com/en-us/dotnet/api/system.console.outputencoding
Note that successfully displaying Unicode characters to the console requires the following:
- The console must use a TrueType font, such as Lucida Console or Consolas, to display characters.
Here is the simplest way Only with javascript:
var allElements = document.querySelectorAll('*');
for (var i = 0; i < allElements.length; i++) {
if (allElements[i].hasAttribute("class")) {
//console.log(allElements[i].className);
if (allElements[i].className.includes("_the _class ")) {
console.log("I see the class");
}
}
}
This is the official Microsoft answer from the MS Connect forums. I am copying the relevant text below :-
When targeting .NET 4.5 Unobtrusive Validation is enabled by default. You need to have jQuery in your project and have something like this in Global.asax to register jQuery properly:
ScriptManager.ScriptResourceMapping.AddDefinition("jquery",
new ScriptResourceDefinition {
Path = "~/scripts/jquery-1.4.1.min.js",
DebugPath = "~/scripts/jquery-1.4.1.js",
CdnPath = "http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.1.min.js",
CdnDebugPath = "http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.1.js"
});
Replacing the version of jQuery with the version you are using.
You can also disable this new feature in web.config by removing the following line:
<add key="ValidationSettings:UnobtrusiveValidationMode" value="WebForms" />
The answers that use pattern and a regex write the user's password into the input properties as plain text pattern='mypassword'
. This will only be visible if developer tools are open but it still doesn't seem like a good idea.
Another issue with using pattern to check for a match is that you are likely to want to use pattern to check that the password is of the right form, e.g. mixed letters and numbers.
I also think these methods won't work well if the user switches between inputs.
Here's my solution which uses a bit more JavaScript but performs a simple equality check when either input is updated and then sets a custom HTML validity. Both inputs can still be tested for a pattern such as email format or password complexity.
For a real page you would change the input types to 'password'.
<form>
<input type="text" id="password1" oninput="setPasswordConfirmValidity();">
<input type="text" id="password2" oninput="setPasswordConfirmValidity();">
</form>
<script>
function setPasswordConfirmValidity(str) {
const password1 = document.getElementById('password1');
const password2 = document.getElementById('password2');
if (password1.value === password2.value) {
password2.setCustomValidity('');
} else {
password2.setCustomValidity('Passwords must match');
}
console.log('password2 customError ', document.getElementById('password2').validity.customError);
console.log('password2 validationMessage ', document.getElementById('password2').validationMessage);
}
</script>
In my case, program was not waiting because I was using watcher
command to auto run the program. Manually running the program go run main.go
resulted in "Enter text" and eventually printing to console.
fmt.Print("Enter text: ")
var input string
fmt.Scanln(&input)
fmt.Print(input)
The conflict message:
CONFLICT (delete/modify): res/layout/dialog_item.xml deleted in dialog and modified in HEAD
means that res/layout/dialog_item.xml
was deleted in the 'dialog' branch you are merging, but was modified in HEAD (in the branch you are merging to).
So you have to decide whether
git rm res/layout/dialog_item.xml
"or
git add res/layout/dialog_item.xml
"Then you finalize merge with "git commit
".
Note that git will warn you that you are creating a merge commit, in the (rare) case where it is something you don't want. Probably remains from the days where said case was less rare.
Find Arabic chars and replace them with its UTF-8 encoding. some thing like this:
for (int i = 0; i < urlAsString.length(); i++) {
if (urlAsString.charAt(i) > 255) {
urlAsString = urlAsString.substring(0, i) + URLEncoder.encode(urlAsString.charAt(i)+"", "UTF-8") + urlAsString.substring(i+1);
}
}
encodedURL = urlAsString;
CentOS 7:
I tried solutions in this post
sudo yum -y install libcurl libcurl-devel
sudo yum -y install openssl-devel
but wasn't enough.
Checking R error in Console gave me the anwser. In my case it was lacking libxml-2.0 below (and Console printed an explanation with package name to different Linux versions and other possible R configs)
sudo yum -y install libxml2-devel
"before" by default implies before(:each)
. Ref The Rspec Book, copyright 2010, page 228.
before(scope = :each, options={}, &block)
I use before(:each)
to seed some data for each example group without having to call the let
method to create the data in the "it" block. Less code in the "it" block in this case.
I use let
if I want some data in some examples but not others.
Both before and let are great for DRYing up the "it" blocks.
To avoid any confusion, "let" is not the same as before(:all)
. "Let" re-evaluates its method and value for each example ("it"), but caches the value across multiple calls in the same example. You can read more about it here: https://www.relishapp.com/rspec/rspec-core/v/2-6/docs/helper-methods/let-and-let
I recently bought a new SSD and went from Windows to Linux.My build times are now an order of magnitude faster, and no longer annoying.
Though it does not directly answer your question as to why it's slower than eclipse, it shows that the process is disk-bounded and an upgrade to an SSD might be a (somewhat expensive) solution. I'm guessing there will be people googling the issue and ending up here, who might appreciate my experience.
Best and easiest way is to use anchor tag in CodeIgniter like eg.
<?php
$this->load->helper('url');
echo anchor('name_of_controller_file/function_name_if_any', 'Sign Out', array('class' => '', 'id' => ''));
?>
Refer https://www.codeigniter.com/user_guide/helpers/url_helper.html for details
This will surely work.
Up until now (December 2017), this is the only solution I found which works both inside and outside the IDE.
Use PathMatchingResourcePatternResolver
Note: it works also in spring-boot
In this example I'm reading some files located in src/main/resources/my_folder:
try {
// Get all the files under this inner resource folder: my_folder
String scannedPackage = "my_folder/*";
PathMatchingResourcePatternResolver scanner = new PathMatchingResourcePatternResolver();
Resource[] resources = scanner.getResources(scannedPackage);
if (resources == null || resources.length == 0)
log.warn("Warning: could not find any resources in this scanned package: " + scannedPackage);
else {
for (Resource resource : resources) {
log.info(resource.getFilename());
// Read the file content (I used BufferedReader, but there are other solutions for that):
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resource.getInputStream()));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
// ...
// ...
}
bufferedReader.close();
}
}
} catch (Exception e) {
throw new Exception("Failed to read the resources folder: " + e.getMessage(), e);
}
It depends on number of entities which are going to be updated, if you have large number of entities using JPA Query Update statement is better as you dont have to load all the entities from database, if you are going to update just one entity then using find and update is fine.
Search in any revision, any file (unix/linux):
git rev-list --all | xargs git grep <regexp>
Search only in some given files, for example XML files:
git rev-list --all | xargs -I{} git grep <regexp> {} -- "*.xml"
The result lines should look like this: 6988bec26b1503d45eb0b2e8a4364afb87dde7af:bla.xml: text of the line it found...
You can then get more information like author, date, and diff using git show
:
git show 6988bec26b1503d45eb0b2e8a4364afb87dde7af
I had a need to add a guid primary key column in an existing table and populate it with unique GUID's and this update query with inner select worked for me:
UPDATE sri_issued_quiz SET quiz_id=(SELECT uuid());
So simple :-)
My objective was to create a new Django project from the command line in Ubuntu, like so:
django-admin.py startproject mysite
I have python2.7.5 installed. I got this error:
ImportError: No module named zlib
For hours I could not find a solution, until now!
Here is a link to the solution -
http://doc.biblissima-condorcet.fr/loris-setup-guide-ubuntu-debian
I followed and executed instruction in Section 1.1 and it is working perfectly! It is an easy solution.
Add programatically noborder class to specific row to hide it
<style>
.noborder
{
border:none;
}
</style>
<table>
<tr>
<th>heading1</th>
<th>heading2</th>
</tr>
<tr>
<td>content1</td>
<td>content2</td>
</tr>
/*no border for this row */
<tr class="noborder">
<td>content1</td>
<td>content2</td>
</tr>
</table>
overflow-y: scroll;
Notice if you remove the -y
from the overflow-y
property, the horizontal scroll bar is shown.
That is called a shebang, it tells the shell what program to interpret the script with, when executed.
In your example, the script is to be interpreted and run by the bash shell.
Some other example shebangs are:
(From Wikipedia)
#!/bin/sh — Execute the file using sh, the Bourne shell, or a compatible shell
#!/bin/csh — Execute the file using csh, the C shell, or a compatible shell
#!/usr/bin/perl -T — Execute using Perl with the option for taint checks
#!/usr/bin/php — Execute the file using the PHP command line interpreter
#!/usr/bin/python -O — Execute using Python with optimizations to code
#!/usr/bin/ruby — Execute using Ruby
and a few additional ones I can think off the top of my head, such as:
#!/bin/ksh
#!/bin/awk
#!/bin/expect
In a script with the bash shebang, for example, you would write your code with bash syntax; whereas in a script with expect shebang, you would code it in expect syntax, and so on.
Response to updated portion:
It depends on what /bin/sh
actually points to on your system. Often it is just a symlink to /bin/bash
. Sometimes portable scripts are written with #!/bin/sh
just to signify that it's a shell script, but it uses whichever shell is referred to by /bin/sh
on that particular system (maybe it points to /bin/bash
, /bin/ksh
or /bin/zsh
)
set the wrapper to height 100%
.vwrapper {
display: flex;
flex-direction: column;
flex-wrap: nowrap;
justify-content: flex-start;
align-items: stretch;
align-content: stretch;
height: 100%;
}
and set the 3rd row to flex-grow
#row3 {
background-color: green;
flex: 1 1 auto;
display: flex;
}
Yep, even in plain JavaScript it's pretty easy. You give an element an id and then you can use that as a "bookmark":
<div id="here">here</div>
If you want it to scroll there when a user clicks a link, you can just use the tried-and-true method:
<a href="#here">scroll to over there</a>
To do it programmatically, use scrollIntoView()
document.getElementById("here").scrollIntoView()
int random = minimum + Double.valueOf(Math.random()*(maximum-minimum )).intValue();
Or take a look to RandomUtils from Apache Commons.
Change your Method as following and check it will work
private void initViews() {
inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.id_number_edit_text_custom, this, true);
View view = (View) inflater.inflate(R.layout.main, null);
editText = (EditText) view.findViewById(R.id.id_number_custom);
loadButton = (ImageButton) view.findViewById(R.id.load_data_button);
loadButton.setVisibility(RelativeLayout.INVISIBLE);
loadData();
}
A note to this:
IE 8.0s emulation only promises to display the page the same. There are subtle differences that might cause functionality to break. I recently had a problem with just that. Where IE 7.0 uses a javascript wrapper-function called "anonymous()" in IE 8.0 the wrapper was named differently.
So do not expect things like JavaScript to "just work", because you turn on emulation.