CSS Keyframes support is pretty good these days:
.fade-in {_x000D_
opacity: 1;_x000D_
animation-name: fadeInOpacity;_x000D_
animation-iteration-count: 1;_x000D_
animation-timing-function: ease-in;_x000D_
animation-duration: 2s;_x000D_
}_x000D_
_x000D_
@keyframes fadeInOpacity {_x000D_
0% {_x000D_
opacity: 0;_x000D_
}_x000D_
100% {_x000D_
opacity: 1;_x000D_
}_x000D_
}
_x000D_
<h1 class="fade-in">Fade Me Down Scotty</h1>
_x000D_
GRANT
s on different objects are separate. GRANT
ing on a database doesn't GRANT
rights to the schema within. Similiarly, GRANT
ing on a schema doesn't grant rights on the tables within.
If you have rights to SELECT
from a table, but not the right to see it in the schema that contains it then you can't access the table.
The rights tests are done in order:
Do you have `USAGE` on the schema?
No: Reject access.
Yes: Do you also have the appropriate rights on the table?
No: Reject access.
Yes: Check column privileges.
Your confusion may arise from the fact that the public
schema has a default GRANT
of all rights to the role public
, which every user/group is a member of. So everyone already has usage on that schema.
The phrase:
(assuming that the objects' own privilege requirements are also met)
Is saying that you must have USAGE
on a schema to use objects within it, but having USAGE
on a schema is not by itself sufficient to use the objects within the schema, you must also have rights on the objects themselves.
It's like a directory tree. If you create a directory somedir
with file somefile
within it then set it so that only your own user can access the directory or the file (mode rwx------
on the dir, mode rw-------
on the file) then nobody else can list the directory to see that the file exists.
If you were to grant world-read rights on the file (mode rw-r--r--
) but not change the directory permissions it'd make no difference. Nobody could see the file in order to read it, because they don't have the rights to list the directory.
If you instead set rwx-r-xr-x
on the directory, setting it so people can list and traverse the directory but not changing the file permissions, people could list the file but could not read it because they'd have no access to the file.
You need to set both permissions for people to actually be able to view the file.
Same thing in Pg. You need both schema USAGE
rights and object rights to perform an action on an object, like SELECT
from a table.
(The analogy falls down a bit in that PostgreSQL doesn't have row-level security yet, so the user can still "see" that the table exists in the schema by SELECT
ing from pg_class
directly. They can't interact with it in any way, though, so it's just the "list" part that isn't quite the same.)
Here is a working example of above. http://jsfiddle.net/z7L6m2sc/ Now select2 has been updated the classes have change may be why you cannot get it to work. Here is the css....
.select2-dropdown.select2-dropdown--below{
width: 148px !important;
}
.select2-container--default .select2-selection--single{
padding:6px;
height: 37px;
width: 148px;
font-size: 1.2em;
position: relative;
}
.select2-container--default .select2-selection--single .select2-selection__arrow {
background-image: -khtml-gradient(linear, left top, left bottom, from(#424242), to(#030303));
background-image: -moz-linear-gradient(top, #424242, #030303);
background-image: -ms-linear-gradient(top, #424242, #030303);
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #424242), color-stop(100%, #030303));
background-image: -webkit-linear-gradient(top, #424242, #030303);
background-image: -o-linear-gradient(top, #424242, #030303);
background-image: linear-gradient(#424242, #030303);
width: 40px;
color: #fff;
font-size: 1.3em;
padding: 4px 12px;
height: 27px;
position: absolute;
top: 0px;
right: 0px;
width: 20px;
}
There is a convention (not necessary) of placing jsp pages under WEB-INF directory so that they cannot be deep linked or bookmarked to. This way all requests to jsp page must be directed through our application, so that user experience is guaranteed.
You can use hh
to tell printf
that the argument is an unsigned char. Use 0
to get zero padding and 2
to set the width to 2. x
or X
for lower/uppercase hex characters.
uint8_t a = 0x0a;
printf("%02hhX", a); // Prints "0A"
printf("0x%02hhx", a); // Prints "0x0a"
Edit: If readers are concerned about 2501's assertion that this is somehow not the 'correct' format specifiers I suggest they read the printf
link again. Specifically:
Even though %c expects int argument, it is safe to pass a char because of the integer promotion that takes place when a variadic function is called.
The correct conversion specifications for the fixed-width character types (int8_t, etc) are defined in the header
<cinttypes>
(C++) or<inttypes.h>
(C) (although PRIdMAX, PRIuMAX, etc is synonymous with %jd, %ju, etc).
As for his point about signed vs unsigned, in this case it does not matter since the values must always be positive and easily fit in a signed int. There is no signed hexideximal format specifier anyway.
Edit 2: ("when-to-admit-you're-wrong" edition):
If you read the actual C11 standard on page 311 (329 of the PDF) you find:
hh: Specifies that a following
d
,i
,o
,u
,x
, orX
conversion specifier applies to asigned char
orunsigned char
argument (the argument will have been promoted according to the integer promotions, but its value shall be converted tosigned char
orunsigned char
before printing); or that a followingn
conversion specifier applies to a pointer to asigned char
argument.
Unless you get a better answer from a Scala user (which I'm not), here's my understanding.
It only appears as part of an expression beginning with for
, which states how to generate a new list from an existing list.
Something like:
var doubled = for (n <- original) yield n * 2
So there's one output item for each input (although I believe there's a way of dropping duplicates).
This is quite different from the "imperative continuations" enabled by yield in other languages, where it provides a way to generate a list of any length, from some imperative code with almost any structure.
(If you're familiar with C#, it's closer to LINQ's select
operator than it is to yield return
).
I'm not a Javascript expert, but here is one simple attempt to solve it. I check for three things:
object
and also that it is not null
because typeof null
is object
.function deepEqual (first, second) {_x000D_
// Not equal if either is not an object or is null._x000D_
if (!isObject(first) || !isObject(second) ) return false;_x000D_
_x000D_
// If properties count is different_x000D_
if (keys(first).length != keys(second).length) return false;_x000D_
_x000D_
// Return false if any property value is different._x000D_
for(prop in first){_x000D_
if (first[prop] != second[prop]) return false;_x000D_
}_x000D_
return true;_x000D_
}_x000D_
_x000D_
// Checks if argument is an object and is not null_x000D_
function isObject(obj) {_x000D_
return (typeof obj === "object" && obj != null);_x000D_
}_x000D_
_x000D_
// returns arrays of object keys_x000D_
function keys (obj) {_x000D_
result = [];_x000D_
for(var key in obj){_x000D_
result.push(key);_x000D_
}_x000D_
return result;_x000D_
}_x000D_
_x000D_
// Some test code_x000D_
obj1 = {_x000D_
name: 'Singh',_x000D_
age: 20_x000D_
}_x000D_
_x000D_
obj2 = {_x000D_
age: 20,_x000D_
name: 'Singh'_x000D_
}_x000D_
_x000D_
obj3 = {_x000D_
name: 'Kaur',_x000D_
age: 19_x000D_
}_x000D_
_x000D_
console.log(deepEqual(obj1, obj2));_x000D_
console.log(deepEqual(obj1, obj3));
_x000D_
Put your script after the completion of body tag...it works...
In your generic method, T
is just a placeholder for a type. However, the compiler doesn't per se know anything about the concrete type(s) being used runtime, so it can't assume that they will have a var
member.
The usual way to circumvent this is to add a generic type constraint to your method declaration to ensure that the types used implement a specific interface (in your case, it could be ITest
):
public void PrintGeneric<T>(T test) where T : ITest
Then, the members of that interface would be directly available inside the method. However, your ITest
is currently empty, you need to declare common stuff there in order to enable its usage within the method.
I found the example RichardTheKiwi quite informative.
Just to offer another approach if you're looking for something like IF EXISTS (SELECT 1 ..) THEN ...
-- what I might write in MSSQL
IF EXISTS (SELECT 1 FROM Table WHERE FieldValue='')
BEGIN
SELECT TableID FROM Table WHERE FieldValue=''
END
ELSE
BEGIN
INSERT INTO TABLE(FieldValue) VALUES('')
SELECT SCOPE_IDENTITY() AS TableID
END
-- rewritten for MySQL
IF (SELECT 1 = 1 FROM Table WHERE FieldValue='') THEN
BEGIN
SELECT TableID FROM Table WHERE FieldValue='';
END;
ELSE
BEGIN
INSERT INTO Table (FieldValue) VALUES('');
SELECT LAST_INSERT_ID() AS TableID;
END;
END IF;
Just to add to all the conversation. Since arrays requires consecutive memory locations to store the item, so if we create an array of references then it's not guaranteed that they will be at consecutive memory location so accessing will be a problem and hence we can't even apply all the mathematical operations on array.
There's a whole page of the Django documentation devoted to this, well indexed from the contents page.
As that page states, you need to do:
my_obj.categories.add(fragmentCategory.objects.get(id=1))
or
my_obj.categories.create(name='val1')
To do links, you can do
.social h2 a:link {
color: pink;
font-size: 14px;
}
You can change the hover, visited, and active link styling too. Just replace "link" with what you want to style. You can learn more at the w3schools page CSS Links.
I created a fiddle using only CSS.
.wrapper {_x000D_
width: 100px; /* Set the size of the progress bar */_x000D_
height: 100px;_x000D_
position: absolute; /* Enable clipping */_x000D_
clip: rect(0px, 100px, 100px, 50px); /* Hide half of the progress bar */_x000D_
}_x000D_
/* Set the sizes of the elements that make up the progress bar */_x000D_
.circle {_x000D_
width: 80px;_x000D_
height: 80px;_x000D_
border: 10px solid green;_x000D_
border-radius: 50px;_x000D_
position: absolute;_x000D_
clip: rect(0px, 50px, 100px, 0px);_x000D_
}_x000D_
/* Using the data attributes for the animation selectors. */_x000D_
/* Base settings for all animated elements */_x000D_
div[data-anim~=base] {_x000D_
-webkit-animation-iteration-count: 1; /* Only run once */_x000D_
-webkit-animation-fill-mode: forwards; /* Hold the last keyframe */_x000D_
-webkit-animation-timing-function:linear; /* Linear animation */_x000D_
}_x000D_
_x000D_
.wrapper[data-anim~=wrapper] {_x000D_
-webkit-animation-duration: 0.01s; /* Complete keyframes asap */_x000D_
-webkit-animation-delay: 3s; /* Wait half of the animation */_x000D_
-webkit-animation-name: close-wrapper; /* Keyframes name */_x000D_
}_x000D_
_x000D_
.circle[data-anim~=left] {_x000D_
-webkit-animation-duration: 6s; /* Full animation time */_x000D_
-webkit-animation-name: left-spin;_x000D_
}_x000D_
_x000D_
.circle[data-anim~=right] {_x000D_
-webkit-animation-duration: 3s; /* Half animation time */_x000D_
-webkit-animation-name: right-spin;_x000D_
}_x000D_
/* Rotate the right side of the progress bar from 0 to 180 degrees */_x000D_
@-webkit-keyframes right-spin {_x000D_
from {_x000D_
-webkit-transform: rotate(0deg);_x000D_
}_x000D_
to {_x000D_
-webkit-transform: rotate(180deg);_x000D_
}_x000D_
}_x000D_
/* Rotate the left side of the progress bar from 0 to 360 degrees */_x000D_
@-webkit-keyframes left-spin {_x000D_
from {_x000D_
-webkit-transform: rotate(0deg);_x000D_
}_x000D_
to {_x000D_
-webkit-transform: rotate(360deg);_x000D_
}_x000D_
}_x000D_
/* Set the wrapper clip to auto, effectively removing the clip */_x000D_
@-webkit-keyframes close-wrapper {_x000D_
to {_x000D_
clip: rect(auto, auto, auto, auto);_x000D_
}_x000D_
}
_x000D_
<div class="wrapper" data-anim="base wrapper">_x000D_
<div class="circle" data-anim="base left"></div>_x000D_
<div class="circle" data-anim="base right"></div>_x000D_
</div>
_x000D_
Also check this fiddle here (CSS only)
@import url(http://fonts.googleapis.com/css?family=Josefin+Sans:100,300,400);_x000D_
_x000D_
.arc1 {_x000D_
width: 160px;_x000D_
height: 160px;_x000D_
background: #00a0db;_x000D_
-webkit-transform-origin: -31% 61%;_x000D_
margin-left: -30px;_x000D_
margin-top: 20px;_x000D_
-webkit-transform: translate(-54px,50px);_x000D_
-moz-transform: translate(-54px,50px);_x000D_
-o-transform: translate(-54px,50px);_x000D_
}_x000D_
.arc2 {_x000D_
width: 160px;_x000D_
height: 160px;_x000D_
background: #00a0db;_x000D_
-webkit-transform: skew(45deg,0deg);_x000D_
-moz-transform: skew(45deg,0deg);_x000D_
-o-transform: skew(45deg,0deg);_x000D_
margin-left: -180px;_x000D_
margin-top: -90px;_x000D_
position: absolute;_x000D_
-webkit-transition: all .5s linear;_x000D_
-moz-transition: all .5s linear;_x000D_
-o-transition: all .5s linear;_x000D_
}_x000D_
_x000D_
.arc-container:hover .arc2 {_x000D_
margin-left: -50px;_x000D_
-webkit-transform: skew(-20deg,0deg);_x000D_
-moz-transform: skew(-20deg,0deg);_x000D_
-o-transform: skew(-20deg,0deg);_x000D_
}_x000D_
_x000D_
.arc-wrapper {_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
border-radius:150px;_x000D_
background: #424242;_x000D_
overflow:hidden;_x000D_
left: 50px;_x000D_
top: 50px;_x000D_
position: absolute;_x000D_
}_x000D_
.arc-hider {_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
border-radius: 150px;_x000D_
border: 50px solid #e9e9e9;_x000D_
position:absolute;_x000D_
z-index:5;_x000D_
box-shadow:inset 0px 0px 20px rgba(0,0,0,0.7);_x000D_
}_x000D_
_x000D_
.arc-inset {_x000D_
font-family: "Josefin Sans";_x000D_
font-weight: 100;_x000D_
position: absolute;_x000D_
font-size: 413px;_x000D_
margin-top: -64px;_x000D_
z-index: 5;_x000D_
left: 30px;_x000D_
line-height: 327px;_x000D_
height: 280px;_x000D_
-webkit-mask-image: -webkit-linear-gradient(top, rgba(0,0,0,1), rgba(0,0,0,0.2));_x000D_
}_x000D_
.arc-lowerInset {_x000D_
font-family: "Josefin Sans";_x000D_
font-weight: 100;_x000D_
position: absolute;_x000D_
font-size: 413px;_x000D_
margin-top: -64px;_x000D_
z-index: 5;_x000D_
left: 30px;_x000D_
line-height: 327px;_x000D_
height: 280px;_x000D_
color: white;_x000D_
-webkit-mask-image: -webkit-linear-gradient(top, rgba(0,0,0,0.2), rgba(0,0,0,1));_x000D_
}_x000D_
.arc-overlay {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background-image: linear-gradient(bottom, rgb(217,217,217) 10%, rgb(245,245,245) 90%, rgb(253,253,253) 100%);_x000D_
background-image: -o-linear-gradient(bottom, rgb(217,217,217) 10%, rgb(245,245,245) 90%, rgb(253,253,253) 100%);_x000D_
background-image: -moz-linear-gradient(bottom, rgb(217,217,217) 10%, rgb(245,245,245) 90%, rgb(253,253,253) 100%);_x000D_
background-image: -webkit-linear-gradient(bottom, rgb(217,217,217) 10%, rgb(245,245,245) 90%, rgb(253,253,253) 100%);_x000D_
_x000D_
padding-left: 32px;_x000D_
box-sizing: border-box;_x000D_
-moz-box-sizing: border-box;_x000D_
line-height: 100px;_x000D_
font-family: sans-serif;_x000D_
font-weight: 400;_x000D_
text-shadow: 0 1px 0 #fff;_x000D_
font-size: 22px;_x000D_
border-radius: 100px;_x000D_
position: absolute;_x000D_
z-index: 5;_x000D_
top: 75px;_x000D_
left: 75px;_x000D_
box-shadow:0px 0px 20px rgba(0,0,0,0.7);_x000D_
}_x000D_
.arc-container {_x000D_
position: relative;_x000D_
background: #e9e9e9;_x000D_
height: 250px;_x000D_
width: 250px;_x000D_
}
_x000D_
<div class="arc-container">_x000D_
<div class="arc-hider"></div>_x000D_
<div class="arc-inset">_x000D_
o_x000D_
</div>_x000D_
<div class="arc-lowerInset">_x000D_
o_x000D_
</div>_x000D_
<div class="arc-overlay">_x000D_
35%_x000D_
</div>_x000D_
<div class="arc-wrapper">_x000D_
<div class="arc2"></div>_x000D_
<div class="arc1"></div>_x000D_
</div>_x000D_
</div>
_x000D_
Or this beautiful round progress bar with HTML5, CSS3 and JavaScript.
The shorter ones are vectorized, meaning they can return a vector, like this:
((-2:2) >= 0) & ((-2:2) <= 0)
# [1] FALSE FALSE TRUE FALSE FALSE
The longer form evaluates left to right examining only the first element of each vector, so the above gives
((-2:2) >= 0) && ((-2:2) <= 0)
# [1] FALSE
As the help page says, this makes the longer form "appropriate for programming control-flow and [is] typically preferred in if clauses."
So you want to use the long forms only when you are certain the vectors are length one.
You should be absolutely certain your vectors are only length 1, such as in cases where they are functions that return only length 1 booleans. You want to use the short forms if the vectors are length possibly >1. So if you're not absolutely sure, you should either check first, or use the short form and then use all
and any
to reduce it to length one for use in control flow statements, like if
.
The functions all
and any
are often used on the result of a vectorized comparison to see if all or any of the comparisons are true, respectively. The results from these functions are sure to be length 1 so they are appropriate for use in if clauses, while the results from the vectorized comparison are not. (Though those results would be appropriate for use in ifelse
.
One final difference: the &&
and ||
only evaluate as many terms as they need to (which seems to be what is meant by short-circuiting). For example, here's a comparison using an undefined value a
; if it didn't short-circuit, as &
and |
don't, it would give an error.
a
# Error: object 'a' not found
TRUE || a
# [1] TRUE
FALSE && a
# [1] FALSE
TRUE | a
# Error: object 'a' not found
FALSE & a
# Error: object 'a' not found
Finally, see section 8.2.17 in The R Inferno, titled "and and andand".
If you are using bootstrap and font-awesome then it is easy, no need to write a single line of new code, just add fa-Nx, as big you want, See the demo
<span class="glyphicon glyphicon-globe"></span>
<span class="glyphicon glyphicon-globe fa-lg"></span>
<span class="glyphicon glyphicon-globe fa-2x"></span>
<span class="glyphicon glyphicon-globe fa-3x"></span>
<span class="glyphicon glyphicon-globe fa-4x"></span>
<span class="glyphicon glyphicon-globe fa-5x"></span>
I used all the above answers and it was giving me errors so I tried
adb shell monkey -p com.yourpackage.name -c android.intent.category.LAUNCHER 1
and it worked. One advantage is you dont have to specify your launcher activity if you use this command.
If you want to access the variables some sort of dynamic you may use reflection. However Reflection works not for local variables. It is only applyable for class attributes.
A rough quick and dirty example is this:
public class T {
public Integer n1;
public Integer n2;
public Integer n3;
public void accessAttributes() throws IllegalArgumentException, SecurityException, IllegalAccessException,
NoSuchFieldException {
for (int i = 1; i < 4; i++) {
T.class.getField("n" + i).set(this, 5);
}
}
}
You need to improve this code in various ways it is only an example. This is also not considered to be good code.
Including this in the read.csv
command worked for me: strip.white = TRUE
(I found this solution here.)
I was looking for getting val by internal field name instead of ID and came from google to this post which help but did not find the solution I need, but I got the solution and here it is:
So this might help somebody looking for selected value with field internal name instead of using long id for SharePoint lists:
var e = $('select[title="IntenalFieldName"] option:selected').text();
This is due to a security vulnerability that has been addressed in Ghostscript 9.24 (source). If you have a newer version, you don't need this workaround anymore. On Ubuntu 19.10 with Ghostscript 6, this means:
Make sure you have Ghostscript =9.24:
gs --version
If yes, just remove this whole following section from /etc/ImageMagick-6/policy.xml
:
<!-- disable ghostscript format types -->
<policy domain="coder" rights="none" pattern="PS" />
<policy domain="coder" rights="none" pattern="PS2" />
<policy domain="coder" rights="none" pattern="PS3" />
<policy domain="coder" rights="none" pattern="EPS" />
<policy domain="coder" rights="none" pattern="PDF" />
<policy domain="coder" rights="none" pattern="XPS" />
I found this maven
repo where you could download from directly a zip
file containing all the jars you need.
The solution I prefer is using Maven
, it is easy and you don't have to download each jar
alone. You can do it with the following steps:
Create an empty folder anywhere with any name you prefer, for example spring-source
Create a new file named pom.xml
Copy the xml below into this file
Open the spring-source
folder in your console
Run mvn install
After download finished, you'll find spring jars in /spring-source/target/dependencies
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>spring-source-download</groupId>
<artifactId>SpringDependencies</artifactId>
<version>1.0</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.8</version>
<executions>
<execution>
<id>download-dependencies</id>
<phase>generate-resources</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/dependencies</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Also, if you need to download any other spring project, just copy the dependency
configuration from its corresponding web page.
For example, if you want to download Spring Web Flow
jars, go to its web page, and add its dependency
configuration to the pom.xml
dependencies
, then run mvn install
again.
<dependency>
<groupId>org.springframework.webflow</groupId>
<artifactId>spring-webflow</artifactId>
<version>2.3.2.RELEASE</version>
</dependency>
I have done it in this manner (I'm new in java(also in programming))
import java.util.Scanner;
public class SortingNumbers {
public static void main(String[] args) {
Scanner scan1=new Scanner(System.in);
System.out.print("How many numbers you want to sort: ");
int a=scan1.nextInt();
int i,j,k=0; // i and j is used in various loops.
int num[]=new int[a];
int great[]= new int[a]; //This array elements will be used to store "the number of being greater."
Scanner scan2=new Scanner(System.in);
System.out.println("Enter the numbers: ");
for(i=0;i<a;i++)
num[i] = scan2.nextInt();
for (i=0;i<a;i++) {
for(j=0;j<a;j++) {
if(num[i]>num[j]) //first time when executes this line, i=0 and j=0 and then i=0;j=1 and so on. each time it finishes second for loop the value of num[i] changes.
k++;}
great[i]=k++; //At the end of each for loop (second one) k++ contains the total of how many times a number is greater than the others.
k=0;} // And then, again k is forced to 0, so that it can collect (the total of how many times a number is greater) for another number.
System.out.print("Ascending Order: ");
for(i=0;i<a;i++)
for(j=0;j<a;j++)
if(great[j]==i) System.out.print(num[j]+","); //there is a fixed value for each great[j] that is, from 0 upto number of elements(input numbers).
System.out.print("Discending Order: ");
for(i=0;i<=a;i++)
for(j=0;j<a;j++)
if(great[j]==a-i) System.out.print(+num[j]+",");
}
}
From what I learned after several days of research, Here is the Guide for ASP .Net Core MVC 2.x Custom User Authentication
In Startup.cs
:
Add below lines to ConfigureServices
method :
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(
CookieAuthenticationDefaults.AuthenticationScheme
).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
options =>
{
options.LoginPath = "/Account/Login";
options.LogoutPath = "/Account/Logout";
});
services.AddMvc();
// authentication
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});
services.AddTransient(
m => new UserManager(
Configuration
.GetValue<string>(
DEFAULT_CONNECTIONSTRING //this is a string constant
)
)
);
services.AddDistributedMemoryCache();
}
keep in mind that in above code we said that if any unauthenticated user requests an action which is annotated with [Authorize]
, they well force redirect to /Account/Login
url.
Add below lines to Configure
method :
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler(ERROR_URL);
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: DEFAULT_ROUTING);
});
}
Create your UserManager
class that will also manage login and logout. it should look like below snippet (note that i'm using dapper):
public class UserManager
{
string _connectionString;
public UserManager(string connectionString)
{
_connectionString = connectionString;
}
public async void SignIn(HttpContext httpContext, UserDbModel user, bool isPersistent = false)
{
using (var con = new SqlConnection(_connectionString))
{
var queryString = "sp_user_login";
var dbUserData = con.Query<UserDbModel>(
queryString,
new
{
UserEmail = user.UserEmail,
UserPassword = user.UserPassword,
UserCellphone = user.UserCellphone
},
commandType: CommandType.StoredProcedure
).FirstOrDefault();
ClaimsIdentity identity = new ClaimsIdentity(this.GetUserClaims(dbUserData), CookieAuthenticationDefaults.AuthenticationScheme);
ClaimsPrincipal principal = new ClaimsPrincipal(identity);
await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
}
}
public async void SignOut(HttpContext httpContext)
{
await httpContext.SignOutAsync();
}
private IEnumerable<Claim> GetUserClaims(UserDbModel user)
{
List<Claim> claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id().ToString()));
claims.Add(new Claim(ClaimTypes.Name, user.UserFirstName));
claims.Add(new Claim(ClaimTypes.Email, user.UserEmail));
claims.AddRange(this.GetUserRoleClaims(user));
return claims;
}
private IEnumerable<Claim> GetUserRoleClaims(UserDbModel user)
{
List<Claim> claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id().ToString()));
claims.Add(new Claim(ClaimTypes.Role, user.UserPermissionType.ToString()));
return claims;
}
}
Then maybe you have an AccountController
which has a Login
Action that should look like below :
public class AccountController : Controller
{
UserManager _userManager;
public AccountController(UserManager userManager)
{
_userManager = userManager;
}
[HttpPost]
public IActionResult LogIn(LogInViewModel form)
{
if (!ModelState.IsValid)
return View(form);
try
{
//authenticate
var user = new UserDbModel()
{
UserEmail = form.Email,
UserCellphone = form.Cellphone,
UserPassword = form.Password
};
_userManager.SignIn(this.HttpContext, user);
return RedirectToAction("Search", "Home", null);
}
catch (Exception ex)
{
ModelState.AddModelError("summary", ex.Message);
return View(form);
}
}
}
Now you are able to use [Authorize]
annotation on any Action
or Controller
.
Feel free to comment any questions or bug's.
If this is coming from SQL Server Import Wizard, try editing the definition of the column on the Data Source, it is 50 characters by default, but it can be longer.
Data Soruce -> Advanced -> Look at the column that goes in error -> change OutputColumnWidth to 200 and try again.
All of these methods are great. I have found another simple resource that is a great example of creating a dynamic form using "onchange" with AJAX.
http://www.w3schools.com/php/php_ajax_database.asp
I simply modified the text table output to anther select dropdown populated based on the selection of the first drop down. For my application a user will select a state then the second dropdown will be populated with the cities for the selected state. Much like the JSON example above but with php and mysql.
As of now, the Go compiler generates identical code in both cases, so it is a matter of taste. GCCGo does generate different code, but barely anyone uses it so I wouldn't worry about that.
jQuery < 1.8
May I suggest that you use $.ajax()
instead of $.post()
as it's much more customizable.
If you are calling $.post()
, e.g., like this:
$.post( url, data, success, dataType );
You could turn it into its $.ajax()
equivalent:
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType,
async:false
});
Please note the async:false
at the end of the $.ajax()
parameter object.
Here you have a full detail of the $.ajax()
parameters: jQuery.ajax() – jQuery API Documentation.
jQuery >=1.8 "async:false" deprecation notice
jQuery >=1.8 won't block the UI during the http request, so we have to use a workaround to stop user interaction as long as the request is processed. For example:
$.ajax()
, and then remove it when the AJAX .done()
callback is called.Please have a look at this answer for an example.
We're using Django for RESTful web services.
Note that -- out of the box -- Django did not have fine-grained enough authentication for our needs. We used the Django-REST interface, which helped a lot. [We've since rolled our own because we'd made so many extensions that it had become a maintenance nightmare.]
We have two kinds of URL's: "html" URL's which implement the human-oriented HTML pages, and "json" URL's which implement the web-services oriented processing. Our view functions often look like this.
def someUsefulThing( request, object_id ):
# do some processing
return { a dictionary with results }
def htmlView( request, object_id ):
d = someUsefulThing( request, object_id )
render_to_response( 'template.html', d, ... )
def jsonView( request, object_id ):
d = someUsefulThing( request, object_id )
data = serializers.serialize( 'json', d['object'], fields=EXPOSED_FIELDS )
response = HttpResponse( data, status=200, content_type='application/json' )
response['Location']= reverse( 'some.path.to.this.view', kwargs={...} )
return response
The point being that the useful functionality is factored out of the two presentations. The JSON presentation is usually just one object that was requested. The HTML presentation often includes all kinds of navigation aids and other contextual clues that help people be productive.
The jsonView
functions are all very similar, which can be a bit annoying. But it's Python, so make them part of a callable class or write decorators if it helps.
Try to change Tomcat version, in my case tomcat "8.0.41" and "8.5.8" didn't work. But "8.5.37" worked fine.
Your Make file will have one or two dependency rules depending on whether you compile and link with a single command, or with one command for the compile and one for the link.
Dependency are a tree of rules that look like this (note that the indent must be a TAB):
main_target : source1 source2 etc
command to build main_target from sources
source1 : dependents for source1
command to build source1
There must be a blank line after the commands for a target, and there must not be a blank line before the commands. The first target in the makefile is the overall goal, and other targets are built only if the first target depends on them.
So your makefile will look something like this.
a3a.exe : a3driver.obj
link /out:a3a.exe a3driver.obj
a3driver.obj : a3driver.cpp
cc a3driver.cpp
Use libraries https://jar-download.com/maven-repository-class-search.php?search_box=org.apache.http.entity.mime Download the library and put it in your project
Be sure to serve up the file without a no-cache header! IE has issues with this, if user tries to "open" the download without saving first.
Use look behinds in preg_replace
to remove anything before //
.
preg_replace('(^[a-z]+:\/\/)', '', $url);
This will only replace if found in the beginning of the string, and will ignore if found later
There are various ways to make it done, very simple technique with security peace in mind, here might help you
1. First you need to install Flask
pip install flask
in your command prompt, which is a python microframework, don't be afraid that you need to have another prior knowledge to learn that, it's really simple and just a few line of code.
If you wish you learn Flask quickly for complete novice here is the tutorial that I also learn from Flask Tutorial for beginner (YouTube)
2.Create a new folder
- 1st file will be
server.py
from flask import Flask, render_template_x000D_
app = Flask(__name__)_x000D_
_x000D_
@app.route('/')_x000D_
def index():_x000D_
return render_template('index.html')_x000D_
_x000D_
@app.route('/my-link/')_x000D_
def my_link():_x000D_
print ('I got clicked!')_x000D_
_x000D_
return 'Click.'_x000D_
_x000D_
if __name__ == '__main__':_x000D_
app.run(debug=True)
_x000D_
-2nd create another subfolder inside previous folder and name it as templates file will be your html file
index.html
<!doctype html>_x000D_
_x000D_
_x000D_
<head><title>Test</title> _x000D_
<meta charset=utf-8> </head>_x000D_
<body>_x000D_
<h1>My Website</h1>_x000D_
<form action="/my-link/">_x000D_
<input type="submit" value="Click me" />_x000D_
</form>_x000D_
_x000D_
<button> <a href="/my-link/">Click me</a></button>_x000D_
_x000D_
</body>
_x000D_
3.. To run, open command prompt to the New folder directory, type python server.py
to run the script, then go to browser type localhost:5000
, then you will see button. You can click and route to destination script file you created.
Hope this helpful. thank you.
I'd suggest using the request module. Downloading a file is as simple as the following code:
var fs = require('fs'),
request = require('request');
var download = function(uri, filename, callback){
request.head(uri, function(err, res, body){
console.log('content-type:', res.headers['content-type']);
console.log('content-length:', res.headers['content-length']);
request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
});
};
download('https://www.google.com/images/srpr/logo3w.png', 'google.png', function(){
console.log('done');
});
Using @Marc Gravell 's answer, I found a way to use the following method:
source.TakeWhile(x => x != value).Count();
in order to get -1 when the item cannot be found:
internal static class Utils
{
public static int IndexOf<T>(this IEnumerable<T> enumerable, T item) => enumerable.IndexOf(item, EqualityComparer<T>.Default);
public static int IndexOf<T>(this IEnumerable<T> enumerable, T item, EqualityComparer<T> comparer)
{
int index = enumerable.TakeWhile(x => comparer.Equals(x, item)).Count();
return index == enumerable.Count() ? -1 : index;
}
}
I guess this way could be both the fastest and the simpler. However, I've not tested performances yet.
Python threads cannot take advantage of many cores. This is due to an internal implementation detail called the GIL (global interpreter lock) in the C implementation of python (cPython) which is almost certainly what you use.
The workaround is the multiprocessing
module http://www.python.org/dev/peps/pep-0371/ which was developed for this purpose.
Documentation: http://docs.python.org/library/multiprocessing.html
(Or use a parallel language.)
You can find the most up to date answer for the value in your project just execute the
mvn3 help:effective-pom
command and find the <build> ... <directory>
tag's value in the result aka in the effective-pom. It will show the value of the Super POM unless you have overwritten.
Despite other answers here, you should not use display:none
to hide the label element.
The accessible way to hide a label visually is to use an 'off-left' or 'clip' rule in your CSS. Using display:none
will prevent people who use screen-readers from having access to the content of the label element. Using display:none hides content from all users, and that includes screen-reader users (who benefit most from label elements).
label[for="foo"] {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
}
The W3C and WAI offer more guidance on this topic, including CSS for the 'clip' technique.
✗
✗
✘
✘
✕
✕
✖
✖
I think you can use the overload of Regex.Replace to specify the maximum number of times to replace...
var regex = new Regex(Regex.Escape("o"));
var newText = regex.Replace("Hello World", "Foo", 1);
Sub
don't return values and function
s don't have side effects.
Sometimes you want both side effect and return value.
This is easy to be done once you know that VBA passes arguments by default by reference so you can write your code in this way:
Sub getValue(retValue as Long)
...
retValue = 42
End SUb
Sub Main()
Dim retValue As Long
getValue retValue
...
End SUb
For PHP < 5.3 use:
$upOne = realpath(dirname(__FILE__) . '/..');
In PHP 5.3 to 5.6 use:
$upOne = realpath(__DIR__ . '/..');
In PHP >= 7.0 use:
$upOne = dirname(__DIR__, 1);
The best way to add PHP pages in WordPress to Page Template
in the child-theme
folder.
How to create Page Template
in WordPress.
Create a file named template-custom.php
and put it in /wp-content/theme/my-theme/
.
<?php
/*
* Template Name: Custom Template
* Custom template used for custom php code display
* @package Portafolio WordPress Theme
* @author Gufran Hasan
* @copyright Copyright templatecustom.com
* @link http://www.templatecustom.com
*/
?>
<?php get_header(); ?>
<?php
//write code here
?>
<?php get_footer(); ?>
Check your object owner if you copy the file from another aws account.
In my case, I copy the file from another aws account without acl, so file's owner is the other aws account, it's mean the file belongs to origin account.
To fix it, copy or sync s3 files with acl, example:
aws s3 cp --acl bucket-owner-full-control s3://bucket1/key s3://bucket2/key
or use display property with table-cell;
css
.table-layout {
display:table;
width:100%;
}
.table-layout .table-cell {
display:table-cell;
border:solid 1px #ccc;
}
.fixed-width-200 {
width:200px;
}
html
<div class="table-layout">
<div class="table-cell fixed-width-200">
<p>fixed width div</p>
</div>
<div class="table-cell">
<p>fluid width div</p>
</div>
</div>
Another way (assuming you are using vue-router
), is to map the query param to a prop in your router. Then you can treat it like any other prop in your component code. For example, add this route;
{
path: '/mypage',
name: 'mypage',
component: MyPage,
props: (route) => ({ foo: route.query.foo })
}
Then in your component you can add the prop as normal;
props: {
foo: {
type: String,
default: null
}
},
Then it will be available as this.foo
and you can do anything you want with it (like set a watcher, etc.)
Here is a simple example using the MVVM Light Messenger instead of an event. The view model sends a close message when a button is clicked:
public MainViewModel()
{
QuitCommand = new RelayCommand(ExecuteQuitCommand);
}
public RelayCommand QuitCommand { get; private set; }
private void ExecuteQuitCommand()
{
Messenger.Default.Send<CloseMessage>(new CloseMessage());
}
Then it is received in the code behind of the window.
public Main()
{
InitializeComponent();
Messenger.Default.Register<CloseMessage>(this, HandleCloseMessage);
}
private void HandleCloseMessage(CloseMessage closeMessage)
{
Close();
}
You could use tabs instead of spaces between columns, and/or set maximum size for a column in format strings ...
TextView textv = (TextView) findViewById(R.id.textview1);
textv.setShadowLayer(1, 0, 0, Color.BLACK);
Patrick is correct, both in the use of the xsl:if
, and in the syntax for checking for the existence of a node. However, as Patrick's response implies, there is no xsl equivalent to if-then-else, so if you are looking for something more like an if-then-else, you're normally better off using xsl:choose
and xsl:otherwise
. So, Patrick's example syntax will work, but this is an alternative:
<xsl:choose>
<xsl:when test="/html/body">body node exists</xsl:when>
<xsl:otherwise>body node missing</xsl:otherwise>
</xsl:choose>
Use this style to change only the nested lists:
ol {
counter-reset: item;
}
ol > li {
counter-increment: item;
}
ol ol > li {
display: block;
}
ol ol > li:before {
content: counters(item, ".") ". ";
margin-left: -20px;
}
You can check it easily using Java.lang.Class.getSimpleName()
Method Only if variable has non-primitive type. It doesnt work with primitive types int ,long etc.
reference - Here is the Oracle docs link
Assuming these are text files (since you are using notepad++) and that you are on Windows, you could fashion a simple batch script to concatenate them together.
For example, in the directory with all the text files, execute the following:
for %f in (*.txt) do type "%f" >> combined.txt
This will merge all files matching *.txt into one file called combined.txt.
For more information:
Well, if you study the structure of how the application life-cycle works,here , then you'll come to know that onPause()
is called when another activity gains focus, and onStop()
is called when the activity is no longer visible.
From what I have learned yet, you can call finish()
only from the activity which is active and/or has the focus. If you're calling finish()
from the onPause()
method that means you're calling it when the activity is no longer active. thus an exception is thrown.
When you're calling finish()
from onStop()
then the activity is being sent to background, thus will no longer be visible, then this exception.
When you press the back
button, onStop()
is called.
Most probably, Android will automatically do for you what you are currently wanting to do.
Filter the version number.
java -version 2>&1 | head -n 1 | awk -F '"' '{print $2}'
This works for me in irb:
irb> (1..4).to_a
=> [1, 2, 3, 4]
I notice that:
irb> 1..4.to_a
(irb):1: warning: default `to_a' will be obsolete
ArgumentError: bad value for range
from (irb):1
So perhaps you are missing the parentheses?
(I am running Ruby 1.8.6 patchlevel 114)
Use the logging module
def init_logging():
rootLogger = logging.getLogger('my_logger')
LOG_DIR = os.getcwd() + '/' + 'logs'
if not os.path.exists(LOG_DIR):
os.makedirs(LOG_DIR)
fileHandler = logging.FileHandler("{0}/{1}.log".format(LOG_DIR, "g2"))
rootLogger.addHandler(fileHandler)
rootLogger.setLevel(logging.DEBUG)
consoleHandler = logging.StreamHandler()
rootLogger.addHandler(consoleHandler)
return rootLogger
Get the logger:
logger = init_logging()
And start logging/output(ing):
logger.debug('Hi! :)')
I was in the same boat. Installed Eclipse, realized need CDT.
sudo apt-get install eclipse eclipse-cdt g++
This just adds the CDT package on top of existing installation - no un-installation etc. required.
The standard requires the array length to be a value that is computable at compile time so that the compiler is able to allocate enough space on the stack. In your case, you are trying to set the array length to a value that is unknown at compile time. Yes, i know that it seems obvious that it should be known to the compiler, but this is not the case here. The compiler cannot make any assumptions about the contents of non-constant variables. So go with:
const int row = 8;
const int col= 8;
int a[row][col];
UPD: some compilers will actually allow you to pull this off. IIRC, g++ has this feature. However, never use it because your code will become un-portable across compilers.
You have some very good answers here, but I'm to me, it looks like a case of "when all you know is a hammer"...
The simplest answer of to why there is no standard way to initialise a static map, is there is no good reason to ever use a static map...
A map is a structure designed for fast lookup, of an unknown set of elements. If you know the elements before hand, simply use a C-array. Enter the values in a sorted manner, or run sort on them, if you can't do this. You can then get log(n) performance by using the stl::functions to loop-up entries, lower_bound/upper_bound. When I have tested this previously they normally perform at least 4 times faster than a map.
The advantages are many fold... - faster performance (*4, I've measured on many CPU's types, it's always around 4) - simpler debugging. It's just easier to see what's going on with a linear layout. - Trivial implementations of copy operations, should that become necessary. - It allocates no memory at run time, so will never throw an exception. - It's a standard interface, and so is very easy to share across, DLL's, or languages, etc.
I could go on, but if you want more, why not look at Stroustrup's many blogs on the subject.
One common error is leaving a space before the class names. Even if this was the correct syntax:
.menu a:hover .main-nav-item
it never would have worked.
Therefore, you would not write
.menu a .main-nav-item:hover
it would be
.menu a.main-nav-item:hover
comm -23 <(ls dir1 |sort) <(ls dir2|sort)
This command will give you files those are in dir1 and not in dir2.
About <( )
sign, you can google it as 'process substitution'.
This should help you.
* {
margin: 0;
}
html, body {
height: 100%;
}
.wrapper {
min-height: 100%;
height: auto !important;
height: 100%;
margin: 0 auto -155px; /* the bottom margin is the negative value of the footer's height */
}
.footer {
height: 155px;
}
I took the various examples here, but in my particular situation we have a @PromisedDate for delivery and a @ReceivedDate for the actual receipt of the item. When an item was received before the "PromisedDate" the calculations were not totaling correctly unless I ordered the dates passed into the function by calendar order. Not wanting to check the dates every time, I changed the function to handle this for me.
Create FUNCTION [dbo].[fnGetBusinessDays]
(
@PromiseDate date,
@ReceivedDate date
)
RETURNS integer
AS
BEGIN
DECLARE @days integer
SELECT @days =
Case when @PromiseDate > @ReceivedDate Then
DATEDIFF(d,@PromiseDate,@ReceivedDate) +
ABS(DATEDIFF(wk,@PromiseDate,@ReceivedDate)) * 2 +
CASE
WHEN DATENAME(dw, @PromiseDate) <> 'Saturday' AND DATENAME(dw, @ReceivedDate) = 'Saturday' THEN 1
WHEN DATENAME(dw, @PromiseDate) = 'Saturday' AND DATENAME(dw, @ReceivedDate) <> 'Saturday' THEN -1
ELSE 0
END +
(Select COUNT(*) FROM CompanyHolidays
WHERE HolidayDate BETWEEN @ReceivedDate AND @PromiseDate
AND DATENAME(dw, HolidayDate) <> 'Saturday' AND DATENAME(dw, HolidayDate) <> 'Sunday')
Else
DATEDIFF(d,@PromiseDate,@ReceivedDate) -
ABS(DATEDIFF(wk,@PromiseDate,@ReceivedDate)) * 2 -
CASE
WHEN DATENAME(dw, @PromiseDate) <> 'Saturday' AND DATENAME(dw, @ReceivedDate) = 'Saturday' THEN 1
WHEN DATENAME(dw, @PromiseDate) = 'Saturday' AND DATENAME(dw, @ReceivedDate) <> 'Saturday' THEN -1
ELSE 0
END -
(Select COUNT(*) FROM CompanyHolidays
WHERE HolidayDate BETWEEN @PromiseDate and @ReceivedDate
AND DATENAME(dw, HolidayDate) <> 'Saturday' AND DATENAME(dw, HolidayDate) <> 'Sunday')
End
RETURN (@days)
END
Type in "netstat -ano" into your command line. I saw that it was showing something for Local Address port 0.0.0.0:80.
My issue was because I had SQL Server Reporting Services on Port 80. So I followed these instructions and changed the port # from 80 to 81:
Here is a picture of my command line after I changed the port number for SQL Server Reporting Services:
If you are still having the same issue, read this forum:
start
did not work for me.
I used:
firefox http://www.stackoverflow.com
or
chrome http://www.stackoverflow.com
Obviously not great for distributing it, but if you're using it for a specific machine, it should work fine.
Without annotations, inferred property name (to match from JSON) would be "set", and not -- as seems to be the intent -- "isSet". This is because as per Java Beans specification, methods of form "isXxx" and "setXxx" are taken to mean that there is logical property "xxx" to manage.
Check this out with IsNullOrEmpty and IsNullOrwhiteSpace
string sTestes = "I like sweat peaches";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
for (int i = 0; i < 5000000; i++)
{
for (int z = 0; z < 500; z++)
{
var x = string.IsNullOrEmpty(sTestes);// OR string.IsNullOrWhiteSpace
}
}
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);
Console.ReadLine();
You'll see that IsNullOrWhiteSpace is much slower :/
Basically I corrected it like below and everything worked fine.
<servlet>
<servlet-name >MyWebApplication</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.feature.Redirect</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.config.property.JSPTemplatesBasePath</param-name>
<param-value>/views/</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.config.property.WebPageContentRegex</param-name>
<param-value>/(images|css|jsp)/.*</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>MyWebApplication</servlet-name>
<url-pattern>/myapp/*</url-pattern>
</servlet-mapping>
Sometimes learning by example helps the most. Run this console application in three different console windows. You'll see that the application you ran first acquires the mutex first, while the other two are waiting their turn. Then press enter in the first application, you'll see that application 2 now continues running by acquiring the mutex, however application 3 is waiting its turn. After you press enter in application 2 you'll see that application 3 continues. This illustrates the concept of a mutex protecting a section of code to be executed only by one thread (in this case a process) like writing to a file as an example.
using System;
using System.Threading;
namespace MutexExample
{
class Program
{
static Mutex m = new Mutex(false, "myMutex");//create a new NAMED mutex, DO NOT OWN IT
static void Main(string[] args)
{
Console.WriteLine("Waiting to acquire Mutex");
m.WaitOne(); //ask to own the mutex, you'll be queued until it is released
Console.WriteLine("Mutex acquired.\nPress enter to release Mutex");
Console.ReadLine();
m.ReleaseMutex();//release the mutex so other processes can use it
}
}
}
var updateQueryStringParameter = function (key, value) {
var baseUrl = [location.protocol, '//', location.host, location.pathname].join(''),
urlQueryString = document.location.search,
newParam = key + '=' + value,
params = '?' + newParam;
// If the "search" string exists, then build params from it
if (urlQueryString) {
var updateRegex = new RegExp('([\?&])' + key + '[^&]*');
var removeRegex = new RegExp('([\?&])' + key + '=[^&;]+[&;]?');
if( typeof value == 'undefined' || value == null || value == '' ) {
params = urlQueryString.replace(removeRegex, "$1");
params = params.replace( /[&;]$/, "" );
} else if (urlQueryString.match(updateRegex) !== null) {
params = urlQueryString.replace(updateRegex, "$1" + newParam);
} else {
params = urlQueryString + '&' + newParam;
}
}
// no parameter was set so we don't need the question mark
params = params == '?' ? '' : params;
window.history.replaceState({}, "", baseUrl + params);
};
In case your DateTime has also hour:minutes:seconds and you still want to have the number of days..
/**
* Returns the total number of days between to DateTimes,
* if it is within the same year
* @param $start
* @param $end
*/
public function dateTimesToDays($start,$end){
return intval($end->format('z')) - intval($start->format('z')) + 1;
}
Yes, you can get it from the File
object by using File.toPath()
. Keep in mind that this is only for Java 7+. Java versions 6 and below do not have it.
If you are trying to take a value from the same array and trying to update it, you can use the following code.
{ 'condition': {
'ts': [ '5a81625ba0ff65023c729022',
'5a8161ada0ff65023c728f51',
'5a815fb4a0ff65023c728dcd']}
If the collection is userData['condition']['ts'] and we need to
for i,supplier in enumerate(userData['condition']['ts']):
supplier = ObjectId(supplier)
userData['condition']['ts'][i] = supplier
The output will be
{'condition': { 'ts': [ ObjectId('5a81625ba0ff65023c729022'),
ObjectId('5a8161ada0ff65023c728f51'),
ObjectId('5a815fb4a0ff65023c728dcd')]}
An important point that the other answers forgot, is that "@keyword" is compiled into "keyword" in the CIL.
So if you have a framework that was made in, say, F#, which requires you to define a class with a property named "class", you can actually do it.
It is not that useful in practice, but not having it would prevent C# from some forms of language interop.
I usually see it used not for interop, but to avoid the keyword restrictions (usually on local variable names, where this is the only effect) ie.
private void Foo(){
int @this = 2;
}
but I would strongly discourage that! Just find another name, even if the 'best' name for the variable is one of the reserved names.
Here is one way to do this using css
HTML
<div class="imageWrapper">
<img src="http://lorempixel.com/300/300/" alt="" />
<a href="http://google.com" class="cornerLink">Link</a>
</div>?
CSS
.imageWrapper {
position: relative;
width: 300px;
height: 300px;
}
.imageWrapper img {
display: block;
}
.imageWrapper .cornerLink {
opacity: 0;
position: absolute;
bottom: 0px;
left: 0px;
right: 0px;
padding: 2px 0px;
color: #ffffff;
background: #000000;
text-decoration: none;
text-align: center;
-webkit-transition: opacity 500ms;
-moz-transition: opacity 500ms;
-o-transition: opacity 500ms;
transition: opacity 500ms;
}
.imageWrapper:hover .cornerLink {
opacity: 0.8;
}
Or if you just want it in the bottom left corner:
You can use the excellent jquery-Json plugin:
http://code.google.com/p/jquery-json/
Makes it easy to convert to and from Json objects.
The very best and simplest answer is:
var isDefinedPath = function (path) {
var items = path.split ('.');
if (!items || items.length < 1 || !(items[0] in window)) { return false; }
var buffer = [items[0]];
for (var i = 1, e = items.length; i < e; i ++) {
buffer.push (items[i]);
if (eval ('typeof(' + buffer.join ('.') + ') == "undefined"')) {
return false;
}
}
return true;
}
test: isDefinedPath ('level1.level2.level3');
first level cannot be array, others can
I've extracted my sql from PreparedStatement using preparedStatement.toString() In my case toString() returns String like this:
org.hsqldb.jdbc.JDBCPreparedStatement@7098b907[sql=[INSERT INTO
TABLE_NAME(COLUMN_NAME, COLUMN_NAME, COLUMN_NAME) VALUES(?, ?, ?)],
parameters=[[value], [value], [value]]]
Now I've created a method (Java 8), which is using regex to extract both query and values and put them into map:
private Map<String, String> extractSql(PreparedStatement preparedStatement) {
Map<String, String> extractedParameters = new HashMap<>();
Pattern pattern = Pattern.compile(".*\\[sql=\\[(.*)],\\sparameters=\\[(.*)]].*");
Matcher matcher = pattern.matcher(preparedStatement.toString());
while (matcher.find()) {
extractedParameters.put("query", matcher.group(1));
extractedParameters.put("values", Stream.of(matcher.group(2).split(","))
.map(line -> line.replaceAll("(\\[|])", ""))
.collect(Collectors.joining(", ")));
}
return extractedParameters;
}
This method returns map where we have key-value pairs:
"query" -> "INSERT INTO TABLE_NAME(COLUMN_NAME, COLUMN_NAME, COLUMN_NAME) VALUES(?, ?, ?)"
"values" -> "value, value, value"
Now - if you want values as list you can just simply use:
List<String> values = Stream.of(yourExtractedParametersMap.get("values").split(","))
.collect(Collectors.toList());
If your preparedStatement.toString() is different than in my case it's just a matter of "adjusting" regex.
Quite an old article on mssqlcity attempts to explain the types of locks:
Shared locks are used for operations that do not change or update data, such as a SELECT statement.
Update locks are used when SQL Server intends to modify a page, and later promotes the update page lock to an exclusive page lock before actually making the changes.
Exclusive locks are used for the data modification operations, such as UPDATE, INSERT, or DELETE.
What it doesn't discuss are Intent (which basically is a modifier for these lock types). Intent (Shared/Exclusive) locks are locks held at a higher level than the real lock. So, for instance, if your transaction has an X lock on a row, it will also have an IX lock at the table level (which stops other transactions from attempting to obtain an incompatible lock at a higher level on the table (e.g. a schema modification lock) until your transaction completes or rolls back).
The concept of "sharing" a lock is quite straightforward - multiple transactions can have a Shared lock for the same resource, whereas only a single transaction may have an Exclusive lock, and an Exclusive lock precludes any transaction from obtaining or holding a Shared lock.
If you want to compare to a string literal you need to put it in (single) quotes:
<xsl:if test="Count != 'N/A'">
almost there, just change outerWidth: 100%;
to width: auto;
(outerWidth is not a CSS property)
alternatively, apply the following styles to bar:
width: auto;
display: block;
You can increase the List View Threshold beyond the 5,000 default, but it is highly recommended that you don't, as it has performance implications. The recommended fix is to add an index to the field or fields used in the query (usually the ID field for a list or the Title field for a library).
When there is an index, that is used to retrieve the item(s); when there is no index the whole list is opened for a scan (and therefore hits the threshold). You create the index on the List (or Library) settings page.
This article is a good overview: http://office.microsoft.com/en-us/sharepoint-foundation-help/manage-lists-and-libraries-with-many-items-HA010377496.aspx
I've used xcode-select --install
given in the accepted answer in previous major releases.
I've just upgraded to OS X 10.15 Catalina and run the Software Update tool from preferences again after the OS upgrade completed. The Xcode utilities update was available there, which also sorted the issue using git which had just output
xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)
We can change context root path using a simple entry in the properties file.
application.properties
### Spring boot 1.x #########
server.contextPath=/ClientApp
### Spring boot 2.x #########
server.servlet.context-path=/ClientApp
You can create an html page with a form, having method="post" and action="yourdesiredurl" and open it with your browser.
As an alternative, there are some browser plugins for developers that allow you to do that, like Web Developer Toolbar for Firefox
Hash map works on the principle of hashing
HashMap get(Key k) method calls hashCode method on the key object and applies returned hashValue to its own static hash function to find a bucket location(backing array) where keys and values are stored in form of a nested class called Entry (Map.Entry) . So you have concluded that from the previous line that Both key and value is stored in the bucket as a form of Entry object . So thinking that Only value is stored in the bucket is not correct and will not give a good impression on the interviewer .
If key is null , then Null keys always map to hash 0, thus index 0.
If key is not null then , it will call hashfunction on the key object , see line 4 in above method i.e. key.hashCode() ,so after key.hashCode() returns hashValue , line 4 looks like
int hash = hash(hashValue)
and now ,it applies returned hashValue into its own hashing function .
We might wonder why we are calculating the hashvalue again using hash(hashValue). Answer is It defends against poor quality hash functions.
Now final hashvalue is used to find the bucket location at which the Entry object is stored . Entry object stores in the bucket like this (hash,key,value,bucketindex)
While Docker for Windows is perfectly able to run Linux containers, the converse, while theoretically possible, is not implemented due to practical reasons.
The most obvious one is, while Docker for Windows can run a Linux VM freely, Docker for Linux would require a Windows license in order to run it inside a VM.
Also, Linux is completely customizable, so the Linux VM used by Docker for Windows has been stripped down to just a few MB, containing only the bare minimum needed to run the containers, while the smallest Windows distribution available is about 1.5 GB. It may not be an impracticable size, but it is much more cumbersome than the Linux on Windows counterpart.
While it is certainly possible for someone to sell a Docker for Linux variation bundled with a Windows license and ready to run Windows containers under Linux (and I don't know if such product exists), the bottom line is that you can't avoid paying Windows vendor lock-in price: both in money and storage space.
FindViewById can be null if you call the wrong super constructor in a custom view. The ID tag is part of attrs, so if you ignore attrs, you delete the ID.
This would be wrong
public CameraSurfaceView(Context context, AttributeSet attrs) {
super(context);
}
This is correct
public CameraSurfaceView(Context context, AttributeSet attrs) {
super(context,attrs);
}
Library Seaborn has this built in with function .despine()
.
Just add:
import seaborn as sns
Now create your graph. And add at the end:
sns.despine()
If you look at some of the default parameter values of the function it removes the top and right spine and keeps the bottom and left spine:
sns.despine(top=True, right=True, left=False, bottom=False)
Check out further documentation here: https://seaborn.pydata.org/generated/seaborn.despine.html
I'd also suggest moving the event handler outside render.
var OnSubmitTest = React.createClass({
submit: function(e){
e.preventDefault();
alert('it works!');
}
render: function() {
return (
<form onSubmit={this.submit}>
<button>Click me</button>
</form>
);
}
});
On modern browsers (FF >= 3.6, Chrome >= 19.0, Opera >= 12.0, and buggy on Safari), you can use the HTML5 File API. When the value of a file input changes, this API will allow you to check whether the file size is within your requirements. Of course, this, as well as MAX_FILE_SIZE
, can be tampered with so always use server side validation.
<form method="post" enctype="multipart/form-data" action="upload.php">
<input type="file" name="file" id="file" />
<input type="submit" name="submit" value="Submit" />
</form>
<script>
document.forms[0].addEventListener('submit', function( evt ) {
var file = document.getElementById('file').files[0];
if(file && file.size < 10485760) { // 10 MB (this size is in bytes)
//Submit form
} else {
//Prevent default and display error
evt.preventDefault();
}
}, false);
</script>
On the server side, it is impossible to stop an upload from happening from PHP because once PHP has been invoked the upload has already completed. If you are trying to save bandwidth, you can deny uploads from the server side with the ini setting upload_max_filesize
. The trouble with this is this applies to all uploads so you'll have to pick something liberal that works for all of your uploads. The use of MAX_FILE_SIZE
has been discussed in other answers. I suggest reading the manual on it. Do know that it, along with anything else client side (including the javascript check), can be tampered with so you should always have server side (PHP) validation.
On the server side you should validate that the file is within the size restrictions (because everything up to this point except for the INI setting could be tampered with). You can use the $_FILES
array to find out the upload size. (Docs on the contents of $_FILES
can be found below the MAX_FILE_SIZE
docs)
upload.php
<?php
if(isset($_FILES['file'])) {
if($_FILES['file']['size'] > 10485760) { //10 MB (size is also in bytes)
// File too big
} else {
// File within size restrictions
}
}
Now in new version magento2 on Generate error Service Temporarily Unavailable.
Remove maintenance.flag
From this path which is changed magento2/var/maintenance.flag
.
Also
$ rm maintenance.flag
If the place you're gonna paste have no problem with pasting a table formating (like the browser URL bar), I think the easiest way is this:
Sheets(1).Range("A1000").Value = string
Sheets(1).Range("A1000").Copy
MsgBox "Paste before closing this dialog."
Sheets(1).Range("A1000").Value = ""
Shows the Computer Name, Use a Button to call it
Dim strHostName As String
strHostName = System.Net.Dns.GetHostName(). MsgBox(strHostName)
Shows the User Name, Use a Button to call it
If TypeOf My.User.CurrentPrincipal Is Security.Principal.WindowsPrincipal Then
Dim parts() As String = Split(My.User.Name, "\") Dim username As String = parts(1) MsgBox(username) End If
For IP Address its little complicated, But I try to explain as much as I can. First write the next code, before Form1_Load but after import section
Public Class Form1
Dim mem As String Private Sub GetIPAddress() Dim strHostName As String Dim strIPAddress As String strHostName = System.Net.Dns.GetHostName() strIPAddress = System.Net.Dns.GetHostByName(strHostName).AddressList(0).ToString() mem = strIPAddress MessageBox.Show("IP Address: " & strIPAddress) End Sub
Then in Form1_Load Section just call it
GetIPAddress()
Result: On form load it will show a msgbox along with the IP address, for put into Label1.text or some where else play with the code.
I think you just need to set the db to single user mode before attempting to restore, like below, just make sure you're using master
USE master
GO
ALTER DATABASE AdventureWorksDW
SET SINGLE_USER
I used the attached formula to categorize sales figures into/within intervals of a bin range as shown the formula is:
=IF(MOD(B5,$B$1)<>0,($B$1*(1+((B5-(MOD(B5,$B$1)))/$B$1))),($B$1*(1+((B5-(MOD(B5,$B$1)))/$B$1))-$B$1))
Here cells are as shown in example
No, is not possible to downgrade a database. 10.50.1600 is the SQL Server 2008 R2 version. There is absolutely no way you can restore or attach this database to the SQL Server 2008 instance you are trying to restore on (10.00.1600 is SQL Server 2008). Your only options are:
Here's a library that really helps: https://cdn.rawgit.com/ccampbell/mousetrap/2e5c2a8adbe80a89050aaf4e02c45f02f1cc12d4/tests/libs/key-event.js
I don't know from where did it came from, but it is helpful. It adds a .simulate()
method to window.KeyEvent
, so you use it simply with KeyEvent.simulate(0, 13)
for simulating an enter
or KeyEvent.simulate(81, 81)
for a 'Q'
.
I got it at https://github.com/ccampbell/mousetrap/tree/master/tests.
E.g : "abcd: efg: 1006746" "bhddy: nshhf36: 1006754" "hfquv: nd: 5894254"
-Step 1: String firstString = "abcd: efg: 1006746";
-Step 2: String lastSevenNumber = firstString.substring(firstString.lastIndexOf(':'), firstString.length()).trim();
Update project gradle version
classpath 'com.android.tools.build:gradle:3.2.1'
Update app gradle:implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
By creating the increment table you should be aware not to delete inserted rows. reason for this is to avoid storing large dumb data in db with ID-s in it. Otherwise in case of mysql restart it would get max existing row and continue increment from that point as mention in documentation http://dev.mysql.com/doc/refman/5.0/en/innodb-auto-increment-handling.html
For the record, none of the answers above helped except for one. To summarize, you can do the backup operation using --files-from=
by using either:
rsync -aSvuc `cat rsync-src-files` /mnt/d/rsync_test/
OR
rsync -aSvuc --recursive --files-from=rsync-src-files . /mnt/d/rsync_test/
The former command is self explanatory, beside the content of the file rsync-src-files
which I will elaborate down below. Now, if you want to use the latter version, you need to keep in mind the following four remarks:
--files-from
and the source directory--recursive
. rsync-src-files
is a user created file and it was placed within the src directory for this testrsyn-src-files
contain the files and folders to copy and they are taken relative to the source directory. IMPORTANT: Make sure there is not trailing spaces or blank lines in the file. In the example below, there are only two lines, not three (Figure it out by chance). Content of rsynch-src-files
is:folderName1
folderName2
Use jQuery's
$(this).addClass('showhideExtra_up_hover');
and
$(this).addClass('showhideExtra_down_hover');
To inject an Object, its class must be known to the CDI mechanism. Usualy adding the @Named annotation will do the trick.
It is not standard as far as I know. A quick look at http://json.org/ confirms this.
Open folder path of Android application, open src
folder then Add your image in /res/drawable
folder
I came across the same error after updating to the latest version of JQuery. Therefore I updated the jquery file I was working on, as stated in a previous answer, so it said .on("load")
instead of .load()
.
This fix isn't very stable and sometimes it didn't work for me. Therefore to fix this issue you should update your code from:
.load();
to
.trigger("load");
I got this fix from the following source: https://github.com/stevenwanderski/bxslider-4/pull/1024
I submit my own implementation, which handles null
values and should be more performant on account of using array lookup tables, manual hex conversion, and avoiding switch
statements.
using System;
using System.Text;
using System.Linq;
public static class StringLiteralEncoding {
private static readonly char[] HEX_DIGIT_LOWER = "0123456789abcdef".ToCharArray();
private static readonly char[] LITERALENCODE_ESCAPE_CHARS;
static StringLiteralEncoding() {
// Per http://msdn.microsoft.com/en-us/library/h21280bw.aspx
var escapes = new string[] { "\aa", "\bb", "\ff", "\nn", "\rr", "\tt", "\vv", "\"\"", "\\\\", "??", "\00" };
LITERALENCODE_ESCAPE_CHARS = new char[escapes.Max(e => e[0]) + 1];
foreach(var escape in escapes)
LITERALENCODE_ESCAPE_CHARS[escape[0]] = escape[1];
}
/// <summary>
/// Convert the string to the equivalent C# string literal, enclosing the string in double quotes and inserting
/// escape sequences as necessary.
/// </summary>
/// <param name="s">The string to be converted to a C# string literal.</param>
/// <returns><paramref name="s"/> represented as a C# string literal.</returns>
public static string Encode(string s) {
if(null == s) return "null";
var sb = new StringBuilder(s.Length + 2).Append('"');
for(var rp = 0; rp < s.Length; rp++) {
var c = s[rp];
if(c < LITERALENCODE_ESCAPE_CHARS.Length && '\0' != LITERALENCODE_ESCAPE_CHARS[c])
sb.Append('\\').Append(LITERALENCODE_ESCAPE_CHARS[c]);
else if('~' >= c && c >= ' ')
sb.Append(c);
else
sb.Append(@"\x")
.Append(HEX_DIGIT_LOWER[c >> 12 & 0x0F])
.Append(HEX_DIGIT_LOWER[c >> 8 & 0x0F])
.Append(HEX_DIGIT_LOWER[c >> 4 & 0x0F])
.Append(HEX_DIGIT_LOWER[c & 0x0F]);
}
return sb.Append('"').ToString();
}
}
You can just use the one-liner
echo colorscheme koehler >> ~/.vimrc
and replace koehler
with any other available colorscheme. Imho, all of them are better than default.
See this article for a longer discussion of named actions. It also shows that you can use the [HttpGet] attribute instead of prefixing the action name with "get".
http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
I came here because I had the same problem.
What was the problem for me was that the procedure was defined in the package body, but not in the package header.
I was executing my function with a lose BEGIN END statement.
I'm not going to get in a debate about whether or not this method should be used, but this will let you set specific css attributes for IE8-9 only (note: it is not a selector, so a bit different than what you asked):
Use '\0/' after each css declaration, so:
#nav li ul {
left: -39px\0/ !important;
}
And to build off another answer, you can do this to assign variou styles to IE6, IE7, and IE8:
#nav li ul {
*left: -7px !important; /* IE 7 (IE6 also uses this, so put it first) */
_left: -6px !important; /* IE 6 */
left: -8px\0/ !important; /* IE 8-9 */
}
source: http://dimox.net/personal-css-hacks-for-ie6-ie7-ie8/
I am going to give you a simplistic answer that hopefully will help you with VBA in general. The easiest way to learn how VBA works and how to reference and access elements is to record your macro then edit it in the VBA editor. This is how I learned VBA. It is based on visual basic so all the programming conventions of VB apply. Recording the macro lets you see how to access and do things.
you could use something like this:
var result = 0
Sheets("Sheet1").Select
result = Range("A1").Value * Range("B1").Value
Sheets("Sheet2").Select
Range("D1").Value = result
Alternatively you can also reference a cell using Cells(1,1).Value
This way you can set variables and increment them as you wish. I think I am just not clear on exactly what you are trying to do but i hope this helps.
Update
The procedure presented below gives an example of parsing XML with VBA using the XML DOM objects. Code is based on a beginners guide of the XML DOM.
Public Sub LoadDocument()
Dim xDoc As MSXML.DOMDocument
Set xDoc = New MSXML.DOMDocument
xDoc.validateOnParse = False
If xDoc.Load("C:\My Documents\sample.xml") Then
' The document loaded successfully.
' Now do something intersting.
DisplayNode xDoc.childNodes, 0
Else
' The document failed to load.
' See the previous listing for error information.
End If
End Sub
Public Sub DisplayNode(ByRef Nodes As MSXML.IXMLDOMNodeList, _
ByVal Indent As Integer)
Dim xNode As MSXML.IXMLDOMNode
Indent = Indent + 2
For Each xNode In Nodes
If xNode.nodeType = NODE_TEXT Then
Debug.Print Space$(Indent) & xNode.parentNode.nodeName & _
":" & xNode.nodeValue
End If
If xNode.hasChildNodes Then
DisplayNode xNode.childNodes, Indent
End If
Next xNode
End Sub
Nota Bene - This initial answer shows the simplest possible thing I could imagine (at the time I was working on a very specific issue) . Naturally using the XML facilities built into the VBA XML Dom would be much better. See the updates above.
Original Response
I know this is a very old post but I wanted to share my simple solution to this complicated question. Primarily I've used basic string functions to access the xml data.
This assumes you have some xml data (in the temp variable) that has been returned within a VBA function. Interestingly enough one can also see how I am linking to an xml web service to retrieve the value. The function shown in the image also takes a lookup value because this Excel VBA function can be accessed from within a cell using = FunctionName(value1, value2) to return values via the web service into a spreadsheet.
openTag = ""
closeTag = ""
' Locate the position of the enclosing tags
startPos = InStr(1, temp, openTag)
endPos = InStr(1, temp, closeTag)
startTagPos = InStr(startPos, temp, ">") + 1
' Parse xml for returned value
Data = Mid(temp, startTagPos, endPos - startTagPos)
A note in response to Belter's comment on fedtuck's accepted answer above, since I lack the reputation to add comments.
This is not true for any of which I am aware, in line with the Mozilla docs
disabled equals to true or false
When the disabled attribute is present the element is disabled regardless of value. See this example
<input placeholder="i can be changed"/>
<input disabled placeholder="i can NOT be changed"/>
<input disabled="true" placeholder="i can NOT be changed"/>
<input disabled="false" placeholder="i can NOT be changed"/>
The shortest way around - try:
echo $opt | sed "s/\"//g"
It actually removes all "
s (double quotes) from opt
(are there really going to be any more double quotes other than in the beginning and the end though? So it's actually the same thing, and much more brief ;-))
You can directly access a global variable inside a function. If you want to change the value of that global variable, use "global variable_name". See the following example:
var = 1
def global_var_change():
global var
var = "value changed"
global_var_change() #call the function for changes
print var
Generally speaking, this is not a good programming practice. By breaking namespace logic, code can become difficult to understand and debug.
You almost did it. You were tricked by the fact that abs(imagem-255)
will give a wrong result since your dtype
is an unsigned integer. You have to do (255-imagem)
in order to keep the integers unsigned:
def inverte(imagem, name):
imagem = (255-imagem)
cv2.imwrite(name, imagem)
You can also invert the image using the bitwise_not
function of OpenCV:
imagem = cv2.bitwise_not(imagem)
For nested dictionary/JSON lookups, you can use dictor
pip install dictor
dict object
{
"characters": {
"Lonestar": {
"id": 55923,
"role": "renegade",
"items": [
"space winnebago",
"leather jacket"
]
},
"Barfolomew": {
"id": 55924,
"role": "mawg",
"items": [
"peanut butter jar",
"waggy tail"
]
},
"Dark Helmet": {
"id": 99999,
"role": "Good is dumb",
"items": [
"Shwartz",
"helmet"
]
},
"Skroob": {
"id": 12345,
"role": "Spaceballs CEO",
"items": [
"luggage"
]
}
}
}
to get Lonestar's items, simply provide a dot-separated path, ie
import json
from dictor import dictor
with open('test.json') as data:
data = json.load(data)
print dictor(data, 'characters.Lonestar.items')
>> [u'space winnebago', u'leather jacket']
you can provide fallback value in case the key isnt in path
theres tons more options you can do, like ignore letter casing and using other characters besides '.' as a path separator,
Update 3: There is an official api added for this, please use ActivityLifecycleCallbacks instead.
For Notepad++ v.7.6 and above Plugins Admin... is available.
Open Menu Plugins > Plugins Admin...
Search JSON Viewer
Check JSON Viewer in List
Click on Install Button
Restart Notepad++
Select JSON text
Go to Plugins > JSON Viewer > Format JSON ( Ctrl + Alt + Shift + M )
We can install any Notepad++ supported plugins using Plugins Admin...
The best practice is using File.separator in the paths.
The only solution that worked for me was this command :
docker-compose build --no-cache
This will automatically pull fresh image from repo and won't use the cache version that is prebuild with any parameters you've been using before.
Cookies are not for authentication. Why reinvent a wheel? HTTP has well-designed authentication mechanisms. If we use cookies, we fall into using HTTP as a transport protocol only, thus we need to create our own signaling system, for example, to tell users that they supplied wrong authentication (using HTTP 401 would be incorrect as we probably wouldn't supply Www-Authenticate
to a client, as HTTP specs require :) ). It should also be noted that Set-Cookie
is only a recommendation for client. Its contents may be or may not be saved (for example, if cookies are disabled), while Authorization
header is sent automatically on every request.
Another point is that, to obtain an authorization cookie, you'll probably want to supply your credentials somewhere first? If so, then wouldn't it be RESTless? Simple example:
GET /a
without cookiePOST /auth
Set-Cookie
GET /a
with cookie. But does GET /a
behave idempotently in this case?To sum this up, I believe that if we access some resource and we need to authenticate, then we must authenticate on that same resource, not anywhere else.
Let's answer your questions one by one.
Another way to use key($array) in a foreach loop is by using next($array) at the end of the loop, just make sure each iteration calls the next() function (in case you have complex branching inside the loop)
On my system (Ubuntu 17.10) your example just works as desired, both when typed from the command line (into sh
) and when executed as a sh
script:
[bash]§ sh
$ STR="Hello\nWorld"
$ echo $STR
Hello
World
$ exit
[bash]§ echo "STR=\"Hello\nWorld\"
> echo \$STR" > test-str.sh
[bash]§ cat test-str.sh
STR="Hello\nWorld"
echo $STR
[bash]§ sh test-str.sh
Hello
World
I guess this answers your question: it just works. (I have not tried to figure out details such as at what moment exactly the substitution of the newline character for \n
happens in sh
).
However, i noticed that this same script would behave differently when executed with bash
and would print out Hello\nWorld
instead:
[bash]§ bash test-str.sh
Hello\nWorld
I've managed to get the desired output with bash
as follows:
[bash]§ STR="Hello
> World"
[bash]§ echo "$STR"
Note the double quotes around $STR
. This behaves identically if saved and run as a bash
script.
The following also gives the desired output:
[bash]§ echo "Hello
> World"
This is a limit of the C++ compiler. If you put the function in the header, all the cpp files where it can be inlined can see the "source" of your function and the inlining can be done by the compiler. Otherwhise the inlining would have to be done by the linker (each cpp file is compiled in an obj file separately). The problem is that it would be much more difficult to do it in the linker. A similar problem exists with "template" classes/functions. They need to be instantiated by the compiler, because the linker would have problem instantiating (creating a specialized version of) them. Some newer compiler/linker can do a "two pass" compilation/linking where the compiler does a first pass, then the linker does its work and call the compiler to resolve unresolved things (inline/templates...)
Copy your images into the assets folder. Angular can only access static files like images and config files from assets folder.
Try like this: <img src="assets/img/myimage.png">
status of 200 will be the default when using res.send
, res.json
, etc.
You can set the status like res.status(500).json({ error: 'something is wrong' });
Often I'll do something like...
router.get('/something', function(req, res, next) {
// Some stuff here
if(err) {
res.status(500);
return next(err);
}
// More stuff here
});
Then have my error middleware send the response, and do anything else I need to do when there is an error.
Additionally: res.sendStatus(status)
has been added as of version 4.9.0
http://expressjs.com/4x/api.html#res.sendStatus
To dynamically construct the returnUrl in any View, try this:
@{
var formCollection =
new FormCollection
{
new FormCollection(Request.Form),
new FormCollection(Request.QueryString)
};
var parameters = new RouteValueDictionary();
formCollection.AllKeys
.Select(k => new KeyValuePair<string, string>(k, formCollection[k])).ToList()
.ForEach(p => parameters.Add(p.Key, p.Value));
}
<!-- Option #1 -->
@Html.ActionLink("Option #1", "Action", "Controller", parameters, null)
<!-- Option #2 -->
<a href="/Controller/Action/@[email protected](ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString(), parameters)">Option #2</a>
<!-- Option #3 -->
<a href="@Url.Action("Action", "Controller", new { object.ID, returnUrl = Url.Action(ViewContext.RouteData.Values["action"].ToString(), ViewContext.RouteData.Values["controller"].ToString(), parameters) }, null)">Option #3</a>
This also works in Layout Pages, Partial Views and Html Helpers
Related: MVC3 Dynamic Return URL (Same but from within any Controller/Action)
Another simple way:
Dir.mkdir('tmp/excel') unless Dir.exist?('tmp/excel')
To send an objective-c message in this instance you would do
[self score];
I suggest you read the Objective-C programming guide Objective-C Programming Guide
Try to delete that "angular/cli": "1.0.0-beta.28.3",
in the devDependencies
it is useless , and add instead of it "@angular/compiler-cli": "^2.3.1",
(since it is the current version, else add it by npm i --save-dev @angular/compiler-cli
), then in your root app folder run those commands:
rm -r node_modules
(or delete your node_modules
folder manually)npm cache clean
(npm > v5 add --force
so: npm cache clean --force
)npm install
Find the constraint
SELECT *
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('TABLE_NAME')
Execute the SQL generated by this SQL
SELECT
'ALTER TABLE ' + OBJECT_SCHEMA_NAME(parent_object_id) +
'.[' + OBJECT_NAME(parent_object_id) +
'] DROP CONSTRAINT ' + name
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('TABLE_NAME')
Safeway.
Note: Added solution for droping the constraint so that table can be dropped or modified without any constraint error.
After spending few hours on this i think this is best way to apply pagination. And more importantly it works.
This is my paginator code
<mat-paginator #paginatoR [length]="length" [pageSize]="pageSize" [pageSizeOptions]="pageSizeOptions">
Inside my component @ViewChild(MatPaginator) paginator: MatPaginator;
to view child and finally you have to bind paginator to table dataSource and this is how it is done
ngAfterViewInit() {this.dataSource.paginator = this.paginator;}
Easy right? if it works for you then mark this as answer.
Arrays.sort(arr);
int max=0,mode=0,count=0;
for(int i=0;i<N;i=i+count) {
count = 1;
for(int j=i+1; j<N; j++) {
if(arr[i] == arr[j])
count++;
}
if(count>max) {
max=count;
mode = arr[i];
}
}
os.walk is the answer, this will find the first match:
import os
def find(name, path):
for root, dirs, files in os.walk(path):
if name in files:
return os.path.join(root, name)
And this will find all matches:
def find_all(name, path):
result = []
for root, dirs, files in os.walk(path):
if name in files:
result.append(os.path.join(root, name))
return result
And this will match a pattern:
import os, fnmatch
def find(pattern, path):
result = []
for root, dirs, files in os.walk(path):
for name in files:
if fnmatch.fnmatch(name, pattern):
result.append(os.path.join(root, name))
return result
find('*.txt', '/path/to/dir')
I realize this is an old thread, but @alex 's answer needs to be marked as the correct answer
element.getBoundingClientRect()
is an exact match to jQuery's $(element).offset()
And it's compatible with IE4+ ... https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect
If I remember correctly, you have to add the following code to your form, to get rid of this problem:
<%= token_tag(nil) %>
Don't forget the parameter.
You can use the ExceptionUtils.getStackTrace(Throwable t);
from Apache Commons 3 class org.apache.commons.lang3.exception.ExceptionUtils
.
http://commons.apache.org/proper/commons-lang/
ExceptionUtils.getStackTrace(Throwable t)
Code example:
try {
// your code here
} catch(Exception e) {
String s = ExceptionUtils.getStackTrace(e);
}
Another quick comment... even in XCode 6.1, there is a bug with vertical spaces appearing at the top of UIScrollViews
, UITextViews
and UITableViews
.
Sometimes, the only way to fix this issue is to go into the Storyboard and drag the problem control so it's no longer the first subview on the page.
(My thanks to Oded for pointing me in this direction... I'm posting this comment, just to add a few screenshots, to demonstrate the symptoms and fix.)
An intuitive explanation to this is by simply analysing a single loop:
So the total time for a single loop is O(1)+O(e). Now sum it for each vertex as each vertex is visited once. This gives
For every V
=>
O(1)
+
O(e)
=> O(V) + O(E)
Simple solution (ES6)
If you don't have duplicate element
Array.prototype.remove = function(elem) {
var indexElement = this.findIndex(el => el === elem);
if (indexElement != -1)
this.splice(indexElement, 1);
return this;
};
For those who are using: implementation 'androidx.recyclerview:recyclerview:1.1.0-beta05'
make sure you are using this in your xml layout
I also experienced a crash when running my app below API 27. Here's a link to the message
Originally, I have created a style to change the font size of my textview inside the recyclerview that's why I created this code below: (I could have just called @dimen when changing the font size based on screen sizes)
and added this in my theme
After investigating, I found out that this is the one causing me an error and after removing the style, I no longer experiencing a crash.
I tried all the possible solutions I found here in stack overflow and almost gave up on this, thankfully in my curiosity I thought why not removing the style maybe this causes the crash and then boom the crash is gone.
def match_string(words):
nums = 0
letter = 0
other = 0
for i in words :
if i.isalpha():
letter+=1
elif i.isdigit():
nums+=1
else:
other+=1
return nums,letter,other
x = match_string("Hello World")
print(x)
>>>
(0, 10, 2)
>>>
Short answer : theoretically YES, but this has to be a VERY GOOD friend of yours, but again, you might prefer to buy a used mac-mini
TLDR : You will need this Mac for a really long time, depending on your app requirements, your development skills, and your luck with Apple. For example:
So, from my experience the development of an iOS app is a very lengthy procedure, without even considering the actual code-development time. Can you borrow a Mac for that long ?
Just remember to return false right after the function call if you're using the arrow keys since Chrome fricks the frack up otherwise.
{
document.getElementById('moveto3').setSelectionRange(3,3);
return false;
}
If I good understood this what is returned is fine except you want to see only one column. If so this below should be much simpler:
return Response::eloquent(Theme::with('user')->get(['username']));
Not using awk but the simplest way I was able to get this done was to just use csvtool. I had other use cases as well to use csvtool and it can handle the quotes or delimiters appropriately if they appear within the column data itself.
csvtool format '%(2)\n' input.csv
csvtool format '%(2),%(3),%(4)\n' input.csv
Replacing 2 with the column number will effectively extract the column data you are looking for.
If you are using a non default MySQL port number then do the following:
33747
then paste the following
$cfg['Servers'][$i]['port'] = 33747;
under the
/* Authentication type and info */
section.This is a sample simplelogger.properties
which you can place on the classpath (uncomment the properties you wish to use):
# SLF4J's SimpleLogger configuration file
# Simple implementation of Logger that sends all enabled log messages, for all defined loggers, to System.err.
# Default logging detail level for all instances of SimpleLogger.
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, defaults to "info".
#org.slf4j.simpleLogger.defaultLogLevel=info
# Logging detail level for a SimpleLogger instance named "xxxxx".
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, the default logging detail level is used.
#org.slf4j.simpleLogger.log.xxxxx=
# Set to true if you want the current date and time to be included in output messages.
# Default is false, and will output the number of milliseconds elapsed since startup.
#org.slf4j.simpleLogger.showDateTime=false
# The date and time format to be used in the output messages.
# The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat.
# If the format is not specified or is invalid, the default format is used.
# The default format is yyyy-MM-dd HH:mm:ss:SSS Z.
#org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS Z
# Set to true if you want to output the current thread name.
# Defaults to true.
#org.slf4j.simpleLogger.showThreadName=true
# Set to true if you want the Logger instance name to be included in output messages.
# Defaults to true.
#org.slf4j.simpleLogger.showLogName=true
# Set to true if you want the last component of the name to be included in output messages.
# Defaults to false.
#org.slf4j.simpleLogger.showShortLogName=false
Here is a complete example
class Example
{
public static void Main()
{
double x, y;
int i;
x = 10.0;
y = 3.0;
// cast double to int, fractional component lost (Line to be replaced)
i = (int) (x / y);
Console.WriteLine("Integer outcome of x / y: " + i);
}
}
If you want to round the number to the closer integer do the following:
i = (int) Math.Round(x / y); // Line replaced
Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.). The axis labels are collectively referred to as the index. The basic method to create a Series is to call:
s = pd.Series(data, index=index)
DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects.
d = {'one' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']),
two' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)
This might also be the displayed error message if you try to run 32-bit gcc binaries on a 64-bit OS and missing 32-bit glibc. According to this readme: "For 64 bit system, 32 bit libc and libncurses are required to run the tools.". In this case there is no problem with the path and cc1 is actually found, but reported as missing as no 32 bit glibc.
At the root of your project type below in the console:
gradlew --version
You will have gradle version with other information (as a sample):
------------------------------------------------------------
Gradle 5.1.1 << Here is the version
------------------------------------------------------------
Build time: 2019-01-10 23:05:02 UTC
Revision: 3c9abb645fb83932c44e8610642393ad62116807
Kotlin DSL: 1.1.1
Kotlin: 1.3.11
Groovy: 2.5.4
Ant: Apache Ant(TM) version 1.9.13 compiled on July 10 2018
JVM: 10.0.2 ("Oracle Corporation" 10.0.2+13)
OS: Windows 10 10.0 amd64
I think for gradle version it uses gradle/wrapper/gradle-wrapper.properties
under the hood.
The existing answers show a possible solution for single files or file types. However, you can define the charset standard in VS Code by following this path:
File > Preferences > Settings > Encoding > Choose your option
This will define a character set as default. Besides that, you can always change the encoding in the lower right corner of the editor (blue symbol line) for the current project.
a.txt
this is line 1
this is line 2
code:
Python 3.4.0 (default, Mar 20 2014, 22:43:40)
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file = open('a.txt').read()
>>> file
>>> file.split('\n')
['this is line 1', 'this is line 2', '']
I'm on Linux, but I guess you just use \r\n
on Windows and it would also work
Python 3.3 and later now uses the 2010 compiler. To best way to solve the issue is to just install Visual C++ Express 2010 for free.
Now comes the harder part for 64 bit users and to be honest I just moved to 32 bit but 2010 express doesn't come with a 64 bit compiler (you get a new error, ValueError: ['path'] ) so you have to install Microsoft SDK 7.1 and follow the directions here to get the 64 bit compiler working with python: Python PIP has issues with path for MS Visual Studio 2010 Express for 64-bit install on Windows 7
It may just be easier for you to use the 32 bit version for now. In addition to getting the compiler working, you can bypass the need to compile many modules by getting the binary wheel file from this locaiton http://www.lfd.uci.edu/~gohlke/pythonlibs/
Just download the .whl file you need, shift + right click the download folder and select "open command window here" and run
pip install module-name.whl
I used that method on 64 bit 3.4.3 before I broke down and decided to just get a working compiler for pip compiles modules from source by default, which is why the binary wheel files work and having pip build from source doesn't.
People getting this (vcvarsall.bat) error on Python 2.7 can instead install "Microsoft Visual C++ Compiler for Python 2.7"
You can just replace each space with %
SELECT `name` FROM `table` WHERE `name` LIKE '%Stylus%2100%'
There are several possible methods, but for you, there is already a builtin parse_str
function
$array = array();
parse_str($string, $array);
var_dump($array);
In order to pause the streaming in fast-csv you can do the following:
let csvstream = csv.fromPath(filePath, { headers: true })
.on("data", function (row) {
csvstream.pause();
// do some heavy work
// when done resume the stream
csvstream.resume();
})
.on("end", function () {
console.log("We are done!")
})
.on("error", function (error) {
console.log(error)
});
You can validate that and much more by using an XML schema language, like XSD.
If you mean conditionally, within code, then XPath is worth a look as well.
check the round function and how does the length
argument works. It controls the behaviour of the precision of the result
I just had the same problem, and none of the suggestions above worked. Finally I tried unchecking "Atomic soft tabs" in the Editor Settings menu, which worked.
If you can tolerate a different kind of placeholder (i.e. %s
in place of {}
) you can use String.format
method for that:
String s = "hello %s!";
s = String.format(s, "world" );
assertEquals(s, "hello world!"); // true
This works for me
hdmi_group=2
hdmi_mode=1
hdmi_mode=87
hdmi_cvt 800 480 60 6 0 0 0
max_usb_current=1
It turns out that you can create 32-bit ODBC connections using C:\Windows\SysWOW64\odbcad32.exe
. My solution was to create the 32-bit ODBC connection as a System DSN. This still didn't allow me to connect to it since .NET couldn't look it up. After significant and fruitless searching to find how to get the OdbcConnection class to look for the DSN in the right place, I stumbled upon a web site that suggested modifying the registry to solve a different problem.
I ended up creating the ODBC connection directly under HKLM\Software\ODBC
. I looked in the SysWOW6432 key to find the parameters that were set up using the 32-bit version of the ODBC administration tool and recreated this in the standard location. I didn't add an entry for the driver, however, as that was not installed by the standard installer for the app either.
After creating the entry (by hand), I fired up my windows service and everything was happy.
<div style="float: left;margin-right:10px">
<table>
<tr>
<td>..</td>
</tr>
</table>
</div>
<div style="float: left">
<table>
<tr>
<td>..</td>
</tr>
</table>
</div>
I create a directive and registered on bower.
This lib will help you modeling input file, not only return file data but also file dataurl or base 64.
{
"lastModified": 1438583972000,
"lastModifiedDate": "2015-08-03T06:39:32.000Z",
"name": "gitignore_global.txt",
"size": 236,
"type": "text/plain",
"data": "data:text/plain;base64,DQojaWdub3JlIHRodW1ibmFpbHMgY3JlYXRlZCBieSB3aW5kb3dz…xoDQoqLmJhaw0KKi5jYWNoZQ0KKi5pbGsNCioubG9nDQoqLmRsbA0KKi5saWINCiouc2JyDQo="
}
The only problem is that any additional certificates in resulted file will not be recognized, as tools don't expect more than one certificate per PEM/DER encoded file. Even openssl itself. Try
openssl x509 -outform DER -in certificate.cer | openssl x509 -inform DER -outform PEM
and see for yourself.
VB.NET:
Dim URI As New Uri("D:\Development\~AppFolder\Att\1.gif")
Different outputs:
URI.AbsolutePath -> D:/Development/~AppFolder/Att/1.gif
URI.AbsoluteUri -> file:///D:/Development/~AppFolder/Att/1.gif
URI.OriginalString -> D:\Development\~AppFolder\Att\1.gif
URI.ToString -> file:///D:/Development/~AppFolder/Att/1.gif
URI.LocalPath -> D:\Development\~AppFolder\Att\1.gif
One liner:
New Uri("D:\Development\~AppFolder\Att\1.gif").AbsoluteUri
Output:
file:///D:/Development/~AppFolder/Att/1.gif
You can directly run the following command on terminal of your remote server to run tensorboard:
tensorboard --logdir {tf_log directory path} --host "0.0.0.0" --port 6006
Or you can also start the tensorboard within your ipython notebook:
%load_ext tensorboard
%tensorboard --logdir {tf_log directory path} --host "0.0.0.0" --port 6006
The answer from JUnit.org FAQ page:
But if you must...
If you are using JDK 1.3 or higher, you can use reflection to subvert the access control mechanism with the aid of the PrivilegedAccessor. For details on how to use it, read this article.
If you are using JDK 1.6 or higher and you annotate your tests with @Test, you can use Dp4j to inject reflection in your test methods. For details on how to use it, see this test script.
P.S. I'm the main contributor to Dp4j, ask me if you need help. :)
Although I've just begun looking at this area of development, I think it comes down to this basic difference: some tools retain the original code, and some port to native...
for instance, PhoneGap just keeps the HTML/CSS/JS code that you write, and wraps it in sufficient iOS code to qualify as an app, whereas Appcelerator delivers you an XCode project...so if you're not familiar with iOS, then that wouldn't really provide any benefit to you over PhoneGap, but if you DO know a bit, that might give you just a bit more ability to tweak the native versions after your larger coding effort.
I haven't used appcelerator myself, but worked on a project a couple weeks ago where one of our team members made an entire iPad app in about 24 hours using it.
And yes, to actually submit to apple, you'll have to get a mac, but if that's not your primary work platform you can go cheap.
How about this...
<style type="text/css">
div.frame { background-color: #000; }
img.pic:hover {
opacity: .6;
filter:alpha(opacity=60);
}
</style>
<div class="frame">
<img class="pic" src="path/to/image" />
</div>
A short RegEx: ^(?:(?:^|\.)(?:2(?:5[0-5]|[0-4]\d)|1?\d?\d)){4}$
Example
const isValidIp = value => (/^(?:(?:^|\.)(?:2(?:5[0-5]|[0-4]\d)|1?\d?\d)){4}$/.test(value) ? true : false);_x000D_
_x000D_
_x000D_
// valid_x000D_
console.log("isValidIp('0.0.0.0') ? ", isValidIp('0.0.0.0'));_x000D_
console.log("isValidIp('115.42.150.37') ? ", isValidIp('115.42.150.37'));_x000D_
console.log("isValidIp('192.168.0.1') ? ", isValidIp('192.168.0.1'));_x000D_
console.log("isValidIp('110.234.52.124' ? ", isValidIp('110.234.52.124'));_x000D_
console.log("isValidIp('115.42.150.37') ? ", isValidIp('115.42.150.37'));_x000D_
console.log("isValidIp('115.42.150.38') ? ", isValidIp('115.42.150.38'));_x000D_
console.log("isValidIp('115.42.150.50') ? ", isValidIp('115.42.150.50'));_x000D_
_x000D_
// Invalid_x000D_
console.log("isValidIp('210.110') ? ", isValidIp('210.110'));_x000D_
console.log("isValidIp('255') ? ", isValidIp('255'));_x000D_
console.log("isValidIp('y.y.y.y' ? ", isValidIp('y.y.y.y'));_x000D_
console.log(" isValidIp('255.0.0.y') ? ", isValidIp('255.0.0.y'));_x000D_
console.log("isValidIp('666.10.10.20') ? ", isValidIp('666.10.10.20'));_x000D_
console.log("isValidIp('4444.11.11.11') ? ", isValidIp('4444.11.11.11'));_x000D_
console.log("isValidIp('33.3333.33.3') ? ", isValidIp('33.3333.33.3'));
_x000D_
try
.something {
background: url(images/bg.jpg) no-repeat center center fixed;
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
z-index: -100;
}
The UNION statement is your friend:
SELECT a.playername, a.games, a.goals
FROM tblMadrid as a
WHERE a.playername = "ronaldo"
UNION
SELECT b.playername, b.games, b.goals
FROM tblBarcelona as b
WHERE b.playername = "messi"
ORDER BY goals;
More simple than that.
List<Integer> arrayIntegers = new ArrayList<>(Arrays.asList(1,2,3));
arrayIntegers.get(1);
In the first line you create the object and in the constructor you pass an array parameter to List.
In the second line you have all the methods of the List class: .get (...)
Perhaps:
> data.frame(aname=NA, bname=NA)[numeric(0), ]
[1] aname bname
<0 rows> (or 0-length row.names)
{% if variable is defined %}
is true if the variable is None
.
Since not is None
is not allowed, that means that
{% if variable != None %}
is really your only option.
'RESTless' is a term not often used.
You can define 'RESTless' as any system that is not RESTful. For that it is enough to not have one characteristic that is required for a RESTful system.
Most systems are RESTless by this definition because they don't implement HATEOAS.
THIRD VERSION OF MY ANSWER:
Here's a multiple line example of inline Jade Javascript. I don't think you can write it without using a -
. This is a flash message example that I use in a partial. Hope this helps!
-if(typeof(info) !== 'undefined')
-if (info)
- if(info.length){
ul
-info.forEach(function(info){
li= info
-})
-}
Is the code you're trying to get to compile the code in your question?
If so, you don't need two things: first, you don't need to declare that it's Javascript/a script, you can just started coding after typing -
; second, after you type -if
you don't need to type the {
or }
either. That's what makes Jade pretty sweet.
--------------ORIGINAL ANSWER BELOW ---------------
Try prepending if
with -
:
-if(10 == 10)
//do whatever you want here as long as it's indented two spaces from
the `-` above
There are also tons of Jade examples at:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
<newBooks>
<xsl:for-each select="books/book">
<newBook>
<countNo><xsl:value-of select="position()"/></countNo>
<title>
<xsl:value-of select="title"/>
</title>
</newBook>
</xsl:for-each>
</newBooks>
</xsl:template>
</xsl:stylesheet>
A constructor should no have a return type . remove void before each constructor .
Some very basic characteristic of a constructor :
a. Same name as class b. no return type. c. will be called every time an object is made with the class. for eg- in your program if u made two objects of Flow, Flow flow1=new Flow(); Flow flow2=new Flow(); then Flow constructor will be called for 2 times.
d. If you want to call the constructor just for once then declare that as static (static constructor) and dont forget to remove any access modifier from static constructor ..
I usually use:
l = [ word.strip() for word in text.split(',') ]
the strip
remove spaces around words.
Seems quite simple these days. This is the Swift version.
let tap = UITapGestureRecognizer(target: self, action: #selector(viewTapped))
view.addGestureRecognizer(tap)
@objc func viewTapped(recognizer: UIGestureRecognizer)
{
//Do what you need to do!
}
Is there a way to limit a regex to 100 characters WITH regex?
Your example suggests that you'd like to grab a number from inside the regex and then use this number to place a maximum length on another part that is matched later in the regex. This usually isn't possible in a single pass. Your best bet is to have two separate regular expressions:
If you just want to limit the number of characters matched by an expression, most regular expressions support bounds by using braces. For instance,
\d{3}-\d{3}-\d{4}
will match (US) phone numbers: exactly three digits, then a hyphen, then exactly three digits, then another hyphen, then exactly four digits.
Likewise, you can set upper or lower limits:
\d{5,10}
means "at least 5, but not more than 10 digits".
Update: The OP clarified that he's trying to limit the value, not the length. My new answer is don't use regular expressions for that. Extract the value, then compare it against the maximum you extracted from the size parameter. It's much less error-prone.
The total used / free memory of a program can be obtained in the program via
java.lang.Runtime.getRuntime();
The runtime has several methods which relate to the memory. The following coding example demonstrates its usage.
public class PerformanceTest {
private static final long MEGABYTE = 1024L * 1024L;
public static long bytesToMegabytes(long bytes) {
return bytes / MEGABYTE;
}
public static void main(String[] args) {
// I assume you will know how to create an object Person yourself...
List <Person> list = new ArrayList <Person> ();
for (int i = 0; i <= 100_000; i++) {
list.add(new Person("Jim", "Knopf"));
}
// Get the Java runtime
Runtime runtime = Runtime.getRuntime();
// Run the garbage collector
runtime.gc();
// Calculate the used memory
long memory = runtime.totalMemory() - runtime.freeMemory();
System.out.println("Used memory is bytes: " + memory);
System.out.println("Used memory is megabytes: " + bytesToMegabytes(memory));
}
}
According to this helpful list of operators [an operator can be thought of as a mathematical expression] found here, you can tell the batch compiler that you are manipulating variables instead of fixed numbers by using the += operator instead of the + operator.
Hope I Helped!
Please note you may need to display div text again after it has disappeared. So you will need to also empty and then re-show the element at some point.
You can do this with 1 line of code:
$('#element_id').empty().show().html(message).delay(3000).fadeOut(300);
If you're using jQuery you don't need setTimeout, at least not to autohide an element.
complete
executes after either the success
or error
callback were executed.
Maybe you should check the second parameter complete
offers too. It's a String holding the type of success the ajaxCall had.
The different callbacks are described a little more in detail here jQuery.ajax( options )
I guess you missed the fact that the complete
and the success
function (I know inconsistent API) get different data passed in. success
gets only the data, complete
gets the whole XMLHttpRequest
object. Of course there is no responseText
property on the data string.
So if you replace complete
with success
you also have to replace data.responseText
with data
only.
success
The function gets passed two arguments: The data returned from the server, formatted according to the 'dataType' parameter, and a string describing the status.
complete
The function gets passed two arguments: The XMLHttpRequest object and a string describing the type of success of the request.
If you need to have access to the whole XMLHttpRequest
object in the success callback I suggest trying this.
var myXHR = $.ajax({
...
success: function(data, status) {
...do whatever with myXHR; e.g. myXHR.responseText...
},
...
});
This worked for me
Deactivate AdBlock.
Go to inspect -> settings gear -> Uncheck 'enable javascript source maps' and 'enable css source map'.
Refresh.
In Android Studio 1.1.0: File - Project Structure - Tab Flavors - Select Min SDK Version which is higher than in Manifest
Try to avoid using grep
, if looking at resources.
if ( grep( /^$value$/, @badparams ) ) {
print "found";
}
for (@badparams) {
if ($_ eq $value) {
print "found";
last;
}
}
my %hash = map {$_ => 1} @badparams;
print "found" if (exists $hash{$value});
(added in Perl 5.10, marked is experimental in Perl 5.18).
use experimental 'smartmatch'; # for perl 5.18
print "found" if ($value ~~ @badparams);
List::MoreUtils
use List::MoreUtils qw(any);
@badparams = (1,2,3);
$value = 1;
print "found" if any {$_ == $value} @badparams;