Try this:
$(document).ready(function() {
if ($('#leftmenu').html() === "") {
$('#menuTitleWrapper').remove();
$('#middlemenu').css({'right' : '0', 'position' : 'absolute'});
$('#PageContent').css({'top' : '30px', 'position' : 'relative'});
}
});
It's not the prettiest, but it should work. It checks whether the innerHTML (the contents of #leftmenu) is an empty string (i.e. there's nothing inside of it).
For img tags if you define one side then other side is resized to keep aspect ratio and by default images expand to their original size.
Using this fact if you wrap each img tag into div tag and set its width to 100% of parent div then height will be according to aspect ratio as you wanted.
* {
margin: 0;
padding: 0;
}
.slider {
display: flex;
}
.slider .slide img {
width: 100%;
}
slide to right
viewPager.arrowScroll(View.FOCUS_RIGHT);
slide to left
viewPager.arrowScroll(View.FOCUS_LEFT);
Have a look at here this link and their roadmap. They have RO|C on the way, and that can connect to their web services, which probably includes SOAP (I use the VCL version which definitely includes it).
I think the poster meant to say You do not have to allocate everything on the
heap
rather than the the stack
.
Basically objects are allocated on the stack (if the object size allows, of course) because of the cheap cost of stack-allocation, rather than heap-based allocation which involves quite some work by the allocator, and adds verbosity because then you have to manage data allocated on the heap.
Consider adding the switch /D_USE_MATH_DEFINES to your compilation command line, or to define the macro in the project settings. This will drag the symbol to all reachable dark corners of include and source files leaving your source clean for multiple platforms. If you set it globally for the whole project, you will not forget it later in a new file(s).
Please note that adding the get_author
function would slow the list_display in the admin, because showing each person would make a SQL query.
To avoid this, you need to modify get_queryset
method in PersonAdmin, for example:
def get_queryset(self, request):
return super(PersonAdmin,self).get_queryset(request).select_related('book')
Before: 73 queries in 36.02ms (67 duplicated queries in admin)
After: 6 queries in 10.81ms
In my case I was getting this error because the option (HttpActivation) was not enabled.
In short, if you have multiple routes defined for your app's routing, enclosed with Switch
component like this;
<Switch>
<Route exact path="/" component={Home} />
<Route path="/detail" component={Detail} />
<Route exact path="/functions" component={Functions} />
<Route path="/functions/:functionName" component={FunctionDetails} />
</Switch>
Then you have to put exact
keyword to the Route which it's path is also included by another Route's path. For example home path /
is included in all paths so it needs to have exact
keyword to differentiate it from other paths which start with /
. The reason is also similar to /functions
path. If you want to use another route path like /functions-detail
or /functions/open-door
which includes /functions
in it then you need to use exact
for the /functions
route.
Try this:
if ($.browser.msie)
{
// Some other solution as applies to whatever IE compatible video player used.
}
else
{
$('video')[0].pause();
}
But, consider that $.browser is deprecated, but I haven't found a comparable solution.
I've recently released xUnit++, specifically as an alternative to Google Test and the Boost Test Library (view the comparisons). If you're familiar with xUnit.Net, you're ready for xUnit++.
#include "xUnit++/xUnit++.h"
FACT("Foo and Blah should always return the same value")
{
Check.Equal("0", Foo()) << "Calling Foo() with no parameters should always return \"0\".";
Assert.Equal(Foo(), Blah());
}
THEORY("Foo should return the same value it was given, converted to string", (int input, std::string expected),
std::make_tuple(0, "0"),
std::make_tuple(1, "1"),
std::make_tuple(2, "2"))
{
Assert.Equal(expected, Foo(input));
}
Main features:
Assert.Equal(-1, foo(i)) << "Failed with i = " << i;
Log.Debug << "Starting test"; Log.Warn << "Here's a warning";
A simple solution for you if you're new to HTML, is just to use a table to line everything up.
<form>
<table>
<tr>
<td align="right">First Name:</td>
<td align="left"><input type="text" name="first" /></td>
</tr>
<tr>
<td align="right">Last Name:</td>
<td align="left"><input type="text" name="last" /></td>
</tr>
<tr>
<td align="right">Email:</td>
<td align="left"><input type="text" name="email" /></td>
</tr>
</table>
</form>
I put my customized changes in the User package:
*nix: ~/.config/sublime-text-2/Packages/User/Scala.tmLanguage
*Windows: %APPDATA%\Sublime Text 2\Packages\User\Scala.tmLanguage
Which also means it's in JSON format:
{
"extensions":
[
"sbt"
]
}
This is the same place the
View -> Syntax -> Open all with current extension as ...
menu item adds it (creating the file if it doesn't exist).
Close the first Bootstrap modal and open the new modal dynamically.
$('#Modal_One').modal('hide');
setTimeout(function () {
$('#Modal_New').modal({
backdrop: 'dynamic',
keyboard: true
});
}, 500);
Supplementing the answer by p.s.w.g
, here are three other ways of achieving this using lodash
4.17.5
, without using _.includes()
:
Say you want to add object entry
to an array of objects numbers
, only if entry
does not exist already.
let numbers = [
{ to: 1, from: 2 },
{ to: 3, from: 4 },
{ to: 5, from: 6 },
{ to: 7, from: 8 },
{ to: 1, from: 2 } // intentionally added duplicate
];
let entry = { to: 1, from: 2 };
/*
* 1. This will return the *index of the first* element that matches:
*/
_.findIndex(numbers, (o) => { return _.isMatch(o, entry) });
// output: 0
/*
* 2. This will return the entry that matches. Even if the entry exists
* multiple time, it is only returned once.
*/
_.find(numbers, (o) => { return _.isMatch(o, entry) });
// output: {to: 1, from: 2}
/*
* 3. This will return an array of objects containing all the matches.
* If an entry exists multiple times, if is returned multiple times.
*/
_.filter(numbers, _.matches(entry));
// output: [{to: 1, from: 2}, {to: 1, from: 2}]
If you want to return a Boolean
, in the first case, you can check the index that is being returned:
_.findIndex(numbers, (o) => { return _.isMatch(o, entry) }) > -1;
// output: true
System.out.println(isLeapYear);
should work just fine.
Incidentally, in
else if ((year % 4 == 0) && (year % 100 == 0)) isLeapYear = false; else if ((year % 4 == 0) && (year % 100 == 0) && (year % 400 == 0)) isLeapYear = true;
the year % 400
part will never be reached because if (year % 4 == 0) && (year % 100 == 0) && (year % 400 == 0)
is true, then (year % 4 == 0) && (year % 100 == 0)
must have succeeded.
Maybe swap those two conditions or refactor them:
else if ((year % 4 == 0) && (year % 100 == 0))
isLeapYear = (year % 400 == 0);
If using JDK 9 +, use Objects.requireNonNullElse(T obj, T defaultObj)
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/substr
From link:
string.substr(start[, length])
Haven't seen this solution yet so here's how I did it without using read_csv:
df.rename(columns={'A':'','B':''})
If you rename all your column names to empty strings your table will return without a header.
And if you have a lot of columns in your table you can just create a dictionary first instead of renaming manually:
df_dict = dict.fromkeys(df.columns, '')
df.rename(columns = df_dict)
If you are using a third party library called apache commons-lang, the following solution can be useful:
Use StringUtils
class of apache commons-lang :
int i = 5;
StringUtils.leftPad(String.valueOf(i), 3, "0"); // --> "005"
As StringUtils.leftPad()
is faster than String.format()
Move points into test:
def test():
points = 0
addpoint = raw_input ("type ""add"" to add a point")
...
or use global statement, but it is bad practice. But better way it move points to parameters:
def test(points=0):
addpoint = raw_input ("type ""add"" to add a point")
...
let elements = [1, 2, 3, 4, 5, 5]
elements.contains(5) // true
elements.firstIndex(of: 5) // 4
elements.firstIndex(of: 10) // nil
let results = elements.filter { element in element == 5 }
results.count // 2
request.getAttribute("servletName")
method will return Object
that you need to cast to ArrayList
ArrayList<Category> list =new ArrayList<Category>();
//storing passed value from jsp
list = (ArrayList<Category>)request.getAttribute("servletName");
"End Process" on the Processes-Tab calls TerminateProcess
which is the most ultimate way Windows knows to kill a process.
If it doesn't go away, it's currently locked waiting on some kernel resource (probably a buggy driver) and there is nothing (short of a reboot) you could do to make the process go away.
Have a look at this blog-entry from wayback when: http://blogs.technet.com/markrussinovich/archive/2005/08/17/unkillable-processes.aspx
Unix based systems like Linux also have that problem where processes could survive a kill -9
if they are in what's known as "Uninterruptible sleep" (shown by top and ps as state D
) at which point the processes sleep so well that they can't process incoming signals (which is what kill
does - sending signals).
Normally, Uninterruptible sleep should not last long, but as under Windows, broken drivers or broken userpace programs (vfork
without exec
) can end up sleeping in D
forever.
In addition to @KenM's answer, another important distinction is that, when loading in a saved object, you can assign the contents of an Rds
file. Not so for Rda
> x <- 1:5
> save(x, file="x.Rda")
> saveRDS(x, file="x.Rds")
> rm(x)
## ASSIGN USING readRDS
> new_x1 <- readRDS("x.Rds")
> new_x1
[1] 1 2 3 4 5
## 'ASSIGN' USING load -- note the result
> new_x2 <- load("x.Rda")
loading in to <environment: R_GlobalEnv>
> new_x2
[1] "x"
# NOTE: `load()` simply returns the name of the objects loaded. Not the values.
> x
[1] 1 2 3 4 5
It can also be used as below:
from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)
I was facing similar issue when trying to logon through Mobaxterm. The private key was generated through puttygen. Regenerating the key helped in my case.
The patch is here: https://code.ros.org/trac/opencv/attachment/ticket/862/OpenCV-2.2-nov4l1.patch
By adding #ifdef HAVE_CAMV4L
around
#include <linux/videodev.h>
in OpenCV-2.2.0/modules/highgui/src/cap_v4l.cpp
and removing || defined (HAVE_CAMV4L2)
from line 174
allowed me to compile.
You want instanceof
:
if (value instanceof Integer)
This will be true even for subclasses, which is usually what you want, and it is also null-safe. If you really need the exact same class, you could do
if (value.getClass() == Integer.class)
or
if (Integer.class.equals(value.getClass())
Character varying is different than text. Try running
ALTER TABLE product_product ALTER COLUMN code TYPE text;
That will change the column type to text, which is limited to some very large amount of data (you would probably never actually hit it.)
I just found something in the TypeScript language specification, it's fairly easy. I was pretty close.
the syntax is the following:
public myCallback: (name: type) => returntype;
In my example, it would be
class CallbackTest
{
public myCallback: () => void;
public doWork(): void
{
//doing some work...
this.myCallback(); //calling callback
}
}
int &z = 12;
On the right hand side, a temporary object of type int
is created from the integral literal 12
, but the temporary cannot be bound to non-const reference. Hence the error. It is same as:
int &z = int(12); //still same error
Why a temporary gets created? Because a reference has to refer to an object in the memory, and for an object to exist, it has to be created first. Since the object is unnamed, it is a temporary object. It has no name. From this explanation, it became pretty much clear why the second case is fine.
A temporary object can be bound to const reference, which means, you can do this:
const int &z = 12; //ok
For the sake of the completeness, I would like to add that C++11 has introduced rvalue-reference, which can bind to temporary object. So in C++11, you can write this:
int && z = 12; //C+11 only
Note that there is &&
intead of &
. Also note that const
is not needed anymore, even though the object which z
binds to is a temporary object created out of integral-literal 12
.
Since C++11 has introduced rvalue-reference, int&
is now henceforth called lvalue-reference.
You can remove some extra spacing as well if you place a border-collapse: collapse;
CSS statement on your table.
Probably not. While I can't log into the Apple Development site, according to this post you need an intel mac platform.
http://tinleyharrier.blogspot.com/2008/03/iphone-sdk-requirements.html
import csv
with open('filepath/filename.csv', "rt", encoding='ascii') as infile:
read = csv.reader(infile)
for row in read :
print (row)
This will solve your problem. Don't forget to give the encoding.
You need to look into Ajax; Start here this is the best way to stay on the current page and be able to send inputs to php.
<!DOCTYPE html>
<html>
<head>
<script>
function showHint(str)
{
var xmlhttp;
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<h3>Start typing a name in the input field below:</h3>
<form action="">
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
This gets the users input on the textbox and opens the webpage gethint.php?q=ja from here the php script can do anything with $_GET['q'] and echo back to the page James, Jason....etc
process.cwd()
returns the current working directory,
i.e. the directory from which you invoked the node
command.
__dirname
returns the directory name of the directory containing the JavaScript source code file
Did a quick google. Seems that to find the file size you do this,
long size = f.length();
The differences between the three methods you posted can be found here
getFreeSpace() and getTotalSpace() are pretty self explanatory, getUsableSpace() seems to be the space that the JVM can use, which in most cases will be the same as the amount of free space.
The answer from @edutesoy points to the documentation of PowerMockito
and mentions constructor mocking as a hint but doesn't mention how to apply that to the current problem in the question.
Here is a solution based on that. Taking the code from the question:
public class MyClass {
void method1 {
MyObject obj1 = new MyObject();
obj1.method1();
}
}
The following test will create a mock of the MyObject
instance class via preparing the class that instantiates it (in this example I am calling it MyClass
) with PowerMock
and letting PowerMockito
to stub the constructor of MyObject
class, then letting you stub the MyObject
instance method1()
call:
@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class)
public class MyClassTest {
@Test
public void testMethod1() {
MyObject myObjectMock = mock(MyObject.class);
when(myObjectMock.method1()).thenReturn(<whatever you want to return>);
PowerMockito.whenNew(MyObject.class).withNoArguments().thenReturn(myObjectMock);
MyClass objectTested = new MyClass();
objectTested.method1();
... // your assertions or verification here
}
}
With that your internal method1()
call will return what you want.
If you like the one-liners you can make the code shorter by creating the mock and the stub inline:
MyObject myObjectMock = when(mock(MyObject.class).method1()).thenReturn(<whatever you want>).getMock();
Why not make use of the meaningful data already there, instead of adding arbitrary data?
i.e. use <a href="/articles/5/page-title" class="article-link">
, and then you can programmatically get all article links on the page (via the classname) and the article ID (matching the regex /articles\/(\d+)/
against this.href
).
Using @Tarkus's answer, here are the regexes I used in R:
getColNames <- function(conn, tableName) {
x <- dbGetQuery( conn, paste0("SELECT sql FROM sqlite_master WHERE tbl_name = '",tableName,"' AND type = 'table'") )[1,1]
x <- str_split(x,"\\n")[[1]][-1]
x <- sub("[()]","",x)
res <- gsub( '"',"",str_extract( x[1], '".+"' ) )
x <- x[-1]
x <- x[-length(x)]
res <- c( res, gsub( "\\t", "", str_extract( x, "\\t[0-9a-zA-Z_]+" ) ) )
res
}
Code is somewhat sloppy, but it appears to work.
yourLabel.intrinsicContentSize.width
for Objective-C / Swift
Selection
is its own object within VBA. It functions much like a Range
object.
Selection and Range do not share all the same properties and methods, though, so for ease of use it might make sense just to create a range and set it equal to the Selection, then you can deal with it programmatically like any other range.
Dim myRange as Range
Set myRange = Selection
For further reading, check out the MSDN article.
NONE of the above helped me. but doing this did help:
self.tableView.contentInset = UIEdgeInsetsMake(-64, 0, 0, 0)
instead of '-64' you can put any other number depending on the height of your navigation bar.
Give Safe User Permission To Use Port 80
Remember, we do NOT want to run your applications as the root user, but there is a hitch: your safe user does not have permission to use the default HTTP port (80). You goal is to be able to publish a website that visitors can use by navigating to an easy to use URL like http://ip:port/
Unfortunately, unless you sign on as root, you’ll normally have to use a URL like http://ip:port
- where port number > 1024.
A lot of people get stuck here, but the solution is easy. There a few options but this is the one I like. Type the following commands:
sudo apt-get install libcap2-bin
sudo setcap cap_net_bind_service=+ep `readlink -f \`which node\``
Now, when you tell a Node application that you want it to run on port 80, it will not complain.
Check this reference link
You could use itertools's takewhile like this, it will stop once a condition is met that fails your statement. The opposite method would be dropwhile
for x in itertools.takewhile(lambda x: x[2] == 0, list)
print x
Here's another way to do it. Some people will prefer this as the code is a bit cleaner. There are no %s
and a RESET
color to end the coloration.
#include <stdio.h>
#define RED "\x1B[31m"
#define GRN "\x1B[32m"
#define YEL "\x1B[33m"
#define BLU "\x1B[34m"
#define MAG "\x1B[35m"
#define CYN "\x1B[36m"
#define WHT "\x1B[37m"
#define RESET "\x1B[0m"
int main() {
printf(RED "red\n" RESET);
printf(GRN "green\n" RESET);
printf(YEL "yellow\n" RESET);
printf(BLU "blue\n" RESET);
printf(MAG "magenta\n" RESET);
printf(CYN "cyan\n" RESET);
printf(WHT "white\n" RESET);
return 0;
}
This program gives the following output:
This way, it's easy to do something like:
printf("This is " RED "red" RESET " and this is " BLU "blue" RESET "\n");
This line produces the following output:
You can use Environment.GetCommandLineArgs()
to obtain the arguments and Environment.CommandLine
to obtain the actual command line as entered.
Also, you can use Assembly.GetEntryAssembly()
or Process.GetCurrentProcess()
.
However, when debugging, you should be careful as this final example may give your debugger's executable name (depending on how you attach the debugger) rather than your executable, as may the other examples.
There are two ways to look at it:
Inline functions are defined in the header because, in order to inline a function call, the compiler must be able to see the function body. For a naive compiler to do that, the function body must be in the same translation unit as the call. (A modern compiler can optimize across translation units, and so a function call may be inlined even though the function definition is in a separate translation unit, but these optimizations are expensive, aren't always enabled, and weren't always supported by the compiler)
functions defined in the header must be marked inline
because otherwise, every translation unit which includes the header will contain a definition of the function, and the linker will complain about multiple definitions (a violation of the One Definition Rule). The inline
keyword suppresses this, allowing multiple translation units to contain (identical) definitions.
The two explanations really boil down to the fact that the inline
keyword doesn't exactly do what you'd expect.
A C++ compiler is free to apply the inlining optimization (replace a function call with the body of the called function, saving the call overhead) any time it likes, as long as it doesn't alter the observable behavior of the program.
The inline
keyword makes it easier for the compiler to apply this optimization, by allowing the function definition to be visible in multiple translation units, but using the keyword doesn't mean the compiler has to inline the function, and not using the keyword doesn't forbid the compiler from inlining the function.
You can check this way where 'HAS' - Returns true if this object has a mapping for name. The mapping may be NULL.
if (json.has("status")) {
String status = json.getString("status"));
}
if (json.has("club")) {
String club = json.getString("club"));
}
You can also check using 'isNull' - Returns true if this object has no mapping for name or if it has a mapping whose value is NULL.
if (!json.isNull("club"))
String club = json.getString("club"));
I am using the AMD processor and had the same issue. To solve this go to control panel-> turn windows features on or off -> check the hyper-V checkbox and click Ok and restart your computer. Now you can create virtual device
Looks file you use the .mkdirs()
method on a File
object: http://www.roseindia.net/java/beginners/java-create-directory.shtml
// Create a directory; all non-existent ancestor directories are
// automatically created
success = (new File("../potentially/long/pathname/without/all/dirs")).mkdirs();
if (!success) {
// Directory creation failed
}
Depends what it is that you're trying to do it with. You could use something like this:
echo "<a href=\"javascript:history.go(-1)\">GO BACK</a>";
That's the simplest option. The other poster is right about having a proper flow of history but this is an example for you.
Just edited, orig version wasn't indented and looked like nothing. ;)
Changed the set to remove % as that will write to text file as Echo on or off
echo off
title Custom Text File
cls
set /p txt=What do you want it to say? ;
echo %txt% > "D:\Testing\dblank.txt"
exit
See Class Constants:
class MyClass
{
const MYCONSTANT = 'constant value';
function showConstant() {
echo self::MYCONSTANT. "\n";
}
}
echo MyClass::MYCONSTANT. "\n";
$classname = "MyClass";
echo $classname::MYCONSTANT. "\n"; // As of PHP 5.3.0
$class = new MyClass();
$class->showConstant();
echo $class::MYCONSTANT."\n"; // As of PHP 5.3.0
In this case echoing MYCONSTANT
by itself would raise a notice about an undefined constant and output the constant name converted to a string: "MYCONSTANT"
.
EDIT - Perhaps what you're looking for is this static properties / variables:
class MyClass
{
private static $staticVariable = null;
public static function showStaticVariable($value = null)
{
if ((is_null(self::$staticVariable) === true) && (isset($value) === true))
{
self::$staticVariable = $value;
}
return self::$staticVariable;
}
}
MyClass::showStaticVariable(); // null
MyClass::showStaticVariable('constant value'); // "constant value"
MyClass::showStaticVariable('other constant value?'); // "constant value"
MyClass::showStaticVariable(); // "constant value"
The answer given here works for some MVC versions but not for others.
The simple solution worked for MVC1 but on upgrading to MVC2 the views were no longer being compliled. This was due to a bug in the website project files. See this Haacked article.
See this: http://haacked.com/archive/2011/05/09/compiling-mvc-views-in-a-build-environment.aspx
It is completely fine to leave memory unfreed when you exit; malloc() allocates the memory from the memory area called "the heap", and the complete heap of a process is freed when the process exits.
That being said, one reason why people still insist that it is good to free everything before exiting is that memory debuggers (e.g. valgrind on Linux) detect the unfreed blocks as memory leaks, and if you have also "real" memory leaks, it becomes more difficult to spot them if you also get "fake" results at the end.
So basically you want to find a file in mounted filesystem (not necessarily in PATH directories only) and check if it is executable. This translates to following plan:
I'd say, doing this in a portable way will require lots of computing power and time. Is it really what you need?
var firstObjectsOfValues = (from d in dic select d.Value[0].ComponentValue("Dep"));
Indeed, as has been mentioned above (and elsewhere on SO), in order to convert the string to a date, you need a specific date of the month. From the as.Date()
manual page:
If the date string does not specify the date completely, the returned answer may be system-specific. The most common behaviour is to assume that a missing year, month or day is the current one. If it specifies a date incorrectly, reliable implementations will give an error and the date is reported as NA. Unfortunately some common implementations (such as
glibc
) are unreliable and guess at the intended meaning.
A simple solution would be to paste the date "01"
to each date and use strptime()
to indicate it as the first day of that month.
For those seeking a little more background on processing dates and times in R:
In R, times use POSIXct
and POSIXlt
classes and dates use the Date
class.
Dates are stored as the number of days since January 1st, 1970 and times are stored as the number of seconds since January 1st, 1970.
So, for example:
d <- as.Date("1971-01-01")
unclass(d) # one year after 1970-01-01
# [1] 365
pct <- Sys.time() # in POSIXct
unclass(pct) # number of seconds since 1970-01-01
# [1] 1450276559
plt <- as.POSIXlt(pct)
up <- unclass(plt) # up is now a list containing the components of time
names(up)
# [1] "sec" "min" "hour" "mday" "mon" "year" "wday" "yday" "isdst" "zone"
# [11] "gmtoff"
up$hour
# [1] 9
To perform operations on dates and times:
plt - as.POSIXlt(d)
# Time difference of 16420.61 days
And to process dates, you can use strptime()
(borrowing these examples from the manual page):
strptime("20/2/06 11:16:16.683", "%d/%m/%y %H:%M:%OS")
# [1] "2006-02-20 11:16:16 EST"
# And in vectorized form:
dates <- c("1jan1960", "2jan1960", "31mar1960", "30jul1960")
strptime(dates, "%d%b%Y")
# [1] "1960-01-01 EST" "1960-01-02 EST" "1960-03-31 EST" "1960-07-30 EDT"
Multiple generic constraints can't be combined in an OR fashion (less restrictive), only in an AND fashion (more restrictive). Meaning that one method can't handle both scenarios. The generic constraints also cannot be used to make a unique signature for the method, so you'd have to use 2 separate method names.
However, you can use the generic constraints to make sure that the methods are used correctly.
In my case, I specifically wanted null to be returned, and never the default value of any possible value types. GetValueOrDefault = bad. GetValueOrNull = good.
I used the words "Null" and "Nullable" to distinguish between reference types and value types. And here is an example of a couple extension methods I wrote that compliments the FirstOrDefault method in System.Linq.Enumerable class.
public static TSource FirstOrNull<TSource>(this IEnumerable<TSource> source)
where TSource: class
{
if (source == null) return null;
var result = source.FirstOrDefault(); // Default for a class is null
return result;
}
public static TSource? FirstOrNullable<TSource>(this IEnumerable<TSource?> source)
where TSource : struct
{
if (source == null) return null;
var result = source.FirstOrDefault(); // Default for a nullable is null
return result;
}
You can try this for DataGrid:
DataGridCellInfo cellInfo = new DataGridCellInfo(myDataGrid.Items[colRow], myDataGrid.Columns[colNum]);
DataGridCell cellToFocus = (DataGridCell)cellInfo.Column.GetCellContent(cellInfo.Item).Parent;
ViewControlHelper.SetFocus(cellToFocus, e);
Restarting ADB server works for me, but no need to go for it from command line.
Ctrl + Maj + A -> Troubleshoot Device Connections -> Next -> Next -> Restart ADB Server
For example, your remote host is example.com and remote login name is user1:
scp [email protected]:/path/to/file /path/to/store/file
There is a new player in the field, offering advanced Navigation Charts that are using Canvas for super-smooth animations and performance:
Example of charts:
Documentation: https://zoomcharts.com/en/javascript-charts-library/charts-packages/pie-chart/
What is cool about this lib:
Charts are free for non-commercial use, commercial licenses and technical support available as well.
Also interactive Time charts and Net Charts are there for you to use.
Charts come with extensive API and Settings, so you can control every aspect of the charts.
Without the need of an external package:
if your date is in the following format:
myDate = as.POSIXct("2013-01-01")
Then to get the month number:
format(myDate,"%m")
And to get the month string:
format(myDate,"%B")
Now you can do it like so (you do not need to go to github or open new directory from git):
In the past (i.e. WinXP days), I used to depend/rely on DLL Dependency Walker (depends.exe) but there are times when I am still not able to determine the DLL issue(s). Ideally, we'd like to find out before runtime by inspections but if that does not resolve it (or taking too much time), you can try enabling the "loader snap" as described on http://blogs.msdn.com/b/junfeng/archive/2006/11/20/debugging-loadlibrary-failures.aspx and https://msdn.microsoft.com/en-us/library/windows/hardware/ff556886(v=vs.85).aspx and briefly mentioned LoadLibrary fails; GetLastError no help
WARNING: I've messed up my Windows in the past fooling around with gflag making it crawl to its knees, you have been forewarned.
Note: "Loader snap" is per-process so the UI enable won't stay checked (use cdb or glfags -i)
From the page you referenced:
When you raise Http404 from within a view, Django will load a special view devoted to handling 404 errors. It finds it by looking for the variable handler404 in your root URLconf (and only in your root URLconf; setting handler404 anywhere else will have no effect), which is a string in Python dotted syntax – the same format the normal URLconf callbacks use. A 404 view itself has nothing special: It’s just a normal view.
So I believe you need to add something like this to your urls.py:
handler404 = 'views.my_404_view'
and similar for handler500.
Meet same Issue on one mac, but ok on another mac. I'm sure bundle ID is fine and unique.
I know it is provisioning profile issue, so Try refreshing the provisioning profile on your Local computer. Then It Works!
cd ~/Library/MobileDevice/Provisioning\ Profiles
rm *
Download Manual Profiles
The be-all-end-all, for no selecting or dragging, with all browser prefixes:
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
-ms-user-select: none;
user-select: none;
-webkit-user-drag: none;
-khtml-user-drag: none;
-moz-user-drag: none;
-o-user-drag: none;
-ms-user-drag: none;
user-drag: none;
You can also set the draggable
attribute to false
. You can do this with inline HTML: draggable="false"
, with Javascript: elm.draggable = false
, or with jQuery: elm.attr('draggable', false)
.
You can also handle the onmousedown
function to return false
. You can do this with inline HTML: onmousedown="return false"
, with Javascript: elm.onmousedown=()=>return false;
, or with jQuery: elm.mousedown(()=>return false)
The way to store dates in SQLite is:
yyyy-mm-dd hh:mm:ss.xxxxxx
SQLite also has some date and time functions you can use. See SQL As Understood By SQLite, Date And Time Functions.
select D.DeptName from [Department] D where D.DeptID in
(
select E.DeptId from [Employee] E
where E.Salary > 1000
group by E.DeptId
having count(*) > 2
)
You can define a method in spec_helper.rb that sends a message both to Rails.logger.info and to puts and use that for debugging:
def log_test(message)
Rails.logger.info(message)
puts message
end
Assuming that you know that the root elements are zero, here's the pseudocode to output to text:
function PrintLevel (int curr, int level)
//print the indents
for (i=1; i<=level; i++)
print a tab
print curr \n;
for each child in the table with a parent of curr
PrintLevel (child, level+1)
for each elementID where the parentid is zero
PrintLevel(elementID, 0)
You could use inline styles and define the width in the <th>
tag. Make it so that the sum of the widths = 100%.
<tr>
<th style="width:10%">Size</th>
<th style="width:30%">Bust</th>
<th style="width:50%">Waist</th>
<th style="width:10%">Hips</th>
</tr>
Typically using inline styles is not ideal, however this does provide flexibility because you can get very specific and granular with exact widths.
Have you tried adding a configsection
handler to your app.config? e.g.
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
If you want to get request path (more info):
echo parse_url($_SERVER["REQUEST_URI"])['path']
If you want to remove the query and (and maybe fragment also):
function strposa($haystack, $needles=array(), $offset=0) {
$chr = array();
foreach($needles as $needle) {
$res = strpos($haystack, $needle, $offset);
if ($res !== false) $chr[$needle] = $res;
}
if(empty($chr)) return false;
return min($chr);
}
$i = strposa($_SERVER["REQUEST_URI"], ['#', '?']);
echo strrpos($_SERVER["REQUEST_URI"], 0, $i);
Swift 4+
You can use simplified regex "^[6-9]\\d{9}$"
^ #Match the beginning of the string
[6-9] #Match a 6, 7, 8 or 9
\\d #Match a digit (0-9 and anything else that is a "digit" in the regex engine)
{9} #Repeat the previous "\d" 9 times (9 digits)
$ #Match the end of the string
Indian 10 Digit Mobile validation(can start with 6,7,8,9) -
extension String {
var isValidContact: Bool {
let phoneNumberRegex = "^[6-9]\\d{9}$"
let phoneTest = NSPredicate(format: "SELF MATCHES %@", phoneNumberRegex)
let isValidPhone = phoneTest.evaluate(with: self)
return isValidPhone
}
}
Usage:-
print("9292929292".isValidContact)//true
print("5454545454".isValidContact)//false
For email validation you can check this
You can use jade + express:
app.get('/', function (req, res) { res.render('index', { title : 'Home' } ) });
above you see 'index' and an object {title : 'Home'}, 'index' is your html and the object is your data that will be rendered in your html.
Here's what I've found. If you want an app to open on your secondary monitor by default do the following:
1. Open the application.
2. Re-size the window so that it is not maximized or minimized.
3. Move the window to the monitor you want it to open on by default.
4. Close the application. Do not re-size prior to closing.
5. Open the application.
It should open on the monitor you just moved it to and closed it on.
6. Maximize the window.
The application will now open on this monitor by default. If you want to change it to another monitor, just follow steps 1-6 again.
You can use the following class. Just change zero to any default value you like. The solution was tested in Python 2.7.
class cDefaultDict(dict):
# dictionary that returns zero for missing keys
# keys with zero values are not stored
def __missing__(self,key):
return 0
def __setitem__(self, key, value):
if value==0:
if key in self: # returns zero anyway, so no need to store it
del self[key]
else:
dict.__setitem__(self, key, value)
I know this question is 4-5 years old, but still, this might be useful:
Sometimes, if you have only a few elements that "exit the screen", the list might not scroll. That's because the operating system doesn't view it as actually exceeding the screen.
I'm saying this because I ran into this problem today - I only had 2 or 3 elements that were exceeding the screen limits, and my list wasn't scrollable. And it was a real mystery. As soon as I added a few more, it started to scroll.
So you have to make sure it's not a design problem at first, like the list appearing to go beyond the borders of the screen but in reality, "it doesn't", and adjust its dimensions and margin values and see if it's starting to "become scrollable". It did, for me.
It's the default formatting that Oracle provides. If you want leading zeros on output, you'll need to explicitly provide the format. Use:
SELECT TO_CHAR(0.56,'0.99') FROM DUAL;
or even:
SELECT TO_CHAR(.56,'0.99') FROM DUAL;
The same is true for trailing zeros:
SQL> SELECT TO_CHAR(.56,'0.990') val FROM DUAL;
VAL
------
0.560
The general form of the TO_CHAR conversion function is:
One [very] hacky way to do it (I saw it work for version 4.0.3):
var selection = $("#DelegateId").data("select2").selection;
var evt = document.createEvent("UIEvents");
selection._handleClear(evt);
selection.trigger("toggle", {});
If you use Packer, just go far the 'shrink variables' option and gzip the resulting code. The base62 option is only for if your server cannot send gzipped files. Packer with 'shrink vars' achieves better compression the YUI, but can introduce bugs if you've skipped a semicolon somewhere.
base62 is basically a poor man's gzip, which is why gzipping base62-ed code gives you bigger files than gzipping shrink-var-ed code.
You did not add #
before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.
See documentation: http://api.jquery.com/category/selectors/
its your friend.
Try this:
It seems that id: $("#Shareitem").val()
is wrong if you want to pass the value of
<input type="hidden" name="id" value="" id="id">
you need to change this line:
id: $("#Shareitem").val()
by
id: $("#id").val()
All together:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function(){
$("#Shareitem").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "/imball-reagens/public/shareitem",
data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
success:function(result){
$("#sharelink").html(result);
}});
});
});
</script>
bool
is just a macro that expands to _Bool
. You can use _Bool
with no #include
very much like you can use int
or double
; it is a C99 keyword.
The macro is defined in <stdbool.h>
along with 3 other macros.
The macros defined are
bool
: macro expands to _Bool
false
: macro expands to 0
true
: macro expands to 1
__bool_true_false_are_defined
: macro expands to 1
from
a directory_of_modules
, you can import
a specific_module.py
specific_module.py
, can contain a Class
with some_methods()
or just functions()
specific_module.py
, you can instantiate a Class
or call functions()
Class
, you can execute some_method()
Example:
#!/usr/bin/python3
from directory_of_modules import specific_module
instance = specific_module.DbConnect("username","password")
instance.login()
Excerpts from PEP 8 - Style Guide for Python Code:
Modules should have short and all-lowercase names.
Notice: Underscores can be used in the module name if it improves readability.
A Python module is simply a source file(*.py), which can expose:
Class: names using the "CapWords" convention.
Function: names in lowercase, words separated by underscores.
Global Variables: the conventions are about the same as those for Functions.
You can execute this in 2 simple statements:
row.names(samp) <- samp$names
samp[1] <- NULL
While Hash#has_key?
gets the job done, as Matz notes here, it has been deprecated in favour of Hash#key?
.
hash.key?(some_key)
You can use also this without creating additional variables nor copying the data in the memory like foreach() does.
while (false !== (list($item, $values) = each($array)))
{
...
}
@Html.DropDownListFor(m => m.SelectedValue,Your List,"ID","Values")
Here Value is that object of model where you want to save your Selected Value
Put very simple ::
is the scoping operator, .
is the access operator (I forget what the actual name is?), and ->
is the dereference arrow.
::
- Scopes a function. That is, it lets the compiler know what class the function lives in and, thus, how to call it. If you are using this operator to call a function, the function is a static
function.
.
- This allows access to a member function on an already created object. For instance, Foo x; x.bar()
calls the method bar()
on instantiated object x
which has type Foo
. You can also use this to access public class variables.
->
- Essentially the same thing as .
except this works on pointer types. In essence it dereferences the pointer, than calls .
. Using this is equivalent to (*ptr).method()
With text type of input you can use this for a better validation,
return (event.keyCode? (event.keyCode == 69 ? false : event.keyCode >= 48 && event.keyCode <= 57) : (event.charCode >= 48 && event.charCode <= 57))? true : event.preventDefault();
No, how you are doing it is correct.
http://www.w3.org/MarkUp/html-spec/html-spec_8.html#SEC8.2.2
select sysdate from dual
30-MAR-17
select count(1) from masterdata where to_date(inactive_from_date,'DD-MON-YY'
between '01-JAN-16' to '31-DEC-16'
12998 rows
//In order to get yesterday's date in mm/dd/yyyy.
function gimmeYesterday(toAdd) {
if (!toAdd || toAdd == '' || isNaN(toAdd)) return;
var d = new Date();
d.setDate(d.getDate() - parseInt(toAdd));
var yesterDAY = (d.getMonth() +1) + "/" + d.getDate() + "/" + d.getFullYear();
$("#endDate").html(yesterDAY);
}
$(document).ready(function() {
gimmeYesterday(1);
});
you can try here: http://jsfiddle.net/ZQAHE/
Add this one to your header file:
template <typename T> vector<T> concat(vector<T> &a, vector<T> &b) {
vector<T> ret = vector<T>();
copy(a.begin(), a.end(), back_inserter(ret));
copy(b.begin(), b.end(), back_inserter(ret));
return ret;
}
and use it this way:
vector<int> a = vector<int>();
vector<int> b = vector<int>();
a.push_back(1);
a.push_back(2);
b.push_back(62);
vector<int> r = concat(a, b);
r will contain [1,2,62]
Use distinct-colors.
Written in javascript.
It generates a palette of visually distinct colors.
distinct-colors is highly configurable:
A PROGRAM TO CONVERT INT INTO ASCII.
#include<stdio.h>
#include<string.h>
#include<conio.h>
char data[1000]= {' '}; /*thing in the bracket is optional*/
char data1[1000]={' '};
int val, a;
char varray [9];
void binary (int digit)
{
if(digit==0)
val=48;
if(digit==1)
val=49;
if(digit==2)
val=50;
if(digit==3)
val=51;
if(digit==4)
val=52;
if(digit==5)
val=53;
if(digit==6)
val=54;
if(digit==7)
val=55;
if(digit==8)
val=56;
if(digit==9)
val=57;
a=0;
while(val!=0)
{
if(val%2==0)
{
varray[a]= '0';
}
else
varray[a]='1';
val=val/2;
a++;
}
while(a!=7)
{
varray[a]='0';
a++;
}
varray [8] = NULL;
strrev (varray);
strcpy (data1,varray);
strcat (data1,data);
strcpy (data,data1);
}
void main()
{
int num;
clrscr();
printf("enter number\n");
scanf("%d",&num);
if(num==0)
binary(0);
else
while(num>0)
{
binary(num%10);
num=num/10;
}
puts(data);
getch();
}
I check my coding and its working good.let me know if its helpful.thanks.
You can use setState
inside componentDidUpdate
. The problem is that somehow you are creating an infinite loop because there's no break condition.
Based on the fact that you need values that are provided by the browser once the component is rendered, I think your approach about using componentDidUpdate
is correct, it just needs better handling of the condition that triggers the setState
.
if you have "scattered" (not inside an array) values you can use:
var max_value = Math.max(val1, val2, val3, val4, val5);
Run the script as source= to run in debug mode as well.
source= ./myscript.sh
It's not a direct answer to the question but you could just use the OR-operator
( grep "#SystemMaxUse=" journald.conf > /dev/null && sed -i 's/\#SystemMaxUse=/SystemMaxUse=50M/g' journald.conf ) || echo "This file has been edited. You'll need to do it manually."
Groupby can helps you:
grouped = data.groupby(['name'])
Then you can work with each group like with a dataframe for each participant. And DataFrameGroupBy object methods such as (apply, transform, aggregate, head, first, last) return a DataFrame object.
Or you can make list from grouped
and get all DataFrame's by index:
l_grouped = list(grouped)
l_grouped[0][1]
- DataFrame for first group with first name.
Try the maven-exec-plugin. From there:
mvn exec:java -Dexec.mainClass="com.example.Main"
This will run your class in the JVM. You can use -Dexec.args="arg0 arg1"
to pass arguments.
If you're on Windows, apply quotes for
exec.mainClass
andexec.args
:mvn exec:java -D"exec.mainClass"="com.example.Main"
If you're doing this regularly, you can add the parameters into the pom.xml as well:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<mainClass>com.example.Main</mainClass>
<arguments>
<argument>foo</argument>
<argument>bar</argument>
</arguments>
</configuration>
</plugin>
Based on the following plunk, consider the following HTML markup:
<body>
<div log='some-div'></div>
</body>
With the following directive declaration:
myApp.directive('log', function() {
return {
controller: function( $scope, $element, $attrs, $transclude ) {
console.log( $attrs.log + ' (controller)' );
},
compile: function compile( tElement, tAttributes ) {
console.log( tAttributes.log + ' (compile)' );
return {
pre: function preLink( scope, element, attributes ) {
console.log( attributes.log + ' (pre-link)' );
},
post: function postLink( scope, element, attributes ) {
console.log( attributes.log + ' (post-link)' );
}
};
}
};
});
The console output will be:
some-div (compile)
some-div (controller)
some-div (pre-link)
some-div (post-link)
We can see that compile
is executed first, then controller
, then pre-link
and last is post-link
.
Note: The following does not apply to directives that render their children in their link function. Quite a few Angular directives do so (like ngIf, ngRepeat, or any directive with
transclude
). These directives will natively have theirlink
function called before their child directivescompile
is called.
The original HTML markup is often made of nested elements, each with its own directive. Like in the following markup (see plunk):
<body>
<div log='parent'>
<div log='..first-child'></div>
<div log='..second-child'></div>
</div>
</body>
The console output will look like this:
// The compile phase
parent (compile)
..first-child (compile)
..second-child (compile)
// The link phase
parent (controller)
parent (pre-link)
..first-child (controller)
..first-child (pre-link)
..first-child (post-link)
..second-child (controller)
..second-child (pre-link)
..second-child (post-link)
parent (post-link)
We can distinguish two phases here - the compile phase and the link phase.
When the DOM is loaded Angular starts the compile phase, where it traverses the markup top-down, and calls compile
on all directives. Graphically, we could express it like so:
It is perhaps important to mention that at this stage, the templates the compile function gets are the source templates (not instance template).
DOM instances are often simply the result of a source template being rendered to the DOM, but they may be created by ng-repeat
, or introduced on the fly.
Whenever a new instance of an element with a directive is rendered to the DOM, the link phase starts.
In this phase, Angular calls controller
, pre-link
, iterates children, and call post-link
on all directives, like so:
I'm using this code, pretty good. You will very easy to know user-agents visitted your site. This code is opening a file and write the user_agent down the file. You can check each day this file by go to yourdomain.com/useragent.txt
and know about new user_agents and put them in your condition of if clause.
$user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
if(!preg_match("/Googlebot|MJ12bot|yandexbot/i", $user_agent)){
// if not meet the conditions then
// do what you need
// here open a file and write the user_agent down the file. You can check each day this file useragent.txt and know about new user_agents and put them in your condition of if clause
if($user_agent!=""){
$myfile = fopen("useragent.txt", "a") or die("Unable to open file useragent.txt!");
fwrite($myfile, $user_agent);
$user_agent = "\n";
fwrite($myfile, $user_agent);
fclose($myfile);
}
}
This is the content of useragent.txt
Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)
Mozilla/5.0 (compatible; MJ12bot/v1.4.6; http://mj12bot.com/)Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)
Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)mozilla/5.0 (compatible; yandexbot/3.0; +http://yandex.com/bots)
mozilla/5.0 (compatible; yandexbot/3.0; +http://yandex.com/bots)
mozilla/5.0 (compatible; yandexbot/3.0; +http://yandex.com/bots)
mozilla/5.0 (compatible; yandexbot/3.0; +http://yandex.com/bots)
mozilla/5.0 (compatible; yandexbot/3.0; +http://yandex.com/bots)
mozilla/5.0 (iphone; cpu iphone os 9_3 like mac os x) applewebkit/601.1.46 (khtml, like gecko) version/9.0 mobile/13e198 safari/601.1
mozilla/5.0 (windows nt 6.1; wow64) applewebkit/537.36 (khtml, like gecko) chrome/53.0.2785.143 safari/537.36
mozilla/5.0 (compatible; linkdexbot/2.2; +http://www.linkdex.com/bots/)
mozilla/5.0 (windows nt 6.1; wow64; rv:49.0) gecko/20100101 firefox/49.0
mozilla/5.0 (windows nt 6.1; wow64; rv:33.0) gecko/20100101 firefox/33.0
mozilla/5.0 (windows nt 6.1; wow64; rv:49.0) gecko/20100101 firefox/49.0
mozilla/5.0 (windows nt 6.1; wow64; rv:33.0) gecko/20100101 firefox/33.0
mozilla/5.0 (windows nt 6.1; wow64; rv:49.0) gecko/20100101 firefox/49.0
mozilla/5.0 (windows nt 6.1; wow64; rv:33.0) gecko/20100101 firefox/33.0
mozilla/5.0 (windows nt 6.1; wow64; rv:49.0) gecko/20100101 firefox/49.0
mozilla/5.0 (windows nt 6.1; wow64; rv:33.0) gecko/20100101 firefox/33.0
mozilla/5.0 (windows nt 6.1; wow64) applewebkit/537.36 (khtml, like gecko) chrome/53.0.2785.143 safari/537.36
mozilla/5.0 (windows nt 6.1; wow64) applewebkit/537.36 (khtml, like gecko) chrome/53.0.2785.143 safari/537.36
mozilla/5.0 (compatible; baiduspider/2.0; +http://www.baidu.com/search/spider.html)
zoombot (linkbot 1.0 http://suite.seozoom.it/bot.html)
mozilla/5.0 (windows nt 10.0; wow64) applewebkit/537.36 (khtml, like gecko) chrome/44.0.2403.155 safari/537.36 opr/31.0.1889.174
mozilla/5.0 (windows nt 10.0; wow64) applewebkit/537.36 (khtml, like gecko) chrome/44.0.2403.155 safari/537.36 opr/31.0.1889.174
sogou web spider/4.0(+http://www.sogou.com/docs/help/webmasters.htm#07)
mozilla/5.0 (windows nt 10.0; wow64) applewebkit/537.36 (khtml, like gecko) chrome/44.0.2403.155 safari/537.36 opr/31.0.1889.174
How to select all children of an element except the last child using CSS?
Answer: this code will work
<style>
.parent *:not(:last-child) {
color:red;
}
</style>
<div class='parent'>
<p>this is paragraph</p>
<h1>this is heading</h1>
<b>text is bold</b>
</div>
We wrote a CLI tool for this purpose: docker-ls It allows you to browse a docker registry and supports authentication via token or basic auth.
I'm suggest that you learn about Jquery, most popular JS library. With jquery it's simple to acomplish what you want.Simle example below:
$(“#DIV_YOU_WANT_CHANGE”).click(function() {
$(this).addClass(“.your_class_with_new_color”);
});
I use if (ptr)
, but this is completely not worth arguing about.
I like my way because it's concise, though others say == NULL
makes it easier to read and more explicit. I see where they're coming from, I just disagree the extra stuff makes it any easier. (I hate the macro, so I'm biased.) Up to you.
I disagree with your argument. If you're not getting warnings for assignments in a conditional, you need to turn your warning levels up. Simple as that. (And for the love of all that is good, don't switch them around.)
Note in C++0x, we can do if (ptr == nullptr)
, which to me does read nicer. (Again, I hate the macro. But nullptr
is nice.) I still do if (ptr)
, though, just because it's what I'm used to.
I created a Eclipse plugin, which can count the lines of source code. It support Kotlin, Java, Java Script, JSP, XML, C/C++, C#, and many other file types.
Please take a look at it. Any feedback would be appreciated!
You can use ScriptEngine, example:
public class Main {
public static void main(String[] args) {
StringBuffer javascript = null;
ScriptEngine runtime = null;
try {
runtime = new ScriptEngineManager().getEngineByName("javascript");
javascript = new StringBuffer();
javascript.append("1 + 1");
double result = (Double) runtime.eval(javascript.toString());
System.out.println("Result: " + result);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
The cleanest solution is probably to specify your divs as exact children.
Try changing this:
div.rounded div div {
background: url('bl.gif') no-repeat bottom left;
}
To this:
div.rounded > div > div {
background: url('bl.gif') no-repeat bottom left;
}
You can try the %v
, %+v
or %#v
verbs of go fmt:
fmt.Printf("%v", projects)
If your array (or here slice) contains struct
(like Project
), you will see their details.
For more precision, you can use %#v
to print the object using Go-syntax, as for a literal:
%v the value in a default format.
when printing structs, the plus flag (%+v) adds field names
%#v a Go-syntax representation of the value
For basic types, fmt.Println(projects)
is enough.
Note: for a slice of pointers, that is []*Project
(instead of []Project
), you are better off defining a String()
method in order to display exactly what you want to see (or you will see only pointer address).
See this play.golang example.
Here is the puppet script with all the available puppet log functions.
node default {
notice("try to run this script with -v and -d to see difference between log levels")
notice("function documentation is available here: http://docs.puppetlabs.com/references/latest/function.html")
notice("--------------------------------------------------------------------------")
debug("this is debug. visible only with -d or --debug")
info("this is info. visible only with -v or --verbose or -d or --debug")
alert("this is alert. always visible")
crit("this is crit. always visible")
emerg("this is emerg. always visible")
err("this is err. always visible")
warning("and this is warning. always visible")
notice("this is notice. always visible")
#fail will break execution
fail("this is fail. always visible. fail will break execution process")
}
Script output (on puppet 2.7):
NB: puppet 3.x colours may alter (all the errors will be printed in red)!
As @user786653 suggested, use the xxd(1)
program:
xxd -r -p input.txt output.bin
Since hashes aren't inherently ordered, there isn't a notion of appending. Ruby hashes since 1.9 maintain insertion order, however. Here are the ways to add new key/value pairs.
The simplest solution is
h[:key] = "bar"
If you want a method, use store
:
h.store(:key, "bar")
If you really, really want to use a "shovel" operator (<<
), it is actually appending to the value of the hash as an array, and you must specify the key:
h[:key] << "bar"
The above only works when the key exists. To append a new key, you have to initialize the hash with a default value, which you can do like this:
h = Hash.new {|h, k| h[k] = ''}
h[:key] << "bar"
You may be tempted to monkey patch Hash to include a shovel operator that works in the way you've written:
class Hash
def <<(k,v)
self.store(k,v)
end
end
However, this doesn't inherit the "syntactic sugar" applied to the shovel operator in other contexts:
h << :key, "bar" #doesn't work
h.<< :key, "bar" #works
Your best option is to call System.gc()
which simply is a hint to the garbage collector that you want it to do a collection. There is no way to force and immediate collection though as the garbage collector is non-deterministic.
Taken from @EvenMien and added in some of the comments. (Also for my own use case)
public struct AgentAction
{
private AgentAction(string value) { Value = value; }
public string Value { get; private set; }
public override string ToString()
{
return this.Value;
}
public static AgentAction Login = new AgentAction("Logout");
public static AgentAction Logout = new AgentAction("Logout");
public static implicit operator string(AgentAction action) { return action.ToString(); }
}
Try this on your TA:
# Simulate multiplying two N-bit two's-complement numbers
# into a 2N-bit accumulator
# Use shift-add so that it's O(base_2_log(N)) not O(N)
for numa, numb in ((3, 5), (-3, 5), (3, -5), (-3, -5), (-127, -127)):
print numa, numb,
accum = 0
negate = False
if numa < 0:
negate = True
numa = -numa
while numa:
if numa & 1:
accum += numb
numa >>= 1
numb <<= 1
if negate:
accum = -accum
print accum
output:
3 5 15
-3 5 -15
3 -5 -15
-3 -5 15
-127 -127 16129
Try
string reversed(temp.rbegin(), temp.rend());
EDIT: Elaborating as requested.
string::rbegin()
and string::rend()
, which stand for "reverse begin" and "reverse end" respectively, return reverse iterators into the string. These are objects supporting the standard iterator interface (operator*
to dereference to an element, i.e. a character of the string, and operator++
to advance to the "next" element), such that rbegin()
points to the last character of the string, rend()
points to the first one, and advancing the iterator moves it to the previous character (this is what makes it a reverse iterator).
Finally, the constructor we are passing these iterators into is a string constructor of the form:
template <typename Iterator>
string(Iterator first, Iterator last);
which accepts a pair of iterators of any type denoting a range of characters, and initializes the string to that range of characters.
The Main
method is Static. You can not invoke a non-static method from a static method.
GetRandomBits()
is not a static method. Either you have to create an instance of Program
Program p = new Program();
p.GetRandomBits();
or make
GetRandomBits()
static.
You did not described the environment, anyway, you should download apache poi libraries. If you are using eclipse , right click on your root project , so properties and in java build path add external jar and import in your project those libraries :
xmlbeans-2.6.0 ; poi-ooxml-schemas- ... ; poi-ooxml- ... ; poi- .... ;
Use this function:
inline bool ends_with(std::string const & value, std::string const & ending)
{
if (ending.size() > value.size()) return false;
return std::equal(ending.rbegin(), ending.rend(), value.rbegin());
}
It seems like you want barplot(prop.table(table(animals)))
:
However, this is not a histogram.
Only using Session.Clear() when a user logs out can pose a security hole. As the session is still valid as far as the Web Server is concerned. It is then a reasonably trivial matter to sniff, and grab the session Id, and hijack that session.
For this reason, when logging a user out it would be safer and more sensible to use Session.Abandon() so that the session is destroyed, and a new session created (even though the logout UI page would be part of the new session, the new session would not have any of the users details in it and hijacking the new session would be equivalent to having a fresh session, hence it would be mute).
PowerShell has built-in XML and XPath functions. You can use the Select-Xml cmdlet with an XPath query to select nodes from XML object and then .Node.'#text' to access node value.
[xml]$xml = Get-Content $serviceStatePath
$nodes = Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml
$nodes | ForEach-Object {$_.Node.'#text'}
Or shorter
[xml]$xml = Get-Content $serviceStatePath
Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml |
% {$_.Node.'#text'}
Maybe something like this, where you could select more than one element if you'd like?
$("#number").each(function(){
$(this).val(parseFloat($(this).val()).toFixed(2));
});
For anyone else that comes across this post and might find it useful... There is actually nothing wrong with my code. I made the mistake of requesting client_credentials type access code instead of password access code (#facepalms). FYI I am using urlencoded post hence the use of querystring.. So for those that may be looking for some example code.. here is my full request
Big thanks to @swapnil for trying to help me debug this.
const data = {
grant_type: USER_GRANT_TYPE,
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
scope: SCOPE_INT,
username: DEMO_EMAIL,
password: DEMO_PASSWORD
};
axios.post(TOKEN_URL, Querystring.stringify(data))
.then(response => {
console.log(response.data);
USER_TOKEN = response.data.access_token;
console.log('userresponse ' + response.data.access_token);
})
.catch((error) => {
console.log('error ' + error);
});
const AuthStr = 'Bearer '.concat(USER_TOKEN);
axios.get(URL, { headers: { Authorization: AuthStr } })
.then(response => {
// If request is good...
console.log(response.data);
})
.catch((error) => {
console.log('error ' + error);
});
you can use the below to list files by size du -h | sort -hr | more or du -h --max-depth=0 * | sort -hr | more
Use the following query:
SELECT E.I_EmpID AS EMPID,
E.I_EMPCODE AS EMPCODE,
E.I_EmpName AS EMPNAME,
REPLACE(TO_CHAR(A.I_REQDATE, 'DD-Mon-YYYY'), ' ', '') AS FROMDATE,
REPLACE(TO_CHAR(A.I_ENDDATE, 'DD-Mon-YYYY'), ' ', '') AS TODATE,
TO_CHAR(NOD) AS NOD,
DECODE(A.I_DURATION,
'FD',
'FullDay',
'FN',
'ForeNoon',
'AN',
'AfterNoon') AS DURATION,
L.I_LeaveType AS LEAVETYPE,
REPLACE(TO_CHAR((SELECT max(C.I_WORKDATE)
FROM T_COMPENSATION C
WHERE C.I_COMPENSATEDDATE = A.I_REQDATE
AND C.I_EMPID = A.I_EMPID),
'DD-Mon-YYYY'),
' ',
'') AS WORKDATE,
A.I_REASON AS REASON,
AP.I_REJECTREASON AS REJECTREASON
FROM T_LEAVEAPPLY A
INNER JOIN T_EMPLOYEE_MS E
ON A.I_EMPID = E.I_EmpID
AND UPPER(E.I_IsActive) = 'YES'
AND A.I_STATUS = '1'
INNER JOIN T_LeaveType_MS L
ON A.I_LEAVETYPEID = L.I_LEAVETYPEID
LEFT OUTER JOIN T_APPROVAL AP
ON A.I_REQDATE = AP.I_REQDATE
AND A.I_EMPID = AP.I_EMPID
AND AP.I_APPROVALSTATUS = '1'
WHERE E.I_EMPID <> '22'
ORDER BY A.I_REQDATE DESC
The trick is to force the inner query return only one record by adding an aggregate function (I have used max() here). This will work perfectly as far as the query is concerned, but, honestly, OP should investigate why the inner query is returning multiple records by examining the data. Are these multiple records really relevant business wise?
Simply
$os = array("Mac", "NT", "Irix", "Linux");
if (!in_array("BB", $os)) {
echo "BB is not found";
}
you can use this code in your css file:
-webkit-top:9px;
-moz-top:7px;
top:5px;
the code -webkit-top:9px; is for chrome, -moz-top:7px is for mozilla and the last one is for IE. Have Fun!!!
They evaluate the data in the tables underlying the view definition at the time the view is queried. It is a logical view of your tables, with no data stored anywhere else.
The upside of a view is that it will always return the latest data to you. The downside of a view is that its performance depends on how good a select statement the view is based on. If the select statement used by the view joins many tables, or uses joins based on non-indexed columns, the view could perform poorly.
They are similar to regular views, in that they are a logical view of your data (based on a select statement), however, the underlying query result set has been saved to a table. The upside of this is that when you query a materialized view, you are querying a table, which may also be indexed.
In addition, because all the joins have been resolved at materialized view refresh time, you pay the price of the join once (or as often as you refresh your materialized view), rather than each time you select from the materialized view. In addition, with query rewrite enabled, Oracle can optimize a query that selects from the source of your materialized view in such a way that it instead reads from your materialized view. In situations where you create materialized views as forms of aggregate tables, or as copies of frequently executed queries, this can greatly speed up the response time of your end user application. The downside though is that the data you get back from the materialized view is only as up to date as the last time the materialized view has been refreshed.
Materialized views can be set to refresh manually, on a set schedule, or based on the database detecting a change in data from one of the underlying tables. Materialized views can be incrementally updated by combining them with materialized view logs, which act as change data capture sources on the underlying tables.
Materialized views are most often used in data warehousing / business intelligence applications where querying large fact tables with thousands of millions of rows would result in query response times that resulted in an unusable application.
Materialized views also help to guarantee a consistent moment in time, similar to snapshot isolation.
Express.js created by TJ Holowaychuk and now managed by the community. It is one of the most popular frameworks in the node.js. Express can also be used to develop various products such as web applications or RESTful API.For more information please read on the expressjs.com official site.
eaccelerator could be causing the problem since it compiles PHP into blocks...I've had this problem with an Amazon AWS server on a site with heavy load. Free up Inodes by deleting the eaccelerator cache in /var/cache/eaccelerator if you continue to have issues.
rm -rf /var/cache/eaccelerator/*
(or whatever your cache dir)
You can use type()
or isinstance()
.
>>> type([]) is list
True
Be warned that you can clobber list
or any other type by assigning a variable in the current scope of the same name.
>>> the_d = {}
>>> t = lambda x: "aight" if type(x) is dict else "NOPE"
>>> t(the_d) 'aight'
>>> dict = "dude."
>>> t(the_d) 'NOPE'
Above we see that dict
gets reassigned to a string, therefore the test:
type({}) is dict
...fails.
To get around this and use type()
more cautiously:
>>> import __builtin__
>>> the_d = {}
>>> type({}) is dict
True
>>> dict =""
>>> type({}) is dict
False
>>> type({}) is __builtin__.dict
True
R has multiple ways of represeting time series. Since you're working with daily prices of stocks, you may wish to consider that financial markets are closed on weekends and business holidays so that trading days and calendar days are not the same. However, you may need to work with your times series in terms of both trading days and calendar days. For example, daily returns are calculated from sequential daily closing prices regardless of whether a weekend intervenes. But you may also want to do calendar-based reporting such as weekly price summaries. For these reasons the xts package, an extension of zoo, is commonly used with financial data in R. An example of how it could be used with your data follows.
Assuming the data shown in your example is in the dataframe df
library(xts)
stocks <- xts(df[,-1], order.by=as.Date(df[,1], "%m/%d/%Y"))
#
# daily returns
#
returns <- diff(stocks, arithmetic=FALSE ) - 1
#
# weekly open, high, low, close reports
#
to.weekly(stocks$Hero_close, name="Hero")
which gives the output
Hero.Open Hero.High Hero.Low Hero.Close
2013-03-15 1669.1 1684.45 1669.1 1684.45
2013-03-22 1690.5 1690.50 1623.3 1659.60
2013-03-28 1617.7 1617.70 1542.0 1542.00
just set -config
parameter location correctly, i.e :
openssl .................... -config C:\bin\apache\apache2.4.9\conf\openssl.cnf
Obviously, you'll need a rooted android device. Then set up an FTP server and transfer the files.
Firefox doesn't support outerHTML, so you need to define a function to help support it:
function outerHTML(node) {
return node.outerHTML || (
function(n) {
var div = document.createElement('div');
div.appendChild( n.cloneNode(true) );
var h = div.innerHTML;
div = null;
return h;
}
)(node);
}
Then, you can use outerHTML:
var x = outerHTML($('#container').get(0));
$('#save').val(x);
Every even number is divisible by two, regardless of if it's a decimal (but the decimal, if present, must also be even). So you can use the %
(modulo) operator, which divides the number on the left by the number on the right and returns the remainder...
boolean isEven(double num) { return ((num % 2) == 0); }
Consider this implementation of foo():
public void foo(final String a) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.print(a);
}
});
}
Because the Runnable
instance would outlive the method, this wouldn't compile without the final
keyword -- final
tells the compiler that it's safe to take a copy of the reference (to refer to it later). Thus, it's the reference that's considered final, not the value. In other words: As a caller, you can't mess anything up...
In any web application, there will be a web.xml
in the WEB-INF/
folder.
If you dont have one in your web app, as it seems to be the case in your folder structure, the default Tomcat web.xml
is under TOMCAT_HOME/conf/web.xml
Either way, the relevant lines of the web.xml are
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
so any file matching this pattern when found will be shown as the home page.
In Tomcat, a web.xml setting within your web app will override the default, if present.
Further Reading
Also, a good reason to use a controller vs. link function (since they both have access to the scope, element, and attrs) is because you can pass in any available service or dependency into a controller (and in any order), whereas you cannot do that with the link function. Notice the different signatures:
controller: function($scope, $exceptionHandler, $attr, $element, $parse, $myOtherService, someCrazyDependency) {...
vs.
link: function(scope, element, attrs) {... //no services allowed
There are 2 differences:
2 methods creating a user and granting some privileges to him
create user userName identified by password;
grant connect to userName;
and
grant connect to userName identified by password;
do exactly the same. It creates a user and grants him the connect role.
different outcome
resource is a role in oracle, which gives you the right to create objects (tables, procedures, some more but no views!). ALL PRIVILEGES grants a lot more of system privileges.
To grant a user all privileges run you first snippet or
grant all privileges to userName identified by password;
If you have a GIT server with an outdated or self-signed SSL cert fix the server, afterwards everything should run fine.
The following solution is just a mere hotfix on client side and should be avoided as it compromises security of your credentials and content. There is a detailed explanation for this in "How can I make git accept a self signed certificate?" which offers more complex and more secure solutions you can try out if the following works in general.
In my case it was Eclipse using a different storage for the git config as the command line does and thus not having the option
git config http.sslVerify false
set (which I set using command line for the repo for working with invalid/untrusted SSL cert).
Adding the option insides Eclipse immediately resolves the issue. To add the option
Add entry...
, then put http.sslVerify
in the key box and false
in the value box.Seems to be a valid solution for Eclipse 4.4 (Luna), 4.5.x (Mars) and 4.6.x (Neon) on different Operating systems.
I tried the chosen answer, but found when I ran a shell script having it, the whole thing was getting printed to screen (similar to how jupyter notebooks print out everything in '''xx'''
quotes) and there was an error message at end. It wasn't doing anything, but: scary. Then I realised while editing it that single-quotes can span multiple lines. So.. lets just assign the block to a variable.
x='
echo "these lines will all become comments."
echo "just make sure you don_t use single-quotes!"
ls -l
date
'
I usually set the width of my inputs to 99% to fix this:
input {
width: 99%;
}
You can also remove the default styles, but that will make it less obvious that it is a text box. However, I will show the code for that anyway:
input {
width: 100%;
border-width: 0;
margin: 0;
padding: 0;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
Ad@m
Framework 4: no need to use StreamWriter:
System.IO.File.WriteAllLines("SavedLists.txt", Lists.verbList);
I like List comprehensions because of their Math (Set) syntax. So how about this:
L = [1, 2, 3, 4, 5, 6, 7]
odd_numbers = [y for x,y in enumerate(L) if x%2 != 0]
even_numbers = [y for x,y in enumerate(L) if x%2 == 0]
Basically, if you enumerate over a list, you'll get the index x
and the value y
. What I'm doing here is putting the value y
into the output list (even or odd) and using the index x
to find out if that point is odd (x%2 != 0
).
You can set the spinner prompt:
spinner.setPrompt("Select gender...");
I downloaded Android Studio and installed it. The installer said:-
Android Studio => ( 500 MB )
Android SDK => ( 2.3 GB )
Android Studio installer is actually an "Android SDK Installer" along with a sometimes useful tool called "Android Studio".
Most importantly:- Android Studio Installer will not just install the SDK. It will also:-
Things which you will have to do manually if you install the SDK from its zip file.
Just take it easy. Install the Android Studio.
****************************** Edit ******************************
So, being inspired by the responses in the comments I would like to update my answer.
The update is that only (and only) if 500MB of hard disk space does not matter much to you than you should go for Android Studio otherwise other answers would be better for you.
Android Studio worked for me as I had a 1TB hard disk which is 2000 times 500MB.
Also, note: that RAM sizse should not a restriction for you as you would not even be running Android Studio.
I came to this solution as I was myself stuck in this problem. I tried other answers but for some reason (maybe my in-competencies) they did not work for me. I decided to go for Android Studio and realized that it was merely 18% of the total installation and SDK was 82% of it. While I used to think otherwise. I am not deleting the answers inspite of negative rating as the answer worked for me. I might work for someone elese with a 1 TB hard disk (which is pretty common these days).
on Mac:
~/Library/Preferences/SmartGit/19.1
preferences.yml
file and just comment listx
line Instead of using button . you can use Text in react native and then make in touchable
<TouchableOpacity onPress={this._onPressButton}>
<Text style = {'your custome style'}>
button name
</Text>
</TouchableOpacity >
You can't effectively use Distinct
on a collection of objects (without additional work). I will explain why.
It uses the default equality comparer,
Default
, to compare values.
For objects that means it uses the default equation method to compare objects (source). That is on their hash code. And since your objects don't implement the GetHashCode()
and Equals
methods, it will check on the reference of the object, which are not distinct.
UPDATE YourTable
SET ColumnB=ColumnA
WHERE
ColumnB IS NULL
AND ColumnA IS NOT NULL
.style1 {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Works in:
In addition you can try this for an IE solution
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";
zoom: 1;
Credit to this article by Chris Coyier http://css-tricks.com/perfect-full-page-background-image/
A single pipe (|) is the bitwise OR operator.
Two pipes (||) is the logical OR operator.
They are not interchangeable.
In addition to the other answers here, if you've forgotten to put:
cmd.CommandType = CommandType.StoredProcedure;
Then you will also get this error.
You should set height
of html, body, .wrapper
to 100%
(in order to inherit full height) and then just set a flex
value greater than 1
to .row3
and not on the others.
.wrapper, html, body {
height: 100%;
margin: 0;
}
.wrapper {
display: flex;
flex-direction: column;
}
#row1 {
background-color: red;
}
#row2 {
background-color: blue;
}
#row3 {
background-color: green;
flex:2;
display: flex;
}
#col1 {
background-color: yellow;
flex: 0 0 240px;
min-height: 100%;/* chrome needed it a question time , not anymore */
}
#col2 {
background-color: orange;
flex: 1 1;
min-height: 100%;/* chrome needed it a question time , not anymore */
}
#col3 {
background-color: purple;
flex: 0 0 240px;
min-height: 100%;/* chrome needed it a question time , not anymore */
}
_x000D_
<div class="wrapper">
<div id="row1">this is the header</div>
<div id="row2">this is the second line</div>
<div id="row3">
<div id="col1">col1</div>
<div id="col2">col2</div>
<div id="col3">col3</div>
</div>
</div>
_x000D_
Here is the HTML snippet:
<td><iframe name="idFrame" id="idFrame" src="chat.txt" width="468" height="300"></iframe></td>
And my Javascript code:
window.onload = function(){
setInterval(function(){
parent.frames['idFrame'].location.href = "chat.txt";
},1000);}
Look into android.util.Log
. It lets you write to the log with various log levels, and you can specify different tags to group the output.
For example
Log.w("myApp", "no network");
will output a warning with the tag myApp and the message no network.
Those errors :
"CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage"
means you haven't installed mingw32-base.
Go to http://sourceforge.net/projects/mingw/files/latest/download?source=files
and then make sure you select "mingw32-base"
Make sure you set up environment variables correctly in PATH section. "C:\MinGW\bin"
After that open CMake and Select Installation --> Delete Cache.
And click configure button again. I solved the problem this way, hope you solve the problem.
There is a possibility that your package.json
is causing this.
Parse your package.json
to find the unexpected token
or
Delete your package.json
file and create one through
npm install
Just for fun, don't do this!
$.fn.transitiondone = function () {
return this.each(function () {
var $this = $(this);
setTimeout(function () {
$this.trigger('transitiondone');
}, (parseFloat($this.css('transitionDelay')) + parseFloat($this.css('transitionDuration'))) * 1000);
});
};
$('div').on('mousedown', function (e) {
$(this).addClass('bounce').transitiondone();
});
$('div').on('transitiondone', function () {
$(this).removeClass('bounce');
});
Here are two ways:
In HTML:
<div class="ics">⛱</div>
This will result into ⛱
In Css:
.ics::before {content: "\9969;"}
with HTML code <div class="ics"></div>
This also results in ⛱
git branch -d [branch name]
for local delete
git branch -D [branch name]
also for local delete but forces it
JAVA8: Use LocalDateTime.now().toString()
In the provided example your decimal is 8.6. Had it been 8.5 or 9.5, the statement i1 == i2 might have been true. Infact it would have been true for 8.5, and false for 9.5.
Explanation:
Regardless of the decimal part, the second statement, int i2 = (int)score
will discard the decimal part and simply return you the integer part. Quite dangerous thing to do, as data loss might occur.
Now, for the first statement, two things can happen. If the decimal part is 5, that is, it is half way through, a decision is to be made. Do we round up or down? In C#, the Convert class implements banker's rounding. See this answer for deeper explanation. Simply put, if the number is even, round down, if the number is odd, round up.
E.g. Consider:
double score = 8.5;
int i1 = Convert.ToInt32(score); // 8
int i2 = (int)score; // 8
score += 1;
i1 = Convert.ToInt32(score); // 10
i2 = (int)score; // 9
The script from @larsmans, a bit improved:
#!/bin/sh
set -x
CURRENT=`git rev-parse --abbrev-ref HEAD`
git fetch --all
for branch in "$@"; do
if ["$branch" -ne "$CURRENT"]; then
git checkout "$branch" || exit 1
git rebase "origin/$branch" || exit 1
fi
done
git checkout "$CURRENT" || exit 1
git rebase "origin/$CURRENT" || exit 1
This, after it finishes, leaves working copy checked out from the same branch as it was before the script was called.
The git pull
version:
#!/bin/sh
set -x
CURRENT=`git rev-parse --abbrev-ref HEAD`
git fetch --all
for branch in "$@"; do
if ["$branch" -ne "$CURRENT"]; then
git checkout "$branch" || exit 1
git pull || exit 1
fi
done
git checkout "$CURRENT" || exit 1
git pull || exit 1
><
by >\n<
with Regular Expressions enabled::
is used to link something ( a variable, a function, a class, a typedef etc...) to a namespace, or to a class.
if there is no left hand side before ::
, then it underlines the fact you are using the global namespace.
e.g.:
::doMyGlobalFunction();
Use a third variable like this:
var a = 1,
b = 2,
c = a;
a = b; // must be first or a and b end up being both 1
b = c;
DEMO - Using a third variable
So ridiculous, but I still wanna share my experience in case of that someone falls into the situation like me.
Please check if you changed: compileSdkVersion
--> implementationSdkVersion
by mistake
I know this thread is very old, but i think this would help anyone that landed here from google like me.
In GAE Flex (NodeJs), you could set the enviroment variable TZ (the one that manages all date timezones in the app) in the app.yaml file, i leave you here an example:
app.yaml
# [START env]
env_variables:
# Timezone
TZ: America/Argentina/Buenos_Aires
Is there some kind of query language ...
jq defines a JSON query language that is very similar to JSONPath -- see https://github.com/stedolan/jq/wiki/For-JSONPath-users
... [which] I can used to find an item in [0].objects where id = 3?
I'll assume this means: find all JSON objects under the specified key with id == 3, no matter where the object may be. A corresponding jq query would be:
.[0].objects | .. | objects | select(.id==3)
where "|" is the pipe-operator (as in command shell pipes), and where the segment ".. | objects" corresponds to "no matter where the object may be".
The basics of jq are largely obvious or intuitive or at least quite simple, and most of the rest is easy to pick up if you're at all familiar with command-shell pipes. The jq FAQ has pointers to tutorials and the like.
jq is also like SQL in that it supports CRUD operations, though the jq processor never overwrites its input. jq can also handle streams of JSON entities.
Two other criteria you might wish to consider in assessing a JSON-oriented query language are:
Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:
GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/
[SOLVED]
I only observed this error today, for me the Error code was different though.
SCRIPT7002: XMLHttpRequest: Network Error 0x2efd, Could not complete the operation due to error 00002efd.
It was occurring randomly and not all the time. but what it noticed is, if it comes for subsequent ajax calls. so i put some delay of 5 seconds between the ajax calls and it resolved.
What I do when it happens is Disable the COM port into the Device Manager and Enable it again.
It stop the communications with another program or thread and become free for you.
I hope this works for you. Regards.
Use "vol" shell command and parse serial from it's output, like this. Works at least in Win7
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CheckHD
{
class HDSerial
{
const string MY_SERIAL = "F845-BB23";
public static bool CheckSerial()
{
string res = ExecuteCommandSync("vol");
const string search = "Number is";
int startI = res.IndexOf(search, StringComparison.InvariantCultureIgnoreCase);
if (startI > 0)
{
string currentDiskID = res.Substring(startI + search.Length).Trim();
if (currentDiskID.Equals(MY_SERIAL))
return true;
}
return false;
}
public static string ExecuteCommandSync(object command)
{
try
{
// create the ProcessStartInfo using "cmd" as the program to be run,
// and "/c " as the parameters.
// Incidentally, /c tells cmd that we want it to execute the command that follows,
// and then exit.
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
// Display the command output.
return result;
}
catch (Exception)
{
// Log the exception
return null;
}
}
}
}
Found it with:
sudo tail /var/log/redis/redis-server.log -n 100
So if the setup was more standard that should be:
sudo tail /var/log/redis_6379.log -n 100
This outputs the last 100 lines of the file.
Where your log file is located is in your configs that you can access with:
redis-cli CONFIG GET *
The log file may not always be shown using the above. In that case use
tail -f `less /etc/redis/redis.conf | grep logfile|cut -d\ -f2`
Typically you would always put the hyphen first in the []
match section. EG, to match any alphanumeric character including hyphens (written the long way), you would use [-a-zA-Z0-9]
All cookies are client and server
There is no difference. A regular cookie can be set server side or client side. The 'classic' cookie will be sent back with each request. A cookie that is set by the server, will be sent to the client in a response. The server only sends the cookie when it is explicitly set or changed, while the client sends the cookie on each request.
But essentially it's the same cookie.
But, behavior can change
A cookie is basically a name=value
pair, but after the value can be a bunch of semi-colon separated attributes that affect the behavior of the cookie if it is so implemented by the client (or server).
Those attributes can be about lifetime, context and various security settings.
HTTP-only (is not server-only)
One of those attributes can be set by a server to indicate that it's an HTTP-only cookie. This means that the cookie is still sent back and forth, but it won't be available in JavaScript. Do note, though, that the cookie is still there! It's only a built in protection in the browser, but if somebody would use a ridiculously old browser like IE5, or some custom client, they can actually read the cookie!
So it seems like there are 'server cookies', but there are actually not. Those cookies are still sent to the client. On the client there is no way to prevent a cookie from being sent to the server.
Alternatives to achieve 'only-ness'
If you want to store a value only on the server, or only on the client, then you'd need some other kind of storage, like a file or database on the server, or Local Storage on the client.
[What you have is just an object, not a "json-object". JSON is a textual notation. What you've quoted is JavaScript code using an array initializer and an object initializer (aka, "object literal syntax").]
If you can rely on having ECMAScript5 features available, you can use the Object.keys
function to get an array of the keys (property names) in an object. All modern browsers have Object.keys
(including IE9+).
Object.keys(jsonData).forEach(function(key) {
var value = jsonData[key];
// ...
});
The rest of this answer was written in 2011. In today's world, A) You don't need to polyfill this unless you need to support IE8 or earlier (!), and B) If you did, you wouldn't do it with a one-off you wrote yourself or grabbed from an SO answer (and probably shouldn't have in 2011, either). You'd use a curated polyfill, possibly from es5-shim
or via a transpiler like Babel that can be configured to include polyfills (which may come from es5-shim
).
Here's the rest of the answer from 2011:
Note that older browsers won't have it. If not, this is one of the ones you can supply yourself:
if (typeof Object.keys !== "function") {
(function() {
var hasOwn = Object.prototype.hasOwnProperty;
Object.keys = Object_keys;
function Object_keys(obj) {
var keys = [], name;
for (name in obj) {
if (hasOwn.call(obj, name)) {
keys.push(name);
}
}
return keys;
}
})();
}
That uses a for..in
loop (more info here) to loop through all of the property names the object has, and uses Object.prototype.hasOwnProperty
to check that the property is owned directly by the object rather than being inherited.
(I could have done it without the self-executing function, but I prefer my functions to have names, and to be compatible with IE you can't use named function expressions [well, not without great care]. So the self-executing function is there to avoid having the function declaration create a global symbol.)
HTML:
<form name="foo" action="form.php" method="POST" id="foo">
<label for="bar">A bar</label>
<input id="bar" class="inputs" name="bar" type="text" value="" />
<input type="submit" value="Send" onclick="submitform(); return false;" />
</form>
JavaScript:
function submitform()
{
var inputs = document.getElementsByClassName("inputs");
var formdata = new FormData();
for(var i=0; i<inputs.length; i++)
{
formdata.append(inputs[i].name, inputs[i].value);
}
var xmlhttp;
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest;
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
}
}
xmlhttp.open("POST", "insert.php");
xmlhttp.send(formdata);
}
build gradle:
testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"
code:
interface MyCallback {
fun someMethod(value: String)
}
class MyTestableManager(private val callback: MyCallback){
fun perform(){
callback.someMethod("first")
callback.someMethod("second")
callback.someMethod("third")
}
}
test:
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.mock
...
val callback: MyCallback = mock()
val manager = MyTestableManager(callback)
manager.perform()
val captor: KArgumentCaptor<String> = com.nhaarman.mockitokotlin2.argumentCaptor<String>()
verify(callback, times(3)).someMethod(captor.capture())
assertTrue(captor.allValues[0] == "first")
assertTrue(captor.allValues[1] == "second")
assertTrue(captor.allValues[2] == "third")
You can have a look at this page showing Deep Folder Copy, it uses recursive means to iterate throught the files and has some really nice tips, like filtering techniques etc.
http://www.codeproject.com/Tips/512208/Folder-Directory-Deep-Copy-including-sub-directori
Very simply: use an XML library. That way it will actually be right instead of requiring detailed knowledge of bits of the XML spec.
You are pointing your JAVA_HOME to the JRE which is the Java Runtime Environment. The runtime environment doesn't have a java compiler in its bin folder. You should download the JDK which is the Java Development Kit. Once you've installed that, you can see in your bin folder that there's a file called javac.exe. That's your compiler.
$Group
is an object, but you will actually need to check if $Group.samaccountname.StartsWith("string")
.
Change $Group.StartsWith("S_G_")
to $Group.samaccountname.StartsWith("S_G_")
.
So I do in Windows 10 and Python 3.7.1 (tested):
import subprocess
Quellpfad = r"C:\Users\MeMySelfAndI\Desktop"
Quelldatei = r"\a.bat"
Quelle = Quellpfad + Quelldatei
print(Quelle)
subprocess.call(Quelle)
1)Go to configure build path . 2)Remove unbound JRE library . 3)Add library --> JRE System library .
Then project compile and done ..
Just use format(number, qtyDecimals) sample: format(1000, 2) result 1000.00