The VOLUME
command will mount a directory inside your container and store any files created or edited inside that directory on your hosts disk outside the container file structure, bypassing the union file system.
The idea is that your volumes can be shared between your docker containers and they will stay around as long as there's a container (running or stopped) that references them.
You can have other containers mount existing volumes (effectively sharing them between containers) by using the --volumes-from
command when you run a container.
The fundamental difference between VOLUME
and -v
is this: -v
will mount existing files from your operating system inside your docker container and VOLUME
will create a new, empty volume on your host and mount it inside your container.
Example:
VOLUME /var/lib/mysql
.some-volume
And then,
docker run --volumes-from some-volume docker-image-name:tag
some-volume
mounted in /var/lib/mysql
Note: Using --volumes-from
will mount the volume over whatever exists in the location of the volume. I.e., if you had stuff in /var/lib/mysql
, it will be replaced with the contents of the volume.
Given
volumes:
- /dir/on/host:/var/www/html
if /dir/on/host
doesn't exist, it is created on the host and the empty content is mounted in the container at /var/www/html
. Whatever content you had before in /var/www/html
inside the container is inaccessible, until you unmount the volume; the new mount is hiding the old content.
Constructors are not inherited, you must create a new, identically prototyped constructor in the subclass that maps to its matching constructor in the superclass.
Here is an example of how this works:
class Foo {
Foo(String str) { }
}
class Bar extends Foo {
Bar(String str) {
// Here I am explicitly calling the superclass
// constructor - since constructors are not inherited
// you must chain them like this.
super(str);
}
}
The suggestion to install a signal handler is a good one, and I use it a lot. For example, bzr by default installs a SIGQUIT handler that invokes pdb.set_trace()
to immediately drop you into a pdb prompt. (See the bzrlib.breakin module's source for the exact details.) With pdb you can not only get the current stack trace (with the (w)here
command) but also inspect variables, etc.
However, sometimes I need to debug a process that I didn't have the foresight to install the signal handler in. On linux, you can attach gdb to the process and get a python stack trace with some gdb macros. Put http://svn.python.org/projects/python/trunk/Misc/gdbinit in ~/.gdbinit
, then:
gdb -p
PID
pystack
It's not totally reliable unfortunately, but it works most of the time.
Finally, attaching strace
can often give you a good idea what a process is doing.
If you don't care about supporting old browsers, you can use :not()
to exclude that element:
.parent:hover span:not(:hover) {
border: 10px solid red;
}
Demo: http://jsfiddle.net/vz9A9/1/
If you do want to support them, the I guess you'll have to either use JavaScript or override the CSS properties again:
.parent span:hover {
border: 10px solid green;
}
This work for me:
const handleCopyLink = useCallback(() => {
const textField = document.createElement('textarea')
textField.innerText = url
document.body.appendChild(textField)
if (window.navigator.platform === 'iPhone') {
textField.setSelectionRange(0, 99999)
} else {
textField.select()
}
document.execCommand('copy')
textField.remove()
toast.success('Link successfully copied')
}, [url])
That error is a parse error. The parser is throwing it while going through the code, trying to understand it. No code is being executed yet in the parsing stage. Because of that it hasn't yet executed the error_reporting
line, therefore the error reporting settings aren't changed yet.
You cannot change error reporting settings (or really, do anything) in a file with syntax errors.
Running
git remote set-head origin --auto
followed by
git gc
I've had the same issue in the past. Normally a shrink and a trn backup need to occur multiple times. In extreme cases I set the DB to "Simple" recovery and then run a shrink operation on the log file. That always works for me. However recently I had a situation where that would not work. The issue was caused by a long running query that did not complete, so any attempts to shrink were useless until I could kill that process then run my shrink operations. We are talking a log file that grew to 60 GB and is now shrunk to 500 MB.
Remember, as soon as you change from FULL to Simple recovery mode and do the shrink, dont forget to set it back to FULL. Then immediately afterward you must do a FULL DB backup.
case isnull(B.[stat],0)
when 0 then dateadd(dd,10,(c.[Eventdate]))
end
you can add in else statement if you want to add 30 days to the same .
Maybe, you want to concatenate more of two Dataframes. I found a issue which use pandas Dataframe conversion.
Suppose you have 3 spark Dataframe who want to concatenate.
The code is the following:
list_dfs = []
list_dfs_ = []
df = spark.read.json('path_to_your_jsonfile.json',multiLine = True)
df2 = spark.read.json('path_to_your_jsonfile2.json',multiLine = True)
df3 = spark.read.json('path_to_your_jsonfile3.json',multiLine = True)
list_dfs.extend([df,df2,df3])
for df in list_dfs :
df = df.select([column for column in df.columns]).toPandas()
list_dfs_.append(df)
list_dfs.clear()
df_ = sqlContext.createDataFrame(pd.concat(list_dfs_))
In Typescript 3.5+:
interface TypographyProps {
variant: string
fontSize: number
}
type TypographyPropsMinusVariant = Omit<TypographyProps, "variant">
find()
- Limited to lookups by tag name
you can see more information
https://docs.angularjs.org/api/ng/function/angular.element
Also you can access by name or id or call please following example:
angular.element(document.querySelector('#txtName')).attr('class', 'error');
This works. A hackish way probably, but it works nicely. It was tested for responsive (Y).
.centered {
background-color: teal;
text-align: center;
}
Hey make sure to do this changes to the pom.xml
<packaging>war</packaging>
in the dependencies section make sure to indicated the tomcat is provided so you dont need the embeded tomcat plugin.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
This is the whole pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<start-class>com.example.Application</start-class>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
And the Application class should be like this
Application.java
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
/**
* Used when run as JAR
*/
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
/**
* Used when run as WAR
*/
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(Application.class);
}
}
And you can add a controller for testing MyController.java
package com.example;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MyController {
@RequestMapping("/hi")
public @ResponseBody String hiThere(){
return "hello world!";
}
}
Then you can run the project in a tomcat 8 version and access the controller like this
If for some reason you are not able to add the project to tomcat do a right click in the project and then go to the Build Path->configure build path->Project Faces
make sure only this 3 are selected
Dynamic web Module 3.1 Java 1.8 Javascript 1.0
CSS transitions only animate from one set of styles to another; what you're looking for is CSS animations.
You need to define the animation keyframes and apply it to the element:
@keyframes changewidth {
from {
width: 100px;
}
to {
width: 300px;
}
}
div {
animation-duration: 0.1s;
animation-name: changewidth;
animation-iteration-count: infinite;
animation-direction: alternate;
}
Check out the link above to figure out how to customize it to your liking, and you'll have to add browser prefixes.
Based on Nrzonline's answer: I fixed the problem of the multiple "." at the end of the input by adding a
let lastCharacterEntered
outside of the input and then onKeyPress
e => {
var allowedChars = "0123456789.";
function contains(stringValue, charValue) {
return stringValue.indexOf(charValue) > -1;
}
var invalidKey =
(e.key.length === 1 && !contains(allowedChars, e.key)) ||
(e.key === "." && contains(e.target.value, "."));
console.log(e.target.value);
invalidKey && e.preventDefault();
if (!invalidKey) {
if (lastCharacterEntered === "." && e.key === ".") {
e.preventDefault();
} else {
lastCharacterEntered = e.key;
}
}
}
To produce a border inset within an element the only solution I've found (and I've tried all the suggestions in this thread to no avail) is to use a pseudo-element such as :before
E.g.
.has-inset-border:before {
content: "foo"; /* you need something or it will be invisible at least on Chrome */
color: transparent;
position: absolute;
left: 10px;
right: 10px;
top: 10px;
bottom: 10px;
border: 4px dashed red;
}
The box-sizing property won't work, as the border always ends up outside everything.
The box-shadow options has the dual disadvantages of not really working and not being supported as widely (and costing more CPU cycles to render, if you care).
TO_DATE supports conversion to DATE datatype, which doesn't support milliseconds. If you want millisecond support in Oracle, you should look at TIMESTAMP datatype and TO_TIMESTAMP function.
Hope that helps.
I have now been able to get Keyboard input in Swift by using the following:
In my main.swift file I declared a variable i and assigned to it the function GetInt() which I defined in Objective C. Through a so called Bridging Header where I declared the function prototype for GetInt I could link to main.swift. Here are the files:
main.swift:
var i: CInt = GetInt()
println("Your input is \(i) ");
Bridging Header:
#include "obj.m"
int GetInt();
obj.m:
#import <Foundation/Foundation.h>
#import <stdio.h>
#import <stdlib.h>
int GetInt()
{
int i;
scanf("%i", &i);
return i;
}
In obj.m it is possible to include the c standard output and input, stdio.h, as well as the c standard library stdlib.h which enables you to program in C in Objective-C, which means there is no need for including a real swift file like user.c or something like that.
Hope I could help,
Edit: It is not possible to get String input through C because here I am using the CInt -> the integer type of C and not of Swift. There is no equivalent Swift type for the C char*. Therefore String is not convertible to string. But there are fairly enough solutions around here to get String input.
Raul
You can try this
$('#startdate').val()
or
$('#startdate').data('date')
WiX is the way to go for new installers. If WiX alone is too complicated or not flexible enough on the GUI side consider using SharpSetup - it allows you to create installer GUI in WinForms of WPF and has other nice features like translations, autoupdater, built-in prerequisites, improved autocompletion in VS and more.
(Disclaimer: I am the author of SharpSetup.)
I had this problem too. I solved it by removing the unnecessary blank line between equation tags. This gives the error:
\begin{equation}
P(\underline{\hat{X}} | \underline{Y}) = ...
\end{equation}
while this code compiles succesfully:
\begin{equation}
P(\underline{\hat{X}} | \underline{Y}) = ...
\end{equation}
When it shows the red writing - the error , don't close the emulator - leave it as is and run the application again.
No.
You can use grouping selectors and/or multiple classes on a single element, or you can use a template language and process it with software to write your CSS.
See also my article on CSS inheritance.
Based on the documentation the origin
parameter is optional and it defaults to the user's location.
... Defaults to most relevant starting location, such as user location, if available. If none, the resulting map may provide a blank form to allow a user to enter the origin....
ex: https://www.google.com/maps/dir/?api=1&destination=Pike+Place+Market+Seattle+WA&travelmode=bicycling
For me this works on Desktop, IOS and Android.
I am yet to have the privilege to comment so this is simply additional information related to @peter's answer above answer.
I found HTML did not align as expected if IE conditional comments in the header were not completely in-line e.g. flush to the left:
<!--[if lt IE 7]>
<p class='chromeframe'>Your browser is <em>unsupported</em>. <a href="http://browsehappy.com/">Upgrade to a different browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">install Google Chrome Frame</a> to experience this site.</p>
<![endif]-->
<!-- Le HTML5 shim, for IE6-8 support of HTML elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
tree -L 2 -u -g -p -d
Prints the directory tree in a pretty format up to depth 2 (-L 2). Print user (-u) and group (-g) and permissions (-p). Print only directories (-d). tree has a lot of other useful options.
Here are the few techniques I've heard of:
Use clone()
if the class implements Cloneable
. This API is a bit flawed in java and I never quite understood why clone
is not defined in the interface, but in Object
. Still, it might work.
Create a clone manually. If there is a constructor that accepts all parameters, it might be simple, e.g new User( user.ID, user.Age, ... )
. You might even want a constructor that takes a User: new User( anotherUser ).
Implement something to copy from/to a user. Instead of using a constructor, the class may have a method copy( User )
. You can then first snapshot the object backupUser.copy( user )
and then restore it user.copy( backupUser )
. You might have a variant with methods named backup
/restore
/snapshot
.
Use the state pattern.
Use serialization. If your object is a graph, it might be easier to serialize/deserialize it to get a clone.
That all depends on the use case. Go for the simplest.
EDIT
I also recommend to have a look at these questions:
if (
document.forms["form"]["mon"].checked==false &&
document.forms["form"]["tues"].checked==false &&
document.forms["form"]["wed"].checked==false &&
document.forms["form"]["thrs"].checked==false &&
document.forms["form"]["fri"].checked==false
) {
alert("Select at least One Day into Five Days");
return false;
}
Is JSTL's join()
, what you searched for?
<c:set var="myVar" value="${fn:join(myParams.items, ' ')}" />
Unfortunately, there's no exit two levels of for
statement, but there are a few workarounds to do what you want:
Goto. In general, using goto
is considered to be bad practice (and rightfully so), but using goto
solely for a forward jump out of structured control statements is usually considered to be OK, especially if the alternative is to have more complicated code.
For Each item In itemList
For Each item1 In itemList1
If item1.Text = "bla bla bla" Then
Goto end_of_for
End If
Next
Next
end_of_for:
Dummy outer block
Do
For Each item In itemList
For Each item1 In itemList1
If item1.Text = "bla bla bla" Then
Exit Do
End If
Next
Next
Loop While False
or
Try
For Each item In itemlist
For Each item1 In itemlist1
If item1 = "bla bla bla" Then
Exit Try
End If
Next
Next
Finally
End Try
Separate function: Put the loops inside a separate function, which can be exited with return
. This might require you to pass a lot of parameters, though, depending on how many local variables you use inside the loop. An alternative would be to put the block into a multi-line lambda, since this will create a closure over the local variables.
Boolean variable: This might make your code a bit less readable, depending on how many layers of nested loops you have:
Dim done = False
For Each item In itemList
For Each item1 In itemList1
If item1.Text = "bla bla bla" Then
done = True
Exit For
End If
Next
If done Then Exit For
Next
I was facing this problem even with use Illuminate\Http\Request;
line at the top of my controller. Kept pulling my hair till I realized that I was doing $request::ip()
instead of $request->ip()
. Can happen to you if you didn't sleep all night and are looking at the code at 6am with half-opened eyes.
Hope this helps someone down the road.
Try to execute the procedure like this,
var c refcursor;
execute pkg_name.get_user('14232', '15', 'TDWL', 'SA', 1, :c);
print c;
You need to specify the classpath. This should do it:
java -cp . Echo "hello"
This tells java to use .
(the current directory) as its classpath, i.e. the place where it looks for classes. Note than when you use packages, the classpath has to contain the root directory, not the package subdirectories. e.g. if your class is my.package.Echo
and the .class file is bin/my/package/Echo.class
, the correct classpath directory is bin
.
My Crypto based take on the problem. Using ES6 and omitting any browser feature checks. Any comments on security or performance?
const generatePassword = (
passwordLength = 12,
passwordChars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
) =>
[...window.crypto.getRandomValues(new Uint32Array(passwordLength))]
.map(x => passwordChars[x % passwordChars.length])
.join('');
Download the latest build from https://github.com/macvim-dev/macvim/releases
Expand the archive.
Put MacVim.app into /Applications/
.
Done.
if the value is 0 then it wasn't successful, but if 1 then successful.
$this->db->affected_rows();
Go to your Target or Project settings, click the Gear icon at the bottom left, and select "Add User-Defined Setting". The new setting name should be GCC_PREPROCESSOR_DEFINITIONS
, and you can type your definitions in the right-hand field.
Per Steph's comments, the full syntax is:
constant_1=VALUE constant_2=VALUE
Note that you don't need the '='s if you just want to #define a symbol, rather than giving it a value (for #ifdef
statements)
You best see if you have a parent element of the div you are querying. If so get the parent element and perform an element.querySelectorAll("div")
. Once you get the nodeList
apply a filter on it over the innerText
property. Assume that a parent element of the div that we are querying has an id
of container
. You can normally access container directly from the id but let's do it the proper way.
var conty = document.getElementById("container"),
divs = conty.querySelectorAll("div"),
myDiv = [...divs].filter(e => e.innerText == "SomeText");
So that's it.
This solves the issue when you scroll past the beginning or end of the div
var selScrollable = '.scrollable';
// Uses document because document will be topmost level in bubbling
$(document).on('touchmove',function(e){
e.preventDefault();
});
// Uses body because jQuery on events are called off of the element they are
// added to, so bubbling would not work if we used document instead.
$('body').on('touchstart', selScrollable, function(e) {
if (e.currentTarget.scrollTop === 0) {
e.currentTarget.scrollTop = 1;
} else if (e.currentTarget.scrollHeight === e.currentTarget.scrollTop + e.currentTarget.offsetHeight) {
e.currentTarget.scrollTop -= 1;
}
});
// Stops preventDefault from being called on document if it sees a scrollable div
$('body').on('touchmove', selScrollable, function(e) {
e.stopPropagation();
});
Note that this won't work if you want to block whole page scrolling when a div does not have overflow. To block that, use the following event handler instead of the one immediately above (adapted from this question):
$('body').on('touchmove', selScrollable, function(e) {
// Only block default if internal div contents are large enough to scroll
// Warning: scrollHeight support is not universal. (https://stackoverflow.com/a/15033226/40352)
if($(this)[0].scrollHeight > $(this).innerHeight()) {
e.stopPropagation();
}
});
The trick here is that the ToolTip control is an extender control, which means that it will extend the set of properties for other controls on the form. Behind the scenes this is achieved by generating code like in Svetlozar's answer. There are other controls working in the same manner (such as the HelpProvider
).
padding-left
is what controls the indentation of ul
not margin-left
.
Compare: Here's setting padding-left
to 0
, notice all the indentation disappears.
ul {
padding-left: 0;
}
_x000D_
<ul>
<li>section a
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
</li>
</ul>
<ul>
<li>section b
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
</li>
</ul>
_x000D_
and here's setting margin-left
to 0px
. Notice the indentation does NOT change.
ul {
margin-left: 0;
}
_x000D_
<ul>
<li>section a
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
</li>
</ul>
<ul>
<li>section b
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
</li>
</ul>
_x000D_
I wrote a little bash onliner that you can write to a script to get a friendly output:
mysql_references_to:
mysql -uUSER -pPASS -A DB_NAME -se "USE information_schema; SELECT * FROM KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_NAME = '$1' AND REFERENCED_COLUMN_NAME = 'id'\G" | sed 's/^[ \t]*//;s/[ \t]*$//' |egrep "\<TABLE_NAME|\<COLUMN_NAME" |sed 's/TABLE_NAME: /./g' |sed 's/COLUMN_NAME: //g' | paste -sd "," -| tr '.' '\n' |sed 's/,$//' |sed 's/,/./'
So the execution: mysql_references_to transaccion
(where transaccion is a random table name) gives an output like this:
carrito_transaccion.transaccion_id
comanda_detalle.transaccion_id
comanda_detalle_devolucion.transaccion_positiva_id
comanda_detalle_devolucion.transaccion_negativa_id
comanda_transaccion.transaccion_id
cuenta_operacion.transaccion_id
...
We have resolved the circular dependency(Parent-child Entities) by mapping the child entity instead of parent entity in Grails 4(GORM).
Example:
Class Person {
String name
}
Class Employee extends Person{
String empId
}
//Before my code
Class Address {
static belongsTo = [person: Person]
}
//We changed our Address class to:
Class Address {
static belongsTo = [person: Employee]
}
Another way to resolve this problem:
$('input').oninvalid(function (event, errorMessage) {
event.target.focus();
});
If the script creates any variables or functions in the global space you can check for their existance:
External JS (in global scope) --
var myCustomFlag = true;
And to check if this has run:
if (typeof window.myCustomFlag == 'undefined') {
//the flag was not found, so the code has not run
$.getScript('<external JS>');
}
You can check for the existence of the <script>
tag in question by selecting all of the <script>
elements and checking their src
attributes:
//get the number of `<script>` elements that have the correct `src` attribute
var len = $('script').filter(function () {
return ($(this).attr('src') == '<external JS>');
}).length;
//if there are no scripts that match, the load it
if (len === 0) {
$.getScript('<external JS>');
}
Or you can just bake this .filter()
functionality right into the selector:
var len = $('script[src="<external JS>"]').length;
You can achieve this directly in Xcode:
The very last checkbox, make sure secure
is checked .
Or you can do it using code:
Identifies whether the text object should hide the text being entered.
Declaration
optional var secureTextEntry: Bool { get set }
Discussion
This property is set to false
by default. Setting this property to true
creates a password-style text object, which hides the text being entered.
example:
texfield.secureTextEntry = true
Read many answers and posts and determined the most accurate solution. Tested in Safari, Chrome, Firefox (desktop and iOS versions). First we need to detect Apple
vendor and then exclude Chrome and Firefox (for iOS).
let isSafari = navigator.vendor.match(/apple/i) &&
!navigator.userAgent.match(/crios/i) &&
!navigator.userAgent.match(/fxios/i);
if (isSafari) {
//
} else {
//
}
Use attributed string:
// Define attributes
let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 18)
let attributes :Dictionary = [NSFontAttributeName : labelFont]
// Create attributed string
var attrString = NSAttributedString(string: "Foo", attributes:attributes)
label.attributedText = attrString
You need to define attributes.
Using attributed string you can mix colors, sizes, fonts etc within one text
it's simple! just type bellow query
alter table table_Name alter column column_name datatype
alter table Message alter column message nvarchar(1024);
it will work happy programming
Go to File->Import Settings... and select the jar settings file
Update as of IntelliJ 2020:
Go to File -> Manage IDE Settings -> Import Settings...
Like this:
var myAssembly = System.Reflection.Assembly.GetEntryAssembly();
var myAssemblyLocation = System.IO.Path.GetDirectoryName(a.Location);
var myHtmlPath = Path.Combine(myAssemblyLocation, "my.html");
Loop through your list and do a contains or startswith.
ArrayList<String> resList = new ArrayList<String>();
String searchString = "bea";
for (String curVal : list){
if (curVal.contains(searchString)){
resList.add(curVal);
}
}
You can wrap that in a method. The contains checks if its in the list. You could also go for startswith.
There is an another way to see XML SOAP - custom MessageEncoder. The main difference from IClientMessageInspector is that it works on lower level, so it captures original byte content including any malformed xml.
In order to implement tracing using this approach you need to wrap a standard textMessageEncoding with custom message encoder as new binding element and apply that custom binding to endpoint in your config.
Also you can see as example how I did it in my project - wrapping textMessageEncoding, logging encoder, custom binding element and config.
The :
is a bitfield. As for !!
, that is logical double negation and so returns 0
for false or 1
for true. And the -
is a minus sign, i.e. arithmetic negation.
It's all just a trick to get the compiler to barf on invalid inputs.
Consider BUILD_BUG_ON_ZERO
. When -!!(e)
evaluates to a negative value, that produces a compile error. Otherwise -!!(e)
evaluates to 0, and a 0 width bitfield has size of 0. And hence the macro evaluates to a size_t
with value 0.
The name is weak in my view because the build in fact fails when the input is not zero.
BUILD_BUG_ON_NULL
is very similar, but yields a pointer rather than an int
.
>>> x = 'foo'
>>> x
'foo'
So the name x
is attached to 'foo'
string. When you call for example repr(x)
the interpreter puts 'foo'
instead of x
and then calls repr('foo')
.
>>> repr(x)
"'foo'"
>>> x.__repr__()
"'foo'"
repr
actually calls a magic method __repr__
of x
, which gives the string containing the representation of the value 'foo'
assigned to x
. So it returns 'foo'
inside the string ""
resulting in "'foo'"
. The idea of repr
is to give a string which contains a series of symbols which we can type in the interpreter and get the same value which was sent as an argument to repr
.
>>> eval("'foo'")
'foo'
When we call eval("'foo'")
, it's the same as we type 'foo'
in the interpreter. It's as we directly type the contents of the outer string ""
in the interpreter.
>>> eval('foo')
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
eval('foo')
File "<string>", line 1, in <module>
NameError: name 'foo' is not defined
If we call eval('foo')
, it's the same as we type foo
in the interpreter. But there is no foo
variable available and an exception is raised.
>>> str(x)
'foo'
>>> x.__str__()
'foo'
>>>
str
is just the string representation of the object (remember, x
variable refers to 'foo'
), so this function returns string.
>>> str(5)
'5'
String representation of integer 5
is '5'
.
>>> str('foo')
'foo'
And string representation of string 'foo'
is the same string 'foo'
.
Actually, I found the best, most-succinct, fastest, and most-compatible way using pure JavaScript (assuming you don't need to fully support IE lte 8) is the following:
var values = Array.prototype.slice.call(document.querySelectorAll('#select-meal-type option:checked'),0).map(function(v,i,a) {
return v.value;
});
UPDATE (2017-02-14):
An even more succinct way using ES6/ES2015 (for the browsers that support it):
const selected = document.querySelectorAll('#select-meal-type option:checked');
const values = Array.from(selected).map(el => el.value);
Here's an answer that gives the switch-or-launch behaviour of Start, without the Command Prompt window. It does have the drawback that it can be fooled by an Explorer window that has a folder of the same name elsewhere opened. I might fix that by diving into the child windows and looking for the actual path, I need to figure out how to navigate that.
Usage (requires "Windows Script Host Object Model" in your project's References):
Dim mShell As wshShell
mDocPath = whatever_path & "\" & lastfoldername
mExplorerPath = mShell.ExpandEnvironmentStrings("%SystemRoot%") & "\Explorer.exe"
If Not SwitchToFolder(lastfoldername) Then
Shell PathName:=mExplorerPath & " """ & mDocPath & """", WindowStyle:=vbNormalFocus
End If
Module:
Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" _
(ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long
Private Declare Function GetClassName Lib "user32" Alias "GetClassNameA" _
(ByVal hWnd As Long, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" _
(ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Private Declare Function BringWindowToTop Lib "user32" _
(ByVal lngHWnd As Long) As Long
Function SwitchToFolder(pFolder As String) As Boolean
Dim hWnd As Long
Dim mRet As Long
Dim mText As String
Dim mWinClass As String
Dim mWinTitle As String
SwitchToFolder = False
hWnd = FindWindowEx(0, 0&, vbNullString, vbNullString)
While hWnd <> 0 And SwitchToFolder = False
mText = String(100, Chr(0))
mRet = GetClassName(hWnd, mText, 100)
mWinClass = Left(mText, mRet)
If mWinClass = "CabinetWClass" Then
mText = String(100, Chr(0))
mRet = GetWindowText(hWnd, mText, 100)
If mRet > 0 Then
mWinTitle = Left(mText, mRet)
If UCase(mWinTitle) = UCase(pFolder) Or _
UCase(Right(mWinTitle, Len(pFolder) + 1)) = "\" & UCase(pFolder) Then
BringWindowToTop hWnd
SwitchToFolder = True
End If
End If
End If
hWnd = FindWindowEx(0, hWnd, vbNullString, vbNullString)
Wend
End Function
Check this post under FileUpload Control
Additionally, the “Include local directory path when uploading files” URLAction has been set to "Disable" for the Internet Zone. This change prevents leakage of potentially sensitive local file-system information to the Internet. For instance, rather than submitting the full path C:\users\ericlaw\documents\secret\image.png, Internet Explorer 8 will now submit only the filename image.png.
Its an option under Internet security that can be enabled
Make sure you don't include extension of the resource, nor path to it. It's only the resource file name.
PictureBoxName.Image = My.Resources.ResourceManager.GetObject("object_name")
You just need to iterate the anchors in the two links.
<a href="#hide2" class="hide" id="hide2">+</a>
<a href="#show2" class="show" id="show2">-</a>
See this jsfiddle http://jsfiddle.net/eJX8z/
I also added some margin to the FAQ call to improve the format.
Call decode()
on a bytes
instance to get the text which it encodes.
str = bytes.decode()
In your example, you can break the string into two pieces:
alert ( "Please Select file"
+ " to delete");
Or, when it's a string, as in your case, you can use a backslash as @Gumbo suggested:
alert ( "Please Select file\
to delete");
Note that this backslash approach is not necessarily preferred, and possibly not universally supported (I had trouble finding hard data on this). It is not in the ECMA 5.1 spec.
When working with other code (not in quotes), line breaks are ignored, and perfectly acceptable. For example:
if(SuperLongConditionWhyIsThisSoLong
&& SuperLongConditionOnAnotherLine
&& SuperLongConditionOnThirdLineSheesh)
{
// launch_missiles();
}
Hope this helps : Declared a variable , in case of any changes need to be made thats only once .
declare @line varchar(100)
set @line ='[email protected]'
select SUBSTRING(@line ,(charindex('-',@line)+1), CHARINDEX('@',@line)-charindex('-',@line)-1)
Try http://prettydiff.com/ The algorithm is similar to HTML Tidy, but is more complete. The program is written entirely in JavaScript, so you don't have to install anything.
I have a more generic regex to allow the user to enter only numbers, +
, -
, whitespace
and ()
. It respects the parenthesis balance and there is always a number after a symbol.
^([+]?[\s0-9]+)?(\d{3}|[(]?[0-9]+[)])?([-]?[\s]?[0-9])+$
false, ""
false, "+48 504 203 260@@"
false, "+48.504.203.260"
false, "+55(123) 456-78-90-"
false, "+55(123) - 456-78-90"
false, "504.203.260"
false, " "
false, "-"
false, "()"
false, "() + ()"
false, "(21 7777"
false, "+48 (21)"
false, "+"
true , " 1"
true , "1"
true, "555-5555-555"
true, "+48 504 203 260"
true, "+48 (12) 504 203 260"
true, "+48 (12) 504-203-260"
true, "+48(12)504203260"
true, "+4812504203260"
true, "4812504203260
Pickle uses different protocols
to convert your data to a binary stream.
In python 2 there are 3 different protocols (0
, 1
, 2
) and the default is 0
.
In python 3 there are 5 different protocols (0
, 1
, 2
, 3
, 4
) and the default is 3
.
You must specify in python 3 a protocol lower than 3
in order to be able to load the data in python 2. You can specify the protocol
parameter when invoking pickle.dump
.
Queue is an interface in java, you can not do that.
Instead you have two options:
option1:
Queue<Integer> Q = new LinkedList<>();
option2:
Queue<Integer> Q = new ArrayDeque<>();
I recommend using option2 as it is bit faster than the other
Your sudo path does not know about your local path... go into superuser mode, add the path, and install it from there.
sudo su
export PATH=$PATH:/usr/local/mysql/bin/
pip install mysql-python
exit
And you're up and running on OSX. Now you have an updated global python.
You can make responsive grid of squares with verticaly and horizontaly centered content only with CSS. I will explain how in a step by step process but first here are 2 demos of what you can achieve :
Now let's see how to make these fancy responsive squares!
The trick for keeping elements square (or whatever other aspect ratio) is to use percent padding-bottom
.
Side note: you can use top padding too or top/bottom margin but the background of the element won't display.
As top padding is calculated according to the width of the parent element (See MDN for reference), the height of the element will change according to its width. You can now Keep its aspect ratio according to its width.
At this point you can code :
HTML :
<div></div>
CSS
div {
width: 30%;
padding-bottom: 30%; /* = width for a square aspect ratio */
}
Here is a simple layout example of 3*3 squares grid using the code above.
With this technique, you can make any other aspect ratio, here is a table giving the values of bottom padding according to the aspect ratio and a 30% width.
Aspect ratio | padding-bottom | for 30% width
------------------------------------------------
1:1 | = width | 30%
1:2 | width x 2 | 60%
2:1 | width x 0.5 | 15%
4:3 | width x 0.75 | 22.5%
16:9 | width x 0.5625 | 16.875%
As you can't add content directly inside the squares (it would expand their height and squares wouldn't be squares anymore) you need to create child elements (for this example I am using divs) inside them with position: absolute;
and put the content inside them. This will take the content out of the flow and keep the size of the square.
Don't forget to add position:relative;
on the parent divs so the absolute children are positioned/sized relatively to their parent.
Let's add some content to our 3x3 grid of squares :
HTML :
<div class="square">
<div class="content">
.. CONTENT HERE ..
</div>
</div>
... and so on 9 times for 9 squares ...
CSS :
.square {
float:left;
position: relative;
width: 30%;
padding-bottom: 30%; /* = width for a 1:1 aspect ratio */
margin:1.66%;
overflow:hidden;
}
.content {
position:absolute;
height:80%; /* = 100% - 2*10% padding */
width:90%; /* = 100% - 2*5% padding */
padding: 10% 5%;
}
RESULT <-- with some formatting to make it pretty!
Horizontally :
This is pretty easy, you just need to add text-align:center
to .content
.
RESULT
Vertical alignment
This becomes serious! The trick is to use
display:table;
/* and */
display:table-cell;
vertical-align:middle;
but we can't use display:table;
on .square
or .content
divs because it conflicts with position:absolute;
so we need to create two children inside .content
divs. Our code will be updated as follow :
HTML :
<div class="square">
<div class="content">
<div class="table">
<div class="table-cell">
... CONTENT HERE ...
</div>
</div>
</div>
</div>
... and so on 9 times for 9 squares ...
CSS :
.square {
float:left;
position: relative;
width: 30%;
padding-bottom : 30%; /* = width for a 1:1 aspect ratio */
margin:1.66%;
overflow:hidden;
}
.content {
position:absolute;
height:80%; /* = 100% - 2*10% padding */
width:90%; /* = 100% - 2*5% padding */
padding: 10% 5%;
}
.table{
display:table;
height:100%;
width:100%;
}
.table-cell{
display:table-cell;
vertical-align:middle;
height:100%;
width:100%;
}
We have now finished and we can take a look at the result here :
In case you want to improve the commit message with header and body after you created the commit, you can reword it. This approach is more useful because you know what the code does only after you wrote it.
git rebase -i origin/master
Then, your commits will appear:
pick e152ce2 Update framework
pick ffcf91e Some magic
pick fa672e1 Update comments
Select the commit you want to reword and save.
pick e152ce2 Update framework
reword ffcf91e Some magic
pick fa672e1 Update comments
Now, you have the opportunity to add header and body, where the first line will be the header.
Create perpetuum mobile
Redesign laws of physics with a pinch of imagination. Open a wormhole in 23 dimensions. Add protection to avoid high instability.
ViewGroup's onInterceptTouchEvent()
is always the entry point for ACTION_DOWN
event which is first event to occur.
If you want ViewGroup to process this gesture, return true from onInterceptTouchEvent()
.
On returning true, ViewGroup's onTouchEvent()
will receive all subsequent events till next ACTION_UP
or ACTION_CANCEL
, and in most cases, the touch events between ACTION_DOWN
and ACTION_UP
or ACTION_CANCEL
are ACTION_MOVE
, which will normally be recognized as scrolling/fling gestures.
If you return false from onInterceptTouchEvent()
, the target view's onTouchEvent()
will be called. It will be repeated for subsequent messages till you return true from onInterceptTouchEvent()
.
Since there is only one WiFi hardware on the computer its not possible to connect one WiFi hardware to multiple WiFi networks, if you want to that I think you have to map WiFi hardware to guest OS and how host you'll have to use some other hardware (may be Ethernet) but I'm sure that it will work in that way as no VM software allow us to allocate Hardware to Guest except for USB, you can also get USB WiFI and allocate that to VM only.
JSON.stringify
returns a String
. So, for example:
var data = [
{ id: 1, name: "bob" },
{ id: 2, name: "john" },
{ id: 3, name: "jake" },
];
JSON.stringify(data)
will return the equivalent of:
"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]"
as a String
value.
So when you have
<% for(var i=0; i<JSON.stringify(data).length; i++) {%>
what that ends up looking like is:
<% for(var i=0; i<"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]".length; i++) {%>
which is probably not what you want. What you probably do want is something like this:
<table>
<% for(var i=0; i < data.length; i++) { %>
<tr>
<td><%= data[i].id %></td>
<td><%= data[i].name %></td>
</tr>
<% } %>
</table>
This will output the following table (using the example data
from above):
<table>
<tr>
<td>1</td>
<td>bob</td>
</tr>
<tr>
<td>2</td>
<td>john</td>
</tr>
<tr>
<td>3</td>
<td>jake</td>
</tr>
</table>
Here you can see that there are 2 public static void main (String args[])
in a single file with the name Test.java
(specifically didn't use the name of file as either of the 2 classes names) and the 2 classes are with the default access specifier.
class Sum {
int add(int a, int b) {
return (a+b);
}
public static void main (String args[]) {
System.out.println(" using Sum class");
Sum a = new Sum();
System.out.println("Sum is :" + a.add(5, 10));
}
public static void main (int i) {
System.out.println(" Using Sum class main function with integer argument");
Sum a = new Sum();
System.out.println("Sum is :" + a.add(20, 10));
}
}
class DefClass {
public static void main (String args[]) {
System.out.println(" using DefClass");
Sum a = new Sum();
System.out.println("Sum is :" + a.add(5, 10));
Sum.main(null);
Sum.main(1);
}
}
When we compile the code Test.java it will generate 2 .class
files (viz Sum.class
and DefClass.class
) and if we run Test.java we cannot run it as it won't find any main class with the name Test. Instead if we do java Sum
or java DefClass
both will give different outputs using different main()
. To use the main method of Sum class we can use the class name Sum.main(null)
or Sum.main(1)//Passing integer value in the DefClass main()
.
In a class scope we can have only one public static void main (String args[])
per class since a static method of a class belongs to a class and not to its objects and is called using its class name. Even if we create multiple objects and call the same static methods using them then the instance of the static method to which these call will refer will be the same.
We can also do the overloading of the main method by passing different set of arguments in the main. The Similar example is provided in the above code but by default the control flow will start with the public static void main (String args[])
of the class file which we have invoked using java classname
. To invoke the main method with other set of arguments we have to explicitly call it from other classes.
You should have a 'skeleton' somewhere in /etc
, probably /etc/skeleton
, or check the default settings, probably /etc/default
or something. Those are scripts that define standard environment variables getting set during a login.
If it is just for your own account: check the (hidden) file ~/.profile
and ~/.login
. Or generate them, if they don't exist. These are also evaluated by the login process.
What ever data you have inserted into one text file or log file that can put on one path in hdfs and then write a query as follows in hive
hive>load data inpath<<specify inputpath>> into table <<tablename>>;
EXAMPLE:
hive>create table foo (id int, name string)
row format delimited
fields terminated by '\t' or '|'or ','
stored as text file;
table created..
DATA INSERTION::
hive>load data inpath '/home/hive/foodata.log' into table foo;
This is quite easy to do with your Apache environment variables. This only works with Apache 2, which I assume you are using.
Simply use the following PHP code:
<?php
$request_url = apache_getenv("HTTP_HOST") . apache_getenv("REQUEST_URI");
echo $request_url;
?>
foreach($equipxml as $equip) {
$current_device = $equip->xpath("name");
if ( $current_device[0] == $device ) {
// found a match in the file
$nodeid = $equip->id;
break;
}
}
Simply use break
. That will do it.
How about this one
<video class="play-video" muted onclick="this.paused?this.play():this.pause();">
<source src="" type="video/mp4">
</video>
The error - "Expected an assignment or function call and instead saw an expression no-unused-expressions" comes when we use curly braces i.e {} to return an object literal expression. In such case we can fix it with 2 options
Example :
const items = ["Test1", "Test2", "Test3", "Test4"];
console.log(articles.map(item => { `this is ${item}` })); // wrong
console.log(items.map(item => (`this is ${item}`))); // Option1
console.log(items.map(item => { return `this is ${item}` })); // Option2
exp(x) = e^x where e= 2.718281(approx)
import numpy as np
ar=np.array([1,2,3])
ar=np.exp(ar)
print ar
outputs:
[ 2.71828183 7.3890561 20.08553692]
That combination of username, host, and password is not allowed to connect to the server. Verify the permission tables (reloading grants if required) on the server and that you're connecting to the correct server.
Try Adding this
$('input[name="daterangepicker"]').daterangepicker({
"locale": {
"firstDay" :1 // 0 Tuesday - 6 - Monday between
}});
It must be completed within the locale object of the defined daterangepicker. detailed information can be found here.
In my benchmark script, each method is tested 10000 times and the difference of the total time for each method is printed. You should this on your own configuration, I'm sure results will vary!
These are my results:
SELECT NULL" -> PGO()
faster by ~ 0.35 secondsSHOW TABLE STATUS" -> mysqli()
faster by ~ 2.3 secondsSELECT * FROM users" -> mysqli()
faster by ~ 33 secondsNote: by using ->fetch_row() for mysqli, the column names are not added to the array, I didn't find a way to do that in PGO. But even if I use ->fetch_array() , mysqli is slightly slower but still faster than PGO (except for SELECT NULL).
Adding the actual code here for future reference
So, there are 3 steps, and therefore 3 SQL statements:
Step 1: Move the non duplicates (unique tuples) into a temporary table
CREATE TABLE new_table as
SELECT * FROM old_table WHERE 1 GROUP BY [column to remove duplicates by];
Step 2: delete the old table (or rename it) We no longer need the table with all the duplicate entries, so drop it!
DROP TABLE old_table;
Step 3: rename the new_table to the name of the old_table
RENAME TABLE new_table TO old_table;
And of course, don't forget to fix your buggy code to stop inserting duplicates!
If you want a cross-platform method of doing this, the general pattern is to derive from QThread and create a function (static, if you'd like) in your derived class that will call one of the sleep functions in QThread.
#define DEBUG
#ifdef DEBUG
#define PRINT print
#else
#define PRINT(...) ((void)0) //strip out PRINT instructions from code
#endif
void print(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
vsprintf(str, fmt, args);
va_end(args);
printf("%s\n", str);
}
int main() {
PRINT("[%s %d, %d] Hello World", "March", 26, 2009);
return 0;
}
If the compiler does not understand variadic macros, you can also strip out PRINT with either of the following:
#define PRINT //
or
#define PRINT if(0)print
The first comments out the PRINT instructions, the second prevents PRINT instruction because of a NULL if condition. If optimization is set, the compiler should strip out never executed instructions like: if(0) print("hello world"); or ((void)0);
Use empty() and/or is_null()
http://www.php.net/empty http://www.php.net/is_null
Empty alone will achieve your current usage, is_null would just make more control possible if you wanted to distinguish between a field that is null and a field that is empty.
Using Java 8 - Stream Funtion:
Converting A String into Character List:
ArrayList<Character> characterList = givenStringVariable
.chars()
.mapToObj(c-> (char)c)
.collect(collectors.toList());
Converting A Character List into String:
String givenStringVariable = characterList
.stream()
.map(String::valueOf)
.collect(Collectors.joining())
BigInteger n = new BigInteger(byteArray);
String hexa = n.toString(16));
When importing an existing Gradle project (one with a build.gradle
) into IntelliJ IDEA, when presented with the following screen, select Import from external model -> Gradle.
Optionally, select Auto Import on the next screen to automatically import new dependencies.
just use
file:///
works in IE, Firefox and Chrome as far as I can tell.
see http://msdn.microsoft.com/en-us/library/aa767731(VS.85).aspx for more info
Note that groupBy
as used above won't work for postgres.
Using distinct
is probably a better option - e.g.
$users = User::query()->distinct()->get();
If you use query
you can select all the columns as requested.
Here's how to create a copy of a DataFrame
excluding a list of columns:
df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
df2 = df.drop(['B', 'D'], axis=1)
But be careful! You mention views in your question, suggesting that if you changed df
, you'd want df2
to change too. (Like a view would in a database.)
This method doesn't achieve that:
>>> df.loc[0, 'A'] = 999 # Change the first value in df
>>> df.head(1)
A B C D
0 999 -0.742688 -1.980673 -0.920133
>>> df2.head(1) # df2 is unchanged. It's not a view, it's a copy!
A C
0 0.251262 -1.980673
Note also that this is also true of @piggybox's method. (Although that method is nice and slick and Pythonic. I'm not doing it down!!)
For more on views vs. copies see this SO answer and this part of the Pandas docs which that answer refers to.
Please find the code below for Vlookup
:
Function vlookupVBA(lookupValue, rangeString, colOffset)
vlookupVBA = "#N/A"
On Error Resume Next
Dim table_lookup As range
Set table_lookup = range(rangeString)
vlookupVBA = Application.WorksheetFunction.vlookup(lookupValue, table_lookup, colOffset, False)
End Function
The only built-in way to "downgrade" a database from one SQL Server version to a lower one is the hard way: Script out the whole database, schema and data, then execute the script on the target server.
This is do-able but tends to be brutal.
CGFloat is a regular float on 32-bit systems and a double on 64-bit systems
typedef float CGFloat;// 32-bit
typedef double CGFloat;// 64-bit
So you won't get any performance penalty.
A very flexible way to do that kind of things is using ARRAYFORMULA.
As an example imagine you want to count non empty strings (text fields) you can use this code:
=ARRAYFORMULA(SUM(IF(Len(B3:B14)>0, 1, 0)))
What happens here is that "ArrayFormula" let you operate over a set of values. Using the SUM function you indicates "ArrayFormula" to sum any value of the set. The "If" clause is only used to check "empty" or "not empty", 1 for not empty and 0 otherwise. "Len" returns the length of the different text fields, there is where you define the set (range) you want to check. Finally "ArrayFormula" will sum 1 for each field inside the set(range) in which "len" returns more than 0.
If you want to check any other condition, just modify the first argument of the IF clause.
After countless attempts, I found the following quote:
If you are using My KNOX, you cannot enable USB debugging mode while the container is installed. Unfortunately, you have to root your device ... - continue reading
Furthermore make sure:
I switched to another device without KNOX (not rooted as well) to save time. Maybe this quote will save someone some time. It was the only explanation to me in this case.
Cheers!
It can be cleaner to add an extension to FileManager for this kind of awkward call, for tidiness if nothing else. Something like:
extension FileManager {
static var documentDir : URL {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
}
}
Here is the formula
create a new rule in conditional formating based on a formula. Use the following formula and apply it to $A:$A
=NOT(ISERROR(MATCH(A1,$B$1:$B$1000,0)))
here is the example sheet to download if you encounter problems
UPDATE
here is @pnuts's suggestion which works perfect as well:
=MATCH(A1,B:B,0)>0
If you already have the xml, and comes more than one attribute, you can handle it as follows:
String output = "<ciudads><ciudad><idCiudad>1</idCiudad>
<nomCiudad>BOGOTA</nomCiudad></ciudad><ciudad><idCiudad>6</idCiudad>
<nomCiudad>Pereira</nomCiudad></ciudads>";
DocumentBuilder db = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(output));
Document doc = db.parse(is);
NodeList nodes = ((org.w3c.dom.Document) doc)
.getElementsByTagName("ciudad");
for (int i = 0; i < nodes.getLength(); i++) {
Ciudad ciudad = new Ciudad();
Element element = (Element) nodes.item(i);
NodeList name = element.getElementsByTagName("idCiudad");
Element element2 = (Element) name.item(0);
ciudad.setIdCiudad(Integer
.valueOf(getCharacterDataFromElement(element2)));
NodeList title = element.getElementsByTagName("nomCiudad");
element2 = (Element) title.item(0);
ciudad.setNombre(getCharacterDataFromElement(element2));
ciudades.getPartnerAccount().add(ciudad);
}
}
for (Ciudad ciudad1 : ciudades.getPartnerAccount()) {
System.out.println(ciudad1.getIdCiudad());
System.out.println(ciudad1.getNombre());
}
the method getCharacterDataFromElement is
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
this is how I do it
JAVASCRIPT:
var module = angular.module('yourModuleName', ['ui.router']);
module.run( ['$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}
]);
HTML:
<pre id="uiRouterInfo">
$state = {{$state.current.name}}
$stateParams = {{$stateParams}}
$state full url = {{ $state.$current.url.source }}
</pre>
EXAMPLE
Please use Homebrew Formulae page to see the list of installable packages. https://formulae.brew.sh/formula/
To install any package => command to use is :
brew install node
HOW TO FORCE UNLOCK for locked tables in MySQL:
Breaking locks like this may cause atomicity in the database to not be enforced on the sql statements that caused the lock.
This is hackish, and the proper solution is to fix your application that caused the locks. However, when dollars are on the line, a swift kick will get things moving again.
1) Enter MySQL
mysql -u your_user -p
2) Let's see the list of locked tables
mysql> show open tables where in_use>0;
3) Let's see the list of the current processes, one of them is locking your table(s)
mysql> show processlist;
4) Kill one of these processes
mysql> kill <put_process_id_here>;
You need a Spinner
. Here it is an example:
spinner_1 = (Spinner) findViewById(R.id.spinner1);
spinner_1.setOnItemSelectedListener(this);
List<String> list = new ArrayList<String>();
list.add("RANJITH");
list.add("ARUN");
list.add("JEESMON");
list.add("NISAM");
list.add("SREEJITH");
list.add("SANJAY");
list.add("AKSHY");
list.add("FIROZ");
list.add("RAHUL");
list.add("ARJUN");
list.add("SAVIYO");
list.add("VISHNU");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_1.setAdapter(adapter);
spinner_2 = (Spinner) findViewById(R.id.spinner_two);
spinner_2.setOnItemSelectedListener(this);
List<String> city = new ArrayList<String>();
city.add("KASARGOD");
city.add("KANNUR");
city.add("THRISSUR");
city.add("KOZHIKODE");
city.add("TRIVANDRUM");
city.add("ERNAMKULLAM");
city.add("WAYANAD");
city.add("PALAKKAD");
city.add("ALAPUZHA");
city.add("IDUKKI");
city.add("KOTTAYAM");
city.add("PATHANAMTHITTA");
city.add("KOLLAM");
city.add("MALAPPURAM");
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, city);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_2.setAdapter(adapter2);
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(this, "YOUR SELECTION IS : " + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
Here's what you CAN do:
You can attach (to the email) an html document that contains javascript.
Then, when the recipient opens the attachment, their web browser will facilitate the dynamic features you've implemented.
I’m going to hold the unpopular on SO selenium tag opinion that XPath is preferable to CSS in the longer run.
This long post has two sections - first I'll put a back-of-the-napkin proof the performance difference between the two is 0.1-0.3 milliseconds (yes; that's 100 microseconds), and then I'll share my opinion why XPath is more powerful.
Let's first tackle "the elephant in the room" – that xpath is slower than css.
With the current cpu power (read: anything x86 produced since 2013), even on browserstack/saucelabs/aws VMs, and the development of the browsers (read: all the popular ones in the last 5 years) that is hardly the case. The browser's engines have developed, the support of xpath is uniform, IE is out of the picture (hopefully for most of us). This comparison in the other answer is being cited all over the place, but it is very contextual – how many are running – or care about – automation against IE8?
If there is a difference, it is in a fraction of a millisecond.
Yet, most higher-level frameworks add at least 1ms of overhead over the raw selenium call anyways (wrappers, handlers, state storing etc); my personal weapon of choice – RobotFramework – adds at least 2ms, which I am more than happy to sacrifice for what it provides. A network roundtrip from an AWS us-east-1 to BrowserStack's hub is usually 11 milliseconds.
So with remote browsers if there is a difference between xpath and css, it is overshadowed by everything else, in orders of magnitude.
There are not that many public comparisons (I've really seen only the cited one), so – here's a rough single-case, dummy and simple one.
It will locate an element by the two strategies X times, and compare the average time for that.
The target – BrowserStack's landing page, and its "Sign Up" button; a screenshot of the html as writing this post:
Here's the test code (python):
from selenium import webdriver
import timeit
if __name__ == '__main__':
xpath_locator = '//div[@class="button-section col-xs-12 row"]'
css_locator = 'div.button-section.col-xs-12.row'
repetitions = 1000
driver = webdriver.Chrome()
driver.get('https://www.browserstack.com/')
css_time = timeit.timeit("driver.find_element_by_css_selector(css_locator)",
number=repetitions, globals=globals())
xpath_time = timeit.timeit('driver.find_element_by_xpath(xpath_locator)',
number=repetitions, globals=globals())
driver.quit()
print("css total time {} repeats: {:.2f}s, per find: {:.2f}ms".
format(repetitions, css_time, (css_time/repetitions)*1000))
print("xpath total time for {} repeats: {:.2f}s, per find: {:.2f}ms".
format(repetitions, xpath_time, (xpath_time/repetitions)*1000))
For those not familiar with Python – it opens the page, and finds the element – first with the css locator, then with the xpath; the find operation is repeated 1,000 times. The output is the total time in seconds for the 1,000 repetitions, and average time for one find in milliseconds.
The locators are:
Deliberately chosen not to be over-tuned; also, the class selector is cited for the css as "the second fastest after an id".
The environment – Chrome v66.0.3359.139, chromedriver v2.38, cpu: ULV Core M-5Y10 usually running at 1.5GHz (yes, a "word-processing" one, not even a regular i7 beast).
Here's the output:
css total time 1000 repeats: 8.84s, per find: 8.84ms xpath total time for 1000 repeats: 8.52s, per find: 8.52ms
Obviously the per find timings are pretty close; the difference is 0.32 milliseconds. Don't jump "the xpath is faster" – sometimes it is, sometimes it's css.
Let's try with another set of locators, a tiny-bit more complicated – an attribute having a substring (common approach at least for me, going after an element's class when a part of it bears functional meaning):
xpath_locator = '//div[contains(@class, "button-section")]'
css_locator = 'div[class~=button-section]'
The two locators are again semantically the same – "find a div element having in its class attribute this substring".
Here are the results:
css total time 1000 repeats: 8.60s, per find: 8.60ms xpath total time for 1000 repeats: 8.75s, per find: 8.75ms
Diff of 0.15ms.
As an exercise - the same test as done in the linked blog in the comments/other answer - the test page is public, and so is the testing code.
They are doing a couple of things in the code - clicking on a column to sort by it, then getting the values, and checking the UI sort is correct.
I'll cut it - just get the locators, after all - this is the root test, right?
The same code as above, with these changes in:
The url is now http://the-internet.herokuapp.com/tables
; there are 2 tests.
The locators for the first one - "Finding Elements By ID and Class" - are:
css_locator = '#table2 tbody .dues'
xpath_locator = "//table[@id='table2']//tr/td[contains(@class,'dues')]"
And here is the outcome:
css total time 1000 repeats: 8.24s, per find: 8.24ms xpath total time for 1000 repeats: 8.45s, per find: 8.45ms
Diff of 0.2 milliseconds.
The "Finding Elements By Traversing":
css_locator = '#table1 tbody tr td:nth-of-type(4)'
xpath_locator = "//table[@id='table1']//tr/td[4]"
The result:
css total time 1000 repeats: 9.29s, per find: 9.29ms xpath total time for 1000 repeats: 8.79s, per find: 8.79ms
This time it is 0.5 ms (in reverse, xpath turned out "faster" here).
So 5 years later (better browsers engines) and focusing only on the locators performance (no actions like sorting in the UI, etc), the same testbed - there is practically no difference between CSS and XPath.
So, out of xpath and css, which of the two to choose for performance? The answer is simple – choose locating by id.
Long story short, if the id of an element is unique (as it's supposed to be according to the specs), its value plays an important role in the browser's internal representation of the DOM, and thus is usually the fastest.
Yet, unique and constant (e.g. not auto-generated) ids are not always available, which brings us to "why XPath if there's CSS?"
With the performance out of the picture, why do I think xpath is better? Simple – versatility, and power.
Xpath is a language developed for working with XML documents; as such, it allows for much more powerful constructs than css.
For example, navigation in every direction in the tree – find an element, then go to its grandparent and search for a child of it having certain properties.
It allows embedded boolean conditions – cond1 and not(cond2 or not(cond3 and cond4))
; embedded selectors – "find a div having these children with these attributes, and then navigate according to it".
XPath allows searching based on a node's value (its text) – however frowned upon this practice is, it does come in handy especially in badly structured documents (no definite attributes to step on, like dynamic ids and classes - locate the element by its text content).
The stepping in css is definitely easier – one can start writing selectors in a matter of minutes; but after a couple of days of usage, the power and possibilities xpath has quickly overcomes css.
And purely subjective – a complex css is much harder to read than a complex xpath expression.
Finally, again very subjective - which one to chose?
IMO, there is no right or wrong choice - they are different solutions to the same problem, and whatever is more suitable for the job should be picked.
Being "a fan" of XPath I'm not shy to use in my projects a mix of both - heck, sometimes it is much faster to just throw a CSS one, if I know it will do the work just fine.
On Windows XP -
rundll32.exe syssetup,SetupOobeBnk
This will reset the 30 day timer for activation back to 30 days so you can enter in the key normally.
In a fresh spreadsheet (US locale) with 12/19/11
in A1 and DT 30
in B1 then:
=A1+right(B1,2)
in say C1 returns 1/18/12
.
As a string function RIGHT returns Text but that can be coerced into a number when adding. In adding a number to dates unity is treated as one day. Within (very wide) limits, months and even years are adjusted automatically.
If by any chance git pull
prints Already up-to-date
then you might want to check the global git push.default
param (In ~/.gitconfig
). Set it to simple
if it was in matching
. The below answer explains why:
Git - What is the difference between push.default "matching" and "simple"
Also, it is worth checking if your local branch is out of date using git remote show origin
and do a pull if needed
Here's the most simplest code for everyone
Note: Showing Pearson's Rho and not R^2.
library(ggplot2)
library(ggpubr)
df <- data.frame(x = c(1:100)
df$y <- 2 + 3 * df$x + rnorm(100, sd = 40)
p <- ggplot(data = df, aes(x = x, y = y)) +
geom_smooth(method = "lm", se=FALSE, color="black", formula = y ~ x) +
geom_point()+
stat_cor(label.y = 35)+ #this means at 35th unit in the y axis, the r squared and p value will be shown
stat_regline_equation(label.y = 30) #this means at 30th unit regresion line equation will be shown
p
It happens when you have a file with the same name as Makefile target name in the directory where the Makefile is present.
After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.
* The arguments which may be supplied in the recovery.command file:
* --send_intent=anystring - write the text out to recovery.intent
* --update_package=path - verify install an OTA package file
* --wipe_data - erase user data (and cache), then reboot
* --wipe_cache - wipe cache (but not user data), then reboot
* --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:
adb shell
recovery --wipe_data
Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.
EDIT:
For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command
For more information please see here: https://github.com/CyanogenMod/android_bootable_recovery/blob/cm-10.2/recovery.c
<a href="index.html">_x000D_
<button type="button">Submit</button>_x000D_
</a>
_x000D_
<button type="submit" onclick="myFunction()">Submit</button>_x000D_
<script>_x000D_
function myFunction() {_x000D_
var w = window.open(file:///E:/Aditya%20panchal/index.html);_x000D_
}_x000D_
</script>
_x000D_
When you are manipulating the data like:
this.data.profiles[i].icon.url = '';
Then you should use in order to detect changes:
let array = this.data.profiles.map(x => Object.assign({}, x)); // It will detect changes
Since angular ngOnchanges not be able to detect changes in array, objects then we have to assign a new reference. Works everytime!
The solution using flexbox without justify-content: space-between
.
<div class="title">
<span>Cumulative performance</span>
<span>20/02/2011</span>
</div>
.title {
display: flex;
}
span:first-of-type {
flex: 1;
}
When we use flex:1
on the first <span>
, it takes up the entire remaining space and moves the second <span>
to the right. The Fiddle with this solution: https://jsfiddle.net/2k1vryn7/
Here https://jsfiddle.net/7wvx2uLp/3/ you can see the difference between two flexbox approaches: flexbox with justify-content: space-between
and flexbox with flex:1
on the first <span>
.
import { ActivatedRoute } from '@angular/router';_x000D_
_x000D_
export class ClassName {_x000D_
_x000D_
private router = ActivatedRoute;_x000D_
_x000D_
constructor(r: ActivatedRoute) {_x000D_
this.router =r;_x000D_
}_x000D_
_x000D_
onSuccess() {_x000D_
this.router.navigate(['/user_invitation'],_x000D_
{queryParams: {email: loginEmail, code: userCode}});_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
Get this values:_x000D_
---------------_x000D_
_x000D_
ngOnInit() {_x000D_
this.route_x000D_
.queryParams_x000D_
.subscribe(params => {_x000D_
let code = params['code'];_x000D_
let userEmail = params['email'];_x000D_
});_x000D_
}
_x000D_
Ref: https://angular.io/docs/ts/latest/api/router/index/NavigationExtras-interface.html
If you have a method that you want to throw an error but you want to do some cleanup in your method beforehand you can put the code that will throw the exception inside a try block, then put the cleanup in the catch block, then throw the error.
try {
//Dangerous code: could throw an error
} catch (Exception e) {
//Cleanup: make sure that this methods variables and such are in the desired state
throw e;
}
This way the try/catch block is not actually handling the error but it gives you time to do stuff before the method terminates and still ensures that the error is passed on to the caller.
An example of this would be if a variable changed in the method then that variable was the cause of an error. It may be desirable to revert the variable.
This one was not included:
System.Windows.Forms.Application.ExecutablePath;
~Joe
While Loop is an obsolete structure, I would recommend you to replace "While loop" to "Do While..loop", and you will able to use Exit clause.
check = 0
Do while not rs.EOF
if rs("reg_code") = rcode then
check = 1
Response.Write ("Found")
Exit do
else
rs.MoveNext
end if
Loop
if check = 0 then
Response.Write "Not Found"
end if}
According to the spec for locating Schemas
there may or may not be a schema retrievable via the namespace name... User community and/or consumer/provider agreements may establish circumstances in which [trying to retrieve an xsd from the namespace url] is a sensible default strategy
(thanks for being unambiguous, spec!)
and
in case a document author (human or not) created a document with a particular schema in view, and warrants that some or all of the document conforms to that schema, the schemaLocation and noNamespaceSchemaLocation [attributes] are provided.
So basically with specifying just a namespace, your XML "might" be attempted to be validated against an xsd at that location (even if it lacks a schemaLocation
attribute), depending on your "community." If you specify a specific schemaLocation
, then it basically is implying that the xml document "should" be conformant to said xsd, so "please validate it" (as I read it). My guess is that if you don't do a schemaLocation
or noNamespaceSchemaLocation
attribute it just "isn't validated" most of the time (based on the other answers, appears java does it this way).
Another wrinkle here is that typically, with xsd validation in java libraries [ex: spring config xml files], if your XML files specifies a particular schemaLocation
xsd url in an XML file, like xsi:schemaLocation="http://somewhere http://somewhere/something.xsd"
typically within one of your dependency jars it will contain a copy of that xsd file, in its resources section, and spring has a "mapping" capability saying to treat that xsd file as if it maps to the url http://somewhere/something.xsd
(so you never end up going to web and downloading the file, it just exists locally). See also https://stackoverflow.com/a/41225329/32453 for slightly more info.
An important difference between a 'typedef struct' and a 'struct' in C++ is that inline member initialisation in 'typedef structs' will not work.
// the 'x' in this struct will NOT be initialised to zero
typedef struct { int x = 0; } Foo;
// the 'x' in this struct WILL be initialised to zero
struct Foo { int x = 0; };
Easiest way is used the Date Using Date() and getTime()
Date dte=new Date();
long milliSeconds = dte.getTime();
String strLong = Long.toString(milliSeconds);
System.out.println(milliSeconds)
When using LINQ extension methods (e.g. Select
, Where
), the lambda function might be converted to SQL that might not behave identically to your C# code. For instance, C#'s short-circuit evaluated &&
and ||
are converted to SQL's eager AND
and OR
. This can cause problems when you're checking for null in your lambda.
Example:
MyEnum? type = null;
Entities.Table.Where(a => type == null ||
a.type == (int)type).ToArray(); // Exception: Nullable object must have a value
remove the android:targetSdkVersion="21"
from manifest.xml. it will work!
and from this there is no prob at all in your apk it just a trick i apply this and i found colorful icon in notification
I found a very interesting issue with Android Studio and the mircrosoft upgrade to the web browser. I upgraded "stupidly" to the latest version of ie. of course Microsoft in their infinite wisdom knows exactly what to do with security. When I tried to compile my app I kept getting the error Gradle - build fails -- Execution failed for task. looking in the stack I saw that it did not recognize the path to java.exe. I found that odd as I was just able to compile the day before. I added JAVA_HOME to the env vars for the system, closed Android Studio and reopened it. Low and behold if the fire wall nag screen did not pop asking if I wanted to all jave.exe through.
What a cluster!
Here's a picture explaining the difference between pageY
and clientY
.
Same for pageX
and clientX
, respectively.
pageX/Y
coordinates are relative to the top left corner of the whole rendered page (including parts hidden by scrolling),
while clientX/Y
coordinates are relative to the top left corner of the visible part of the page, "seen" through browser window.
You'll probably never need screenX/Y
I will suggest move all templates to separate files, and don't do spagetti inside repeat
take a look here:
html:
<div ng-repeat = "data in comments">
<div ng-include src="buildUrl(data.type)"></div>
</div>
js:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.comments = [
{"_id":"52fb84fac6b93c152d8b4569",
"post_id":"52fb84fac6b93c152d8b4567",
"user_id":"52df9ab5c6b93c8e2a8b4567",
"type":"hoot"},
{"_id":"52fb798cc6b93c74298b4568",
"post_id":"52fb798cc6b93c74298b4567",
"user_id":"52df9ab5c6b93c8e2a8b4567",
"type":"story"},
{"_id":"52fb7977c6b93c5c2c8b456b",
"post_id":"52fb7977c6b93c5c2c8b456a",
"user_id":"52df9ab5c6b93c8e2a8b4567",
"type":"article"}
];
$scope.buildUrl = function(type) {
return type + '.html';
}
});
Below sample code can read file line by line and write new file in UTF-8 format. Also, i am explicitly specifying Cp1252 encoding.
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream("c:\\filenonUTF.txt"),
"Cp1252"));
String line;
Writer out = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(
"c:\\fileUTF.txt"), "UTF-8"));
try {
while ((line = br.readLine()) != null) {
out.write(line);
out.write("\n");
}
} finally {
br.close();
out.close();
}
}
Try to find out ID of your form element in generated aspx, and you can change target like...
getElementByID('theForm').target = '_blank' or 'myNewWindow'
If you are using MultiDex in your App Gradle then change extends application to extends MultiDexApplication in your application class. It will defiantly work
The solution provided by @user152949, as it was noted in commentaries, skips the first process and doesn't break when "exists" is set to true. Let me provide a fixed version:
#include <windows.h>
#include <tlhelp32.h>
#include <tchar.h>
bool IsProcessRunning(const TCHAR* const executableName) {
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
const auto snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
if (!Process32First(snapshot, &entry)) {
CloseHandle(snapshot);
return false;
}
do {
if (!_tcsicmp(entry.szExeFile, executableName)) {
CloseHandle(snapshot);
return true;
}
} while (Process32Next(snapshot, &entry));
CloseHandle(snapshot);
return false;
}
@Ciwan. You're right. The table goes to full width (much too wide). Not a good solution. Better to do this:
css:
.scrollme {
overflow-x: auto;
}
html:
<div class="scrollme">
<table class="table table-responsive"> ...
</table>
</div>
Edit: changing scroll-y to scroll-x
The value of the match
attribute of the <xsl:template>
instruction must be a match pattern.
Match patterns form a subset of the set of all possible XPath expressions. The first, natural, limitation is that a match pattern must select a set of nodes. There are also other limitations. In particular, reverse axes are not allowed in the location steps (but can be specified within the predicates). Also, no variable or parameter references are allowed in XSLT 1.0, but using these is legal in XSLT 2.x.
/
in XPath denotes the root or document node. In XPath 2.0 (and hence XSLT 2.x) this can also be written as document-node()
.
A match pattern can contain the //
abbreviation.
Examples of match patterns:
<xsl:template match="table">
can be applied on any element named table
.
<xsl:template match="x/y">
can be applied on any element named y
whose parent is an element named x
.
<xsl:template match="*">
can be applied to any element.
<xsl:template match="/*">
can be applied only to the top element of an XML document.
<xsl:template match="@*">
can be applied to any attribute.
<xsl:template match="text()">
can be applied to any text node.
<xsl:template match="comment()">
can be applied to any comment node.
<xsl:template match="processing-instruction()">
can be applied to any processing instruction node.
<xsl:template match="node()">
can be applied to any node: element, text, comment or processing instructon.
It's also important to realize that simply moving the program break pointer around with brk
and sbrk
doesn't actually allocate the memory, it just sets up the address space. On Linux, for example, the memory will be "backed" by actual physical pages when that address range is accessed, which will result in a page fault, and will eventually lead to the kernel calling into the page allocator to get a backing page.
You can trying code bellow
return [
'email' => 'required|email|max:255|unique:users,email,' .$this->get('id'),
'username' => 'required|alpha_dash|max:50|unique:users,username,'.$this->get('id'),
'password' => 'required|min:6',
'confirm-password' => 'required|same:password',
];
I have observed that -
I have prepared a method that works like this, you can replace the value of the variable ftpurl with the parameter TargetDestinationPath. I had tested this method on winforms application :
private void UploadProfileImage(string TargetFileName, string TargetDestinationPath, string FiletoUpload)
{
//Get the Image Destination path
string imageName = TargetFileName; //you can comment this
string imgPath = TargetDestinationPath;
string ftpurl = "ftp://downloads.abc.com/downloads.abc.com/MobileApps/SystemImages/ProfileImages/" + imgPath;
string ftpusername = krayknot_DAL.clsGlobal.FTPUsername;
string ftppassword = krayknot_DAL.clsGlobal.FTPPassword;
string fileurl = FiletoUpload;
FtpWebRequest ftpClient = (FtpWebRequest)FtpWebRequest.Create(ftpurl);
ftpClient.Credentials = new System.Net.NetworkCredential(ftpusername, ftppassword);
ftpClient.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
ftpClient.UseBinary = true;
ftpClient.KeepAlive = true;
System.IO.FileInfo fi = new System.IO.FileInfo(fileurl);
ftpClient.ContentLength = fi.Length;
byte[] buffer = new byte[4097];
int bytes = 0;
int total_bytes = (int)fi.Length;
System.IO.FileStream fs = fi.OpenRead();
System.IO.Stream rs = ftpClient.GetRequestStream();
while (total_bytes > 0)
{
bytes = fs.Read(buffer, 0, buffer.Length);
rs.Write(buffer, 0, bytes);
total_bytes = total_bytes - bytes;
}
//fs.Flush();
fs.Close();
rs.Close();
FtpWebResponse uploadResponse = (FtpWebResponse)ftpClient.GetResponse();
string value = uploadResponse.StatusDescription;
uploadResponse.Close();
}
Let me know in case of any issue, or here is one more link that can help you:
https://msdn.microsoft.com/en-us/library/ms229715(v=vs.110).aspx
This will also work fine :
int ans = 0;
while(num){
ans += (num &1);
num = num >>1;
}
return ans;
I guess you mean this:
class Value:
def __init__(self, v=None):
self.v = v
v1 = Value(1)
v2 = Value(2)
d = {'a': v1, 'b': v1, 'c': v2, 'd': v2}
d['a'].v += 1
d['b'].v == 2 # True
d['a']
and d['b']
to point to the same value that "updates" as it changes, make the value refer to a mutable object (user-defined class like above, or a dict
, list
, set
).d['a']
, d['b']
changes at same time because they both point to same object.You could use a cast:
public class GenSet<Item> {
private Item[] a;
public GenSet(int s) {
a = (Item[]) new Object[s];
}
}
public class TestModels
{
public Dictionary<int, dynamic> sp = new Dictionary<int, dynamic>();
public TestModels()
{
sp.Add(0, new {name="Test One", age=5});
sp.Add(1, new {name="Test Two", age=7});
}
}
You could use the library lxml (Note top level link is now spam) , which is a superset of ElementTree. Its tostring() method includes a parameter pretty_print - for example:
>>> print(etree.tostring(root, pretty_print=True))
<root>
<child1/>
<child2/>
<child3/>
</root>
It does work indeed. Issue was with my less compiler. It was compiled in to:
.container {
min-height: calc(-51vh);
}
Fixed with the following code in less file:
.container {
min-height: calc(~"100vh - 150px");
}
Thanks to this link: Less Aggressive Compilation with CSS3 calc
HTML Input
<input class="minutesInput" type="number" min="10" max="120" value="" />
jQuery
$(".minutesInput").on('keyup keypress blur change', function(e) {
if($(this).val() > 120){
$(this).val('120');
return false;
}
});
Leaving the action value blank will cause the form to post back to itself.
try to change this in your dispatcher-servlet.xml
<!-- Your View Resolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basenames" value="views" />
<property name="order" value="1" />
</bean>
<!-- UrlBasedViewResolver to Handle Redirects & Forward -->
<bean id="urlViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView" />
<property name="order" value="2" />
</bean>
What happens is clearly explained here http://projects.nigelsim.org/wiki/RedirectWithSpringWebMvc
The syntaxes
int[]
and
int[X] // Where X is a compile-time positive integer
are exactly the same as
int*
when in a function parameter list (I left out the optional names).
Additionally, an array name decays to a pointer to the first element when passed to a function (and not passed by reference) so both int firstarray[3]
and int secondarray[5]
decay to int*
s.
It also happens that both an array dereference and a pointer dereference with subscript syntax (subscript syntax is x[y]
) yield an lvalue to the same element when you use the same index.
These three rules combine to make the code legal and work how you expect; it just passes pointers to the function, along with the length of the arrays which you cannot know after the arrays decay to pointers.
From what you've told us it does appear to be a false positive in valgrind. The new
syntax with ()
should value-initialize the object, assuming it is POD.
Is it possible that some subpart of your struct isn't actually POD and that's preventing the expected initialization? Are you able to simplify your code into a postable example that still flags the valgrind error?
Alternately perhaps your compiler doesn't actually value-initialize POD structures.
In any case probably the simplest solution is to write constructor(s) as needed for the struct/subparts.
Windows (unlike some other OS's, like Linux), uses CR+LF for line breaks:
CR = 13 = 0x0D = ^M = \r = carriage return
LF = 10 = 0x0A = ^J = \n = new line
The characters need to be in that order, if you want the line breaks to be consistently visible when copied to other Windows programs. So the Excel function would be:
=SUBSTITUTE(A1,",",CHAR(13) & CHAR(10))
Thank You All! I am able to to load Select List as per MVC now My Working Code is below:
HTML+MVC Code in View:-
<tr>
<th>@Html.Label("Country")</th>
<td>@Html.DropDownListFor(x =>x.Province,SelectListItemHelper.GetCountryList())<span class="required">*</span></td>
</tr>
<tr>
<th>@Html.LabelFor(x=>x.Province)</th>
<td>@Html.DropDownListFor(x =>x.Province,SelectListItemHelper.GetProvincesList())<span class="required">*</span></td>
</tr>
Created a Controller under "UTIL" folder: Code:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MedAvail.Applications.MedProvision.Web.Util
{
public class SelectListItemHelper
{
public static IEnumerable<SelectListItem> GetProvincesList()
{
IList<SelectListItem> items = new List<SelectListItem>
{
new SelectListItem{Text = "California", Value = "B"},
new SelectListItem{Text = "Alaska", Value = "B"},
new SelectListItem{Text = "Illinois", Value = "B"},
new SelectListItem{Text = "Texas", Value = "B"},
new SelectListItem{Text = "Washington", Value = "B"}
};
return items;
}
public static IEnumerable<SelectListItem> GetCountryList()
{
IList<SelectListItem> items = new List<SelectListItem>
{
new SelectListItem{Text = "United States", Value = "B"},
new SelectListItem{Text = "Canada", Value = "B"},
new SelectListItem{Text = "United Kingdom", Value = "B"},
new SelectListItem{Text = "Texas", Value = "B"},
new SelectListItem{Text = "Washington", Value = "B"}
};
return items;
}
}
}
And its working COOL now :-)
Thank you!!
Here is what worked for me:
Context:
Building a project on a server
git status
returns a HEAD detached at <commit-SHA>
What ever operation I did locally, I had this error. More specifically:
Solution
<work-dir>/.git/index
. git status
would indicate that all files in the projet are not tracked (no surprise here).git reset HEAD --hard
HEAD detached at <commit-SHA>
when doing a git status
, but then you should be able togit checkout <some-branch>
and you're back on track!
!! IMPORTANT !!
This works only because I am "merly" building. No precious modification has been performed on the code. If you are actually in "dev-time", then I would recommand to save your work first or go for another method.
Hope it will help :).
It turns out this can be nicely expressed in a vectorized fashion:
> df = pd.DataFrame({'a':[0,0,1,1], 'b':[0,1,0,1]})
> df = df[(df.T != 0).any()]
> df
a b
1 0 1
2 1 0
3 1 1
When you don't care about removing the Html Dom-Element, use *ngIf.
Otherwise, use this:
<div [style.visibility]="(numberOfUnreadAlerts == 0) ? 'hidden' : 'visible' ">
COUNTER: {{numberOfUnreadAlerts}}
</div>
Also, note that there shouldn't be any space after =
:
set JAVA_HOME=C:\Program Files\Java\jdk1.6.0_27
MS Office Interop is slow and even Microsoft does not recommend Interop usage on server side and cannot be use to import large Excel files. For more details see why not to use OLE Automation from Microsoft point of view.
Instead, you can use any Excel library, like EasyXLS for example. This is a code sample that shows how to read the Excel file:
ExcelDocument workbook = new ExcelDocument();
DataSet ds = workbook.easy_ReadXLSActiveSheet_AsDataSet("excel.xls");
DataTable dataTable = ds.Tables[0];
If your Excel file has multiple sheets or for importing only ranges of cells (for better performances) take a look to more code samples on how to import Excel to DataTable in C# using EasyXLS.
Here is a new way to work with SQL views in EF Core: Query Types.
Use something like Notepad++ (or even Notepad), 'Save As', and enter the name .htaccess that way. I always found it weird, but it lets you do it from a program!
tl;dr the "standards" are a hodge-podge mess; it depends who you ask!
Overall, there appears to be no MIME type image/jpg
. Yet, in practice, nearly all software handles image files named "*.jpg
" just fine.
This particular topic is confusing because the varying association of file name extension associated to a MIME type depends which organization created the table of file name extensions to MIME types. In other words, file name extension .jpg
could be many different things.
For example, here are three "complete lists" and one RFC that with varying JPEG Image format file name extensions and the associated MIME types.
.jfif
, .jfif-tbnl
, .jpe
, .jpeg
, .jpg
? image/jpeg
.jfif
, .jpe
, .jpeg
, .jpg
? image/pjpeg
.jpeg
, .jpg
? image/jpeg
.jpeg
, .jpg
? image/x-citrix-jpeg
.pjpeg
? image/pjpeg
jpg
not mentionedjpeg
? see RFC 2045 (no mention), see RFC 2046 ? image/jpeg
13JPEG
? video/JPEG
jpeg2000
? video/jpeg2000
jpm
? image/jpm
(JPEG 2000)jpx
? image/jpx
(JPEG 2000)vnd.sealedmedia.softseal.jpg
? image/vnd.sealedmedia.softseal.jpg
These "complete lists" and RFC do not have MIME type image/jpg
! But for MIME type image/jpeg
some lists do have varying file name extensions (.jpeg
, .jpg
, …). Other lists do not mention image/jpeg
.
Also, there are different types of JPEG Image formats (e.g. Progressive JPEG Image format, JPEG 2000, etcetera) and "JPEG Extensions" that may or may not overlap in file name extension and declared MIME type.
Another confusing thing is RFC 3745 does not appear to match IANA Media Types yet the same RFC is supposed to inform the IANA Media Types document. For example, in RFC 3745 .jpf
is preferred file extension for image/jpx
but in IANA Media Types the name jpf
is not present (and that IANA document references RFC 3745!).
Another confusing thing is IANA Media Types lists "names" but does not list "file name extensions". This is on purpose, but confuses the endeavor of mapping file name extensions to MIME types.
Another confusing thing: is it "mime", or "MIME", or "MIME type", or "mime type", or "mime/type", or "media type"?
The most official seeming document by IANA is surprisingly inadequate. No MIME type is registered for file extension .jpg
yet there exists the odd vnd.sealedmedia.softseal.jpg
. File extension.JPEG
is only known as a video
type while file extension .jpeg
is an image type (when did lowercase and uppercase letters start mattering!?). At the same time, jpeg2000
is type video
yet RFC 3745 considers JPEG 2000 an image
type! The IANA list seems to cater to company-specific jpeg formats (e.g. vnd.sealedmedia.softseal.jpg
).
Because of the prior confusions, it is difficult to find an industry-accepted canonical document that maps file name extensions to MIME types, particularly for the JPEG Image File Format.
Related question "List of ALL MimeTypes on the Planet, mapped to File Extensions?".
Templates and other methods based on preliminary creation of the document in memory are likely to impose certain limits on resulting document size.
Meanwhile a very straightforward and reliable write-on-the-fly approach to creation of plain HTML exists, based on a SAX handler and default XSLT transformer, the latter having intrinsic capability of HTML output:
String encoding = "UTF-8";
FileOutputStream fos = new FileOutputStream("myfile.html");
OutputStreamWriter writer = new OutputStreamWriter(fos, encoding);
StreamResult streamResult = new StreamResult(writer);
SAXTransformerFactory saxFactory =
(SAXTransformerFactory) TransformerFactory.newInstance();
TransformerHandler tHandler = saxFactory.newTransformerHandler();
tHandler.setResult(streamResult);
Transformer transformer = tHandler.getTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "html");
transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
writer.write("<!DOCTYPE html>\n");
writer.flush();
tHandler.startDocument();
tHandler.startElement("", "", "html", new AttributesImpl());
tHandler.startElement("", "", "head", new AttributesImpl());
tHandler.startElement("", "", "title", new AttributesImpl());
tHandler.characters("Hello".toCharArray(), 0, 5);
tHandler.endElement("", "", "title");
tHandler.endElement("", "", "head");
tHandler.startElement("", "", "body", new AttributesImpl());
tHandler.startElement("", "", "p", new AttributesImpl());
tHandler.characters("5 > 3".toCharArray(), 0, 5); // note '>' character
tHandler.endElement("", "", "p");
tHandler.endElement("", "", "body");
tHandler.endElement("", "", "html");
tHandler.endDocument();
writer.close();
Note that XSLT transformer will release you from the burden of escaping special characters like >
, as it takes necessary care of it by itself.
And it is easy to wrap SAX methods like startElement()
and characters()
to something more convenient to one's taste...
Here's user123444555621's awesome HTML one adapted for terminals. Handy for debugging Node scripts:
function prettyJ(json) {
if (typeof json !== 'string') {
json = JSON.stringify(json, undefined, 2);
}
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
function (match) {
let cls = "\x1b[36m";
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = "\x1b[34m";
} else {
cls = "\x1b[32m";
}
} else if (/true|false/.test(match)) {
cls = "\x1b[35m";
} else if (/null/.test(match)) {
cls = "\x1b[31m";
}
return cls + match + "\x1b[0m";
}
);
}
Usage:
// thing = any json OR string of json
prettyJ(thing);
This is detailed with a reasonable amount of detail by Guido himself in his blog post Method Resolution Order (including two earlier attempts).
In your example, Third()
will call First.__init__
. Python looks for each attribute in the class's parents as they are listed left to right. In this case, we are looking for __init__
. So, if you define
class Third(First, Second):
...
Python will start by looking at First
, and, if First
doesn't have the attribute, then it will look at Second
.
This situation becomes more complex when inheritance starts crossing paths (for example if First
inherited from Second
). Read the link above for more details, but, in a nutshell, Python will try to maintain the order in which each class appears on the inheritance list, starting with the child class itself.
So, for instance, if you had:
class First(object):
def __init__(self):
print "first"
class Second(First):
def __init__(self):
print "second"
class Third(First):
def __init__(self):
print "third"
class Fourth(Second, Third):
def __init__(self):
super(Fourth, self).__init__()
print "that's it"
the MRO would be [Fourth, Second, Third, First].
By the way: if Python cannot find a coherent method resolution order, it'll raise an exception, instead of falling back to behavior which might surprise the user.
Edited to add an example of an ambiguous MRO:
class First(object):
def __init__(self):
print "first"
class Second(First):
def __init__(self):
print "second"
class Third(First, Second):
def __init__(self):
print "third"
Should Third
's MRO be [First, Second]
or [Second, First]
? There's no obvious expectation, and Python will raise an error:
TypeError: Error when calling the metaclass bases
Cannot create a consistent method resolution order (MRO) for bases Second, First
Edit: I see several people arguing that the examples above lack super()
calls, so let me explain: The point of the examples is to show how the MRO is constructed. They are not intended to print "first\nsecond\third" or whatever. You can – and should, of course, play around with the example, add super()
calls, see what happens, and gain a deeper understanding of Python's inheritance model. But my goal here is to keep it simple and show how the MRO is built. And it is built as I explained:
>>> Fourth.__mro__
(<class '__main__.Fourth'>,
<class '__main__.Second'>, <class '__main__.Third'>,
<class '__main__.First'>,
<type 'object'>)
The root of the problem is that you are unknowingly using the Frame
class from the ttk
package rather than from the tkinter
package. The one from ttk
does not support the background option.
This is the main reason why you shouldn't do global imports -- you can overwrite the definition of classes and commands.
I recommend doing imports like this:
import tkinter as tk
import ttk
Then you prefix the widgets with either tk
or ttk
:
f1 = tk.Frame(..., bg=..., fg=...)
f2 = ttk.Frame(..., style=...)
It then becomes instantly obvious which widget you are using, at the expense of just a tiny bit more typing. If you had done this, this error in your code would never have happened.
I had to run the following on AWS EC2 Linux instance (PHP Version 7.3):
sudo yum install php73-php-pdo php73-php-mysqlnd
You can use this way to fulfill this requirement. I use the below method to validate the Password and Confirm Password.
To use this method you have to import FormGroup
from @angular/forms
library.
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
FormBuilder Group:
this.myForm= this.formBuilder.group({
password : ['', Validators.compose([Validators.required])],
confirmPassword : ['', Validators.compose([Validators.required])],
},
{validator: this.checkPassword('password', 'confirmPassword') }
);
Method to Validate two fields:
checkPassword(controlName: string, matchingControlName: string) {
return (formGroup: FormGroup) => {
const control = formGroup.controls[controlName];
const matchingControl = formGroup.controls[matchingControlName];
if (matchingControl.errors && !matchingControl.errors.mustMatch) {
// return if another validator has already found an error on the matchingControl
return;
}
// set error on matchingControl if validation fails
if (control.value !== matchingControl.value) {
matchingControl.setErrors({ mustMatch: true });
this.isPasswordSame = (matchingControl.status == 'VALID') ? true : false;
} else {
matchingControl.setErrors(null);
this.isPasswordSame = (matchingControl.status == 'VALID') ? true : false;
}
}
}
HTML: Here I am use personalized isPasswordSame variable you can use the inbuilt hasError or any other.
<form [formGroup]="myForm">
<ion-item>
<ion-label position="floating">Password</ion-label>
<ion-input required type="text" formControlName="password" placeholder="Enter Password"></ion-input>
</ion-item>
<ion-label *ngIf="myForm.controls.password.valid">
<p class="error">Please enter password!!</p>
</ion-label>
<ion-item>
<ion-label position="floating">Confirm Password</ion-label>
<ion-input required type="text" formControlName="confirmPassword" placeholder="Enter Confirm Password"></ion-input>
</ion-item>
<ion-label *ngIf="isPasswordSame">
<p class="error">Password and Confrim Password must be same!!</p>
</ion-label>
</form>
Encountered this too also. Here's what I did.
On my LoginActivity, inside my AsyncTask, I have the following:
CookieStoreHelper.cookieStore = new BasicCookieStore();
BasicHttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, CookieStoreHelper.cookieStore);
HttpResponse postResponse = client.execute(httpPost,localContext);
CookieStoreHelper.sessionCookie = CookieStoreHelper.cookieStore.getCookies();
//WHERE CookieStoreHelper.sessionCookie is another class containing the variable sessionCookie defined as List cookies; and cookieStore define as BasicCookieStore cookieStore;
Then on my Fragment, where my WebView is located i have the following:
//DECLARE LIST OF COOKIE
List<Cookie> sessionCookie;
inside my method or just before you are setting the WebViewClient()
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
sessionCookie = CookieStoreHelper.cookieStore.getCookies();
CookieSyncManager.createInstance(webView.getContext());
CookieSyncManager.getInstance().startSync();
CookieManager cookieManager = CookieManager.getInstance();
CookieManager.getInstance().setAcceptCookie(true);
if (sessionCookie != null) {
for(Cookie c: sessionCookie){
cookieManager.setCookie(CookieStoreHelper.DOMAIN, c.getName() + "=" + c.getValue());
}
CookieSyncManager.getInstance().sync();
}
webView.setWebViewClient(new WebViewClient() {
//AND SO ON, YOUR CODE
}
Quick Tip: Have firebug installed on firefox or use developer console on chrome and test first your webpage, capture the Cookie and check the domain so you can store it somewhere and be sure that you are correctly setting the right domain.
Edit: edited CookieStoreHelper.cookies to CookieStoreHelper.sessionCookie
When you $ pip install jupyter
several dependencies are installed. The best way to uninstall it completely is by running:
$ pip install pip-autoremove
$ pip-autoremove jupyter -y
Kindly refer to this related question.
pip-autoremove
removes a package and its unused dependencies. Here are the docs.
On your server-side code, replace the new lines (\n
) with <br/>
.
If you're using PHP, you can use nl2br()
You can drop in and out of the PHP context using the <?php
and ?>
tags. For example...
<?php
$array = array(1, 2, 3, 4);
?>
<table>
<thead><tr><th>Number</th></tr></thead>
<tbody>
<?php foreach ($array as $num) : ?>
<tr><td><?= htmlspecialchars($num) ?></td></tr>
<?php endforeach ?>
</tbody>
</table>
The T
doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.
The Z
stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).
Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime()
method. You could have used Q
or M
or Monty Python
and the method would have returned them unchanged as well; the method only looks for patterns starting with %
to replace those with information from the datetime
object.
Windows 7 has the arp command within it. arp -a should show you the static and dynamic type interfaces connected to your system.
Try:
output=$(ps -ef | awk '/siebsvc –s siebsrvr/ && !/awk/ { a++ } END { print a }'); echo $output
Wrapping your command in $( )
tells the shell to run that command, instead of attempting to set the command itself to the variable named "output". (Note that you could also use backticks `command`.)
I can highly recommend http://tldp.org/LDP/abs/html/commandsub.html to learn more about command substitution.
Also, as 1_CR correctly points out in a comment, the extra space between the equals sign and the assignment is causing it to fail. Here is a simple example on my machine of the behavior you are experiencing:
jed@MBP:~$ foo=$(ps -ef |head -1);echo $foo
UID PID PPID C STIME TTY TIME CMD
jed@MBP:~$ foo= $(ps -ef |head -1);echo $foo
-bash: UID: command not found
UID PID PPID C STIME TTY TIME CMD
In most of the cases, conversion functions are called frequently. We can optimize it by adding memoization. So,it does not calculate every-time the function is called.
Let's declare a HashMap which will store the calculated values.
private static Map<Float, Float> pxCache = new HashMap<>();
A function which calculates pixel values :
public static float calculateDpToPixel(float dp, Context context) {
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
float px = dp * (metrics.densityDpi / 160f);
return px;
}
A memoization function which returns the value from HashMap and maintains the record of previous values.
Memoization can be implemented in different ways in Java. For Java 7 :
public static float convertDpToPixel(float dp, final Context context) {
Float f = pxCache.get(dp);
if (f == null) {
synchronized (pxCache) {
f = calculateDpToPixel(dp, context);
pxCache.put(dp, f);
}
}
return f;
}
Java 8 supports Lambda function :
public static float convertDpToPixel(float dp, final Context context) {
pxCache.computeIfAbsent(dp, y ->calculateDpToPixel(dp,context));
}
Thanks.
This is the way to iterate on this array:
foreach($hotels as $row) {
foreach($row['rooms'] as $k) {
echo $k['boards']['board_id'];
echo $k['boards']['price'];
}
}
You want to iterate on the hotels and the rooms (the ones with numeric indexes), because those seem to be the "collections" in this case. The other arrays only hold and group properties.
The documentation says:
However, JUnit Jupiter’s
org.junit.jupiter.Assertions
class does not provide anassertThat()
method like the one found in JUnit 4’sorg.junit.Assert
class which accepts a HamcrestMatcher
. Instead, developers are encouraged to use the built-in support for matchers provided by third-party assertion libraries.
Example for Hamcrest:
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.jupiter.api.Test;
class HamcrestAssertionDemo {
@Test
void assertWithHamcrestMatcher() {
SubClass subClass = new SubClass();
assertThat(subClass, instanceOf(BaseClass.class));
}
}
Example for AssertJ:
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
class AssertJDemo {
@Test
void assertWithAssertJ() {
SubClass subClass = new SubClass();
assertThat(subClass).isInstanceOf(BaseClass.class);
}
}
Note that this assumes you want to test behaviors similar to instanceof
(which accepts subclasses). If you want exact equal type, I don’t see a better way than asserting the two class to be equal like you mentioned in the question.
bash doesn't know boolean variables, nor does test
(which is what gets called when you use [
).
A solution would be:
if $myVar ; then ... ; fi
because true
and false
are commands that return 0
or 1
respectively which is what if
expects.
Note that the values are "swapped". The command after if
must return 0
on success while 0
means "false" in most programming languages.
SECURITY WARNING: This works because BASH expands the variable, then tries to execute the result as a command! Make sure the variable can't contain malicious code like rm -rf /
This is not as easy as it seems, some core library functions don't work when only str is overwritten (checked with Python 2.7), see this thread for examples How to make a class JSON serializable Also, try this
import json
class A(unicode):
def __str__(self):
return 'a'
def __unicode__(self):
return u'a'
def __repr__(self):
return 'a'
a = A()
json.dumps(a)
produces
'""'
and not
'"a"'
as would be expected.
EDIT: answering mchicago's comment:
unicode does not have any attributes -- it is an immutable string, the value of which is hidden and not available from high-level Python code. The json
module uses re
for generating the string representation which seems to have access to this internal attribute. Here's a simple example to justify this:
b = A('b')
print b
produces
'a'
while
json.dumps({'b': b})
produces
{"b": "b"}
so you see that the internal representation is used by some native libraries, probably for performance reasons.
See also this for more details: http://www.laurentluce.com/posts/python-string-objects-implementation/
fun hasPermission(permission: String): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return true // must be granted after installed.
return mAppSet.appContext.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
}
You need to include a declaration of the printf()
function.
#include <stdio.h>
No, that's not really possible, as
The goal of the MD5 and its family of hashing functions is
Think that you can get the MD5 of any string, even very long. And the MD5 is only 16 bytes long (32 if you write it in hexa to store or distribute it more easily). If you could reverse them, you'd have a magical compacting scheme.
This being said, as there aren't so many short strings (passwords...) used in the world, you can test them from a dictionary (that's called "brute force attack") or even google for your MD5. If the word is common and wasn't salted, you have a reasonable chance to succeed...
You may have moved on by now, but... as far as I know there's no way to delete a history entry (or state).
One option I've been looking into is to handle the history yourself in JavaScript and use the window.history
object as a carrier of sorts.
Basically, when the page first loads you create your custom history object (we'll go with an array here, but use whatever makes sense for your situation), then do your initial pushState
. I would pass your custom history object as the state object, as it may come in handy if you also need to handle users navigating away from your app and coming back later.
var myHistory = [];
function pageLoad() {
window.history.pushState(myHistory, "<name>", "<url>");
//Load page data.
}
Now when you navigate, you add to your own history object (or don't - the history is now in your hands!) and use replaceState
to keep the browser out of the loop.
function nav_to_details() {
myHistory.push("page_im_on_now");
window.history.replaceState(myHistory, "<name>", "<url>");
//Load page data.
}
When the user navigates backwards, they'll be hitting your "base" state (your state object will be null) and you can handle the navigation according to your custom history object. Afterward, you do another pushState.
function on_popState() {
// Note that some browsers fire popState on initial load,
// so you should check your state object and handle things accordingly.
// (I did not do that in these examples!)
if (myHistory.length > 0) {
var pg = myHistory.pop();
window.history.pushState(myHistory, "<name>", "<url>");
//Load page data for "pg".
} else {
//No "history" - let them exit or keep them in the app.
}
}
The user will never be able to navigate forward using their browser buttons because they are always on the newest page.
From the browser's perspective, every time they go "back", they've immediately pushed forward again.
From the user's perspective, they're able to navigate backwards through the pages but not forward (basically simulating the smartphone "page stack" model).
From the developer's perspective, you now have a high level of control over how the user navigates through your application, while still allowing them to use the familiar navigation buttons on their browser. You can add/remove items from anywhere in the history chain as you please. If you use objects in your history array, you can track extra information about the pages as well (like field contents and whatnot).
If you need to handle user-initiated navigation (like the user changing the URL in a hash-based navigation scheme), then you might use a slightly different approach like...
var myHistory = [];
function pageLoad() {
// When the user first hits your page...
// Check the state to see what's going on.
if (window.history.state === null) {
// If the state is null, this is a NEW navigation,
// the user has navigated to your page directly (not using back/forward).
// First we establish a "back" page to catch backward navigation.
window.history.replaceState(
{ isBackPage: true },
"<back>",
"<back>"
);
// Then push an "app" page on top of that - this is where the user will sit.
// (As browsers vary, it might be safer to put this in a short setTimeout).
window.history.pushState(
{ isBackPage: false },
"<name>",
"<url>"
);
// We also need to start our history tracking.
myHistory.push("<whatever>");
return;
}
// If the state is NOT null, then the user is returning to our app via history navigation.
// (Load up the page based on the last entry of myHistory here)
if (window.history.state.isBackPage) {
// If the user came into our app via the back page,
// you can either push them forward one more step or just use pushState as above.
window.history.go(1);
// or window.history.pushState({ isBackPage: false }, "<name>", "<url>");
}
setTimeout(function() {
// Add our popstate event listener - doing it here should remove
// the issue of dealing with the browser firing it on initial page load.
window.addEventListener("popstate", on_popstate);
}, 100);
}
function on_popstate(e) {
if (e.state === null) {
// If there's no state at all, then the user must have navigated to a new hash.
// <Look at what they've done, maybe by reading the hash from the URL>
// <Change/load the new page and push it onto the myHistory stack>
// <Alternatively, ignore their navigation attempt by NOT loading anything new or adding to myHistory>
// Undo what they've done (as far as navigation) by kicking them backwards to the "app" page
window.history.go(-1);
// Optionally, you can throw another replaceState in here, e.g. if you want to change the visible URL.
// This would also prevent them from using the "forward" button to return to the new hash.
window.history.replaceState(
{ isBackPage: false },
"<new name>",
"<new url>"
);
} else {
if (e.state.isBackPage) {
// If there is state and it's the 'back' page...
if (myHistory.length > 0) {
// Pull/load the page from our custom history...
var pg = myHistory.pop();
// <load/render/whatever>
// And push them to our "app" page again
window.history.pushState(
{ isBackPage: false },
"<name>",
"<url>"
);
} else {
// No more history - let them exit or keep them in the app.
}
}
// Implied 'else' here - if there is state and it's NOT the 'back' page
// then we can ignore it since we're already on the page we want.
// (This is the case when we push the user back with window.history.go(-1) above)
}
}
In Python 3.6, there is another solution for Python 2 and 3:set()
now should keep the order, but
>>> x = [1, 2, 20, 6, 210]
>>> sorted(set(x), key=x.index)
[1, 2, 20, 6, 210]
It sounds like you need an OR instead:
<button type="submit" [disabled]="!validate || !SAForm.valid">Add</button>
This will disable the button if not validate or if not SAForm.valid.
Java 8 way. Works for multiple parameters:
Stream.of(first, second, third).max(Integer::compareTo).get()
Have you added the google maven endpoint?
Important: The support libraries are now available through Google's Maven repository. You do not need to download the support repository from the SDK Manager. For more information, see Support Library Setup.
Add the endpoint to your build.gradle file:
allprojects {
repositories {
jcenter()
maven {
url 'https://maven.google.com'
}
}
}
Which can be replaced by the shortcut google()
since Android Gradle v3:
allprojects {
repositories {
jcenter()
google()
}
}
If you already have any maven url inside repositories
, you can add the reference after them, i.e.:
allprojects {
repositories {
jcenter()
maven {
url 'https://jitpack.io'
}
maven {
url 'https://maven.google.com'
}
}
}
I resolved this by making sure my project shared the same .Net Framework version as the projects/libraries it depended on.
It turned out the libraries (projects within the solution) used .Net 4.6.1 and my project was using 4.5.2
In my case ASP.NET not registered on server. try to execute this in command prompt:
Windows 32bit
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir
Windows 64bit
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir
Google recommends the usage of Android Volley for HTTP/HTTPS connections, since that HttpClient
is deprecated. So, you know the right choice :).
And also, NEVER NUKE SSL Certificates (NEVER!!!).
To nuke SSL Certificates, is totally against the purpose of SSL, which is promoting security. There's no sense of using SSL, if you're planning to bomb all SSL certificates that comes. A better solution would be creating a custom TrustManager
on your App + using Android Volley for HTTP/HTTPS connections.
Here's a Gist which I created, with a basic LoginApp, performing HTTPS connections, using a Self-Signed Certificate on the server-side, accepted on the App.
Here's also another Gist that may help, for creating Self-Signed SSL Certificates for setting up on your Server and also using the certificate on your App. Very important: you must copy the .crt file which was generated by the script above, to the "raw" directory from your Android project.
It won't throw exception, you'll get an empty list.
Weak Entity Type: An entity whose instances cannot exits without being linked with instances of some other entity is called weak entity type. It cannot exist independently. For example: Our PC is depend on us it will not open or close with its own.
Strong Entity Type: An entity whose linked to the instances of any other entity type is called strong entity type. It can exit independently. For example: A person can do every thing can go everywhere and use ever thing
If you need the full url (for instance to send by email) consider using one of the following built-in methods:
With this you create the route to use to build the url:
Url.RouteUrl("OpinionByCompany", new RouteValueDictionary(new{cid=newop.CompanyID,oid=newop.ID}), HttpContext.Request.Url.Scheme, HttpContext.Request.Url.Authority)
Here the url is built after the route engine determine the correct one:
Url.Action("Detail","Opinion",new RouteValueDictionary(new{cid=newop.CompanyID,oid=newop.ID}),HttpContext.Request.Url.Scheme, HttpContext.Request.Url.Authority)
In both methods, the last 2 parameters specifies the protocol and hostname.
Regards.
Here is one way to do it:
List<String> duplicates = lst.GroupBy(x => x)
.Where(g => g.Count() > 1)
.Select(g => g.Key)
.ToList();
The GroupBy
groups the elements that are the same together, and the Where
filters out those that only appear once, leaving you with only the duplicates.
I got this same error when I was trying to import an Eclipse NDK project into Android Studio. It turns out, for NDK support in Android Studio, you need to use a new gradle and android plugin (and gradle version 2.5+ for that matter). This plugin, requires changes in the module's build.gradle file. Specifically the "android{...}" object should be inside "model{...}" object like this:
apply plugin: 'com.android.model.application'
model {
android {
....
}
}
So if you have updated your gradle configuration to use the new gradle plugin, and the new android plugin, but didn't change the module's build.gradle syntax, you could get "Gradle DSL method not found: 'android()'" error.
I prepared a patch file here that has some further explanations in the comments: https://gist.github.com/shumoapp/91d815de6e01f5921d1f These are the changes I had to do after importing the native-audio ndk project into Android Studio.
A good answer for me was to install libtool:
sudo apt-get install libtool
Use sp_helptext
before the view_name
. Example:
sp_helptext Example_1
Hence you will get the query:
CREATE VIEW dbo.Example_1
AS
SELECT a, b, c
FROM dbo.table_name JOIN blah blah blah
WHERE blah blah blah
sp_helptext will give stored procedures.
// Create given String and make with size 30
String str = "Hello How Are You";
// Creating StringBuffer Object for right padding
StringBuffer stringBufferRightPad = new StringBuffer(str);
while (stringBufferRightPad.length() < 30) {
stringBufferRightPad.insert(stringBufferRightPad.length(), "*");
}
System.out.println("after Left padding : " + stringBufferRightPad);
System.out.println("after Left padding : " + stringBufferRightPad.toString());
// Creating StringBuffer Object for right padding
StringBuffer stringBufferLeftPad = new StringBuffer(str);
while (stringBufferLeftPad.length() < 30) {
stringBufferLeftPad.insert(0, "*");
}
System.out.println("after Left padding : " + stringBufferLeftPad);
System.out.println("after Left padding : " + stringBufferLeftPad.toString());
If you are willing to use your own custom output format, you would be able to get the desired behaviour with RDD as well.
Have a look at the following classes: FileOutputFormat, FileOutputCommitter
In file output format you have a method named checkOutputSpecs, which is checking whether the output directory exists. In FileOutputCommitter you have the commitJob which is usually transferring data from the temporary directory to its final place.
I wasn't able to verify it yet (would do it, as soon as I have few free minutes) but theoretically: If I extend FileOutputFormat and override checkOutputSpecs to a method that doesn't throw exception on directory already exists, and adjust the commitJob method of my custom output committer to perform which ever logic that I want (e.g. Override some of the files, append others) than I may be able to achieve the desired behaviour with RDDs as well.
The output format is passed to: saveAsNewAPIHadoopFile (which is the method saveAsTextFile called as well to actually save the files). And the Output committer is configured at the application level.