As mentioned in other answers - when you use an instance method you need to pass self
as the first argument - this is the source of the error.
With addition to that,it is important to understand that only instance methods take self
as the first argument in order to refer to the instance.
In case the method is Static you don't pass self
, but a cls
argument instead (or class_
).
Please see an example below.
class City:
country = "USA" # This is a class level attribute which will be shared across all instances (and not created PER instance)
def __init__(self, name, location, population):
self.name = name
self.location = location
self.population = population
# This is an instance method which takes self as the first argument to refer to the instance
def print_population(self, some_nice_sentence_prefix):
print(some_nice_sentence_prefix +" In " +self.name + " lives " +self.population + " people!")
# This is a static (class) method which is marked with the @classmethod attribute
# All class methods must take a class argument as first param. The convention is to name is "cls" but class_ is also ok
@classmethod
def change_country(cls, new_country):
cls.country = new_country
Some tests just to make things more clear:
# Populate objects
city1 = City("New York", "East", "18,804,000")
city2 = City("Los Angeles", "West", "10,118,800")
#1) Use the instance method: No need to pass "self" - it is passed as the city1 instance
city1.print_population("Did You Know?") # Prints: Did You Know? In New York lives 18,804,000 people!
#2.A) Use the static method in the object
city2.change_country("Canada")
#2.B) Will be reflected in all objects
print("city1.country=",city1.country) # Prints Canada
print("city2.country=",city2.country) # Prints Canada
Try this in MVC 4.0
@Html.TextBoxFor(m => m.YourDate, "{0:dd/MM/yyyy}", new { @class = "datefield form-control", @placeholder = "Enter start date..." })
You're only adding the File object to the JSON object. The File object only contains meta information about the file: Path, name and so on.
You must load the image and read the bytes from it. Then put these bytes into the JSON object.
Supposing you use sql server:
WHERE StartTime BETWEEN DATEADD(HOUR, -1, GetDate())
AND DATEADD(HOUR, 1, GetDate())
ripgrep
Here are the example using ripgrep
:
rg -o "(\w+)?th(\w+)?"
It'll match all words matching th
.
DateTime start1 = DateTime.Parse(txtDate.Text);
SELECT *
FROM dbo.March2010 A
WHERE A.Date >= start1;
First convert TexBox into the Datetime then....use that variable into the Query
You can iterate DefaultView
as the following code by Indexer
:
DataTable dt = new DataTable();
// add some rows to your table
// ...
dt.DefaultView.Sort = "OneColumnName ASC"; // For example
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow oRow = dt.DefaultView[i].Row;
// Do your stuff with oRow
// ...
}
Change your storage engine to InnoDB by going to Operation
It sounds like this
in your code is not referring to your .btn
element. Try referencing it explicitly with a selector:
var votevalue = parseInt($(".btn").data('votevalue'), 10);
Also, don't forget the radix.
As an extra, you can take the Enum.Parse
answers already provided and put them in an easy-to-use static method in a helper class.
public static T ParseEnum<T>(string value)
{
return (T)Enum.Parse(typeof(T), value, ignoreCase: true);
}
And use it like so:
{
Content = ParseEnum<ContentEnum>(fileContentMessage);
};
Especially helpful if you have lots of (different) Enums to parse.
a day is 86400 seconds.
$tomorrow = date('y:m:d', time() + 86400);
Try using the ArrayIntList from the apache framework. It works exactly like an arraylist, except it can hold primitive int.
More details here -
if (ActionsLogWriter.Close || ErrorDumpWriter.Close == true)
{ // Do stuff here
}
Try this
<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="1" />
if you want 0 or 1 "description" elements, Or
<xs:element name="description" type="xs:string" minOccurs="0" maxOccurs="unbounded" />
if you want 0 to infinity number of "description" elements.
Here the simples
a = [x for x in 'abcdefgh'] #['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
Bear in mind that ES6 Sets/Maps don't appear to be reactive as far as i can tell, at time of writing.
Good questions I have been asked are
It would be interesting to see what a candidate would come up with and you'll certainly learn quite a bit about how he/she uses the framework.
Edit: thanks to @superlogical, you can now find and improve the following code in github!
I wrote this class based on some ideas here. The columns width is optimal, an it can handle object arrays with this simple API:
static void Main(string[] args)
{
IEnumerable<Tuple<int, string, string>> authors =
new[]
{
Tuple.Create(1, "Isaac", "Asimov"),
Tuple.Create(2, "Robert", "Heinlein"),
Tuple.Create(3, "Frank", "Herbert"),
Tuple.Create(4, "Aldous", "Huxley"),
};
Console.WriteLine(authors.ToStringTable(
new[] {"Id", "First Name", "Surname"},
a => a.Item1, a => a.Item2, a => a.Item3));
/* Result:
| Id | First Name | Surname |
|----------------------------|
| 1 | Isaac | Asimov |
| 2 | Robert | Heinlein |
| 3 | Frank | Herbert |
| 4 | Aldous | Huxley |
*/
}
Here is the class:
public static class TableParser
{
public static string ToStringTable<T>(
this IEnumerable<T> values,
string[] columnHeaders,
params Func<T, object>[] valueSelectors)
{
return ToStringTable(values.ToArray(), columnHeaders, valueSelectors);
}
public static string ToStringTable<T>(
this T[] values,
string[] columnHeaders,
params Func<T, object>[] valueSelectors)
{
Debug.Assert(columnHeaders.Length == valueSelectors.Length);
var arrValues = new string[values.Length + 1, valueSelectors.Length];
// Fill headers
for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
{
arrValues[0, colIndex] = columnHeaders[colIndex];
}
// Fill table rows
for (int rowIndex = 1; rowIndex < arrValues.GetLength(0); rowIndex++)
{
for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
{
arrValues[rowIndex, colIndex] = valueSelectors[colIndex]
.Invoke(values[rowIndex - 1]).ToString();
}
}
return ToStringTable(arrValues);
}
public static string ToStringTable(this string[,] arrValues)
{
int[] maxColumnsWidth = GetMaxColumnsWidth(arrValues);
var headerSpliter = new string('-', maxColumnsWidth.Sum(i => i + 3) - 1);
var sb = new StringBuilder();
for (int rowIndex = 0; rowIndex < arrValues.GetLength(0); rowIndex++)
{
for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
{
// Print cell
string cell = arrValues[rowIndex, colIndex];
cell = cell.PadRight(maxColumnsWidth[colIndex]);
sb.Append(" | ");
sb.Append(cell);
}
// Print end of line
sb.Append(" | ");
sb.AppendLine();
// Print splitter
if (rowIndex == 0)
{
sb.AppendFormat(" |{0}| ", headerSpliter);
sb.AppendLine();
}
}
return sb.ToString();
}
private static int[] GetMaxColumnsWidth(string[,] arrValues)
{
var maxColumnsWidth = new int[arrValues.GetLength(1)];
for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
{
for (int rowIndex = 0; rowIndex < arrValues.GetLength(0); rowIndex++)
{
int newLength = arrValues[rowIndex, colIndex].Length;
int oldLength = maxColumnsWidth[colIndex];
if (newLength > oldLength)
{
maxColumnsWidth[colIndex] = newLength;
}
}
}
return maxColumnsWidth;
}
}
Edit: I added a minor improvement - if you want the column headers to be the property name, add the following method to TableParser
(note that it will be a bit slower due to reflection):
public static string ToStringTable<T>(
this IEnumerable<T> values,
params Expression<Func<T, object>>[] valueSelectors)
{
var headers = valueSelectors.Select(func => GetProperty(func).Name).ToArray();
var selectors = valueSelectors.Select(exp => exp.Compile()).ToArray();
return ToStringTable(values, headers, selectors);
}
private static PropertyInfo GetProperty<T>(Expression<Func<T, object>> expresstion)
{
if (expresstion.Body is UnaryExpression)
{
if ((expresstion.Body as UnaryExpression).Operand is MemberExpression)
{
return ((expresstion.Body as UnaryExpression).Operand as MemberExpression).Member as PropertyInfo;
}
}
if ((expresstion.Body is MemberExpression))
{
return (expresstion.Body as MemberExpression).Member as PropertyInfo;
}
return null;
}
An API key is a unique value that is assigned to a user of this service when he's accepted as a user of the service.
The service maintains all the issued keys and checks them at each request.
By looking at the supplied key at the request, a service checks whether it is a valid key to decide on whether to grant access to a user or not.
npos is just a token value that tells you that find() did not find anything (probably -1 or something like that). find() checks for the first occurence of the parameter, and returns the index at which the parameter begins. For Example,
string name = "asad.txt";
int i = name.find(".txt");
//i holds the value 4 now, that's the index at which ".txt" starts
if (i==string::npos) //if ".txt" was NOT found - in this case it was, so this condition is false
name.append(".txt");
Arkaitz is correct that string
is a managed type. What this means for you is that you never have to worry about how long the string is, nor do you have to worry about freeing or reallocating the memory of the string.
On the other hand, the char[]
notation in the case above has restricted the character buffer to exactly 256 characters. If you tried to write more than 256 characters into that buffer, at best you will overwrite other memory that your program "owns". At worst, you will try to overwrite memory that you do not own, and your OS will kill your program on the spot.
Bottom line? Strings are a lot more programmer friendly, char[]s are a lot more efficient for the computer.
This is because you are referring to property of controller named HttpContext
. To access the current context use full class name:
System.Web.HttpContext.Current
However this is highly not recommended to access context like this in ASP.NET MVC, so yes, you can think of System.Web.HttpContext.Current
as being deprecated inside ASP.NET MVC. The correct way to access current context is
this.ControllerContext.HttpContext
or if you are inside a Controller, just use member
this.HttpContext
A good example of using ids of other rows in the same table as foreign keys is nested lists.
Deleting a row that has children (i.e., rows, which refer to parent's id), which also have children (i.e., referencing ids of children) will delete a cascade of rows.
This will save a lot of pain (and a lot of code of what to do with orphans - i.e., rows, that refer to non-existing ids).
I get this problem everytime i save a file that gets dynamically compiled (ascx, aspx etc). I wait about 8-10 seconds then it goes away. It's hellishly annoying.
I thought it was perhaps an IIS Express problem so I tried in the inbuilt dev server and am still receiving it after saving a file. I'm running an MVC app, i'm also using T4MVC, maybe that is a factor...
My typical expectation is than when "subject" is used a context like this, it means the target of the certificate. If you think of a certificate as a cryptographically secured description of a thing (person, device, communication channel, etc), then the subject is the stuff related to that thing.
It's not the thing itself. For example, no one would say "the subject takes his SmartCard and authenticates his PIN". That would be the "user".
But it usually relates to the various data items related to that that thing. For example:
Usually, it's used to distinguish between the other players in the PKI world. Namely the "issuer" and the "root". The issuer is the CA that issued the cert (to the subject), and the root is the CA that is end point of all the trust in the heirarchy. The typical relationship is root--->issuer--->subject.
We need to cover at least these aspects to provide a comprehensive answer/comparison (in no particular order of importance): Speed
, Memory usage
, Syntax
and Features
.
My intent is to cover each one of these as clearly as possible from data.table perspective.
Note: unless explicitly mentioned otherwise, by referring to dplyr, we refer to dplyr's data.frame interface whose internals are in C++ using Rcpp.
The data.table syntax is consistent in its form - DT[i, j, by]
. To keep i
, j
and by
together is by design. By keeping related operations together, it allows to easily optimise operations for speed and more importantly memory usage, and also provide some powerful features, all while maintaining the consistency in syntax.
Quite a few benchmarks (though mostly on grouping operations) have been added to the question already showing data.table gets faster than dplyr as the number of groups and/or rows to group by increase, including benchmarks by Matt on grouping from 10 million to 2 billion rows (100GB in RAM) on 100 - 10 million groups and varying grouping columns, which also compares pandas
. See also updated benchmarks, which include Spark
and pydatatable
as well.
On benchmarks, it would be great to cover these remaining aspects as well:
Grouping operations involving a subset of rows - i.e., DT[x > val, sum(y), by = z]
type operations.
Benchmark other operations such as update and joins.
Also benchmark memory footprint for each operation in addition to runtime.
Operations involving filter()
or slice()
in dplyr can be memory inefficient (on both data.frames and data.tables). See this post.
Note that Hadley's comment talks about speed (that dplyr is plentiful fast for him), whereas the major concern here is memory.
data.table interface at the moment allows one to modify/update columns by reference (note that we don't need to re-assign the result back to a variable).
# sub-assign by reference, updates 'y' in-place
DT[x >= 1L, y := NA]
But dplyr will never update by reference. The dplyr equivalent would be (note that the result needs to be re-assigned):
# copies the entire 'y' column
ans <- DF %>% mutate(y = replace(y, which(x >= 1L), NA))
A concern for this is referential transparency. Updating a data.table object by reference, especially within a function may not be always desirable. But this is an incredibly useful feature: see this and this posts for interesting cases. And we want to keep it.
Therefore we are working towards exporting shallow()
function in data.table that will provide the user with both possibilities. For example, if it is desirable to not modify the input data.table within a function, one can then do:
foo <- function(DT) {
DT = shallow(DT) ## shallow copy DT
DT[, newcol := 1L] ## does not affect the original DT
DT[x > 2L, newcol := 2L] ## no need to copy (internally), as this column exists only in shallow copied DT
DT[x > 2L, x := 3L] ## have to copy (like base R / dplyr does always); otherwise original DT will
## also get modified.
}
By not using shallow()
, the old functionality is retained:
bar <- function(DT) {
DT[, newcol := 1L] ## old behaviour, original DT gets updated by reference
DT[x > 2L, x := 3L] ## old behaviour, update column x in original DT.
}
By creating a shallow copy using shallow()
, we understand that you don't want to modify the original object. We take care of everything internally to ensure that while also ensuring to copy columns you modify only when it is absolutely necessary. When implemented, this should settle the referential transparency issue altogether while providing the user with both possibilties.
Also, once
shallow()
is exported dplyr's data.table interface should avoid almost all copies. So those who prefer dplyr's syntax can use it with data.tables.But it will still lack many features that data.table provides, including (sub)-assignment by reference.
Aggregate while joining:
Suppose you have two data.tables as follows:
DT1 = data.table(x=c(1,1,1,1,2,2,2,2), y=c("a", "a", "b", "b"), z=1:8, key=c("x", "y"))
# x y z
# 1: 1 a 1
# 2: 1 a 2
# 3: 1 b 3
# 4: 1 b 4
# 5: 2 a 5
# 6: 2 a 6
# 7: 2 b 7
# 8: 2 b 8
DT2 = data.table(x=1:2, y=c("a", "b"), mul=4:3, key=c("x", "y"))
# x y mul
# 1: 1 a 4
# 2: 2 b 3
And you would like to get sum(z) * mul
for each row in DT2
while joining by columns x,y
. We can either:
1) aggregate DT1
to get sum(z)
, 2) perform a join and 3) multiply (or)
# data.table way
DT1[, .(z = sum(z)), keyby = .(x,y)][DT2][, z := z*mul][]
# dplyr equivalent
DF1 %>% group_by(x, y) %>% summarise(z = sum(z)) %>%
right_join(DF2) %>% mutate(z = z * mul)
2) do it all in one go (using by = .EACHI
feature):
DT1[DT2, list(z=sum(z) * mul), by = .EACHI]
What is the advantage?
We don't have to allocate memory for the intermediate result.
We don't have to group/hash twice (one for aggregation and other for joining).
And more importantly, the operation what we wanted to perform is clear by looking at j
in (2).
Check this post for a detailed explanation of by = .EACHI
. No intermediate results are materialised, and the join+aggregate is performed all in one go.
Have a look at this, this and this posts for real usage scenarios.
In dplyr
you would have to join and aggregate or aggregate first and then join, neither of which are as efficient, in terms of memory (which in turn translates to speed).
Update and joins:
Consider the data.table code shown below:
DT1[DT2, col := i.mul]
adds/updates DT1
's column col
with mul
from DT2
on those rows where DT2
's key column matches DT1
. I don't think there is an exact equivalent of this operation in dplyr
, i.e., without avoiding a *_join
operation, which would have to copy the entire DT1
just to add a new column to it, which is unnecessary.
Check this post for a real usage scenario.
To summarise, it is important to realise that every bit of optimisation matters. As Grace Hopper would say, Mind your nanoseconds!
Let's now look at syntax. Hadley commented here:
Data tables are extremely fast but I think their concision makes it harder to learn and code that uses it is harder to read after you have written it ...
I find this remark pointless because it is very subjective. What we can perhaps try is to contrast consistency in syntax. We will compare data.table and dplyr syntax side-by-side.
We will work with the dummy data shown below:
DT = data.table(x=1:10, y=11:20, z=rep(1:2, each=5))
DF = as.data.frame(DT)
Basic aggregation/update operations.
# case (a)
DT[, sum(y), by = z] ## data.table syntax
DF %>% group_by(z) %>% summarise(sum(y)) ## dplyr syntax
DT[, y := cumsum(y), by = z]
ans <- DF %>% group_by(z) %>% mutate(y = cumsum(y))
# case (b)
DT[x > 2, sum(y), by = z]
DF %>% filter(x>2) %>% group_by(z) %>% summarise(sum(y))
DT[x > 2, y := cumsum(y), by = z]
ans <- DF %>% group_by(z) %>% mutate(y = replace(y, which(x > 2), cumsum(y)))
# case (c)
DT[, if(any(x > 5L)) y[1L]-y[2L] else y[2L], by = z]
DF %>% group_by(z) %>% summarise(if (any(x > 5L)) y[1L] - y[2L] else y[2L])
DT[, if(any(x > 5L)) y[1L] - y[2L], by = z]
DF %>% group_by(z) %>% filter(any(x > 5L)) %>% summarise(y[1L] - y[2L])
data.table syntax is compact and dplyr's quite verbose. Things are more or less equivalent in case (a).
In case (b), we had to use filter()
in dplyr while summarising. But while updating, we had to move the logic inside mutate()
. In data.table however, we express both operations with the same logic - operate on rows where x > 2
, but in first case, get sum(y)
, whereas in the second case update those rows for y
with its cumulative sum.
This is what we mean when we say the DT[i, j, by]
form is consistent.
Similarly in case (c), when we have if-else
condition, we are able to express the logic "as-is" in both data.table and dplyr. However, if we would like to return just those rows where the if
condition satisfies and skip otherwise, we cannot use summarise()
directly (AFAICT). We have to filter()
first and then summarise because summarise()
always expects a single value.
While it returns the same result, using filter()
here makes the actual operation less obvious.
It might very well be possible to use filter()
in the first case as well (does not seem obvious to me), but my point is that we should not have to.
Aggregation / update on multiple columns
# case (a)
DT[, lapply(.SD, sum), by = z] ## data.table syntax
DF %>% group_by(z) %>% summarise_each(funs(sum)) ## dplyr syntax
DT[, (cols) := lapply(.SD, sum), by = z]
ans <- DF %>% group_by(z) %>% mutate_each(funs(sum))
# case (b)
DT[, c(lapply(.SD, sum), lapply(.SD, mean)), by = z]
DF %>% group_by(z) %>% summarise_each(funs(sum, mean))
# case (c)
DT[, c(.N, lapply(.SD, sum)), by = z]
DF %>% group_by(z) %>% summarise_each(funs(n(), mean))
In case (a), the codes are more or less equivalent. data.table uses familiar base function lapply()
, whereas dplyr
introduces *_each()
along with a bunch of functions to funs()
.
data.table's :=
requires column names to be provided, whereas dplyr generates it automatically.
In case (b), dplyr's syntax is relatively straightforward. Improving aggregations/updates on multiple functions is on data.table's list.
In case (c) though, dplyr would return n()
as many times as many columns, instead of just once. In data.table, all we need to do is to return a list in j
. Each element of the list will become a column in the result. So, we can use, once again, the familiar base function c()
to concatenate .N
to a list
which returns a list
.
Note: Once again, in data.table, all we need to do is return a list in
j
. Each element of the list will become a column in result. You can usec()
,as.list()
,lapply()
,list()
etc... base functions to accomplish this, without having to learn any new functions.You will need to learn just the special variables -
.N
and.SD
at least. The equivalent in dplyr aren()
and.
Joins
dplyr provides separate functions for each type of join where as data.table allows joins using the same syntax DT[i, j, by]
(and with reason). It also provides an equivalent merge.data.table()
function as an alternative.
setkey(DT1, x, y)
# 1. normal join
DT1[DT2] ## data.table syntax
left_join(DT2, DT1) ## dplyr syntax
# 2. select columns while join
DT1[DT2, .(z, i.mul)]
left_join(select(DT2, x, y, mul), select(DT1, x, y, z))
# 3. aggregate while join
DT1[DT2, .(sum(z) * i.mul), by = .EACHI]
DF1 %>% group_by(x, y) %>% summarise(z = sum(z)) %>%
inner_join(DF2) %>% mutate(z = z*mul) %>% select(-mul)
# 4. update while join
DT1[DT2, z := cumsum(z) * i.mul, by = .EACHI]
??
# 5. rolling join
DT1[DT2, roll = -Inf]
??
# 6. other arguments to control output
DT1[DT2, mult = "first"]
??
Some might find a separate function for each joins much nicer (left, right, inner, anti, semi etc), whereas as others might like data.table's DT[i, j, by]
, or merge()
which is similar to base R.
However dplyr joins do just that. Nothing more. Nothing less.
data.tables can select columns while joining (2), and in dplyr you will need to select()
first on both data.frames before to join as shown above. Otherwise you would materialiase the join with unnecessary columns only to remove them later and that is inefficient.
data.tables can aggregate while joining (3) and also update while joining (4), using by = .EACHI
feature. Why materialse the entire join result to add/update just a few columns?
data.table is capable of rolling joins (5) - roll forward, LOCF, roll backward, NOCB, nearest.
data.table also has mult =
argument which selects first, last or all matches (6).
data.table has allow.cartesian = TRUE
argument to protect from accidental invalid joins.
Once again, the syntax is consistent with
DT[i, j, by]
with additional arguments allowing for controlling the output further.
do()
...
dplyr's summarise is specially designed for functions that return a single value. If your function returns multiple/unequal values, you will have to resort to do()
. You have to know beforehand about all your functions return value.
DT[, list(x[1], y[1]), by = z] ## data.table syntax
DF %>% group_by(z) %>% summarise(x[1], y[1]) ## dplyr syntax
DT[, list(x[1:2], y[1]), by = z]
DF %>% group_by(z) %>% do(data.frame(.$x[1:2], .$y[1]))
DT[, quantile(x, 0.25), by = z]
DF %>% group_by(z) %>% summarise(quantile(x, 0.25))
DT[, quantile(x, c(0.25, 0.75)), by = z]
DF %>% group_by(z) %>% do(data.frame(quantile(.$x, c(0.25, 0.75))))
DT[, as.list(summary(x)), by = z]
DF %>% group_by(z) %>% do(data.frame(as.list(summary(.$x))))
.SD
's equivalent is .
In data.table, you can throw pretty much anything in j
- the only thing to remember is for it to return a list so that each element of the list gets converted to a column.
In dplyr, cannot do that. Have to resort to do()
depending on how sure you are as to whether your function would always return a single value. And it is quite slow.
Once again, data.table's syntax is consistent with
DT[i, j, by]
. We can just keep throwing expressions inj
without having to worry about these things.
Have a look at this SO question and this one. I wonder if it would be possible to express the answer as straightforward using dplyr's syntax...
To summarise, I have particularly highlighted several instances where dplyr's syntax is either inefficient, limited or fails to make operations straightforward. This is particularly because data.table gets quite a bit of backlash about "harder to read/learn" syntax (like the one pasted/linked above). Most posts that cover dplyr talk about most straightforward operations. And that is great. But it is important to realise its syntax and feature limitations as well, and I am yet to see a post on it.
data.table has its quirks as well (some of which I have pointed out that we are attempting to fix). We are also attempting to improve data.table's joins as I have highlighted here.
But one should also consider the number of features that dplyr lacks in comparison to data.table.
I have pointed out most of the features here and also in this post. In addition:
fread - fast file reader has been available for a long time now.
fwrite - a parallelised fast file writer is now available. See this post for a detailed explanation on the implementation and #1664 for keeping track of further developments.
Automatic indexing - another handy feature to optimise base R syntax as is, internally.
Ad-hoc grouping: dplyr
automatically sorts the results by grouping variables during summarise()
, which may not be always desirable.
Numerous advantages in data.table joins (for speed / memory efficiency and syntax) mentioned above.
Non-equi joins: Allows joins using other operators <=, <, >, >=
along with all other advantages of data.table joins.
Overlapping range joins was implemented in data.table recently. Check this post for an overview with benchmarks.
setorder()
function in data.table that allows really fast reordering of data.tables by reference.
dplyr provides interface to databases using the same syntax, which data.table does not at the moment.
data.table
provides faster equivalents of set operations (written by Jan Gorecki) - fsetdiff
, fintersect
, funion
and fsetequal
with additional all
argument (as in SQL).
data.table loads cleanly with no masking warnings and has a mechanism described here for [.data.frame
compatibility when passed to any R package. dplyr changes base functions filter
, lag
and [
which can cause problems; e.g. here and here.
Finally:
On databases - there is no reason why data.table cannot provide similar interface, but this is not a priority now. It might get bumped up if users would very much like that feature.. not sure.
On parallelism - Everything is difficult, until someone goes ahead and does it. Of course it will take effort (being thread safe).
OpenMP
.I had the same problem,
i solved it by:
1 - i uninstall virtual box
2 - i uninstall genymotion with all new folder that dependency
3 - download latest version of virtual box(from oracle site)
4 - download latest version of Genymotion(without virtual box version
size:about42M)
5 - first install virtual box
6 - install genymotion
7 - before run genymotion you should restart your windows os
8 - run genymotion as admin
Sorry for my english writing
I'm new to learn :D
check it out!
a = [[1, 2], [2, 3], [3, 4]]
a2 = zip(*a)
a2[0]
it is the same thing as above except somehow it is neater the zip does the work but requires single arrays as arguments, the *a syntax unpacks the multidimensional array into single array arguments
You can use the notifyItemChanged(int position)
method from the RecyclerView.Adapter class. From the documentation:
Notify any registered observers that the item at position has changed. Equivalent to calling notifyItemChanged(position, null);.
This is an item change event, not a structural change event. It indicates that any reflection of the data at position is out of date and should be updated. The item at position retains the same identity.
As you already have the position, it should work for you.
I was looking for a solution to quite a related problem: finding the newest records per group which is a specialization of a typical greatest-n-per-group with N = 1.
The solution involves the problem you are dealing with here (i.e., how to build the query in Eloquent) so I am posting it as it might be helpful for others. It demonstrates a cleaner way of sub-query construction using powerful Eloquent fluent interface with multiple join columns and where
condition inside joined sub-select.
In my example I want to fetch the newest DNS scan results (table scan_dns
) per group identified by watch_id
. I build the sub-query separately.
The SQL I want Eloquent to generate:
SELECT * FROM `scan_dns` AS `s`
INNER JOIN (
SELECT x.watch_id, MAX(x.last_scan_at) as last_scan
FROM `scan_dns` AS `x`
WHERE `x`.`watch_id` IN (1,2,3,4,5,42)
GROUP BY `x`.`watch_id`) AS ss
ON `s`.`watch_id` = `ss`.`watch_id` AND `s`.`last_scan_at` = `ss`.`last_scan`
I did it in the following way:
// table name of the model
$dnsTable = (new DnsResult())->getTable();
// groups to select in sub-query
$ids = collect([1,2,3,4,5,42]);
// sub-select to be joined on
$subq = DnsResult::query()
->select('x.watch_id')
->selectRaw('MAX(x.last_scan_at) as last_scan')
->from($dnsTable . ' AS x')
->whereIn('x.watch_id', $ids)
->groupBy('x.watch_id');
$qqSql = $subq->toSql(); // compiles to SQL
// the main query
$q = DnsResult::query()
->from($dnsTable . ' AS s')
->join(
DB::raw('(' . $qqSql. ') AS ss'),
function(JoinClause $join) use ($subq) {
$join->on('s.watch_id', '=', 'ss.watch_id')
->on('s.last_scan_at', '=', 'ss.last_scan')
->addBinding($subq->getBindings());
// bindings for sub-query WHERE added
});
$results = $q->get();
UPDATE:
Since Laravel 5.6.17 the sub-query joins were added so there is a native way to build the query.
$latestPosts = DB::table('posts')
->select('user_id', DB::raw('MAX(created_at) as last_post_created_at'))
->where('is_published', true)
->groupBy('user_id');
$users = DB::table('users')
->joinSub($latestPosts, 'latest_posts', function ($join) {
$join->on('users.id', '=', 'latest_posts.user_id');
})->get();
There is no way to explicitly specify the template arguments when calling a constructor template, so they have to be deduced through argument deduction. This is because if you say:
Foo<int> f = Foo<int>();
The <int>
is the template argument list for the type Foo
, not for its constructor. There's nowhere for the constructor template's argument list to go.
Even with your workaround you still have to pass an argument in order to call that constructor template. It's not at all clear what you are trying to achieve.
Both pandas
and matplotlib.dates
use matplotlib.units
for locating the ticks.
But while matplotlib.dates
has convenient ways to set the ticks manually, pandas seems to have the focus on auto formatting so far (you can have a look at the code for date conversion and formatting in pandas).
So for the moment it seems more reasonable to use matplotlib.dates
(as mentioned by @BrenBarn in his comment).
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)
fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()
(my locale is German, so that Tuesday [Tue] becomes Dienstag [Di])
Another solution you can use is SQL Developer.
With it, you have the ability to import from a csv file (other delimited files are available).
Just open the table view, then:
You have the option to have SQL Developer do the inserts for you, create an sql insert script, or create the data for a SQL Loader script (have not tried this option myself).
Of course all that is moot if you can only use the command line, but if you are able to test it with SQL Developer locally, you can always deploy the generated insert scripts (for example).
Just adding another option to the 2 already very good answers.
Simple and neet : use vw
units for a responsive height/width according to the viewport width.
vw : 1/100th of the width of the viewport. (Source MDN)
HTML:
<div></div>
CSS for a 1:1 aspect ratio:
div{
width:80vw;
height:80vw; /* same as width */
}
Table to calculate height according to the desired aspect ratio and width of element.
aspect ratio | multiply width by
-----------------------------------
1:1 | 1
1:3 | 3
4:3 | 0.75
16:9 | 0.5625
This technique allows you to :
position:absolute;
These units are supported by IE9+ see canIuse for more info
for bootstrap 4 this work with me good
$.validator.setDefaults({
highlight: function(element) {
$(element).closest('.form-group').find(".form-control:first").addClass('is-invalid');
},
unhighlight: function(element) {
$(element).closest('.form-group').find(".form-control:first").removeClass('is-invalid');
$(element).closest('.form-group').find(".form-control:first").addClass('is-valid');
},
errorElement: 'span',
errorClass: 'invalid-feedback',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
hope it will help !
I run into naming problem. Service name has to be exactly name of your implementation. If mismatched, it uses by default basicHttpBinding
resulting in text/xml
content type.
Name of your class is on two places - SVC markup and CS file.
Check endpoint contract too - again exact name of your interface, nothing more. I've added assembly name which just can't be there.
<service name="MyNamespace.MyService">
<endpoint address="" binding="wsHttpBinding" contract="MyNamespace.IMyService" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
You can simply use:
mvn --settings YourOwnSettings.xml clean install
or
mvn -s YourOwnSettings.xml clean install
I was facing same issue (VS Code).Resolved by below method
1) Select Interpreter command from the Command Palette (Ctrl+Shift+P)
2) Search for "Select Interpreter"
3) Select the installed python directory
Ref:- https://code.visualstudio.com/docs/python/environments#_select-an-environment
Links with href="#" should almost always be replaced with a button element:
<button class="someclass">Text</button>
Using links with href="#" is also an accessibility concern as these links will be visible to screen readers, which will read out "Link - Text" but if the user clicks it won't go anywhere.
The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.
The way you get your original array back is by using Convert.FromBase64String
:
byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);
This counts the rows of the inner query:
select count(*) from (
select count(SID)
from Test
where Date = '2012-12-10'
group by SID
) t
However, in this case the effect of that is the same as this:
select count(distinct SID) from Test where Date = '2012-12-10'
LIke this
css
h2 {
border-bottom-width: 1px;
border-bottom-style: solid;
margin: 0;
padding: 0;
}
.edit_button {
float: right;
}
css
h2 {
border-bottom-width: 1px;
border-bottom-style: solid;
border-bottom-color: gray;
float: left;
margin: 0;
padding: 0;
}
.edit_button {
float: right;
}
html
<h2>
Contact Details</h2>
<button type="button" class="edit_button" >My Button</button>
html
<div style="border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: gray; float:left;">
Contact Details
</div>
<button type="button" class="edit_button" style="float: right;">My Button</button>
For Python >= 2.7, use subprocess.check_output()
.
http://docs.python.org/2/library/subprocess.html#subprocess.check_output
There are three types of variables:
The default values for instance and static variables are the same and depends on the type:
An array is an Object. So an array instance variable that is declared but no explicitly initialized will have null value. If you declare an int[] array as instance variable it will have the null value.
Once the array is created all of its elements are assiged with the default type value. For example:
private boolean[] list; // default value is null
private Boolean[] list; // default value is null
once is initialized:
private boolean[] list = new boolean[10]; // all ten elements are assigned to false
private Boolean[] list = new Boolean[10]; // all ten elements are assigned to null (default Object/Boolean value)
You could use HTML entities:
'
for '
"
for "
For more, you can take a look at Character entity references in HTML.
On tables of >1000000 rows I've found that these are both fast, with floor
just slightly faster:
df['mydate'] = df.index.floor('d')
or
df['mydate'] = df.index.normalize()
If your index has timezones and you don't want those in the result, do:
df['mydate'] = df.index.tz_localize(None).floor('d')
df.index.date
is many times slower; to_datetime()
is even worse. Both have the further disadvantage that the results cannot be saved to an hdf store as it does not support type datetime.date.
Note that I've used the index as the date source here; if your source is another column, you would need to add .dt
, e.g. df.mycol.dt.floor('d')
My solution is to use these 2 mappings:
map <leader>n <Esc><Esc>0qq
map <leader>m q:'<,'>-1normal!@q<CR><Down>
How to use them:
V12j
<leader>n
<leader>m
To make another edit you don't need to make the selection again. Just press <leader>n
, make your edit and press <leader>m
to apply.
How this works:
<Esc><Esc>0qq
Exit the visual selection, go to the beginning of the line and start recording a macro.
q
Stop recording the macro.
:'<,'>-1normal!@q<CR>
From the start of the visual selection to the line before the end, play the macro on each line.
<Down>
Go back down to the last line.
You can also just map the same key but for different modes:
vmap <leader>m <Esc><Esc>0qq
nmap <leader>m q:'<,'>-1normal!@q<CR><Down>
Although this messes up your ability to make another edit. You'll have to re-select your lines.
As per doc http://dev.mysql.com/doc/refman/5.0/en/server-status-variables.html#statvar_Connections
Connections
The number of connection attempts (successful or not) to the MySQL server.
import java.util.*;
public class HelloWorld{
public static void main(String []args){
List<String> threadSafeList = new ArrayList<String>();
threadSafeList.add("A");
threadSafeList.add("D");
threadSafeList.add("F");
Set<String> threadSafeList1 = new TreeSet<String>();
threadSafeList1.add("B");
threadSafeList1.add("C");
threadSafeList1.add("E");
threadSafeList1.addAll(threadSafeList);
List mainList = new ArrayList();
mainList.addAll(Arrays.asList(threadSafeList1));
Iterator<String> mainList1 = mainList.iterator();
while(mainList1.hasNext()){
System.out.printf("total : %s %n", mainList1.next());
}
}
}
i have same issue with Amazon server i change my code to this
var connection = mysql.createConnection({
localAddress : '35.160.300.66',
user : 'root',
password : 'root',
database : 'rootdb',
});
check mysql node module https://github.com/mysqljs/mysql
As of C# 6 you can declare and initialise a 'read-only auto-property' in one line:
double FuelConsumption { get; } = 2;
You can set the value from the constructor but not other methods.
check the code below this will be helpful for you:
<script type="text/javascript">
window.opener.location.href = '@Url.Action("Action", "EventstController")', window.close();
</script>
When you install third-party extensions you need to make sure that all the compilation parameters match:
Common glitches includes:
php.ini
file (that's typical with bundles); the right path is shown in phpinfo()
.Not being able to see the startup errors; those should show up in Apache logs, but you can also use the command line to diagnose it, e.g.:
php -d display_startup_errors=1 -d error_reporting=-1 -d display_errors -c "C:\Path\To\php.ini" -m
If everything's right you should see sqlsrv
in the command output and/or phpinfo()
(depending on what SAPI you're configuring):
[PHP Modules]
bcmath
calendar
Core
[...]
SPL
sqlsrv
standard
[...]
Pretty basic but works:
function dynamicHeight() {
var height = jQuery('').height();
jQuery('.edito-wrapper').css('height', editoHeight);
}
editoHeightSize();
jQuery(window).resize(function () {
editoHeightSize();
});
std::cout.precision(2);
std::cout<<std::fixed;
when you are using operator overloading try this.
You only need to do this:
Intent myIntent = new Intent(MainActivity.this, nextActivity.class);
This is probably because an empty line at the end of your input file.
Try this:
for x in f:
try:
print int(x.strip(),16)
except ValueError:
print "Invalid input:", x
Try this:
x = a > b and 10 or 11
This is a sample of execution:
>>> a,b=5,7
>>> x = a > b and 10 or 11
>>> print x
11
Further to my comment against @JBall's answer that helped me along the way, this is the final answer that works for me. I'm using MVC and Razor and I'm submitting a form using jQuery AJAX so I can update a partial view with some new results and I didn't want to do a complete postback (and page flicker).
Add the @Html.AntiForgeryToken()
inside the form as usual.
My AJAX submission button code (i.e. an onclick event) is:
//User clicks the SUBMIT button
$("#btnSubmit").click(function (event) {
//prevent this button submitting the form as we will do that via AJAX
event.preventDefault();
//Validate the form first
if (!$('#searchForm').validate().form()) {
alert("Please correct the errors");
return false;
}
//Get the entire form's data - including the antiforgerytoken
var allFormData = $("#searchForm").serialize();
// The actual POST can now take place with a validated form
$.ajax({
type: "POST",
async: false,
url: "/Home/SearchAjax",
data: allFormData,
dataType: "html",
success: function (data) {
$('#gridView').html(data);
$('#TestGrid').jqGrid('setGridParam', { url: '@Url.Action("GetDetails", "Home", Model)', datatype: "json", page: 1 }).trigger('reloadGrid');
}
});
I've left the "success" action in as it shows how the partial view is being updated that contains an MvcJqGrid and how it's being refreshed (very powerful jqGrid grid and this is a brilliant MVC wrapper for it).
My controller method looks like this:
//Ajax SUBMIT method
[ValidateAntiForgeryToken]
public ActionResult SearchAjax(EstateOutlet_D model)
{
return View("_Grid", model);
}
I have to admit to not being a fan of POSTing an entire form's data as a Model but if you need to do it then this is one way that works. MVC just makes the data binding too easy so rather than subitting 16 individual values (or a weakly-typed FormCollection) this is OK, I guess. If you know better please let me know as I want to produce robust MVC C# code.
You can create multi-line strings by enclosing them in triple quotes. So you can store your HTML in a string and pass that string to write()
:
html_str = """
<table border=1>
<tr>
<th>Number</th>
<th>Square</th>
</tr>
<indent>
<% for i in range(10): %>
<tr>
<td><%= i %></td>
<td><%= i**2 %></td>
</tr>
</indent>
</table>
"""
Html_file= open("filename","w")
Html_file.write(html_str)
Html_file.close()
Weak (Non-Identifying) Relationship
Entity is existence-independent of other enties
PK of Child doesn’t contain PK component of Parent Entity
Strong (Identifying) Relationship
Child entity is existence-dependent on parent
PK of Child Entity contains PK component of Parent Entity
Usually occurs utilizing a composite key for primary key, which means one of this composite key components must be the primary key of the parent entity.
This works for multiple radio buttons
$('input:radio[name="Aspirant.Gender"][value='+jsonData.Gender+']').prop('checked', true);
As you say, this is strictly undefined behaviour, though it will "work" on many platforms. The real reason for using unions is to create variant records.
union A {
int i;
double d;
};
A a[10]; // records in "a" can be either ints or doubles
a[0].i = 42;
a[1].d = 1.23;
Of course, you also need some sort of discriminator to say what the variant actually contains. And note that in C++ unions are not much use because they can only contain POD types - effectively those without constructors and destructors.
In C++ you can create conversion operators, operators that allow the compiler to convert between your types and other defined types. There are two types of conversion operators, implicit and explicit ones.
An implicit conversion operator allows the compiler to implicitly convert (like the conversion between int
and long
) the value of a user-defined type to some other type.
The following is a simple class with an implicit conversion operator:
class my_string {
public:
operator const char*() const {return data_;} // This is the conversion operator
private:
const char* data_;
};
Implicit conversion operators, like one-argument constructors, are user-defined conversions. Compilers will grant one user-defined conversion when trying to match a call to an overloaded function.
void f(const char*);
my_string str;
f(str); // same as f( str.operator const char*() )
At first this seems very helpful, but the problem with this is that the implicit conversion even kicks in when it isn’t expected to. In the following code, void f(const char*)
will be called because my_string()
is not an lvalue, so the first does not match:
void f(my_string&);
void f(const char*);
f(my_string());
Beginners easily get this wrong and even experienced C++ programmers are sometimes surprised because the compiler picks an overload they didn’t suspect. These problems can be mitigated by explicit conversion operators.
Unlike implicit conversion operators, explicit conversion operators will never kick in when you don't expect them to. The following is a simple class with an explicit conversion operator:
class my_string {
public:
explicit operator const char*() const {return data_;}
private:
const char* data_;
};
Notice the explicit
. Now when you try to execute the unexpected code from the implicit conversion operators, you get a compiler error:
prog.cpp: In function ‘int main()’: prog.cpp:15:18: error: no matching function for call to ‘f(my_string)’ prog.cpp:15:18: note: candidates are: prog.cpp:11:10: note: void f(my_string&) prog.cpp:11:10: note: no known conversion for argument 1 from ‘my_string’ to ‘my_string&’ prog.cpp:12:10: note: void f(const char*) prog.cpp:12:10: note: no known conversion for argument 1 from ‘my_string’ to ‘const char*’
To invoke the explicit cast operator, you have to use static_cast
, a C-style cast, or a constructor style cast ( i.e. T(value)
).
However, there is one exception to this: The compiler is allowed to implicitly convert to bool
. In addition, the compiler is not allowed to do another implicit conversion after it converts to bool
(a compiler is allowed to do 2 implicit conversions at a time, but only 1 user-defined conversion at max).
Because the compiler will not cast "past" bool
, explicit conversion operators now remove the need for the Safe Bool idiom. For example, smart pointers before C++11 used the Safe Bool idiom to prevent conversions to integral types. In C++11, the smart pointers use an explicit operator instead because the compiler is not allowed to implicitly convert to an integral type after it explicitly converted a type to bool.
Continue to Overloading new
and delete
.
For anyone finding this post through Google (as I did) here's the correct formula for cell F5 in the above example:
=SUMPRODUCT((MONTH(Sheet1!$A$1:$A$50)=MONTH(DATEVALUE(E5&" 1")))*(Sheet1!$A$1:$A$50<>""))
Formula assumes a list of dates in Sheet1!A1:A50 and a month name or abbr ("April" or "Apr") in cell E5.
Bash.
The various UNIX and Linux implementations have various different source level implementations of ksh, some of which are real ksh, some of which are pdksh implementations and some of which are just symlinks to some other shell that has a "ksh" personality. This can lead to weird differences in execution behavior.
At least with bash you can be sure that it's a single code base, and all you need worry about is what (usually minimum) version of bash is installed. Having done a lot of scripting on pretty much every modern (and not-so-modern) UNIX, programming to bash is more reliably consistent in my experience.
Slightly off topic but could be very useful as it could be the basis for other tasks you might want to do with simulators.
I like to keep my simulator list to a minimum, and since there is no multi-select in the "Devices and Simulators" it is a pain to delete them all.
So I boot all the sims that I want to use then, remove all the simulators that I don't have booted.
Delete all the shutdown simulators:
xcrun simctl list | grep -w "Shutdown" | grep -o "([-A-Z0-9]*)" | sed 's/[\(\)]//g' | xargs -I uuid xcrun simctl delete uuid
If you need individual simulators back, just add them back to the list in "Devices and Simulators" with the plus button.
I think code complete is going to be a hugely popular one for this question, for me it corrected many of my bad habits and re-affirmed my good practices.
Also for my Perl background I really like Perl Best Practices from Damian Conway. Perl can be a nasty language if you don't use style and best practices, which is what I was seeing in the scripts I was reading ( and sometimes writing ) .
I like the Head First Series, they are quite good and easy to read when your are not in the mood for more serious style books.
string col1Value = rdr["ColumnOneName"].ToString();
or
string col1Value = rdr[0].ToString();
These are object
s, so you need to either cast them or .ToString()
.
.
(dot) files are hidden by default on Unix/Linux systems. Most likely, if you know they are .htaccess
files, then they are probably in the root folder for the website.
If you are using a command line (terminal) to access, then they will only show up if you use:
ls -a
If you are using a GUI application, look for a setting to "show hidden files" or something similar.
If you still have no luck, and you are on a terminal, you can execute these commands to search the whole system (may take some time):
cd /
find . -name ".htaccess"
This will list out any files it finds with that name.
if( strtotime($database_date) > strtotime('now') ) {
...
Try with this:
msg.setContent(email.getBody(), "text/html; charset=ISO-8859-1");
You cannot achieve the desired solution with CSS z-index either, as z-index is only relative to the parent element. So if you have parents A and B with respective children a and b, b's z-index is only relative to other children of B and a's z-index is only relative to other children of A.
The z-index of A and B are relative to each other if they share the same parent element, but all of the children of one will share the same relative z-index at this level.
String withoutLast = yourString.Substring(0,(yourString.Length - 1));
import numpy as np
x = np.array([[1,2,3], [4,5,6]])
y = np.array([[-1, 2, 0], [-2, 5, 1]])
x*y
Out:
array([[-1, 4, 0],
[-8, 25, 6]])
%timeit x*y
1000000 loops, best of 3: 421 ns per loop
np.multiply(x,y)
Out:
array([[-1, 4, 0],
[-8, 25, 6]])
%timeit np.multiply(x, y)
1000000 loops, best of 3: 457 ns per loop
Both np.multiply
and *
would yield element wise multiplication known as the Hadamard Product
%timeit
is ipython magic
Fix the permissions of the directory you try to create a directory in.
Maybe these two examples illustrate you the difference between a deadlock and a livelock:
Java-Example for a deadlock:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class DeadlockSample {
private static final Lock lock1 = new ReentrantLock(true);
private static final Lock lock2 = new ReentrantLock(true);
public static void main(String[] args) {
Thread threadA = new Thread(DeadlockSample::doA,"Thread A");
Thread threadB = new Thread(DeadlockSample::doB,"Thread B");
threadA.start();
threadB.start();
}
public static void doA() {
System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
lock1.lock();
System.out.println(Thread.currentThread().getName() + " : holds lock 1");
try {
System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
lock2.lock();
System.out.println(Thread.currentThread().getName() + " : holds lock 2");
try {
System.out.println(Thread.currentThread().getName() + " : critical section of doA()");
} finally {
lock2.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
}
} finally {
lock1.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
}
}
public static void doB() {
System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
lock2.lock();
System.out.println(Thread.currentThread().getName() + " : holds lock 2");
try {
System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
lock1.lock();
System.out.println(Thread.currentThread().getName() + " : holds lock 1");
try {
System.out.println(Thread.currentThread().getName() + " : critical section of doB()");
} finally {
lock1.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
}
} finally {
lock2.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
}
}
}
Sample output:
Thread A : waits for lock 1
Thread B : waits for lock 2
Thread A : holds lock 1
Thread B : holds lock 2
Thread B : waits for lock 1
Thread A : waits for lock 2
Java-Example for a livelock:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LivelockSample {
private static final Lock lock1 = new ReentrantLock(true);
private static final Lock lock2 = new ReentrantLock(true);
public static void main(String[] args) {
Thread threadA = new Thread(LivelockSample::doA, "Thread A");
Thread threadB = new Thread(LivelockSample::doB, "Thread B");
threadA.start();
threadB.start();
}
public static void doA() {
try {
while (!lock1.tryLock()) {
System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
Thread.sleep(100);
}
System.out.println(Thread.currentThread().getName() + " : holds lock 1");
try {
while (!lock2.tryLock()) {
System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
Thread.sleep(100);
}
System.out.println(Thread.currentThread().getName() + " : holds lock 2");
try {
System.out.println(Thread.currentThread().getName() + " : critical section of doA()");
} finally {
lock2.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
}
} finally {
lock1.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
}
} catch (InterruptedException e) {
// can be ignored here for this sample
}
}
public static void doB() {
try {
while (!lock2.tryLock()) {
System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
Thread.sleep(100);
}
System.out.println(Thread.currentThread().getName() + " : holds lock 2");
try {
while (!lock1.tryLock()) {
System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
Thread.sleep(100);
}
System.out.println(Thread.currentThread().getName() + " : holds lock 1");
try {
System.out.println(Thread.currentThread().getName() + " : critical section of doB()");
} finally {
lock1.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
}
} finally {
lock2.unlock();
System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
}
} catch (InterruptedException e) {
// can be ignored here for this sample
}
}
}
Sample output:
Thread B : holds lock 2
Thread A : holds lock 1
Thread A : waits for lock 2
Thread B : waits for lock 1
Thread B : waits for lock 1
Thread A : waits for lock 2
Thread A : waits for lock 2
Thread B : waits for lock 1
Thread B : waits for lock 1
Thread A : waits for lock 2
Thread A : waits for lock 2
Thread B : waits for lock 1
...
Both examples force the threads to aquire the locks in different orders. While the deadlock waits for the other lock, the livelock does not really wait - it desperately tries to acquire the lock without the chance of getting it. Every try consumes CPU cycles.
FileInputStream fis = new FileInputStream(new File("C:/Test.xlsx"));
//create workbook instance
XSSFWorkbook wb = new XSSFWorkbook(fis);
//create a sheet object to retrieve the sheet
XSSFSheet sheet = wb.getSheetAt(0);
//to evaluate cell type
FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
for(Row row : sheet)
{
for(Cell cell : row)
{
switch(formulaEvaluator.evaluateInCell(cell).getCellTypeEnum())
{
case NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
default:
break;
}
}
System.out.println();
}
This code will work fine. Use getCellTypeEnum()
and to compare use just NUMERIC
or STRING
.
You are using wrong JSON. In this case you should use JSON that looks like this:
["orange", "apple"]
If you have to accept JSON in that form :
{"fruits":["apple","orange"]}
You'll have to create wrapper object:
public class FruitWrapper{
List<String> fruits;
//getter
//setter
}
and then your controller method should look like this:
@RequestMapping(value = "/saveFruits", method = RequestMethod.POST,
consumes = "application/json")
@ResponseBody
public ResultObject saveFruits(@RequestBody FruitWrapper fruits){
...
}
The project configuration file angular.json
is able to handle multiple projects (workspaces) which can be individually served.
ng config projects.my-test-project.targets.serve.options.port 4201
Where the my-test-project
part is the project name what you set with the ng new
command just like here:
$ ng new my-test-project
$ cd my-test-project
$ ng config projects.my-test-project.targets.serve.options.port 4201
$ ng serve
** Angular Live Development Server is listening on localhost:4201, open your browser on http://localhost:4201/ **
Legacy:
I usually use the ng set
command to change the Angular CLI settings for project level.
ng set defaults.serve.port=4201
It changes change your .angular.cli.json and adds the port settings as it mentioned earlier.
After this change you can use simply ng serve
and it going to use the prefered port without the need of specifying it every time.
UPDLOCK is used when you want to lock a row or rows during a select statement for a future update statement. The future update might be the very next statement in the transaction.
Other sessions can still see the data. They just cannot obtain locks that are incompatiable with the UPDLOCK and/or HOLDLOCK.
You use UPDLOCK when you wan to keep other sessions from changing the rows you have locked. It restricts their ability to update or delete locked rows.
You use HOLDLOCK when you want to keep other sessions from changing any of the data you are looking at. It restricts their ability to insert, update, or delete the rows you have locked. This allows you to run the query again and see the same results.
Using jQuery it is very simple assuming the URL you wish to post to is on the same server or has implemented CORS
$(function() {
$("#employeeLink").on("click",function(e) {
e.preventDefault(); // cancel the link itself
$.post(this.href,function(data) {
$("#someContainer").html(data);
});
});
});
If you insist on using frames which I strongly discourage, have a form and submit it with the link
<form action="employee.action" method="post" target="myFrame" id="myForm"></form>
and use (in plain JS)
window.addEventListener("load",function() {
document.getElementById("employeeLink").addEventListener("click",function(e) {
e.preventDefault(); // cancel the link
document.getElementById("myForm").submit(); // but make sure nothing has name or ID="submit"
});
});
Without a form we need to make one
window.addEventListener("load",function() {
document.getElementById("employeeLink").addEventListener("click",function(e) {
e.preventDefault(); // cancel the actual link
var myForm = document.createElement("form");
myForm.action=this.href;// the href of the link
myForm.target="myFrame";
myForm.method="POST";
myForm.submit();
});
});
This worked for me:
File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)
clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.
Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.
then in:
Run >> Edit Configurations
Add this line to VM Options:
--module-path /path/to/JavaFX/lib --add-modules=javafx.controls
(oh and don't forget to set the SDK)
Here are some examples for:
1) Simple
2) Fork
3) Threads
based server:
You can target that div from your stylesheet in a number of ways.
Simply use
.col-md-6:first-child {
background-color: blue;
}
Another way is to assign a class to one div and then apply the style to that class.
<div class="col-md-6 blue"></div>
.blue {
background-color: blue;
}
There are also inline styles.
<div class="col-md-6" style="background-color: blue"></div>
Your example code works fine to me. I'm not sure if I undestand what you intend to do, but if you want a blue background on the second div just remove the bg-primary
class from the section and add you custom class to the div.
.blue {_x000D_
background-color: blue;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<section id="about">_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<!-- Columns are always 50% wide, on mobile and desktop -->_x000D_
<div class="col-xs-6">_x000D_
<h2 class="section-heading text-center">Title</h2>_x000D_
<p class="text-faded text-center">.col-md-6</p>_x000D_
</div>_x000D_
<div class="col-xs-6 blue">_x000D_
<h2 class="section-heading text-center">Title</h2>_x000D_
<p class="text-faded text-center">.col-md-6</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</section>
_x000D_
In notepad++ press CTRL+H , in search mode click on the "Extended (\n, \r, \t ...)" radio button then type in the "Find what" box: \r\n (short for CR LF) and leave the "Replace with" box empty..
Finally hit replace all
You're correct that the .swp
file is used by vim for locking and as a recovery file.
Try putting set nobackup
in your vimrc if you don't want these files. See the Vim docs for various backup related options if you want the whole scoop, or want to have .bak files instead...
Bootstrap rows always contain their floats and create new lines. You don't need to worry about filling blank columns, just make sure they don't add up to more than 12.
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">_x000D_
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col-xs-3 col-xs-offset-9">_x000D_
I'm a right column of 3_x000D_
</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-xs-3">_x000D_
I'm a left column of 3_x000D_
</div>_x000D_
</div>_x000D_
<div class="panel panel-default">_x000D_
<div class="panel-body">_x000D_
And I'm some content below both columns_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Important:
I'm sorry to say that the response from "Borealid" is imprecise and somewhat incorrect - firstly there is no relation to statefulness or statelessness to answer this question, and most importantly the definition of the tuple for a socket is incorrect.
First remember below two rules:
Primary key of a socket: A socket is identified by {SRC-IP, SRC-PORT, DEST-IP, DEST-PORT, PROTOCOL}
not by {SRC-IP, SRC-PORT, DEST-IP, DEST-PORT}
- Protocol is an important part of a socket's definition.
OS Process & Socket mapping: A process can be associated with (can open/can listen to) multiple sockets which might be obvious to many readers.
Example 1: Two clients connecting to same server port means: socket1 {SRC-A, 100, DEST-X,80, TCP}
and socket2{SRC-B, 100, DEST-X,80, TCP}
. This means host A connects to server X's port 80 and another host B also connects to same server X to the same port 80. Now, how the server handles these two sockets depends on if the server is single threaded or multiple threaded (I'll explain this later). What is important is that one server can listen to multiple sockets simultaneously.
To answer the original question of the post:
Irrespective of stateful or stateless protocols, two clients can connect to same server port because for each client we can assign a different socket (as client IP will definitely differ). Same client can also have two sockets connecting to same server port - since such sockets differ by SRC-PORT
. With all fairness, "Borealid" essentially mentioned the same correct answer but the reference to state-less/full was kind of unnecessary/confusing.
To answer the second part of the question on how a server knows which socket to answer. First understand that for a single server process that is listening to same port, there could be more than one sockets (may be from same client or from different clients). Now as long as a server knows which request is associated with which socket, it can always respond to appropriate client using the same socket. Thus a server never needs to open another port in its own node than the original one on which client initially tried to connect. If any server allocates different server-ports after a socket is bound, then in my opinion the server is wasting its resource and it must be needing the client to connect again to the new port assigned.
A bit more for completeness:
Example 2: It's a very interesting question: "can two different processes on a server listen to the same port". If you do not consider protocol as one of parameter defining socket then the answer is no. This is so because we can say that in such case, a single client trying to connect to a server-port will not have any mechanism to mention which of the two listening processes the client intends to connect to. This is the same theme asserted by rule (2). However this is WRONG answer because 'protocol' is also a part of the socket definition. Thus two processes in same node can listen to same port only if they are using different protocol. For example two unrelated clients (say one is using TCP and another is using UDP) can connect and communicate to the same server node and to the same port but they must be served by two different server-processes.
Server Types - single & multiple:
When a server's processes listening to a port that means multiple sockets can simultaneously connect and communicate with the same server-process. If a server uses only a single child-process to serve all the sockets then the server is called single-process/threaded and if the server uses many sub-processes to serve each socket by one sub-process then the server is called multi-process/threaded server. Note that irrespective of the server's type a server can/should always uses the same initial socket to respond back (no need to allocate another server-port).
Suggested Books and rest of the two volumes if you can.
A Note on Parent/Child Process (in response to query/comment of 'Ioan Alexandru Cucu')
Wherever I mentioned any concept in relation to two processes say A and B, consider that they are not related by parent child relationship. OS's (especially UNIX) by design allow a child process to inherit all File-descriptors (FD) from parents. Thus all the sockets (in UNIX like OS are also part of FD) that a process A listening to, can be listened by many more processes A1, A2, .. as long as they are related by parent-child relation to A. But an independent process B (i.e. having no parent-child relation to A) cannot listen to same socket. In addition, also note that this rule of disallowing two independent processes to listen to same socket lies on an OS (or its network libraries) and by far it's obeyed by most OS's. However, one can create own OS which can very well violate this restrictions.
sudo apt-get install putty
This will automatically install the puttygen tool.
Now to convert the PPK file to be used with SSH command execute the following in terminal
puttygen mykey.ppk -O private-openssh -o my-openssh-key
Then, you can connect via SSH with:
ssh -v [email protected] -i my-openssh-key
http://www.graphicmist.in/use-your-putty-ppk-file-to-ssh-remote-server-in-ubuntu/#comment-28603
Simplest option ...your can change it from AdminConsole. Login to AdminConsole--->Server-->--->Configuration--->ListenPort (Change it)!
Delete
operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirementsInsert
for arrays is basically Set
as mentioned in the beginningYou can limit mongod process usage using cgroups on Linux.
Using cgroups, our task can be accomplished in a few easy steps.
Create control group:
cgcreate -g memory:DBLimitedGroup
(make sure that cgroups binaries installed on your system, consult your favorite Linux distribution manual for how to do that)
Specify how much memory will be available for this group:
echo 16G > /sys/fs/cgroup/memory/DBLimitedGroup/memory.limit_in_bytes
This command limits memory to 16G (good thing this limits the memory for both malloc allocations and OS cache)
Now, it will be a good idea to drop pages already stayed in cache:
sync; echo 3 > /proc/sys/vm/drop_caches
And finally assign a server to created control group:
cgclassify -g memory:DBLimitedGroup \`pidof mongod\`
This will assign a running mongod process to a group limited by only 16GB memory.
source: Using Cgroups to Limit MySQL and MongoDB memory usage
Use win APIs in your main function:
Then write another function which handles win's messages (mentioned in #1). When you receive the message WM_CREATE you have to call CreateWindow(). The class is what control is that window, for example "edit" is a text box and "button" is a.. button :). You have to specify an ID for each control (of your choice but unique among all). CreateWindow() returns a handle to that control, which needs to be memorized. When the user clicks on a control you receive the WM_COMMAND message with the ID of that control. Here you can handle that event. You might find useful SetWindowText() and GetWindowText() which allows you to set/get the text of any control.
You will need only the win32 SDK. You can get it here.
I made exactly what @grepit made.
But I had to made some changes in my Java code:
In Producer and Receiver project I altered:
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("your-host-ip");
factory.setUsername("username-you-created");
factory.setPassword("username-password");
Doing that, you are connecting an specific host as the user you have created. It works for me!
$("#gst_show>input").change(function(){
var checked = $(this).is(":checked");
if($("#gst_show>input:checkbox").attr("checked",checked)){
alert('Checked Successfully');
}
});
There are a number of methods of obtaining an execution plan, which one to use will depend on your circumstances. Usually you can use SQL Server Management Studio to get a plan, however if for some reason you can't run your query in SQL Server Management Studio then you might find it helpful to be able to obtain a plan via SQL Server Profiler or by inspecting the plan cache.
SQL Server comes with a couple of neat features that make it very easy to capture an execution plan, simply make sure that the "Include Actual Execution Plan" menu item (found under the "Query" menu) is ticked and run your query as normal.
If you are trying to obtain the execution plan for statements in a stored procedure then you should execute the stored procedure, like so:
exec p_Example 42
When your query completes you should see an extra tab entitled "Execution plan" appear in the results pane. If you ran many statements then you may see many plans displayed in this tab.
From here you can inspect the execution plan in SQL Server Management Studio, or right click on the plan and select "Save Execution Plan As ..." to save the plan to a file in XML format.
This method is very similar to method 1 (in fact this is what SQL Server Management Studio does internally), however I have included it for completeness or if you don't have SQL Server Management Studio available.
Before you run your query, run one of the following statements. The statement must be the only statement in the batch, i.e. you cannot execute another statement at the same time:
SET SHOWPLAN_TEXT ON
SET SHOWPLAN_ALL ON
SET SHOWPLAN_XML ON
SET STATISTICS PROFILE ON
SET STATISTICS XML ON -- The is the recommended option to use
These are connection options and so you only need to run this once per connection. From this point on all statements run will be acompanied by an additional resultset containing your execution plan in the desired format - simply run your query as you normally would to see the plan.
Once you are done you can turn this option off with the following statement:
SET <<option>> OFF
Unless you have a strong preference my recommendation is to use the STATISTICS XML
option. This option is equivalent to the "Include Actual Execution Plan" option in SQL Server Management Studio and supplies the most information in the most convenient format.
SHOWPLAN_TEXT
- Displays a basic text based estimated execution plan, without executing the querySHOWPLAN_ALL
- Displays a text based estimated execution plan with cost estimations, without executing the querySHOWPLAN_XML
- Displays an XML based estimated execution plan with cost estimations, without executing the query. This is equivalent to the "Display Estimated Execution Plan..." option in SQL Server Management Studio.STATISTICS PROFILE
- Executes the query and displays a text based actual execution plan.STATISTICS XML
- Executes the query and displays an XML based actual execution plan. This is equivalent to the "Include Actual Execution Plan" option in SQL Server Management Studio.If you can't run your query directly (or your query doesn't run slowly when you execute it directly - remember we want a plan of the query performing badly), then you can capture a plan using a SQL Server Profiler trace. The idea is to run your query while a trace that is capturing one of the "Showplan" events is running.
Note that depending on load you can use this method on a production environment, however you should obviously use caution. The SQL Server profiling mechanisms are designed to minimize impact on the database but this doesn't mean that there won't be any performance impact. You may also have problems filtering and identifying the correct plan in your trace if your database is under heavy use. You should obviously check with your DBA to see if they are happy with you doing this on their precious database!
The plan you get is equivalent to the "Include Actual Execution Plan" option in SQL Server Management Studio.
If you can't run your query directly and you also can't capture a profiler trace then you can still obtain an estimated plan by inspecting the SQL query plan cache.
We inspect the plan cache by querying SQL Server DMVs. The following is a basic query which will list all cached query plans (as xml) along with their SQL text. On most database you will also need to add additional filtering clauses to filter the results down to just the plans you are interested in.
SELECT UseCounts, Cacheobjtype, Objtype, TEXT, query_plan
FROM sys.dm_exec_cached_plans
CROSS APPLY sys.dm_exec_sql_text(plan_handle)
CROSS APPLY sys.dm_exec_query_plan(plan_handle)
Execute this query and click on the plan XML to open up the plan in a new window - right click and select "Save execution plan as..." to save the plan to file in XML format.
Because there are so many factors involved (ranging from the table and index schema down to the data stored and the table statistics) you should always try to obtain an execution plan from the database you are interested in (normally the one that is experiencing a performance problem).
You can't capture an execution plan for encrypted stored procedures.
An actual execution plan is one where SQL Server actually runs the query, whereas an estimated execution plan SQL Server works out what it would do without executing the query. Although logically equivalent, an actual execution plan is much more useful as it contains additional details and statistics about what actually happened when executing the query. This is essential when diagnosing problems where SQL Servers estimations are off (such as when statistics are out of date).
This is a topic worthy enough for a (free) book in its own right.
When moving classes into specific packages like repository, controller, domain just the generic @SpringBootApplication
is not enough.
You will have to specify the base package for component scan
@ComponentScan("base_package")
For JPA
@EnableJpaRepositories(basePackages = "repository")
is also needed, so spring data will know where to look into for repository interfaces.
First you'll need to get it into a byte[]
, so do this:
byte[] ba = Encoding.Default.GetBytes("sample");
and then you can get the string:
var hexString = BitConverter.ToString(ba);
now, that's going to return a string with dashes (-
) in it so you can then simply use this:
hexString = hexString.Replace("-", "");
to get rid of those if you want.
NOTE: you could use a different Encoding
if you needed to.
SELECT Id, 'TRUE' AS NewFiled FROM TABEL1
INTERSECT
SELECT Id, 'TRUE' AS NewFiled FROM TABEL2
UNION
SELECT Id, 'FALSE' AS NewFiled FROM TABEL1
EXCEPT
SELECT Id, 'FALSE' AS NewFiled FROM TABEL2;
The first argument is the file you wish to execute, and the second argument is an array of null-terminated strings that represent the appropriate arguments to the file as specified in the man page.
For example:
char *cmd = "ls";
char *argv[3];
argv[0] = "ls";
argv[1] = "-la";
argv[2] = NULL;
execvp(cmd, argv); //This will run "ls -la" as if it were a command
You might need to clarify a bit. What are you really trying to accomplish? If you really want to find out the column names that only contain null values, then you will have to loop through the scheama and do a dynamic query based on that.
I don't know which DBMS you are using, so I'll put some pseudo-code here.
for each col
begin
@cmd = 'if not exists (select * from tablename where ' + col + ' is not null begin print ' + col + ' end'
exec(@cmd)
end
WARNING:
The syntax list(groupby(...)) won't work the way that you intend. It seems to destroy the internal iterator objects, so using
for x in list(groupby(range(10))):
print(list(x[1]))
will produce:
[]
[]
[]
[]
[]
[]
[]
[]
[]
[9]
Instead, of list(groupby(...)), try [(k, list(g)) for k,g in groupby(...)], or if you use that syntax often,
def groupbylist(*args, **kwargs):
return [(k, list(g)) for k, g in groupby(*args, **kwargs)]
and get access to the groupby functionality while avoiding those pesky (for small data) iterators all together.
You will find I have added the session_start() at the very top of the page. I have also removed the session_start() call later in the page. This page should work fine.
<?php
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="style.css" rel="stylesheet" type="text/css" />
<title>Welcome</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#nav li').hover(
function () {
//show its submenu
$('ul', this).slideDown(100);
},
function () {
//hide its submenu
$('ul', this).slideUp(100);
}
);
});
</script>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td class="header"> </td>
</tr>
<tr>
<td class="menu"><table align="center" cellpadding="0" cellspacing="0" width="80%">
<tr>
<td>
<ul id="nav">
<li><a href="#">Catalog</a>
<ul><li><a href="#">Products</a></li>
<li><a href="#">Bulk Upload</a></li>
</ul>
<div class="clear"></div>
</li>
<li><a href="#">Purchase </a>
</li>
<li><a href="#">Customer Service</a>
<ul>
<li><a href="#">Contact Us</a></li>
<li><a href="#">CS Panel</a></li>
</ul>
<div class="clear"></div>
</li>
<li><a href="#">All Reports</a></li>
<li><a href="#">Configuration</a>
<ul> <li><a href="#">Look and Feel </a></li>
<li><a href="#">Business Details</a></li>
<li><a href="#">CS Details</a></li>
<li><a href="#">Emaqil Template</a></li>
<li><a href="#">Domain and Analytics</a></li>
<li><a href="#">Courier</a></li>
</ul>
<div class="clear"></div>
</li>
<li><a href="#">Accounts</a>
<ul><li><a href="#">Ledgers</a></li>
<li><a href="#">Account Details</a></li>
</ul>
<div class="clear"></div></li>
</ul></td></tr></table></td>
</tr>
<tr>
<td valign="top"><table width="80%" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="2">
<tr>
<td width="22%" height="327" valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="2">
<tr>
<td> </td>
</tr>
<tr>
<td height="45"><strong>-> Products</strong></td>
</tr>
<tr>
<td height="61"><strong>-> Categories</strong></td>
</tr>
<tr>
<td height="48"><strong>-> Sub Categories</strong></td>
</tr>
</table></td>
<td width="78%" valign="top"><table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td> </td>
</tr>
<tr>
<td>
<table width="90%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="26%"> </td>
<td width="74%"><h2>Manage Categories</h2></td>
</tr>
</table></td>
</tr>
<tr>
<td height="30">
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td>
<table width="49%" align="center" cellpadding="0" cellspacing="0">
<tr><td>
<?php
if (isset($_SESSION['error']))
{
echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";
unset($_SESSION['error']);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<p>
<label class="style4">Category Name</label>
<input type="text" name="categoryname" /><br /><br />
<label class="style4">Category Image</label>
<input type="file" name="image" /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<br />
<br />
<input type="submit" id="submit" value="UPLOAD" />
</p>
</form>
<?php
require("includes/conn.php");
function is_valid_type($file)
{
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png");
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
$TARGET_PATH = "images/category";
$cname = $_POST['categoryname'];
$image = $_FILES['image'];
$cname = mysql_real_escape_string($cname);
$image['name'] = mysql_real_escape_string($image['name']);
$TARGET_PATH .= $image['name'];
if ( $cname == "" || $image['name'] == "" )
{
$_SESSION['error'] = "All fields are required";
header("Location: managecategories.php");
exit;
}
if (!is_valid_type($image))
{
$_SESSION['error'] = "You must upload a jpeg, gif, or bmp";
header("Location: managecategories.php");
exit;
}
if (file_exists($TARGET_PATH))
{
$_SESSION['error'] = "A file with that name already exists";
header("Location: managecategories.php");
exit;
}
if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))
{
$sql = "insert into Categories (CategoryName, FileName) values ('$cname', '" . $image['name'] . "')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
header("Location: mangaecategories.php");
exit;
}
else
{
$_SESSION['error'] = "Could not upload file. Check read/write persmissions on the directory";
header("Location: mangagecategories.php");
exit;
}
?>
An interface defines a contract for an API, that is a set of methods that both implementer and user of the API agree upon. An interface does not have an instanced implementation, hence no constructor.
The use case you describe is akin to an abstract class in which the constructor calls a method of an abstract method which is implemented in an child class.
The inherent problem here is that while the base constructor is being executed, the child object is not constructed yet, and therfore in an unpredictable state.
To summarize: is it asking for trouble when you call overloaded methods from parent constructors, to quote mindprod:
In general you must avoid calling any non-final methods in a constructor. The problem is that instance initialisers / variable initialisation in the derived class is performed after the constructor of the base class.
Assuming that your button is in a form, you are not preventing the default behaviour of the button click from happening i.e. Your AJAX call is made in addition to the form submission; what you're very likely seeing is one of
So you should prevent the default behaviour of the button click
$('#btnSave').click(function (e) {
// prevent the default event behaviour
e.preventDefault();
$.ajax({
url: "/Home/SaveDetailedInfo",
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) {
// perform your save call here
if (data.status == "Success") {
alert("Done");
} else {
alert("Error occurs on the Database level!");
}
},
error: function () {
alert("An error has occured!!!");
}
});
});
Here’s how this works all:
You need the ability to access the HTML on the particular webpage you are sharing. It'll probably work site wide too if you use a common header file. I have not tried this, but it should work. You'll just get the same image for all pages if you do this though.
You need to add these HTML meta tags into page in the . It will not work if you put it in the . Make sure to customize per your a) image, b) description, c) URL, and d) title.
A Real Example.
<meta property="og:image" content="http://www.coachesneedsocial.com/wp-content/uploads/2014/12/BannerWCircleImages-1.jpg" />
<meta property="og:description" content="Coaches share their secrets to success so you can rock 2015." />
<meta property="og:url"content="http://www.coachesneedsocial.com/coacheswisdomtelesummit/" />
<meta property="og:title" content="Coaches Wisdom Telesummit" />
https://developers.facebook.com/tools/debug/og/object/
Big Tip.. make sure the “quote marks” are the same in your HTML (they should look like 2 straight marks and no curves… sometimes programs change these to different fonts and it goofs up the code.
I changed mine to default to no host and have a check to catch it. That way the user or cron is forced to provide a single host or group etc. I like the logic from the comment from @wallydrag. The empty_group
contains no hosts in the inventory.
- hosts: "{{ variable_host | default('empty_group') }}"
Then add the check in tasks:
tasks: - name: Fail script if required variable_host parameter is missing fail: msg: "You have to add the --extra-vars='variable_host='" when: (variable_host is not defined) or (variable_host == "")
As of 2016, you're supposed to use Array.findIndex
(an ES2015/ES6 standard) for this:
a = [_x000D_
{prop1:"abc",prop2:"qwe"},_x000D_
{prop1:"bnmb",prop2:"yutu"},_x000D_
{prop1:"zxvz",prop2:"qwrq"}];_x000D_
_x000D_
index = a.findIndex(x => x.prop2 ==="yutu");_x000D_
_x000D_
console.log(index);
_x000D_
It's supported in Google Chrome, Firefox and Edge. For Internet Explorer, there's a polyfill on the linked page.
Performance note
Function calls are expensive, therefore with really big arrays a simple loop will perform much better than findIndex
:
let test = [];_x000D_
_x000D_
for (let i = 0; i < 1e6; i++)_x000D_
test.push({prop: i});_x000D_
_x000D_
_x000D_
let search = test.length - 1;_x000D_
let count = 100;_x000D_
_x000D_
console.time('findIndex/predefined function');_x000D_
let fn = obj => obj.prop === search;_x000D_
_x000D_
for (let i = 0; i < count; i++)_x000D_
test.findIndex(fn);_x000D_
console.timeEnd('findIndex/predefined function');_x000D_
_x000D_
_x000D_
console.time('findIndex/dynamic function');_x000D_
for (let i = 0; i < count; i++)_x000D_
test.findIndex(obj => obj.prop === search);_x000D_
console.timeEnd('findIndex/dynamic function');_x000D_
_x000D_
_x000D_
console.time('loop');_x000D_
for (let i = 0; i < count; i++) {_x000D_
for (let index = 0; index < test.length; index++) {_x000D_
if (test[index].prop === search) {_x000D_
break;_x000D_
}_x000D_
}_x000D_
}_x000D_
console.timeEnd('loop');
_x000D_
As with most optimizations, this should be applied with care and only when actually needed.
If you are usgin Mysql a date column can be passed a String representation of this date
so i using the DateFormatter Class to format it and then set it as a String in the sql statement or prepared statement
here is the code illustration:
private String converUtilDateToSqlDate(java.util.Date utilDate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String sqlDate = sdf.format(utilDate);
return sqlDate;
}
String date = converUtilDateToSqlDate(otherTransaction.getTransDate());
//then pass this date in you sql statement
You can get the full download here: http://download.microsoft.com/download/8/3/a/83aad8f9-38ba-4503-b3cd-ba28c360c27b/ENU/vcsetup.exe
You can use a MultiBinding
combined with the StringFormat
property. Usage would resemble the following:
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} + {1}">
<Binding Path="Name" />
<Binding Path="ID" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
Giving Name
a value of Foo
and ID
a value of 1
, your output in the TextBlock would then be Foo + 1
.
Note:
that this is only supported in .NET 3.5 SP1 and 3.0 SP2 or later.
step into will dig into method calls
step over will just execute the line and go to the next one
You are encoding to UTF-8, then re-encoding to UTF-8. Python can only do this if it first decodes again to Unicode, but it has to use the default ASCII codec:
>>> u'ñ'
u'\xf1'
>>> u'ñ'.encode('utf8')
'\xc3\xb1'
>>> u'ñ'.encode('utf8').encode('utf8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
Don't keep encoding; leave encoding to UTF-8 to the last possible moment instead. Concatenate Unicode values instead.
You can use str.join()
(or, rather, unicode.join()
) here to concatenate the three values with dashes in between:
nombre = u'-'.join(fabrica, sector, unidad)
return nombre.encode('utf-8')
but even encoding here might be too early.
Rule of thumb: decode the moment you receive the value (if not Unicode values supplied by an API already), encode only when you have to (if the destination API does not handle Unicode values directly).
I believe the only way to do this it to add the style as a new CSS declaration with the '!important' suffix. The easiest way to do this is to append a new <style> element to the head of document:
function addNewStyle(newStyle) {
var styleElement = document.getElementById('styles_js');
if (!styleElement) {
styleElement = document.createElement('style');
styleElement.type = 'text/css';
styleElement.id = 'styles_js';
document.getElementsByTagName('head')[0].appendChild(styleElement);
}
styleElement.appendChild(document.createTextNode(newStyle));
}
addNewStyle('td.EvenRow a {display:inline !important;}')
The rules added with the above method will (if you use the !important suffix) override other previously set styling. If you're not using the suffix then make sure to take concepts like 'specificity' into account.
Other answers may have shorter code but this one should be the most efficient and is easy to understand.
/**
* Get key of the max value
*
* @var array $array
* @return mixed
*/
function array_key_max_value($array)
{
$max = null;
$result = null;
foreach ($array as $key => $value) {
if ($max === null || $value > $max) {
$result = $key;
$max = $value;
}
}
return $result;
}
Try
Dim connectionString AS String = "Server=my_server;Database=name_of_db;User Id=user_name;Password=my_password"
And replace my_server, name_of_db, user_name and my_password with your values.
then Using sqlCon = New SqlConnection(connectionString)
should work
also I think your SQL is wrong, it should be SET clickCount= clickCount + 1
I think.
And on a general note, the page you link to has a link called Connection String which shows you how to do this.
Well, it generally depends on the shell. For bash
, it marks the variable as "exportable" meaning that it will show up in the environment for any child processes you run.
Non-exported variables are only visible from the current process (the shell).
From the bash
man page:
export [-fn] [name[=word]] ...
export -p
The supplied names are marked for automatic export to the environment of subsequently executed commands.
If the
-f
option is given, the names refer to functions. If no names are given, or if the-p
option is supplied, a list of all names that are exported in this shell is printed.The
-n
option causes the export property to be removed from each name.If a variable name is followed by
=word
, the value of the variable is set toword
.
export
returns an exit status of 0 unless an invalid option is encountered, one of the names is not a valid shell variable name, or-f
is supplied with a name that is not a function.
You can also set variables as exportable with the typeset
command and automatically mark all future variable creations or modifications as such, with set -a
.
color
and fill
are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:
d + scale_color_manual(values=c("#CC6666", "#9999CC"))
is what you want.
copy this line and replace in your project
var myNewString = myOldString.replace ("username", visitorName);
there is a simple problem with coma (,)
It is indeed possible with the following code
<div href="#" id='a'>
Hover me
</div>
<div id='b'>
Show me
</div>
and css
#a {
display: block;
}
#a:hover + #b {
display:block;
}
#b {
display:none;
}
Now by hovering on element #a shows element #b.
A. Static Method:
Class.method = function () { /* code */ }
method()
here is a function property added to an another function (here Class).Class.method();
new Class()
) for accessing the method(). So you could call it as a static method.B. Prototype Method (Shared across all the instances):
Class.prototype.method = function () { /* code using this.values */ }
method()
here is a function property added to an another function protype (here Class.prototype).new Class()
).Class
C. Class Method (Each instance has its own copy):
function Class () {
this.method = function () { /* do something with the private members */};
}
method()
here is a method defined inside an another function (here Class).Class.method();
new Class()
) for the method() access.new Class()
).Example:
function Class() {
var str = "Constructor method"; // private variable
this.method = function () { console.log(str); };
}
Class.prototype.method = function() { console.log("Prototype method"); };
Class.method = function() { console.log("Static method"); };
new Class().method(); // Constructor method
// Bcos Constructor method() has more priority over the Prototype method()
// Bcos of the existence of the Constructor method(), the Prototype method
// will not be looked up. But you call it by explicity, if you want.
// Using instance
new Class().constructor.prototype.method(); // Prototype method
// Using class name
Class.prototype.method(); // Prototype method
// Access the static method by class name
Class.method(); // Static method
It's an encoding error - so if it's a unicode string, this ought to fix it:
text.encode("windows-1252").decode("utf-8")
If it's a plain string, you'll need an extra step:
text.decode("utf-8").encode("windows-1252").decode("utf-8")
Both of these will give you a unicode string.
By the way - to discover how a piece of text like this has been mangled due to encoding issues, you can use chardet:
>>> import chardet
>>> chardet.detect(u"And the Hip’s coming, too")
{'confidence': 0.5, 'encoding': 'windows-1252'}
I used this solution, which I think is better than onWindowFocusChanged(). If you open a DialogFragment, then rotate the phone, onWindowFocusChanged will be called only when the user closes the dialog):
yourView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// Ensure you call it only once :
yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
// Here you can get the size :)
}
});
Edit : as removeGlobalOnLayoutListener is deprecated, you should now do :
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
@Override
public void onGlobalLayout() {
// Ensure you call it only once :
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
yourView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
else {
yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
// Here you can get the size :)
}
You can use $(window).resize() to detect if the viewport is resized.
jQuery does not have any function to consistently detect the correctly width and height of the viewport[1] when there is a scroll bar present.
I found a solution that uses the Modernizr library and specifically the mq function which opens media queries for javascript.
Here is my solution:
// A function for detecting the viewport minimum width.
// You could use a similar function for minimum height if you wish.
var min_width;
if (Modernizr.mq('(min-width: 0px)')) {
// Browsers that support media queries
min_width = function (width) {
return Modernizr.mq('(min-width: ' + width + ')');
};
}
else {
// Fallback for browsers that does not support media queries
min_width = function (width) {
return $(window).width() >= width;
};
}
var resize = function() {
if (min_width('768px')) {
// Do some magic
}
};
$(window).resize(resize);
resize();
My answer will probably not help resizing a iframe to 100% viewport width with a margin on each side, but I hope it will provide solace for webdevelopers frustrated with browser incoherence of javascript viewport width and height calculation.
Maybe this could help with regards to the iframe:
$('iframe').css('width', '100%').wrap('<div style="margin:2em"></div>');
[1] You can use $(window).width() and $(window).height() to get a number which will be correct in some browsers, but incorrect in others. In those browsers you can try to use window.innerWidth and window.innerHeight to get the correct width and height, but i would advice against this method because it would rely on user agent sniffing.
Usually the different browsers are inconsistent about whether or not they include the scrollbar as part of the window width and height.
Note: Both $(window).width() and window.innerWidth vary between operating systems using the same browser. See: https://github.com/eddiemachado/bones/issues/468#issuecomment-23626238
my experience
get your php version
php --version
Instal package for your php version
sudo apt-get install php7.4-xml
Restart apache
sudo systemctl reload apache2
Most implementations I've seen miss out URL-decoding the names and the values.
Here's a general utility function that also does proper URL-decoding:
function getQueryParams(qs) {
qs = qs.split('+').join(' ');
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}
return params;
}
//var query = getQueryParams(document.location.search);
//alert(query.foo);
Change:
struct timeval, tvalBefore, tvalAfter; /* Looks like an attempt to
delcare a variable with
no name. */
to:
struct timeval tvalBefore, tvalAfter;
It is less likely (IMO) to make this mistake if there is a single declaration per line:
struct timeval tvalBefore;
struct timeval tvalAfter;
It becomes more error prone when declaring pointers to types on a single line:
struct timeval* tvalBefore, tvalAfter;
tvalBefore
is a struct timeval*
but tvalAfter
is a struct timeval
.
This worked for me:
$this->db->where('RecordDate >=', '2018-08-17 00:00:00');
$this->db->where('RecordDate <=', '2018-10-04 05:32:56');
You are looking for scipy.misc.toimage
:
import scipy.misc
rgb = scipy.misc.toimage(np_array)
It seems to be also in scipy 1.0, but has a deprecation warning. Instead, you can use pillow
and PIL.Image.fromarray
You can use it without doing anything special. If you have a local image called blah
you can do FROM blah
. If you do FROM blah
in your Dockerfile, but don't have a local image called blah
, then Docker will try to pull it from the registry.
In other words, if a Dockerfile does FROM ubuntu
, but you have a local image called ubuntu
different from the official one, your image will override it.
In the POSIX standard, which /bin/sh
is supposed to respect, the command is .
(a single dot), not source
. The source
command is a csh
-ism that has been pulled into bash
.
Try
. $env_name/bin/activate
Or if you must have non-POSIX bash
-isms in your code, use #!/bin/bash
.
It does includes boundaries.
declare @startDate date = cast('15-NOV-2016' as date)
declare @endDate date = cast('30-NOV-2016' as date)
create table #test (c1 date)
insert into #test values(cast('15-NOV-2016' as date))
insert into #test values(cast('20-NOV-2016' as date))
insert into #test values(cast('30-NOV-2016' as date))
select * from #test where c1 between @startDate and @endDate
drop table #test
RESULT c1
2016-11-15
2016-11-20
2016-11-30
declare @r1 int = 10
declare @r2 int = 15
create table #test1 (c1 int)
insert into #test1 values(10)
insert into #test1 values(15)
insert into #test1 values(11)
select * from #test1 where c1 between @r1 and @r2
drop table #test1
RESULT c1
10
11
15
The httpd dæmon on OpenBSD uses the following stylesheet for all of its error messages, which presumably covers all the Comic Sans variations on non-Windows systems:
http://openbsd.su/src/usr.sbin/httpd/server_http.c#server_abort_http
810 style = "body { background-color: white; color: black; font-family: "
811 "'Comic Sans MS', 'Chalkboard SE', 'Comic Neue', sans-serif; }\n"
812 "hr { border: 0; border-bottom: 1px dashed; }\n";
E.g., try this:
font-family: 'Comic Sans MS', 'Chalkboard SE', 'Comic Neue', sans-serif;
DataSet is collection of DataTables.... you can get the datatable from DataSet as below.
//here ds is dataset
DatTable dt = ds.Table[0]; /// table of dataset
The simple way is using System.Diagnostics.Debug.WriteLine()
Your can then read what you're writing to the output by clicking the menu "DEBUG" -> "Windows" -> "Output".
I certainly don't know the details on this because I've never done it it, but the native NT API has a capability to fork a process (the POSIX subsystem on Windows needs this capability - I'm not sure if the POSIX subsystem is even supported anymore).
A search for ZwCreateProcess() should get you some more details - for example this bit of information from Maxim Shatskih:
The most important parameter here is SectionHandle. If this parameter is NULL, the kernel will fork the current process. Otherwise, this parameter must be a handle of the SEC_IMAGE section object created on the EXE file before calling ZwCreateProcess().
Though note that Corinna Vinschen indicates that Cygwin found using ZwCreateProcess() still unreliable:
Iker Arizmendi wrote:
> Because the Cygwin project relied solely on Win32 APIs its fork > implementation is non-COW and inefficient in those cases where a fork > is not followed by exec. It's also rather complex. See here (section > 5.6) for details: > > http://www.redhat.com/support/wpapers/cygnus/cygnus_cygwin/architecture.html
This document is rather old, 10 years or so. While we're still using Win32 calls to emulate fork, the method has changed noticably. Especially, we don't create the child process in the suspended state anymore, unless specific datastructes need a special handling in the parent before they get copied to the child. In the current 1.5.25 release the only case for a suspended child are open sockets in the parent. The upcoming 1.7.0 release will not suspend at all.
One reason not to use ZwCreateProcess was that up to the 1.5.25 release we're still supporting Windows 9x users. However, two attempts to use ZwCreateProcess on NT-based systems failed for one reason or another.
It would be really nice if this stuff would be better or at all documented, especially a couple of datastructures and how to connect a process to a subsystem. While fork is not a Win32 concept, I don't see that it would be a bad thing to make fork easier to implement.
You could format the dates before you add them to your array. That is how I did. I used AngularJS
//convert the date to a standard format
var dt = new Date(date);
//take only the date and month and push them to your label array
$rootScope.charts.mainChart.labels.push(dt.getDate() + "-" + (dt.getMonth() + 1));
Use this array in your chart presentation
Here's a possible solution:
public class NumInput {
public static void main(String [] args) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
Scanner s = new Scanner(System.in);
while (true) {
System.out.print("Enter a Value: ");
int val = s.nextInt();
if (val == 0) {
break;
}
if (val < min) {
min = val;
}
if (val > max) {
max = val;
}
}
System.out.println("min: " + min);
System.out.println("max: " + max);
}
}
(not sure about using int or double thought)
I tried an above answer and didn't work until I switched the statements. This is what worked for me:
myEditText.setSelectAllOnFocus(true);
myEditText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onClickMyEditText();
}
});
private void onClickMyEditText() {
if(myEditText.isFocused()){
myEditText.clearFocus();
myEditText.requestFocus();
}else{
myEditText.requestFocus();
myEditText.clearFocus();
}
}
I had to ask if the focus is on the EditText, and if not request the focus first and then clear it. Otherwise the next times I clicked on the EditText the virtual keyboard would never appear
Based on DaveRandom's answer, I was also playing around and found a slightly simpler Apache solution that produces the same result (Access-Control-Allow-Origin
is set to the current specific protocol + domain + port dynamically) without using any rewrite rules:
SetEnvIf Origin ^(https?://.+\.mywebsite\.com(?::\d{1,5})?)$ CORS_ALLOW_ORIGIN=$1
Header append Access-Control-Allow-Origin %{CORS_ALLOW_ORIGIN}e env=CORS_ALLOW_ORIGIN
Header merge Vary "Origin"
And that's it.
Those who want to enable CORS on the parent domain (e.g. mywebsite.com) in addition to all its subdomains can simply replace the regular expression in the first line with this one:
^(https?://(?:.+\.)?mywebsite\.com(?::\d{1,5})?)$
.
Note: For spec compliance and correct caching behavior, ALWAYS add the Vary: Origin
response header for CORS-enabled resources, even for non-CORS requests and those from a disallowed origin (see example why).
In JavaScript, there are no integers but only Number
s, which are implemented as double precision floating point numbers.
It means that if a Number a
is large enough, it can be considered equal to three consecutive integers:
a = 100000000000000000_x000D_
if (a == a+1 && a == a+2 && a == a+3){_x000D_
console.log("Precision loss!");_x000D_
}
_x000D_
True, it's not exactly what the interviewer asked (it doesn't work with a=0
), but it doesn't involve any trick with hidden functions or operator overloading.
For reference, there are a==1 && a==2 && a==3
solutions in Ruby and Python. With a slight modification, it's also possible in Java.
With a custom ==
:
class A
def ==(o)
true
end
end
a = A.new
if a == 1 && a == 2 && a == 3
puts "Don't do this!"
end
Or an increasing a
:
def a
@a ||= 0
@a += 1
end
if a == 1 && a == 2 && a == 3
puts "Don't do this!"
end
class A:
def __eq__(self, who_cares):
return True
a = A()
if a == 1 and a == 2 and a == 3:
print("Don't do that!")
It's possible to modify Java Integer
cache:
package stackoverflow;
import java.lang.reflect.Field;
public class IntegerMess
{
public static void main(String[] args) throws Exception {
Field valueField = Integer.class.getDeclaredField("value");
valueField.setAccessible(true);
valueField.setInt(1, valueField.getInt(42));
valueField.setInt(2, valueField.getInt(42));
valueField.setInt(3, valueField.getInt(42));
valueField.setAccessible(false);
Integer a = 42;
if (a.equals(1) && a.equals(2) && a.equals(3)) {
System.out.println("Bad idea.");
}
}
}
This is my awesome solution for a div
with a dynamic (percentaged) height.
CSS
.vertical_placer{
background:red;
position:absolute;
height:43%;
width:100%;
display: table;
}
.inner_placer{
display: table-cell;
vertical-align: middle;
text-align:center;
}
.inner_placer svg{
position:relative;
color:#fff;
background:blue;
width:30%;
min-height:20px;
max-height:60px;
height:20%;
}
HTML
<div class="footer">
<div class="vertical_placer">
<div class="inner_placer">
<svg> some Text here</svg>
</div>
</div>
</div>
use the String.Trim()
function.
string foo = " hello ";
string bar = foo.Trim();
Console.WriteLine(bar); // writes "hello"
@tasseKATT's Answer is great, but if you don't want to make a directive, why not use $document
?
.controller('ExampleController', ['$scope', '$document', function($scope, $document) {
var dumb = function (id) {
var queryResult = $document[0].getElementById(id)
var wrappedID = angular.element(queryResult);
return wrappedID;
};
You can use re.match()
or re.search()
.
Python offers two different primitive operations based on regular expressions: re.match()
checks for a match only at the beginning of the string, while re.search()
checks for a match anywhere in the string (this is what Perl does by default). refer this
You should always end threads by checking a flag in the run()
loop (if any).
Your thread should look like this:
public class IndexProcessor implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);
private volatile boolean execute;
@Override
public void run() {
this.execute = true;
while (this.execute) {
try {
LOGGER.debug("Sleeping...");
Thread.sleep((long) 15000);
LOGGER.debug("Processing");
} catch (InterruptedException e) {
LOGGER.error("Exception", e);
this.execute = false;
}
}
}
public void stopExecuting() {
this.execute = false;
}
}
Then you can end the thread by calling thread.stopExecuting()
. That way the thread is ended clean, but this takes up to 15 seconds (due to your sleep).
You can still call thread.interrupt() if it's really urgent - but the prefered way should always be checking the flag.
To avoid waiting for 15 seconds, you can split up the sleep like this:
...
try {
LOGGER.debug("Sleeping...");
for (int i = 0; (i < 150) && this.execute; i++) {
Thread.sleep((long) 100);
}
LOGGER.debug("Processing");
} catch (InterruptedException e) {
...
I'd recommend serialization,
public class Person
{
public string FirstName;
public string MI;
public string LastName;
}
static void Serialize()
{
clsPerson p = new Person();
p.FirstName = "Jeff";
p.MI = "A";
p.LastName = "Price";
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
x.Serialize(System.Console.Out, p);
System.Console.WriteLine();
System.Console.WriteLine(" --- Press any key to continue --- ");
System.Console.ReadKey();
}
You can further control serialization with attributes.
But if it is simple, you could use XmlDocument:
using System;
using System.Xml;
public class GenerateXml {
private static void Main() {
XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
XmlNode productsNode = doc.CreateElement("products");
doc.AppendChild(productsNode);
XmlNode productNode = doc.CreateElement("product");
XmlAttribute productAttribute = doc.CreateAttribute("id");
productAttribute.Value = "01";
productNode.Attributes.Append(productAttribute);
productsNode.AppendChild(productNode);
XmlNode nameNode = doc.CreateElement("Name");
nameNode.AppendChild(doc.CreateTextNode("Java"));
productNode.AppendChild(nameNode);
XmlNode priceNode = doc.CreateElement("Price");
priceNode.AppendChild(doc.CreateTextNode("Free"));
productNode.AppendChild(priceNode);
// Create and add another product node.
productNode = doc.CreateElement("product");
productAttribute = doc.CreateAttribute("id");
productAttribute.Value = "02";
productNode.Attributes.Append(productAttribute);
productsNode.AppendChild(productNode);
nameNode = doc.CreateElement("Name");
nameNode.AppendChild(doc.CreateTextNode("C#"));
productNode.AppendChild(nameNode);
priceNode = doc.CreateElement("Price");
priceNode.AppendChild(doc.CreateTextNode("Free"));
productNode.AppendChild(priceNode);
doc.Save(Console.Out);
}
}
And if it needs to be fast, use XmlWriter:
public static void WriteXML()
{
// Create an XmlWriterSettings object with the correct options.
System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = " "; // "\t";
settings.OmitXmlDeclaration = false;
settings.Encoding = System.Text.Encoding.UTF8;
using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create("data.xml", settings))
{
writer.WriteStartDocument();
writer.WriteStartElement("books");
for (int i = 0; i < 100; ++i)
{
writer.WriteStartElement("book");
writer.WriteElementString("item", "Book "+ (i+1).ToString());
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.Flush();
writer.Close();
} // End Using writer
}
And btw, the fastest way to read XML is XmlReader:
public static void ReadXML()
{
using (System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml"))
{
while (xmlReader.Read())
{
if ((xmlReader.NodeType == System.Xml.XmlNodeType.Element) && (xmlReader.Name == "Cube"))
{
if (xmlReader.HasAttributes)
System.Console.WriteLine(xmlReader.GetAttribute("currency") + ": " + xmlReader.GetAttribute("rate"));
}
} // Whend
} // End Using xmlReader
System.Console.ReadKey();
}
And the most convenient way to read XML is to just deserialize the XML into a class.
This also works for creating the serialization classes, btw.
You can generate the class from XML with Xml2CSharp:
https://xmltocsharp.azurewebsites.net/
The key is the sql query, which you will set up as a string:
$sqlquery = "SELECT field1, field2 FROM table WHERE NOT columnA = 'x' AND NOT columbB = 'y'";
Note that there are a lot of ways to specify NOT. Another one that works just as well is:
$sqlquery = "SELECT field1, field2 FROM table WHERE columnA != 'x' AND columbB != 'y'";
Here is a full example of how to use it:
$link = mysql_connect($dbHost,$dbUser,$dbPass) or die("Unable to connect to database");
mysql_select_db("$dbName") or die("Unable to select database $dbName");
$sqlquery = "SELECT field1, field2 FROM table WHERE NOT columnA = 'x' AND NOT columbB = 'y'";
$result=mysql_query($sqlquery);
while ($row = mysql_fetch_assoc($result) {
//do stuff
}
You can do whatever you would like within the above while loop. Access each field of the table as an element of the $row array
which means that $row['field1']
will give you the value for field1
on the current row, and $row['field2']
will give you the value for field2
.
Note that if the column(s) could have NULL
values, those will not be found using either of the above syntaxes. You will need to add clauses to include NULL
values:
$sqlquery = "SELECT field1, field2 FROM table WHERE (NOT columnA = 'x' OR columnA IS NULL) AND (NOT columbB = 'y' OR columnB IS NULL)";
int[]
and int*
are represented the same way, except int[] allocates (IIRC).
ap
is a pointer, therefore giving it the value of an integer is dangerous, as you have no idea what's at address 45.
when you try to access it (x = *ap
), you try to access address 45, which causes the crash, as it probably is not a part of the memory you can access.
If you still can not find anything wrong with your setup, you can try Project -> Clean and clean all the projects in the workspace.
EDIT: Sorry, did not see the suggestion of verbose_mode ... same thing
In my case with Ubuntu 14.04.3 and Apache 2.4.7, the problem was that I copied site1.conf to make site2.conf available, and by copying, something happend and I could not a2ensite site2.conf with the error described in thread.
The solution for me, was to rename site2.conf to site2 and then again rename site2 to site2.conf. After that I was able to a2ensite site2.conf.
Additional to the jQuery thing treated in the other answers there is another meaning in JavaScript - as prefix for the RegExp properties representing matches, for example:
"test".match( /t(e)st/ );
alert( RegExp.$1 );
will alert "e"
But also here it's not "magic" but simply part of the properties name
In C++11 and beyond, you can use the back
member function:
char ch = myStr.back();
In C++03, std::string::back
is not available due to an oversight, but you can get around this by dereferencing the reverse_iterator
you get back from rbegin
:
char ch = *myStr.rbegin();
In both cases, be careful to make sure the string actually has at least one character in it! Otherwise, you'll get undefined behavior, which is a Bad Thing.
Hope this helps!
You can use sp_help
in SQL Server 2008.
sp_help <table_name>;
Keyboard shortcut for the above command: select table name (i.e highlight it) and press ALT+F1.
We usually declare the constant as static
. The reason for that is because Java creates copies of non static variables every time you instantiate an object of the class.
So if we make the constants static
it would not do so and would save memory.
With final
we can make the variable constant.
Hence the best practice to define a constant variable is the following:
private static final String YOUR_CONSTANT = "Some Value";
The access modifier can be private/public
depending on the business logic.
Your stored procedures work as coded. The problem is with the last line, it is unable to invoke either of your stored procedures.
Three choices in SQL*Plus are: call
, exec
, and an anoymous PL/SQL block.
call
appears to be a SQL keyword, and is documented in the SQL Reference. http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_4008.htm#BABDEHHG The syntax diagram indicates that parentesis are required, even when no arguments are passed to the call routine.
CALL test_sp_1();
An anonymous PL/SQL block is PL/SQL that is not inside a named procedure, function, trigger, etc. It can be used to call your procedure.
BEGIN
test_sp_1;
END;
/
Exec
is a SQL*Plus command that is a shortcut for the above anonymous block. EXEC <procedure_name>
will be passed to the DB server as BEGIN <procedure_name>; END;
Full example:
SQL> SET SERVEROUTPUT ON
SQL> CREATE OR REPLACE PROCEDURE test_sp
2 AS
3 BEGIN
4 DBMS_OUTPUT.PUT_LINE('Test works');
5 END;
6 /
Procedure created.
SQL> CREATE OR REPLACE PROCEDURE test_sp_1
2 AS
3 BEGIN
4 DBMS_OUTPUT.PUT_LINE('Testing');
5 test_sp;
6 END;
7 /
Procedure created.
SQL> CALL test_sp_1();
Testing
Test works
Call completed.
SQL> exec test_sp_1
Testing
Test works
PL/SQL procedure successfully completed.
SQL> begin
2 test_sp_1;
3 end;
4 /
Testing
Test works
PL/SQL procedure successfully completed.
SQL>
The issue is due to the missing python3.dll
file in Anaconda3.
To fix the issue, you should simply copy the python3.dll
to C:\Program Files\Anaconda3
(or wherever your Anaconda3 is installed).
You can get the python3.dll
by downloading the binaries provided at the bottom of the Python's Release page and extracting the python3.dll
from the ZIP file.
If you want the Swift UIView subclass to be entirely self contained, and have the ability to be instantiated using init or init(frame:) without exposing the implementation detail of using a Nib, then you can use a protocol extension to achieve this. This solution avoids the nested UIView hierarchy as suggested by many of the other solutions.
public class CustomView: UIView {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var valueLabel: UILabel!
public convenience init() {
self.init(frame: CGRect.zero)
}
public override convenience init(frame: CGRect) {
self.init(internal: nil)
self.frame = frame
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
fileprivate func commonInit() {
}
}
fileprivate protocol _CustomView {
}
extension CustomView: _CustomView {
}
fileprivate extension _CustomView {
// Protocol extension initializer - has the ability to assign to self, unlike
// class initializers. Note that the name of this initializer can be anything
// you like, here we've called it init(internal:)
init(internal: Int?) {
self = Bundle.main.loadNibNamed("CustomView", owner:nil, options:nil)![0] as! Self;
}
}
I also like to use MsgBox for debugging, and I've run into this same issue more than once. Now I always add a Cancel button to the popup, and exit the macro if Cancel is pressed. Example code:
If MsgBox("Debug message", vbOKCancel, "Debugging") = vbCancel Then Exit Sub
You may also use box-shadow
and add transparency to that dashed border
via background-clip
to let you see body
background
.
example
h1 {_x000D_
text-align: center;_x000D_
margin: auto;_x000D_
box-shadow: 0 0 0 5px #1761A2;_x000D_
border: dashed 3px #1761A2;_x000D_
background: linear-gradient(#1761A2, #1761A2) no-repeat;_x000D_
background-clip: border-box;_x000D_
font-size: 2.5em;_x000D_
text-shadow: 0 0 2px white, 0 0 2px white, 0 0 2px white, 0 0 2px white, 0 0 2px white;_x000D_
font-size: 2.5em;_x000D_
min-width: 12em;_x000D_
}_x000D_
body {_x000D_
background: linear-gradient(to bottom left, yellow, gray, tomato, purple, lime, yellow, gray, tomato, purple, lime, yellow, gray, tomato, purple, lime);_x000D_
height: 100vh;_x000D_
margin: 0;_x000D_
display: flex;_x000D_
}_x000D_
::first-line {_x000D_
color: white;_x000D_
text-transform: uppercase;_x000D_
font-size: 0.7em;_x000D_
text-shadow: 0 0_x000D_
}_x000D_
code {_x000D_
color: tomato;_x000D_
text-transform: uppercase;_x000D_
text-shadow: 0 0;_x000D_
}_x000D_
em {_x000D_
mix-blend-mode: screen;_x000D_
text-shadow: 0 0 2px white, 0 0 2px white, 0 0 2px white, 0 0 2px white, 0 0 2px white_x000D_
}
_x000D_
<h1>transparent dashed border<br/>_x000D_
<em>with</em> <code>background-clip</code>_x000D_
</h1>
_x000D_
Just use the following for a "minimal" C# installation:
vs_Community.exe --layout f:\vs2017c --lang en-US --add Microsoft.VisualStudio.Workload.ManagedDesktop
This works for sure. The error in your first commandline was the trailing backslash. Without it it works. You don't have to download all..
You can add for example the following workloads (or a subset) to the commandline:
Microsoft.VisualStudio.Workload.Data Microsoft.VisualStudio.Workload.NetWeb Microsoft.VisualStudio.Workload.Universal Microsoft.VisualStudio.Workload.NetCoreTools
Sometimes the downloader seems to not like too much packages. But you can download the packages (add the other workloads) step-by-step, this works. Like you want.
The interesting thing. The installer afterwards will download (only) the packages you selected which you have NOT downloaded before, so it is quite smart (in this point).
(Of course there are more packages available).
Your problem is on the call for the dialog
If you dont initialize the dialog, you don't have to pass "open" for it to show:
$("#dialog").dialog();
Also, this code needs to be on a $(document).ready();
function or be below the elements for it to work.
this short code worked for me:
Configuration wConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ServiceModelSectionGroup wServiceSection = ServiceModelSectionGroup.GetSectionGroup(wConfig);
ClientSection wClientSection = wServiceSection.Client;
wClientSection.Endpoints[0].Address = <your address>;
wConfig.Save();
Of course you have to create the ServiceClient proxy AFTER the config has changed. You also need to reference the System.Configuration and System.ServiceModel assemblies to make this work.
Cheers
But now it is not working and I contacted our hosting team then they told me to use smtp
Newsflash - it was using SMTP before. They've not provided you with the information you need to solve the problem - or you've not relayed it accurately here.
Its possible that they've disabled the local MTA on the webserver, in which case you'll need to connect the SMTP port on a remote machine. There are lots of toolkits which will do the heavy lifting for you. Personally I like phpmailer because it adds other functionality.
Certainly if they've taken away a facility which was there before and your paying for a service then your provider should be giving you better support than that (there are also lots of programs to drop in in place of a full MTA which would do the job).
C.
I used tmux-powerline to fully pimp my tmux status bar. I was googling for a way to change to background of the status bar when your typing a tmux command. When I stumbled on this post I thought I should mention it for completeness.
Update: This project is in a maintenance mode and no future functionality is likely to be added. tmux-powerline, with all other powerline projects, is replaced by the new unifying powerline. However this project is still functional and can serve as a lightweight alternative for non-python users.
If you're looking for currency formatting (which you didn't specify, but it seems that is what you're looking for) try the NumberFormat
class. It's very simple:
double d = 2.3d;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String output = formatter.format(d);
Which will output (depending on locale):
$2.30
Also, if currency isn't required (just the exact two decimal places) you can use this instead:
NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
String output = formatter.format(d);
Which will output 2.30
You can simply iterate through the DbSet context.tablename
foreach(var row in context.tablename)
Console.WriteLn(row.field);
or to evaluate immediately into your own list
var allRows = context.tablename.ToList();
A silly bug that got me: the joins failed because index dtypes
differed. This was not obvious as both tables were pivot tables of the same original table. After reset_index
, the indices looked identical in Jupyter. It only came to light when saving to Excel...
Fixed with: df1[['key']] = df1[['key']].apply(pd.to_numeric)
Hopefully this saves somebody an hour!
If whichView
is an object of the GuideView Enum, following works well. Please note that there is no qualifier for the constant after case
.
switch (whichView) {
case SEVEN_DAY:
...
break;
case NOW_SHOWING:
...
break;
}
True CSS with proper semantic and accessibility settings.
It is a <button>
, It has text for screen readers.
https://codepen.io/specialweb/pen/ExyWPYv?editors=1100
button {
width: 2rem;
height: 2rem;
padding: 0;
position: absolute;
top: 1rem;
right: 1rem;
cursor: pointer;
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0,0,0,0);
border: 0;
}
button::before,
button::after {
content: '';
width: 1px;
height: 100%;
background: #333;
display: block;
transform: rotate(45deg) translateX(0px);
position: absolute;
left: 50%;
top: 0;
}
button::after {
transform: rotate(-45deg) translateX(0px);
}
/* demo */
body {
background: black;
}
.pane {
margin: 0 auto;
width: 50vw;
min-height: 50vh;
background: #FFF;
position: relative;
border-radius: 5px;
}
_x000D_
<div class="pane">
<button type="button"><span class="sr-only">Close</span></button>
</div>
_x000D_
If you're using on a web page, you can also use CSS:
style="text-transform:capitalize;"
The cleanest way here I believe is going to disable your client side validation and on the server side you will need to:
Seems even a custom view model here wont solve the problem because the number of those 'pre answered' fields could vary. If they dont then a custom view model may indeed be the easiest way, but using the above technique you can get around your validations issues.
This works for me.
Request.Url.OriginalString.Replace(Request.Url.PathAndQuery, "") + Request.ApplicationPath;
So if you want to access your domain name do consider to include the application name in case of:
====================================
For the dev.x.us/web
it return this strong text
No need to use refs, you can access using event
function handleSubmit(e) {
e.preventDefault()
const {username, password } = e.target.elements
console.log({username: username.value, password: password.value })
}
<form onSubmit={handleSubmit}>
<input type="text" id="username"/>
<input type="text" id="password"/>
<input type="submit" value="Login" />
</form>
127.0.0.1
is normally the IP address assigned to the "loopback" or local-only interface. This is a "fake" network adapter that can only communicate within the same host. It's often used when you want a network-capable application to only serve clients on the same host. A process that is listening on 127.0.0.1
for connections will only receive local connections on that socket.
"localhost" is normally the hostname for the 127.0.0.1
IP address. It's usually set in /etc/hosts
(or the Windows equivalent named "hosts" somewhere under %WINDIR%
). You can use it just like any other hostname - try "ping localhost" to see how it resolves to 127.0.0.1
.
0.0.0.0
has a couple of different meanings, but in this context, when a server is told to listen on 0.0.0.0
that means "listen on every available network interface". The loopback adapter with IP address 127.0.0.1
from the perspective of the server process looks just like any other network adapter on the machine, so a server told to listen on 0.0.0.0
will accept connections on that interface too.
That hopefully answers the IP side of your question. I'm not familiar with Jekyll or Vagrant, but I'm guessing that your port forwarding 8080 => 4000
is somehow bound to a particular network adapter, so it isn't in the path when you connect locally to 127.0.0.1
it works for me. if you want to enable future time for choose, you have to delete maximum date. You need to to do like followings.
btnDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
});
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(getActivity(), this, year, month, day);
dialog.getDatePicker().setMaxDate(c.getTimeInMillis());
return dialog;
}
public void onDateSet(DatePicker view, int year, int month, int day) {
btnDate.setText(ConverterDate.ConvertDate(year, month + 1, day));
}
}
In your example, because you use CurrentDB to execute your INSERT you've made it harder for yourself. Instead, this will work:
Dim query As String
Dim newRow As Long ' note change of data type
Dim db As DAO.Database
query = "INSERT INTO InvoiceNumbers (date) VALUES (" & NOW() & ");"
Set db = CurrentDB
db.Execute(query)
newRow = db.OpenRecordset("SELECT @@IDENTITY")(0)
Set db = Nothing
I used to do INSERTs by opening an AddOnly
recordset and picking up the ID from there, but this here is a lot more efficient. And note that it doesn't require ADO
.
My solution, as answered here, is to use:
var json = require('./data.json'); //with path
The file is loaded only once, further requests use cache.
edit To avoid caching, here's the helper function from this blogpost given in the comments, using the fs
module:
var readJson = (path, cb) => {
fs.readFile(require.resolve(path), (err, data) => {
if (err)
cb(err)
else
cb(null, JSON.parse(data))
})
}
You want to use sections when you want a bit of code/content to render in a placeholder that has been defined in a layout page.
In the specific example you linked, he has defined the RenderSection in the _Layout.cshtml. Any view that uses that layout can define an @section of the same name as defined in Layout, and it will replace the RenderSection call in the layout.
Perhaps you're wondering how we know Index.cshtml uses that layout? This is due to a bit of MVC/Razor convention. If you look at the dialog where he is adding the view, the box "Use layout or master page" is checked, and just below that it says "Leave empty if it is set in a Razor _viewstart file". It isn't shown, but inside that _ViewStart.cshtml file is code like:
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
The way viewstarts work is that any cshtml file within the same directory or child directories will run the ViewStart before it runs itself.
Which is what tells us that Index.cshtml uses Shared/_Layout.cshtml.
Programmers often confuse multidimensional arrays with arrays of pointers.
Most programmers are familiar with named multidimensional arrays, but many are unaware of the fact that multidimensional array can also be created anonymously. Multidimensional arrays are often referred to as "arrays of arrays" or "true multidimensional arrays".
When using named multidimensional arrays, all dimensions must be known at compile time:
int H = read_int();
int W = read_int();
int connect_four[6][7]; // okay
int connect_four[H][7]; // ISO C++ forbids variable length array
int connect_four[6][W]; // ISO C++ forbids variable length array
int connect_four[H][W]; // ISO C++ forbids variable length array
This is how a named multidimensional array looks like in memory:
+---+---+---+---+---+---+---+
connect_four: | | | | | | | |
+---+---+---+---+---+---+---+
| | | | | | | |
+---+---+---+---+---+---+---+
| | | | | | | |
+---+---+---+---+---+---+---+
| | | | | | | |
+---+---+---+---+---+---+---+
| | | | | | | |
+---+---+---+---+---+---+---+
| | | | | | | |
+---+---+---+---+---+---+---+
Note that 2D grids such as the above are merely helpful visualizations. From the point of view of C++, memory is a "flat" sequence of bytes. The elements of a multidimensional array are stored in row-major order. That is, connect_four[0][6]
and connect_four[1][0]
are neighbors in memory. In fact, connect_four[0][7]
and connect_four[1][0]
denote the same element! This means that you can take multi-dimensional arrays and treat them as large, one-dimensional arrays:
int* p = &connect_four[0][0];
int* q = p + 42;
some_int_sequence_algorithm(p, q);
With anonymous multidimensional arrays, all dimensions except the first must be known at compile time:
int (*p)[7] = new int[6][7]; // okay
int (*p)[7] = new int[H][7]; // okay
int (*p)[W] = new int[6][W]; // ISO C++ forbids variable length array
int (*p)[W] = new int[H][W]; // ISO C++ forbids variable length array
This is how an anonymous multidimensional array looks like in memory:
+---+---+---+---+---+---+---+
+---> | | | | | | | |
| +---+---+---+---+---+---+---+
| | | | | | | | |
| +---+---+---+---+---+---+---+
| | | | | | | | |
| +---+---+---+---+---+---+---+
| | | | | | | | |
| +---+---+---+---+---+---+---+
| | | | | | | | |
| +---+---+---+---+---+---+---+
| | | | | | | | |
| +---+---+---+---+---+---+---+
|
+-|-+
p: | | |
+---+
Note that the array itself is still allocated as a single block in memory.
You can overcome the restriction of fixed width by introducing another level of indirection.
Here is a named array of five pointers which are initialized with anonymous arrays of different lengths:
int* triangle[5];
for (int i = 0; i < 5; ++i)
{
triangle[i] = new int[5 - i];
}
// ...
for (int i = 0; i < 5; ++i)
{
delete[] triangle[i];
}
And here is how it looks like in memory:
+---+---+---+---+---+
| | | | | |
+---+---+---+---+---+
^
| +---+---+---+---+
| | | | | |
| +---+---+---+---+
| ^
| | +---+---+---+
| | | | | |
| | +---+---+---+
| | ^
| | | +---+---+
| | | | | |
| | | +---+---+
| | | ^
| | | | +---+
| | | | | |
| | | | +---+
| | | | ^
| | | | |
| | | | |
+-|-+-|-+-|-+-|-+-|-+
triangle: | | | | | | | | | | |
+---+---+---+---+---+
Since each line is allocated individually now, viewing 2D arrays as 1D arrays does not work anymore.
Here is an anonymous array of 5 (or any other number of) pointers which are initialized with anonymous arrays of different lengths:
int n = calculate_five(); // or any other number
int** p = new int*[n];
for (int i = 0; i < n; ++i)
{
p[i] = new int[n - i];
}
// ...
for (int i = 0; i < n; ++i)
{
delete[] p[i];
}
delete[] p; // note the extra delete[] !
And here is how it looks like in memory:
+---+---+---+---+---+
| | | | | |
+---+---+---+---+---+
^
| +---+---+---+---+
| | | | | |
| +---+---+---+---+
| ^
| | +---+---+---+
| | | | | |
| | +---+---+---+
| | ^
| | | +---+---+
| | | | | |
| | | +---+---+
| | | ^
| | | | +---+
| | | | | |
| | | | +---+
| | | | ^
| | | | |
| | | | |
+-|-+-|-+-|-+-|-+-|-+
| | | | | | | | | | |
+---+---+---+---+---+
^
|
|
+-|-+
p: | | |
+---+
Array-to-pointer decay naturally extends to arrays of arrays and arrays of pointers:
int array_of_arrays[6][7];
int (*pointer_to_array)[7] = array_of_arrays;
int* array_of_pointers[6];
int** pointer_to_pointer = array_of_pointers;
However, there is no implicit conversion from T[h][w]
to T**
. If such an implicit conversion did exist, the result would be a pointer to the first element of an array of h
pointers to T
(each pointing to the first element of a line in the original 2D array), but that pointer array does not exist anywhere in memory yet. If you want such a conversion, you must create and fill the required pointer array manually:
int connect_four[6][7];
int** p = new int*[6];
for (int i = 0; i < 6; ++i)
{
p[i] = connect_four[i];
}
// ...
delete[] p;
Note that this generates a view of the original multidimensional array. If you need a copy instead, you must create extra arrays and copy the data yourself:
int connect_four[6][7];
int** p = new int*[6];
for (int i = 0; i < 6; ++i)
{
p[i] = new int[7];
std::copy(connect_four[i], connect_four[i + 1], p[i]);
}
// ...
for (int i = 0; i < 6; ++i)
{
delete[] p[i];
}
delete[] p;
Piece of cake.
Use 960Grids Go to the automatic layout builder and make a two column, fluid design. Build a left column to the width of grids that works....this is the only challenge using grids and it's very easy once you read a tutorial. In a nutshell, each column in a grid is a certain width, and you set the amount of columns you want to use. To get a column that's exactly a certain width, you have to adjust your math so that your column width is exact. Not too tough.
No chance of wrapping because others have already fought that battle for you. Compatibility back as far as you likely will ever need to go. Quick and easy....Now, download, customize and deploy.
Voila. Grids FTW.
PDF Hummus. see for http://pdfhummus.com/ - contains all required features for manipulation with PDF files except rendering.
I have a slightly modified version of Mani's.
private static BigDecimal truncateDecimal(final double x, final int numberofDecimals) {
return new BigDecimal(String.valueOf(x)).setScale(numberofDecimals, BigDecimal.ROUND_DOWN);
}
public static void main(String[] args) {
System.out.println(truncateDecimal(0, 2));
System.out.println(truncateDecimal(9.62, 2));
System.out.println(truncateDecimal(9.621, 2));
System.out.println(truncateDecimal(9.629, 2));
System.out.println(truncateDecimal(9.625, 2));
System.out.println(truncateDecimal(9.999, 2));
System.out.println(truncateDecimal(3.545555555, 2));
System.out.println(truncateDecimal(9.0, 2));
System.out.println(truncateDecimal(-9.62, 2));
System.out.println(truncateDecimal(-9.621, 2));
System.out.println(truncateDecimal(-9.629, 2));
System.out.println(truncateDecimal(-9.625, 2));
System.out.println(truncateDecimal(-9.999, 2));
System.out.println(truncateDecimal(-9.0, 2));
System.out.println(truncateDecimal(-3.545555555, 2));
}
Output:
0.00
9.62
9.62
9.62
9.62
9.99
9.00
3.54
-9.62
-9.62
-9.62
-9.62
-9.99
-9.00
-3.54
It's really easy to do: reliable and not messy:
Try Clients.Client.Send(BufferByte) Catch verror As Exception BufferString = verror.ToString End Try If BufferString <> "" Then EventLog.Text &= "User disconnected: " + vbNewLine Clients.Close() End If
I don't know whether a direct way of doing this is available or not, but you surely there is a workaround via code: listen for onFocus event of EditText
, and as soon it gains focus, set the hint to be nothing with something like editText.setHint("")
:
This may not be exactly what you have to do, but it may be something like this-
myEditText.setOnFocusListener(new OnFocusListener(){
public void onFocus(){
myEditText.setHint("");
}
});
you can also use the randomizeMatrix
function in the R package picante
example:
test <- matrix(c(1,1,0,1,0,1,0,0,1,0,0,1,0,1,0,0),nrow=4,ncol=4)
> test
[,1] [,2] [,3] [,4]
[1,] 1 0 1 0
[2,] 1 1 0 1
[3,] 0 0 0 0
[4,] 1 0 1 0
randomizeMatrix(test,null.model = "frequency",iterations = 1000)
[,1] [,2] [,3] [,4]
[1,] 0 1 0 1
[2,] 1 0 0 0
[3,] 1 0 1 0
[4,] 1 0 1 0
randomizeMatrix(test,null.model = "richness",iterations = 1000)
[,1] [,2] [,3] [,4]
[1,] 1 0 0 1
[2,] 1 1 0 1
[3,] 0 0 0 0
[4,] 1 0 1 0
>
The option null.model="frequency"
maintains column sums and richness
maintains row sums.
Though mainly used for randomizing species presence absence datasets in community ecology it works well here.
This function has other null model options as well, check out following link for more details (page 36) of the picante
documentation
Change the checkboxes so that the name includes the index inside the brackets:
<input type="checkbox" class="checkbox_veh" id="checkbox_addveh<?php echo $i; ?>" <?php if ($vehicle_feature[$i]->check) echo "checked"; ?> name="feature[<?php echo $i; ?>]" value="<?php echo $vehicle_feature[$i]->id; ?>">
The checkboxes that aren't checked are never submitted. The boxes that are checked get submitted, but they get numbered consecutively from 0, and won't have the same indexes as the other corresponding input fields.
Use a function style conversion (found in section labeled "Integer and Floating-Point Conversion" from "The Swift Programming Language."[iTunes link])
1> Int(3.4)
$R1: Int = 3
You need the "correlation id" (the "AS SS" thingy) on the sub-select to reference the fields in the "ON" condition. The id's assigned inside the sub select are not usable in the join.
SELECT
cs.CUSID
,dp.DEPID
FROM
CUSTMR cs
LEFT OUTER JOIN (
SELECT
DEPID
,DEPNAME
FROM
DEPRMNT
WHERE
dp.DEPADDRESS = 'TOKYO'
) ss
ON (
ss.DEPID = cs.CUSID
AND ss.DEPNAME = cs.CUSTNAME
)
WHERE
cs.CUSID != ''
To handle eliminating duplicates, implement an IEqualityComparer<Person>
that can be used in the Distinct()
method, and then getting your dictionary will be easy.
Given:
class PersonComparer : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
return x.FirstAndLastName.Equals(y.FirstAndLastName, StringComparison.OrdinalIgnoreCase);
}
public int GetHashCode(Person obj)
{
return obj.FirstAndLastName.ToUpper().GetHashCode();
}
}
class Person
{
public string FirstAndLastName { get; set; }
}
Get your dictionary:
List<Person> people = new List<Person>()
{
new Person() { FirstAndLastName = "Bob Sanders" },
new Person() { FirstAndLastName = "Bob Sanders" },
new Person() { FirstAndLastName = "Jane Thomas" }
};
Dictionary<string, Person> dictionary =
people.Distinct(new PersonComparer()).ToDictionary(p => p.FirstAndLastName, p => p);
this is pretty old, but if you are using Python 3.4 or above use PathLib.
# using OS
import os
path=os.path.dirname("C:/folder1/folder2/filename.xml")
print(path)
print(os.path.basename(path))
# using pathlib
import pathlib
path = pathlib.PurePath("C:/folder1/folder2/filename.xml")
print(path.parent)
print(path.parent.name)
goto Android->sdk->build-tools directory make sure you have all the versions required . if not , download them . after that goto File-->Settigs-->Build,Execution,Depoyment-->Gradle
choose use default gradle wapper (recommended)
and untick Offline work
gradle build finishes successfully for once you can change the settings
If it dosent simply solve the problem
check this link to find an appropriate support library revision
https://developer.android.com/topic/libraries/support-library/revisions
Make sure that the compile sdk and target version same as the support library version. It is recommended maintain network connection atleast for the first time build (Remember to rebuild your project after doing this)
Separate with commas:
http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505
or:
http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505
or:
http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505
Either way, your method signature needs to be:
@RequestMapping(value = "/GetJson", method = RequestMethod.GET)
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
//code to get results from db for those params.
}
I know this question is a couple years old, but I am surprised to find that no one suggested:
text-align: center;
this is a more universal property than justify-content, and is definitely not unique to grid, but I find that when dealing with text, which is what this question specifically asks about, that it aligns text to the center with-out affecting the space between grid items, or the vertical centering. It centers text horizontally where its stands on its vertical axis. I also find it to remove a layer of complexity that justify-content and align-items adds. justify-content and align-items affects the entire grid item or items, text-align centers the text without affecting the container it is in. Hope this helps.
On Unix:
touch .gitignore
On Windows:
echo > .gitignore
These commands executed in a terminal will create a .gitignore
file in the current location.
Then just add information to this .gitignore
file (using Notepad++ for example) which files or folders should be ignored. Save your changes. That's it :)
More information: .gitignore
The simpliest way is to install the needed package:
sudo apt-get install tesseract-ocr-eng #for english
sudo apt-get install tesseract-ocr-tam #for tamil
sudo apt-get install tesseract-ocr-deu #for deutsch (German)
As you can notice, it opens the road to others languages (i.e. tesseract-ocr-fra).
On new El Capitan installation where SIP(rootless prevents access to usr/lib/) is on by default and you cannot create the symlink unless you are in recovery mode. As @yannisxu said you can disable SIP and do your symlink to /usr/lib/local and this will work.
you can use the following command on MAC OSX El Capitan instead of turning off SIP:
sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/local/lib/libmysqlclient.18.dylib
There used to be an option where you can login as root and this can disable SIP but in the final release that is now obsolete, you can read more about it here: https://forums.developer.apple.com/thread/4686
Question:
There is a nvram boot-args command available in Developer Beta 1 which can disable SIP when run with root privileges:
nvram boot-args="rootless=0"
Will this option of disabling SIP also be available in the El Capitan release version? Or is this strictly for the Developer Builds?
Answer:
This nvram boot-args command will be going away. It will not be available in the El Capitan release version and may disappear before the end of the Developer Betas. Keep an eye on the release notes for future Developer Betas.