Placing your list view in a Flexible widget may also help,
Flexible( fit: FlexFit.tight, child: _buildYourListWidget(..),)
I think it is better to update your "mysql-connector" lib package, so database can be still more safe.
I am using mysql of version 8.0.12. When I updated the mysql-connector-java to version 8.0.11, the problem was gone.
Error Code:
error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.29/version: open //./pipe/docker_engine: The system cannot find the file specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect . This error may also indicate that the docker daemon is not running.
Solutions:
1) For Windows 7 Command Window(cmd.exe), open cmd.exe with run as administrator and execute following command:
docker-machine env --shell cmd default
You will receive following output:
SET DOCKER_TLS_VERIFY=1
SET DOCKER_HOST=tcp://192.168.99.100:2376
SET DOCKER_CERT_PATH=C:\Users\USER_NAME\.docker\machine\machines\default
SET DOCKER_MACHINE_NAME=default
SET COMPOSE_CONVERT_WINDOWS_PATHS=true
REM Run this command to configure your shell:
REM @FOR /f "tokens=*" %i IN ('docker-machine env --shell cmd default') DO @%i
Copy the command below and execute on cmd:
@FOR /f "tokens=*" %i IN ('docker-machine env --shell cmd default') DO @%i
And then execute following command to control:
docker version
2) For Windows 7 Powershell, open powershell.exe with run as administrator and execute following command:
docker-machine env --shell=powershell | Invoke-Expression
And then execute following command to control:
docker version
3) If you reopen cmd or powershell, you should repeat the related steps again.
For me, it worked very simply. At first, I made an empty data.frame
, then in each iteration I added one column to it. Here is my code:
df <- data.frame(modelForOneIteration)
for(i in 1:10){
model <- # some processing
df[,i] = model
}
Or, as inspired by @MatheusAraujo:
df[nrow(df) + 1,] = list("v1","v2")
This would allow for mixed data types.
+ theme(plot.title = element_text(size=22))
Here is the full set of things you can change in element_text
:
element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
color = NULL)
For completion's sake, here's the snippet that creates the transport client using proper static method provided by InetSocketTransportAddress
:
Client esClient = TransportClient.builder()
.settings(settings)
.build()
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("143.79.236.xxx"), 9300));
Here's something that will do what you'd want when using a string array for the ChildPath.
$path = "C:"
@( "Program Files", "Microsoft Office" ) | %{ $path = Join-Path $path $_ }
Write-Host $path
Which outputs
C:\Program Files\Microsoft Office
The only caveat I found is that the initial value for $path must have a value (cannot be null or empty).
Another info: If you want use a Route Constraint, imagine that you want force that parameter has int datatype, then you need use this syntax:
[Route("v1/location/**{deviceOrAppid:int?}**", Name = "AddNewLocation")]
The ? character is put always before the last } character
For more information see: Optional URI Parameters and Default Values
Content-Type:application/json
When you define any POST request method input parameter that should be annotated as [FromBody]
, e.g.:
[HttpPost]
public HttpResponseMessage Post([FromBody]ActivityResult ar)
{
return new HttpResponseMessage(HttpStatusCode.OK);
}
Any JSON input data must be raw data.
First: As it currently stands, the $User
variable does not have a .Users
property. In your code, $User
simply represents one line (the "current" line in the foreach loop) from the text file.
$getmembership = Get-ADUser $User -Properties MemberOf | Select -ExpandProperty memberof
Secondly, I do not believe you can query an entire forest with one command. You will have to break it down into smaller chunks:
Get-ADUser
for each domain (you may have to specify alternate credentials via the -Credential
parameterThirdly, to get a list of groups that a user is a member of:
$User = Get-ADUser -Identity trevor -Properties *;
$GroupMembership = ($user.memberof | % { (Get-ADGroup $_).Name; }) -join ';';
# Result:
Orchestrator Users Group;ConfigMgr Administrators;Service Manager Admins;Domain Admins;Schema Admins
Fourthly: To get the final, desired string format, simply add the $User.Name
, a semicolon, and the $GroupMembership
string together:
$User.SamAccountName + ';' + $GroupMembership;
A more generic solution for might be the following.
extendDf <- function (df, n) {
withFactors <- sum(sapply (df, function(X) (is.factor(X)) )) > 0
nr <- nrow (df)
colNames <- names(df)
for (c in 1:length(colNames)) {
if (is.factor(df[,c])) {
col <- vector (mode='character', length = nr+n)
col[1:nr] <- as.character(df[,c])
col[(nr+1):(n+nr)]<- rep(col[1], n) # to avoid extra levels
col <- as.factor(col)
} else {
col <- vector (mode=mode(df[1,c]), length = nr+n)
class(col) <- class (df[1,c])
col[1:nr] <- df[,c]
}
if (c==1) {
newDf <- data.frame (col ,stringsAsFactors=withFactors)
} else {
newDf[,c] <- col
}
}
names(newDf) <- colNames
newDf
}
The function extendDf() extends a data frame with n rows.
As an example:
aDf <- data.frame (l=TRUE, i=1L, n=1, c='a', t=Sys.time(), stringsAsFactors = TRUE)
extendDf (aDf, 2)
# l i n c t
# 1 TRUE 1 1 a 2016-07-06 17:12:30
# 2 FALSE 0 0 a 1970-01-01 01:00:00
# 3 FALSE 0 0 a 1970-01-01 01:00:00
system.time (eDf <- extendDf (aDf, 100000))
# user system elapsed
# 0.009 0.002 0.010
system.time (eDf <- extendDf (eDf, 100000))
# user system elapsed
# 0.068 0.002 0.070
Try this:
> data[match(as.character(data$Code), selected, nomatch = FALSE), ]
Code Value
1 A 1
2 B 2
1.1 A 1
1.2 A 1
Get-ChildItem $originalPath\* -Include @("*.gif", "*.jpg", "*.xls*", "*.doc*", "*.pdf*", "*.wav*", "*.ppt")
Make sure your Java version matches the project's Java version requirement. This could be an another cause for such kinds of issues.
I see some people prefer to generate sources into the target via jaxws-maven-plugin AND make this classes visible in source via build-helper-maven-plugin. As an argument for this structure
the version management system (svn/etc.) would always notice changed sources
With git it is not true. So you can just configure jaxws-maven-plugin
to put them into your sources, but not under the target folder. Next time you build your project, git will not mark these generated files as changed. Here is the simple solution with only one plugin:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<version>2.6</version>
<dependencies>
<dependency>
<groupId>org.jvnet.jaxb2_commons</groupId>
<artifactId>jaxb2-fluent-api</artifactId>
<version>3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-tools</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
<executions>
<execution>
<goals>
<goal>wsimport</goal>
</goals>
<configuration>
<packageName>som.path.generated</packageName>
<xjcArgs>
<xjcArg>-Xfluent-api</xjcArg>
</xjcArgs>
<verbose>true</verbose>
<keep>true</keep> <!--used by default-->
<sourceDestDir>${project.build.sourceDirectory}</sourceDestDir>
<wsdlDirectory>src/main/resources/META-INF/wsdl</wsdlDirectory>
<wsdlLocation>META-INF/wsdl/soap.wsdl</wsdlLocation>
</configuration>
</execution>
</executions>
</plugin>
Additionally (just to note) in this example SOAP classes are generated with Fluent API, so you can create them like:
A a = new A()
.withField1(value1)
.withField2(value2);
SIMPLE..
First check with the closing tag of project. It should be placed after all the dependency tags are closed.This way I solved my error. --Sush happy coding :)
You can also specify the range with the coord_cartesian command to set the y-axis range that you want, an like in the previous post use scales = free_x
p <- ggplot(plot, aes(x = pred, y = value)) +
geom_point(size = 2.5) +
theme_bw()+
coord_cartesian(ylim = c(-20, 80))
p <- p + facet_wrap(~variable, scales = "free_x")
p
The error comes when you try to call sum(x)
and x
is a factor.
What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)
simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:
family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))
For a detailed explanation of why the intermediate as.character
step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?
Usually, define maven-compiler-plugin is sufficient enough. add the following to your compiler plugin definition.
<plugin>
<inherited>true</inherited>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
WebApplicationInitializer is an interface you can implement in one of your classes. At startup Spring is scanning for this classes, as long as you are using servlet spec 3 and have a metadata-complete="false" attribute in your web.xml. But that doesn't seem to be the problem. The only error I can figure out is the missing slf4j-log4j12.jar.
I've found the following "cheat" to work very neatly and error-free
> dimnames <- list(time=c(0, 0.5, 1), name=c("C_0", "C_1"))
> mat <- matrix(data, ncol=2, nrow=3, dimnames=dimnames)
> head(mat, 2) #this returns the number of rows indicated in a data frame format
> df <- data.frame(head(mat, 2)) #"data.frame" might not be necessary
Et voila!
For me the answer was to force a Maven rebuild. In Eclipse:
Did you update the project (right-click on the project, "Maven" > "Update project...")? Otherwise, you need to check if pom.xml
contains the necessary slf4j dependencies, e.g.:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
It would help to have sample information about your output. Recursively using rbind
on bigger and bigger things is not recommended. My first guess at something that would help you:
z <- list(1:3,4:6,7:9)
do.call(rbind,z)
See a related question for more efficiency, if needed.
Vectors and matrices can only be of a single type and cbind
and rbind
on vectors will give matrices. In these cases, the numeric values will be promoted to character values since that type will hold all the values.
(Note that in your rbind
example, the promotion happens within the c
call:
> c(10, "[]", "[[1,2]]")
[1] "10" "[]" "[[1,2]]"
If you want a rectangular structure where the columns can be different types, you want a data.frame
. Any of the following should get you what you want:
> x = data.frame(v1=c(10, 20), v2=c("[]", "[]"), v3=c("[[1,2]]","[[1,3]]"))
> x
v1 v2 v3
1 10 [] [[1,2]]
2 20 [] [[1,3]]
> str(x)
'data.frame': 2 obs. of 3 variables:
$ v1: num 10 20
$ v2: Factor w/ 1 level "[]": 1 1
$ v3: Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2
or (using specifically the data.frame
version of cbind
)
> x = cbind.data.frame(c(10, 20), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
c(10, 20) c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1 10 [] [[1,2]]
2 20 [] [[1,3]]
> str(x)
'data.frame': 2 obs. of 3 variables:
$ c(10, 20) : num 10 20
$ c("[]", "[]") : Factor w/ 1 level "[]": 1 1
$ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2
or (using cbind
, but making the first a data.frame
so that it combines as data.frames do):
> x = cbind(data.frame(c(10, 20)), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
c.10..20. c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1 10 [] [[1,2]]
2 20 [] [[1,3]]
> str(x)
'data.frame': 2 obs. of 3 variables:
$ c.10..20. : num 10 20
$ c("[]", "[]") : Factor w/ 1 level "[]": 1 1
$ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2
I solve this problem with this code in NugetPackageConsole.and it works.The problem was in the version. i thikn it will help others.
I am assuming you are using Eclipse as your developing environment.
Eclipse Juno, Indigo and Kepler when using the bundled maven version(m2e), are not suppressing the message SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". This behaviour is present from the m2e version 1.1.0.20120530-0009 and onwards.
Although, this is indicated as an error your logs will be saved normally. The highlighted error will still be present until there is a fix of this bug. More about this in the m2e support site.
The current available solution is to use an external maven version rather than the bundled version of Eclipse. You can find about this solution and more details regarding this bug in the question below which i believe describes the same problem you are facing.
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error
Use code as follows:
mylist <- lapply(pressure, function(i)read.xlsx(i,colNames = FALSE))#
mydata <- do.call('rbind',mylist)#
You can use the function ginv() (Moore-Penrose generalized inverse) in the MASS package
Had been over looking the issue having surfaced it. Believe this will be a good read for others who come down here with the same issue:
for example you want to add rows of variable 2 to variable 1 of a data named "edges" just do it like this
allEdges <- data.frame(c(edges$V1,edges$V2))
I had a list of dataframes with no common id column.
I had missing data on many dfs. There were Null values.
The dataframes were produced using table function.
The Reduce, Merging, rbind, rbind.fill, and their like could not help me to my aim.
My aim was to produce an understandable merged dataframe, irrelevant of the missing data and common id column.
Therefore, I made the following function. Maybe this function can help someone.
##########################################################
#### Dependencies #####
##########################################################
# Depends on Base R only
##########################################################
#### Example DF #####
##########################################################
# Example df
ex_df <- cbind(c( seq(1, 10, 1), rep("NA", 0), seq(1,10, 1) ),
c( seq(1, 7, 1), rep("NA", 3), seq(1, 12, 1) ),
c( seq(1, 3, 1), rep("NA", 7), seq(1, 5, 1), rep("NA", 5) ))
# Making colnames and rownames
colnames(ex_df) <- 1:dim(ex_df)[2]
rownames(ex_df) <- 1:dim(ex_df)[1]
# Making an unequal list of dfs,
# without a common id column
list_of_df <- apply(ex_df=="NA", 2, ( table) )
it is following the function
##########################################################
#### The function #####
##########################################################
# The function to rbind it
rbind_null_df_lists <- function ( list_of_dfs ) {
length_df <- do.call(rbind, (lapply( list_of_dfs, function(x) length(x))))
max_no <- max(length_df[,1])
max_df <- length_df[max(length_df),]
name_df <- names(length_df[length_df== max_no,][1])
names_list <- names(list_of_dfs[ name_df][[1]])
df_dfs <- list()
for (i in 1:max_no ) {
df_dfs[[i]] <- do.call(rbind, lapply(1:length(list_of_dfs), function(x) list_of_dfs[[x]][i]))
}
df_cbind <- do.call( cbind, df_dfs )
rownames( df_cbind ) <- rownames (length_df)
colnames( df_cbind ) <- names_list
df_cbind
}
Running the example
##########################################################
#### Running the example #####
##########################################################
rbind_null_df_lists ( list_of_df )
I solve it adding this library: slf4j-simple-1.7.25.jar You can download this in official web https://www.slf4j.org/download.html
While only a few lines are required to plot multiple/overlapping histograms in ggplot2, the results are't always satisfactory. There needs to be proper use of borders and coloring to ensure the eye can differentiate between histograms.
The following functions balance border colors, opacities, and superimposed density plots to enable the viewer to differentiate among distributions.
Single histogram:
plot_histogram <- function(df, feature) {
plt <- ggplot(df, aes(x=eval(parse(text=feature)))) +
geom_histogram(aes(y = ..density..), alpha=0.7, fill="#33AADE", color="black") +
geom_density(alpha=0.3, fill="red") +
geom_vline(aes(xintercept=mean(eval(parse(text=feature)))), color="black", linetype="dashed", size=1) +
labs(x=feature, y = "Density")
print(plt)
}
Multiple histogram:
plot_multi_histogram <- function(df, feature, label_column) {
plt <- ggplot(df, aes(x=eval(parse(text=feature)), fill=eval(parse(text=label_column)))) +
geom_histogram(alpha=0.7, position="identity", aes(y = ..density..), color="black") +
geom_density(alpha=0.7) +
geom_vline(aes(xintercept=mean(eval(parse(text=feature)))), color="black", linetype="dashed", size=1) +
labs(x=feature, y = "Density")
plt + guides(fill=guide_legend(title=label_column))
}
Usage:
Simply pass your data frame into the above functions along with desired arguments:
plot_histogram(iris, 'Sepal.Width')
plot_multi_histogram(iris, 'Sepal.Width', 'Species')
The extra parameter in plot_multi_histogram is the name of the column containing the category labels.
We can see this more dramatically by creating a dataframe with many different distribution means:
a <-data.frame(n=rnorm(1000, mean = 1), category=rep('A', 1000))
b <-data.frame(n=rnorm(1000, mean = 2), category=rep('B', 1000))
c <-data.frame(n=rnorm(1000, mean = 3), category=rep('C', 1000))
d <-data.frame(n=rnorm(1000, mean = 4), category=rep('D', 1000))
e <-data.frame(n=rnorm(1000, mean = 5), category=rep('E', 1000))
f <-data.frame(n=rnorm(1000, mean = 6), category=rep('F', 1000))
many_distros <- do.call('rbind', list(a,b,c,d,e,f))
Passing data frame in as before (and widening chart using options):
options(repr.plot.width = 20, repr.plot.height = 8)
plot_multi_histogram(many_distros, 'n', 'category')
your break statement should break out of the for (in in 1:n)
.
Personally I am always wary with break statements and double check it by printing to the console to double check that I am in fact breaking out of the right loop. So before you test add the following statement, which will let you know if you break before it reaches the end. However, I have no idea how you are handling the variable n
so I don't know if it would be helpful to you. Make a n
some test value where you know before hand if it is supposed to break out or not before reaching n
.
for (in in 1:n)
{
if (in == n) #add this statement
{
"sorry but the loop did not break"
}
id_novo <- new_table_df$ID[in]
if(id_velho==id_novo)
{
break
}
else if(in == n)
{
sold_df <- rbind(sold_df,old_table_df[out,])
}
}
You simply use the apply()
function:
R> M <- matrix(1:6, nrow=3, byrow=TRUE)
R> M
[,1] [,2]
[1,] 1 2
[2,] 3 4
[3,] 5 6
R> apply(M, 1, function(x) 2*x[1]+x[2])
[1] 4 10 16
R>
This takes a matrix and applies a (silly) function to each row. You pass extra arguments to the function as fourth, fifth, ... arguments to apply()
.
You have included the dependency for sflj's api, but not the dependency for the implementation of the api, that is a separate jar, you could try slf4j-simple-1.6.1.jar.
I've found this way to create dataframe by raw without matrix.
With automatic column name
df<-data.frame(
t(data.frame(c(1,"a",100),c(2,"b",200),c(3,"c",300)))
,row.names = NULL,stringsAsFactors = FALSE
)
With column name
df<-setNames(
data.frame(
t(data.frame(c(1,"a",100),c(2,"b",200),c(3,"c",300)))
,row.names = NULL,stringsAsFactors = FALSE
),
c("col1","col2","col3")
)
Quick note: if you're also using coord_flip()
to flip the x and the y axis, you won't be able to set range limits using coord_cartesian()
because those two functions are exclusive (see here).
Fortunately, this is an easy fix; set your limits within coord_flip()
like so:
p + coord_flip(ylim = c(3,5), xlim = c(100, 400))
This just alters the visible range (i.e. doesn't remove data points).
If the columns in df1 is a subset of those in df2 (by column names):
df3 <- rbind(df1, df2[, names(df1)])
You need to convert your private key to PKCS8 format using following command:
openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file -nocrypt > pkcs8_key
After this your java program can read it.
An updated visual for those wanting to compare some of the recent answers (I wanted to compare the purrr to dplyr solution). Basically I combined answers from @TheVTM and @rmf.
Code:
library(microbenchmark)
library(data.table)
library(tidyverse)
dflist <- vector(length=10,mode="list")
for(i in 1:100)
{
dflist[[i]] <- data.frame(a=runif(n=260),b=runif(n=260),
c=rep(LETTERS,10),d=rep(LETTERS,10))
}
mb <- microbenchmark(
dplyr::bind_rows(dflist),
data.table::rbindlist(dflist),
purrr::map_df(dflist, bind_rows),
do.call("rbind",dflist),
times=500)
ggplot2::autoplot(mb)
Session Info:
sessionInfo()
R version 3.4.1 (2017-06-30)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
Package Versions:
> packageVersion("tidyverse")
[1] ‘1.1.1’
> packageVersion("data.table")
[1] ‘1.10.0’
Below code disable Focus on ListViewItem
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="Background" Value="Transparent" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListViewItem}">
<ContentPresenter />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
This is your code
<ListView Name="lstCustomers" ItemsSource="{Binding Path=Collection}">
<ListView.View>
<GridView>
<GridViewColumn Header="ID" DisplayMemberBinding="{Binding Id}" Width="40"/>
<GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" Width="100" />
<GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}"/>
</GridView>
</ListView.View>
</ListView>
Try this
<ListView Name="lstCustomers" ItemsSource="{Binding Path=Collection}">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Id}" Width="Auto">
<GridViewColumnHeader Content="ID" Width="Auto" />
</GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding FirstName}" Width="Auto">
<GridViewColumnHeader Content="First Name" Width="Auto" />
</GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding LastName}" Width="Auto">
<GridViewColumnHeader Content="Last Name" Width="Auto" />
</GridViewColumn
</GridView>
</ListView.View>
</ListView>
Html by itself will not send email. You will need something that connects to a SMTP server to send an email. Hence Outlook pops up with mailto: else your form goes to the server which has a script that sends email.
In Swift and as a function, inspired by DarkDust
// Usage: setTextWithLineSpacing(myEpicUILabel,text:"Hello",lineSpacing:20)
func setTextWithLineSpacing(label:UILabel,text:String,lineSpacing:CGFloat)
{
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineSpacing
let attrString = NSMutableAttributedString(string: text)
attrString.addAttribute(NSAttributedString.Key.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
label.attributedText = attrString
}
If you really want to fake multiple inheritance in PHP 5.3, you can use the magic function __call().
This is ugly though it works from class A user's point of view :
class B {
public function method_from_b($s) {
echo $s;
}
}
class C {
public function method_from_c($s) {
echo $s;
}
}
class A extends B
{
private $c;
public function __construct()
{
$this->c = new C;
}
// fake "extends C" using magic function
public function __call($method, $args)
{
$this->c->$method($args[0]);
}
}
$a = new A;
$a->method_from_b("abc");
$a->method_from_c("def");
Prints "abcdef"
Java and Kotlin runs on Java Virtual Machine (JVM).
Converting a Kotlin file to Java file involves two steps i.e. compiling the Kotlin code to the JVM bytecode and then decompile the bytecode to the Java code.
Steps to convert your Kotlin source file to Java source file:
npm install --save bootstrap
afterwards, inside angular.json
(previously .angular-cli.json
) inside the project's root folder, find styles and add the bootstrap css file like this:
for angular 6
"styles": [
"../node_modules/bootstrap/dist/css/bootstrap.min.css",
"styles.css"
],
for angular 7
"styles": [
"node_modules/bootstrap/dist/css/bootstrap.min.css",
"src/styles.css"
],
Try this expression...
string-join(//element3/(concat(element4/text(), '.', element5/text())), " ")
Set your css in the table cell to
white-space:pre-wrap;
document.body.innerHTML = 'First line\nSecond line\nThird line';
_x000D_
body{ white-space:pre-wrap; }
_x000D_
I had exactly same problem (on OS X Maverics 10.9.1 with SQLite3 3.7.13, but I don't think SQLite is related to the cause). I tried to import csv data saved from MS Excel 2011, which btw. uses ';'
as columns separator. I found out that csv file from Excel still uses newline character from Mac OS 9 times, changing it to unix newline solved the problem. AFAIR BBEdit has a command for this, as well as Sublime Text 2.
string mypath = @"..\folder1\folder2\folder2";
string[] directories = mypath.Split(Path.DirectorySeparatorChar);
Edit: This returns each individual folder in the directories array. You can get the number of folders returned like this:
int folderCount = directories.Length;
I resolved it by giving permission to the user on each of the directories that you're using, like so:
sudo chown user /home/user/git
and so on.
I am also having the same problem and I solved by as below.
in macro have a variable called rownumber and initially i set it as zero. this is the error because no excel sheet contains row number as zero. when i set as 1 and increment what i want.
now its working fine.
[EDIT] Years later, I've come back to say: don't do this! See What's wrong with XOR encryption? for details.
A very simple, easy two-way encrytpion is XOR encryption.
mypass
.mypassmypassmypass...
)mypassmypassmypass...
).If you are lucky enough to develop with Kotlin,
you can use take
to achieve your goal.
val someString = "hello"
someString.take(10) // result is "hello"
someString.take(4) // result is "hell" )))
I use this function htmlentities($string):
$msg = "<script>alert("hello")</script> <h1> Hello World </h1>" $msg = htmlentities($msg); echo $msg;
You're almost there: it's NOW() - INTERVAL 1 DAY
you can also just add the vm to your machine
vagrant box add precise32 http://files.vagrantup.com/precise32.box
Spaces are horrible in filenames or directory names.
The correct syntax for this is to include every directory name that includes spaces, in double quotes
cmd /c C:\"Program Files"\"Microsoft Visual Studio 9.0"\Common7\IDE\devenv.com mysolution.sln /build "release|win32"
$id = array(2222,3333,4444,5555,6666);
$ids = "'".implode("','",$id)."'";
$ids = sprintf("'%s'", implode("','", $id ) );
file_get_contents / file_put_contents will not magically convert encoding.
You have to convert the string explicitly; for example with iconv()
or mb_convert_encoding()
.
Try this:
$data = file_get_contents($npath);
$data = mb_convert_encoding($data, 'UTF-8', 'OLD-ENCODING');
file_put_contents('tempfolder/'.$a, $data);
Or alternatively, with PHP's stream filters:
$fd = fopen($file, 'r');
stream_filter_append($fd, 'convert.iconv.UTF-8/OLD-ENCODING');
stream_copy_to_stream($fd, fopen($output, 'w'));
Why not just use the built-in Format() function?
Dim vTest As Variant
vTest = Empty ' or vTest = null or vTest = ""
If Format(vTest) = vbNullString Then
doSomethingWhenEmpty()
Else
doSomethingElse()
End If
Format() will catch empty variants as well as null ones and transforms them in strings. I use it for things like null/empty validations and to check if an item has been selected in a combobox.
Some newer builds require the following additional adb commands to be run first
adb root
adb disable-verity
adb reboot
Then
adb root
adb remount
I have uploaded a sample project. You can take a look.
maybe:
import numpy as np
a=[[1,1],[2,2]]
b=np.asarray(a)
print(type(b))
output:
<class 'numpy.ndarray'>
If you want the name, use Martin's method. If you want to know whether it's an instance of a certain class:
boolean b = a instanceof String
Short answer: final
helps a tiny bit but... use defensive programming on the client side instead.
Indeed, the problem with final
is that it only enforces the reference is unchanged, gleefully allowing the referenced object members to be mutated, unbeknownst to the caller. Hence the best practice in this regard is defensive programming on the caller side, creating deeply immutable instances or deep copies of objects that are in danger of being mugged by unscrupulous APIs.
Try this:
public class ConnectionProvider
{
DbConnection conn;
string connectionString;
DbProviderFactory factory;
// Constructor that retrieves the connectionString from the config file
public ConnectionProvider()
{
this.connectionString = ConfigurationManager.ConnectionStrings[0].ConnectionString.ToString();
factory = DbProviderFactories.GetFactory(ConfigurationManager.ConnectionStrings[0].ProviderName.ToString());
}
// Constructor that accepts the connectionString and Database ProviderName i.e SQL or Oracle
public ConnectionProvider(string connectionString, string connectionProviderName)
{
this.connectionString = connectionString;
factory = DbProviderFactories.GetFactory(connectionProviderName);
}
// Only inherited classes can call this.
public DbConnection GetOpenConnection()
{
conn = factory.CreateConnection();
conn.ConnectionString = this.connectionString;
conn.Open();
return conn;
}
}
if the table does not have primary key or unique non-nullable defined, then MySql workbench could not able to edit the data.
Once you clear the interval using clearInterval
you could setInterval
once again. And to avoid repeating the callback externalize it as a separate function:
var ticker = function() {
console.log('idle');
};
then:
var myTimer = window.setInterval(ticker, 4000);
then when you decide to restart:
window.clearInterval(myTimer);
myTimer = window.setInterval(ticker, 4000);
According to my knowledge we should use ng-change with the select option and in textbox case we should use ng-blur.
After some research on this topic, I found that the error is occured basically if you have an instance of db created previously on your local sql server express. So whenever you have updates on db and try to update the db/run some code on db without running Update Database
command using Package Manager Console
; first of all, you have to delete previous db on our local sql express manually.
Also, this solution works unless you have AutomaticMigrationsEnabled = false;
in your Configuration.
If you work with a version control system (git,svn,etc.) and some other developers update db objects in production phase then this error rises whenever you update your code base and run the application.
As stated above, there are some solutions for this on code base. However, this is the most practical one for some cases.
If you don't care about checking the validity of the certificate just add the --no-check-certificate
option on the wget command-line. This worked well for me.
NOTE: This opens you up to man-in-the-middle (MitM) attacks, and is not recommended for anything where you care about security.
At least at STS (SpringSource Tool Suite) groups are numbered starting form 0, so replace string will be
replace: ((TypeName)$0)
Just a slight addition to the above solution if you are having problem with downloaded file's name...
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");
This will return the exact file name even if it contains spaces or other characters.
The solution did not work for me but the following code works for me. I am working on dynamic items with class of message-box
.
scrollToEnd() {
setTimeout(() => {
this.$el
.getElementsByClassName("message-box")
[
this.$el.getElementsByClassName("message-box").length -
1
].scrollIntoView();
}, 50);
}
Remember to put the method in mounted()
not created()
and add class message-box
to the dynamic item.
setTimeout()
is essential for this to work. You can refer to https://forum.vuejs.org/t/getelementsbyclassname-and-htmlcollection-within-a-watcher/26478 for more information about this.
I would recommend adding headers for the same. Moving metadata to headers helps in getting rid of envelops like result
, data
or records
and response body only contains the data we need. You can use Link header if you generate pagination links too.
HTTP/1.1 200
Pagination-Count: 100
Pagination-Page: 5
Pagination-Limit: 20
Content-Type: application/json
[
{
"id": 10,
"name": "shirt",
"color": "red",
"price": "$23"
},
{
"id": 11,
"name": "shirt",
"color": "blue",
"price": "$25"
}
]
For details refer to:
https://github.com/adnan-kamili/rest-api-response-format
For swagger file:
To build on JJC's helpful answer that builds on Louis's helpful answer...
With PhantomJS 2.1.1-windows this line works:
driver.execute_script("return navigator.userAgent")
If it doesn't work, you can still get the user agent via the log (to build on Mma's answer):
from selenium import webdriver
import json
from fake_useragent import UserAgent
dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = (UserAgent().random)
driver = webdriver.PhantomJS(executable_path=r"your_path", desired_capabilities=dcap)
har = json.loads(driver.get_log('har')[0]['message']) # get the log
print('user agent: ', har['log']['entries'][0]['request']['headers'][1]['value'])
Edit: thanks to @superlogical, you can now find and improve the following code in github!
I wrote this class based on some ideas here. The columns width is optimal, an it can handle object arrays with this simple API:
static void Main(string[] args)
{
IEnumerable<Tuple<int, string, string>> authors =
new[]
{
Tuple.Create(1, "Isaac", "Asimov"),
Tuple.Create(2, "Robert", "Heinlein"),
Tuple.Create(3, "Frank", "Herbert"),
Tuple.Create(4, "Aldous", "Huxley"),
};
Console.WriteLine(authors.ToStringTable(
new[] {"Id", "First Name", "Surname"},
a => a.Item1, a => a.Item2, a => a.Item3));
/* Result:
| Id | First Name | Surname |
|----------------------------|
| 1 | Isaac | Asimov |
| 2 | Robert | Heinlein |
| 3 | Frank | Herbert |
| 4 | Aldous | Huxley |
*/
}
Here is the class:
public static class TableParser
{
public static string ToStringTable<T>(
this IEnumerable<T> values,
string[] columnHeaders,
params Func<T, object>[] valueSelectors)
{
return ToStringTable(values.ToArray(), columnHeaders, valueSelectors);
}
public static string ToStringTable<T>(
this T[] values,
string[] columnHeaders,
params Func<T, object>[] valueSelectors)
{
Debug.Assert(columnHeaders.Length == valueSelectors.Length);
var arrValues = new string[values.Length + 1, valueSelectors.Length];
// Fill headers
for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
{
arrValues[0, colIndex] = columnHeaders[colIndex];
}
// Fill table rows
for (int rowIndex = 1; rowIndex < arrValues.GetLength(0); rowIndex++)
{
for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
{
arrValues[rowIndex, colIndex] = valueSelectors[colIndex]
.Invoke(values[rowIndex - 1]).ToString();
}
}
return ToStringTable(arrValues);
}
public static string ToStringTable(this string[,] arrValues)
{
int[] maxColumnsWidth = GetMaxColumnsWidth(arrValues);
var headerSpliter = new string('-', maxColumnsWidth.Sum(i => i + 3) - 1);
var sb = new StringBuilder();
for (int rowIndex = 0; rowIndex < arrValues.GetLength(0); rowIndex++)
{
for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
{
// Print cell
string cell = arrValues[rowIndex, colIndex];
cell = cell.PadRight(maxColumnsWidth[colIndex]);
sb.Append(" | ");
sb.Append(cell);
}
// Print end of line
sb.Append(" | ");
sb.AppendLine();
// Print splitter
if (rowIndex == 0)
{
sb.AppendFormat(" |{0}| ", headerSpliter);
sb.AppendLine();
}
}
return sb.ToString();
}
private static int[] GetMaxColumnsWidth(string[,] arrValues)
{
var maxColumnsWidth = new int[arrValues.GetLength(1)];
for (int colIndex = 0; colIndex < arrValues.GetLength(1); colIndex++)
{
for (int rowIndex = 0; rowIndex < arrValues.GetLength(0); rowIndex++)
{
int newLength = arrValues[rowIndex, colIndex].Length;
int oldLength = maxColumnsWidth[colIndex];
if (newLength > oldLength)
{
maxColumnsWidth[colIndex] = newLength;
}
}
}
return maxColumnsWidth;
}
}
Edit: I added a minor improvement - if you want the column headers to be the property name, add the following method to TableParser
(note that it will be a bit slower due to reflection):
public static string ToStringTable<T>(
this IEnumerable<T> values,
params Expression<Func<T, object>>[] valueSelectors)
{
var headers = valueSelectors.Select(func => GetProperty(func).Name).ToArray();
var selectors = valueSelectors.Select(exp => exp.Compile()).ToArray();
return ToStringTable(values, headers, selectors);
}
private static PropertyInfo GetProperty<T>(Expression<Func<T, object>> expresstion)
{
if (expresstion.Body is UnaryExpression)
{
if ((expresstion.Body as UnaryExpression).Operand is MemberExpression)
{
return ((expresstion.Body as UnaryExpression).Operand as MemberExpression).Member as PropertyInfo;
}
}
if ((expresstion.Body is MemberExpression))
{
return (expresstion.Body as MemberExpression).Member as PropertyInfo;
}
return null;
}
Bit late to this...I'm surprised that no one mentioned Symfony's VarDumper
component that Laravel includes, in part, for its dd()
(and lesser-known, dump()
) utility functions.
$dumpMe = new App\User([ 'name' => 'Cy Rossignol' ]);
(new Symfony\Component\VarDumper\Dumper\CliDumper())->dump(
(new Symfony\Component\VarDumper\Cloner\VarCloner())->cloneVar($dumpMe)
);
There's a bit more code needed, but, in return, we get nice formatted, readable output in the console—especially useful for debugging complex objects or arrays:
App\User {#17 #attributes: array:1 [ "name" => "Cy Rossignol" ] #fillable: array:3 [ 0 => "name" 1 => "email" 2 => "password" ] #guarded: array:1 [ 0 => "*" ] #primaryKey: "id" #casts: [] #dates: [] #relations: [] ... etc ... }
To take this a step further, we can even colorize the output! Add this helper function to the project to save some typing:
function toConsole($var)
{
$dumper = new Symfony\Component\VarDumper\Dumper\CliDumper();
$dumper->setColors(true);
$dumper->dump((new Symfony\Component\VarDumper\Cloner\VarCloner())->cloneVar($var));
}
If we're running the app behind a full webserver (like Apache or Nginx—not artisan serve
), we can modify this function slightly to send the dumper's prettified output to the log (typically storage/logs/laravel.log):
function toLog($var)
{
$lines = [ 'Dump:' ];
$dumper = new Symfony\Component\VarDumper\Dumper\CliDumper();
$dumper->setColors(true);
$dumper->setOutput(function ($line) use (&$lines) {
$lines[] = $line;
});
$dumper->dump((new Symfony\Component\VarDumper\Cloner\VarCloner())->cloneVar($var));
Log::debug(implode(PHP_EOL, $lines));
}
...and, of course, watch the log using:
$ tail -f storage/logs/laravel.log
PHP's error_log()
works fine for quick, one-off inspection of simple values, but the functions shown above take the hard work out of debugging some of Laravel's more complicated classes.
Yes - for primary keys, no - for foreign keys (more in the docs).
\d <table_name>
in "psql" shows a description of a table including all its indexes.
I think that your mistake is in that your route should be product
instead of /product
.
So more something like
children: [
{
path: '',
component: AboutHomeComponent
},
{
path: 'product',
component: AboutItemComponent
}
]
DateTime d = DateTime.Today.Date;
Console.WriteLine(d.ToShortDateString()); // outputs just date
if you want to compare dates, ignoring the time part, make an use of DateTime.Year
and DateTime.DayOfYear
properties.
code snippet
DateTime d1 = DateTime.Today;
DateTime d2 = DateTime.Today.AddDays(3);
if (d1.Year < d2.Year)
Console.WriteLine("d1 < d2");
else
if (d1.DayOfYear < d2.DayOfYear)
Console.WriteLine("d1 < d2");
'SET' is forgotten
ALTER TABLE ONLY users ALTER COLUMN lang SET DEFAULT 'en_GB';
Here is a site with a clear explanation and graphical illustration of using git merge --no-ff
:
Until I saw this, I was completely lost with git. Using --no-ff
allows someone reviewing history to clearly see the branch you checked out to work on. (that link points to github's "network" visualization tool) And here is another great reference with illustrations. This reference complements the first one nicely with more of a focus on those less acquainted with git.
If you are like me, and not a Git-guru, my answer here describes handling the deletion of files from git's tracking without deleting them from the local filesystem, which seems poorly documented but often occurrence. Another newb situation is getting current code, which still manages to elude me.
I updated a package to my website and had to go back to my notes to see my workflow; I thought it useful to add an example to this answer.
My workflow of git commands:
git checkout -b contact-form
(do your work on "contact-form")
git status
git commit -am "updated form in contact module"
git checkout master
git merge --no-ff contact-form
git branch -d contact-form
git push origin master
Below: actual usage, including explanations.
Note: the output below is snipped; git is quite verbose.
$ git status
# On branch master
# Changed but not updated:
# (use "git add/rm <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified: ecc/Desktop.php
# modified: ecc/Mobile.php
# deleted: ecc/ecc-config.php
# modified: ecc/readme.txt
# modified: ecc/test.php
# deleted: passthru-adapter.igs
# deleted: shop/mickey/index.php
#
# Untracked files:
# (use "git add <file>..." to include in what will be committed)
#
# ecc/upgrade.php
# ecc/webgility-config.php
# ecc/webgility-config.php.bak
# ecc/webgility-magento.php
Notice 3 things from above:
1) In the output you can see the changes from the ECC package's upgrade, including the addition of new files.
2) Also notice there are two files (not in the /ecc
folder) I deleted independent of this change. Instead of confusing those file deletions with ecc
, I'll make a different cleanup
branch later to reflect those files' deletion.
3) I didn't follow my workflow! I forgot about git while I was trying to get ecc working again.
Below: rather than do the all-inclusive git commit -am "updated ecc package"
I normally would, I only wanted to add the files in the /ecc
folder. Those deleted files weren't specifically part of my git add
, but because they already were tracked in git, I need to remove them from this branch's commit:
$ git checkout -b ecc
$ git add ecc/*
$ git reset HEAD passthru-adapter.igs
$ git reset HEAD shop/mickey/index.php
Unstaged changes after reset:
M passthru-adapter.igs
M shop/mickey/index.php
$ git commit -m "Webgility ecc desktop connector files; integrates with Quickbooks"
$ git checkout master
D passthru-adapter.igs
D shop/mickey/index.php
Switched to branch 'master'
$ git merge --no-ff ecc
$ git branch -d ecc
Deleted branch ecc (was 98269a2).
$ git push origin master
Counting objects: 22, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (14/14), done.
Writing objects: 100% (14/14), 59.00 KiB, done.
Total 14 (delta 10), reused 0 (delta 0)
To [email protected]:me/mywebsite.git
8a0d9ec..333eff5 master -> master
Having used this process 10+ times in a day, I have taken to writing batch scripts to execute the commands, so I made an almost-proper git_update.sh <branch> <"commit message">
script for doing the above steps. Here is the Gist source for that script.
Instead of git commit -am
I am selecting files from the "modified" list produced via git status
and then pasting those in this script. This came about because I made dozens of edits but wanted varied branch names to help group the changes.
=IF(ISNUMBER(SEARCH(LEFT(H2,3),I2)),"YES","NO")))
For production environments you should use Forever.js
It's so util for start and stop node process, you can list apps running too.
using System.IO;
//...
string[] files;
if (Directory.Exists(Path)) {
files = Directory.GetFiles(Path, @"*.xml", SearchOption.TopDirectoryOnly);
//...
check for this by calling the library jquery after the noconflict.js or that this calling more than once jquery library after the noconflict.js
For anyone running into a problem where build automatically is unchecked but the project is still building. Make sure your project isn't deployed to the server in the server tab and told to stay synchronous.
There is an HTTP header you can set that will force IE8 to use IE7-compatibility mode.
Well, you might look at System.Threading.Semaphore
class. Other than that - no, you have to make this yourself. AFAIK there is no such built-in collection.
Had the same issue but mine was working for weeks before this. Realised I had changed my password on the server.
Remember to update your password if you've got the option selected 'Run whether user is logged on or not'
i was facing same issue in beautiful soup , I solved this issue by this command , your issue will also get rectified .
You are unable to install requests in python 3.4 because your python libraries are not updated .
use this command
apt-get install python3-requests
Just run it will ask you to add 222 MB space in your hard disk , just press Y and wait for completing process, after ending up whole process . check your problem will be resolved.
the difference is not between <span>
and <div>
specifically, but between inline
and block
elements. <span>
defaults to being display:inline;
whereas <div>
defaults to being display:block;
. But these can be overridden in CSS.
The difference in the way text-align:center
works between the two is down to the width.
A block
element defaults to being the width of its container. It can have its width set using CSS, but either way it is a fixed width.
An inline
element takes its width from the size of its content text.
text-align:center
tells the text to position itself centrally in the element. But in an inline
element, this is clearly not going to have any effect because the element is the same width as the text; aligning it one way or the other is meaningless.
In a block
element, because the element's width is independent of the content, the content can be positioned within the element using the text-align
style.
Finally, a solution for you:
There is an additional value for the display
property which provides a half-way house between block
and inline
. Conveniently enough, it's called inline-block
. If you specify a <span>
to be display:inline-block;
in the CSS, it will continue to work as an inline element but will take on some of the properties of a block as well, such as the ability to specify a width
. Once you specify a width for it, you will be able to center the text within that width using text-align:center;
Hope that helps.
var rotator = function(){
widget.Rotator.rotate();
setTimeout(rotator,5000);
};
rotator();
Or:
setInterval(
function(){ widget.Rotator.rotate() },
5000
);
Or:
setInterval(
widget.Rotator.rotate.bind(widget.Rotator),
5000
);
Simple said:
A hook is a means of executing custom code (function) either before, after, or instead of existing code. For example, a function may be written to "hook" into the login process in order to execute a Captcha function before continuing on to the normal login process.
I have created a sample UI which shows the save and open file dialog. Click on save button to open save dialog and click on open button to open file dialog.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class FileChooserEx {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
new FileChooserEx().createUI();
}
};
EventQueue.invokeLater(r);
}
private void createUI() {
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
JButton saveBtn = new JButton("Save");
JButton openBtn = new JButton("Open");
saveBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
JFileChooser saveFile = new JFileChooser();
saveFile.showSaveDialog(null);
}
});
openBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
JFileChooser openFile = new JFileChooser();
openFile.showOpenDialog(null);
}
});
frame.add(new JLabel("File Chooser"), BorderLayout.NORTH);
frame.add(saveBtn, BorderLayout.CENTER);
frame.add(openBtn, BorderLayout.SOUTH);
frame.setTitle("File Chooser");
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Programmers are lazy...er....efficient....I'd do it like so:
<select><?php
$the_key = 1; // or whatever you want
foreach(array(
1 => 'Yes',
2 => 'No',
3 => 'Fine',
) as $key => $val){
?><option value="<?php echo $key; ?>"<?php
if($key==$the_key)echo ' selected="selected"';
?>><?php echo $val; ?></option><?php
}
?></select>
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
I was able to accomplish this using a FormArray of FormGroups. The FormGroup consists of two controls. One for the data and one to store the checked boolean.
TS
options: options[] = [{id: 1, text: option1}, {id: 2, text: option2}];
this.fb.group({
options: this.fb.array([])
})
populateFormArray() {
this.options.forEach(option => {
let checked = ***is checked logic here***;
this.checkboxGroup.get('options').push(this.createOptionGroup(option, checked))
});
}
createOptionGroup(option: Option, checked: boolean) {
return this.fb.group({
option: this.fb.control(option),
checked: this.fb.control(checked)
});
}
HTML
This allows you to loop through the options and bind to the corresponding checked control.
<form [formGroup]="checkboxGroup">
<div formArrayName="options" *ngFor="let option of options; index as i">
<div [formGroupName]="i">
<input type="checkbox" formControlName="checked" />
{{ option.text }}
</div>
</div>
</form>
Output
The form returns data in the form {option: Option, checked: boolean}[]
.
You can get a list of checked options using the below code
this.checkboxGroup.get('options').value.filter(el => el.checked).map(el => el.option);
What I found is that the Program.cs file was not part of the solution. I did an add existing item and added the file (Program.cs) back to the solution.
This corrected the error: Error 1 Program '..... does not contain a static 'Main' method suitable for an entry point
You can throw a HttpResponseException
HttpResponseMessage response =
this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "your message");
throw new HttpResponseException(response);
You will need to add the jar to your local maven repository. Alternatively (better option) specify the proper repository (if one exists) so it can be automatically downloaded by maven
In either case, remove the <systemPath>
tag from the dependency
Execute command
psql -V
Where
V must be in capital.
Keeping in mind the points made in @John Woo's comment/link above, this is how I typically would handle it:
SELECT t1.ID, t1.Name
FROM Table1 t1
WHERE NOT EXISTS (
SELECT TOP 1 NULL
FROM Table2 t2
WHERE t1.ID = t2.ID
)
You can use this statement:
if ($scope.$root.$$phase != '$apply' && $scope.$root.$$phase != '$digest') {
$scope.$apply();
}
Suppose your origin and upstream info is like below
$ git remote -v
origin [email protected]:<yourname>/<repo_name>.git (fetch)
origin [email protected]:<yourname>/<repo_name>.git (push)
upstream [email protected]:<repo_owner>/<repo_name>.git (fetch)
upstream [email protected]:<repo_owner>/<repo_name>.git (push)
and your branch name is like
<repo_owner>:<BranchName>
then
git pull origin <BranchName>
shall do the job
npm set registry http://85.10.209.91/
(this proxy fetches the original data from registry.npmjs.org and manipulates the tarball urls to fix the tarball file structure issue).
The other solutions seem to have outdated versions.
I had the same problem I used the solution offered above - I dropped the SYNONYM, created a VIEW with the same name as the synonym. it had a select using the dblink , and gave GRANT SELECT to the other schema It worked great.
Another good use for Dispatcher.Invoke
is for immediately updating the UI in a function that performs other tasks:
// Force WPF to render UI changes immediately with this magic line of code...
Dispatcher.Invoke(new Action(() => { }), DispatcherPriority.ContextIdle);
I use this to update button text to "Processing..." and disable it while making WebClient
requests.
Select
p.Name,
p.SS,
f.fear
From
Persons p
left join
Person_Fear pf
inner join
Fears f
on
pf.fearID = f.fearID
on
p.personID = pf.PersonID
Create WEB-INF folder in src/webapp, and include web.xml page inside the WEB-INF folder then
The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.
According to this Google blogpost:
It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.
When referencing the mipmap- folders ensure you are using the following reference:
android:icon="@mipmap/ic_launcher"
The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.
According to my humble opinion and my work experience with git, staging area is not the same as index. I may be wrong of course, but as I said, my experience in using git and my logic tell me, that index is a structure that follows your changes to your working area(local repository) that are not excluded by ignoring settings and staging area is to keep files that are already confirmed to be committed, aka files in index on which add command was run on. You don't notice and realize that "slight" difference, because you use
git commit -a -m "comment"
adding indexed and cached files to stage area and committing in one command or using IDEs like IDEA for that too often. And cache is that what keeps changes in indexed files.
If you want to remove file from index that has not been added to staging area before, options proposed before match for you, but...
If you have done that already, you will need to use
Git restore --staged <file>
And, please, don't ask me where I was 10 years ago... I missed you, this answer is for further generations)
If you can base-64 encode your bytes, you could try using the result as your image source. In your model you might add something like:
public string ImageSource
{
get
{
string mimeType = /* Get mime type somehow (e.g. "image/png") */;
string base64 = Convert.ToBase64String(yourImageBytes);
return string.Format("data:{0};base64,{1}", mimeType, base64);
}
}
And in your view:
<img ... src="@Model.ImageSource" />
I'd use pathos.multiprocesssing
, instead of multiprocessing
. pathos.multiprocessing
is a fork of multiprocessing
that uses dill
. dill
can serialize almost anything in python, so you are able to send a lot more around in parallel. The pathos
fork also has the ability to work directly with multiple argument functions, as you need for class methods.
>>> from pathos.multiprocessing import ProcessingPool as Pool
>>> p = Pool(4)
>>> class Test(object):
... def plus(self, x, y):
... return x+y
...
>>> t = Test()
>>> p.map(t.plus, x, y)
[4, 6, 8, 10]
>>>
>>> class Foo(object):
... @staticmethod
... def work(self, x):
... return x+1
...
>>> f = Foo()
>>> p.apipe(f.work, f, 100)
<processing.pool.ApplyResult object at 0x10504f8d0>
>>> res = _
>>> res.get()
101
Get pathos
(and if you like, dill
) here:
https://github.com/uqfoundation
Try:
SELECT post_datetime
FROM post
WHERE type = 'published'
ORDER BY post_datetime DESC
LIMIT 3
fixed my agent string evaluation by scrubbing the string for LOWERCASE "iphone os 5_0" as opposed to "iPhone OS 5_0." now i am properly assigning iOS 5 specific classes to my html, when the uppercase scrub failed.
Yes, you missed the form encapsulation:
<form>
<input id="tbQuestion" type="text" placeholder="Post a question?" required/>
<input id="btnSubmit" type="submit" />
</form>
Yes, You actually can do that only by using CSS...
body { width:100%; margin-right: 0; margin-left:0; padding-right:0; padding-left:0; }
Tell me if it works
You can use the length()
method on File
which returns the size in bytes.
I always use ADB Driver Installer for installing adb drivers for any mobile. You only need to click on Install button. and all set!
If your device is not listed here, then you can check enable your developer setting, check your USB cable.
Obligatory .map
example:
var checkedVals = $('.theClass:checkbox:checked').map(function() {
return this.value;
}).get();
alert(checkedVals.join(","));
For a multi-threaded implementation tuned for Intel processors I'd check out Intel's MKL library. It's not free, but it's afforable (less than $100) and blazing fast - but you'd need to call it's C dll's via P/Invokes. The Exocortex project stopped development 6 years ago, so I'd be careful using it if this is an important project.
public Integer binaryToInteger(String binary){
char[] numbers = binary.toCharArray();
Integer result = 0;
int count = 0;
for(int i=numbers.length-1;i>=0;i--){
if(numbers[i]=='1')result+=(int)Math.pow(2, count);
count++;
}
return result;
}
I guess I'm even more bored! Modified Hassan's answer to function correctly.
Write your first unit test
Write a JUnit test -- here's mine:
import org.junit.Assert;
import org.junit.Test;
public class MyFirstTest {
@Test
public void firstTest() {
Assert.assertTrue(true);
}
}
The fastest way is using -0:
const num = "12.34" - 0;
It was two things:
I added the volume in docker-compose.yml
:
node:
volumes:
- ./node:/app
I moved the npm install && nodemon app.js
pieces into a CMD
because RUN
adds things to the Union File System, and my volume isn't part of UFS.
# Set the base image to Ubuntu
FROM node:boron
# File Author / Maintainer
MAINTAINER Amin Shah Gilani <[email protected]>
# Install nodemon
RUN npm install -g nodemon
# Add a /app volume
VOLUME ["/app"]
# Define working directory
WORKDIR /app
# Expose port
EXPOSE 8080
# Run npm install
CMD npm install && nodemon app.js
Without a frame this works for me:
JTextField tf = new JTextField(20);
tf.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER){
SwingUtilities.getWindowAncestor(e.getComponent()).dispose();
}
}
});
String[] options = {"Ok", "Cancel"};
int result = JOptionPane.showOptionDialog(
null, tf, "Enter your message",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,0);
message = tf.getText();
curl -X GET -H "Accept: application/vnd.api+json" localhost:8082/v3/clusters
where localhost:8082
is Kafka Proxy address.
Use this JavaScript.
$(":input").inputmask();
$("#phone").inputmask({"mask": "(999) 999-9999"});
I've seen this anti-pattern from people who don't quite get the & address-of operator. If they need to call a function with a pointer, they'll always allocate on the heap so they get a pointer.
void FeedTheDog(Dog* hungryDog);
Dog* badDog = new Dog;
FeedTheDog(badDog);
delete badDog;
Dog goodDog;
FeedTheDog(&goodDog);
I also had this issue and my solution was different, so adding here for any who have similar problem.
My controller had:
@RequestMapping(value = "/setPassword", method = RequestMethod.POST)
public String setPassword(Model model, @RequestParameter SetPassword setPassword) {
...
}
The issue was that this should be @ModelAttribute
for the object, not @RequestParameter
. The error message for this is the same as you describe in your question.
@RequestMapping(value = "/setPassword", method = RequestMethod.POST)
public String setPassword(Model model, @ModelAttribute SetPassword setPassword) {
...
}
But u can find the array length or size using sizeof operator.
Because when we initialise a array compiler give memory on our program like a[10] (10 blocks of 4 size ) and every block has garbage value if we put some value in some index like a[0]=1,a[1]=2,a[3]=8; and other block has garbage value no one can tell which value Is garbage and which value is not garbage that's a reason we cannot calculate how many elements in a array. I hope this will help u to understand . Little concept
The "Usort" function is your answer.
http://php.net/usort
Sorry, brief moment of synapse failure. Here's the real answer.
require 'date'
Time.at(seconds_since_epoch_integer).to_datetime
Brief example (this takes into account the current system timezone):
$ date +%s
1318996912
$ irb
ruby-1.9.2-p180 :001 > require 'date'
=> true
ruby-1.9.2-p180 :002 > Time.at(1318996912).to_datetime
=> #<DateTime: 2011-10-18T23:01:52-05:00 (13261609807/5400,-5/24,2299161)>
Further update (for UTC):
ruby-1.9.2-p180 :003 > Time.at(1318996912).utc.to_datetime
=> #<DateTime: 2011-10-19T04:01:52+00:00 (13261609807/5400,0/1,2299161)>
Recent Update: I benchmarked the top solutions in this thread while working on a HA service a week or two ago, and was surprised to find that Time.at(..)
outperforms DateTime.strptime(..)
(update: added more benchmarks).
# ~ % ruby -v
# => ruby 2.1.5p273 (2014-11-13 revision 48405) [x86_64-darwin13.0]
irb(main):038:0> Benchmark.measure do
irb(main):039:1* ["1318996912", "1318496912"].each do |s|
irb(main):040:2* DateTime.strptime(s, '%s')
irb(main):041:2> end
irb(main):042:1> end
=> #<Benchmark ... @real=2.9e-05 ... @total=0.0>
irb(main):044:0> Benchmark.measure do
irb(main):045:1> [1318996912, 1318496912].each do |i|
irb(main):046:2> DateTime.strptime(i.to_s, '%s')
irb(main):047:2> end
irb(main):048:1> end
=> #<Benchmark ... @real=2.0e-05 ... @total=0.0>
irb(main):050:0* Benchmark.measure do
irb(main):051:1* ["1318996912", "1318496912"].each do |s|
irb(main):052:2* Time.at(s.to_i).to_datetime
irb(main):053:2> end
irb(main):054:1> end
=> #<Benchmark ... @real=1.5e-05 ... @total=0.0>
irb(main):056:0* Benchmark.measure do
irb(main):057:1* [1318996912, 1318496912].each do |i|
irb(main):058:2* Time.at(i).to_datetime
irb(main):059:2> end
irb(main):060:1> end
=> #<Benchmark ... @real=2.0e-05 ... @total=0.0>
Use React Native Hyperlink (Native <A>
tag):
Install:
npm i react-native-a
import:
import A from 'react-native-a'
Usage:
<A>Example.com</A>
<A href="example.com">Example</A>
<A href="https://example.com">Example</A>
<A href="example.com" style={{fontWeight: 'bold'}}>Example</A>
You should form the command with the contents of the textboxes:
sql = "insert into Main (Firt Name, Last Name) values(" + textbox2.Text + "," + textbox3.Text+ ")";
This, of course, provided that you manage to open the connection correctly.
It would be helpful to know what's happening with your current code. If you are getting some error displayed in that message box, it would be great to know what it's saying.
You should also validate the inputs before actually running the command (i.e. make sure they don't contain malicious code...).
You can also resize the profile picture by providing parameters as shown below.
https://graph.facebook.com/[UID]/picture?width=140&height=140
would work too.
Use padStart:
Date.prototype.yyyymmdd = function() {
return [
this.getFullYear(),
(this.getMonth()+1).toString().padStart(2, '0'), // getMonth() is zero-based
this.getDate().toString().padStart(2, '0')
].join('-');
};
def inside():
global var
var = 'info'
inside()
print(var)
>>>'info'
problem ended
You're missing comma (,
) inbetween:
>>> ((1,2) (2,3))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable
Put comma:
>>> ((1,2), (2,3))
((1, 2), (2, 3))
A call to Class#getResourceAsStream(String)
delegates to the class loader and the resource is searched in the class path. In other words, you current code won't work and you should put abc.txt
in WEB-INF/classes
, or in WEB-INF/lib
if packaged in a jar file.
Or use ServletContext.getResourceAsStream(String)
which allows servlet containers to make a resource available to a servlet from any location, without using a class loader. So use this from a Servlet:
this.getServletContext().getResourceAsStream("/WEB-INF/abc.txt") ;
But is there a way I can call getServletContext from my Web Service?
If you are using JAX-WS, then you can get a WebServiceContext
injected:
@Resource
private WebServiceContext wsContext;
And then get the ServletContext
from it:
ServletContext sContext= wsContext.getMessageContext()
.get(MessageContext.SERVLET_CONTEXT));
REST is just a software architecture style for exposing resources.
A typical REST call to return information about customer 34456 could look like:
http://example.com/customer/34456
Have a look at the IBM tutorial for REST web services
The <h:outputLink>
renders a fullworthy HTML <a>
element with the proper URL in the href
attribute which fires a bookmarkable GET request. It cannot directly invoke a managed bean action method.
<h:outputLink value="destination.xhtml">link text</h:outputLink>
The <h:commandLink>
renders a HTML <a>
element with an onclick
script which submits a (hidden) POST form and can invoke a managed bean action method. It's also required to be placed inside a <h:form>
.
<h:form>
<h:commandLink value="link text" action="destination" />
</h:form>
The ?faces-redirect=true
parameter on the <h:commandLink>
, which triggers a redirect after the POST (as per the Post-Redirect-Get pattern), only improves bookmarkability of the target page when the link is actually clicked (the URL won't be "one behind" anymore), but it doesn't change the href
of the <a>
element to be a fullworthy URL. It still remains #
.
<h:form>
<h:commandLink value="link text" action="destination?faces-redirect=true" />
</h:form>
Since JSF 2.0, there's also the <h:link>
which can take a view ID (a navigation case outcome) instead of an URL. It will generate a HTML <a>
element as well with the proper URL in href
.
<h:link value="link text" outcome="destination" />
So, if it's for pure and bookmarkable page-to-page navigation like the SO username link, then use <h:outputLink>
or <h:link>
. That's also better for SEO since bots usually doesn't cipher POST forms nor JS code. Also, UX will be improved as the pages are now bookmarkable and the URL is not "one behind" anymore.
When necessary, you can do the preprocessing job in the constructor or @PostConstruct
of a @RequestScoped
or @ViewScoped
@ManagedBean
which is attached to the destination page in question. You can make use of @ManagedProperty
or <f:viewParam>
to set GET parameters as bean properties.
Immutable objects are objects that can't be changed programmatically. They're especially good for multi-threaded environments or other environments where more than one process is able to alter (mutate) the values in an object.
Just to clarify, however, StringBuilder is actually a mutable object, not an immutable one. A regular java String is immutable (meaning that once it's been created you cannot change the underlying string without changing the object).
For example, let's say that I have a class called ColoredString that has a String value and a String color:
public class ColoredString {
private String color;
private String string;
public ColoredString(String color, String string) {
this.color = color;
this.string = string;
}
public String getColor() { return this.color; }
public String getString() { return this.string; }
public void setColor(String newColor) {
this.color = newColor;
}
}
In this example, the ColoredString is said to be mutable because you can change (mutate) one of its key properties without creating a new ColoredString class. The reason why this may be bad is, for example, let's say you have a GUI application which has multiple threads and you are using ColoredStrings to print data to the window. If you have an instance of ColoredString which was created as
new ColoredString("Blue", "This is a blue string!");
Then you would expect the string to always be "Blue". If another thread, however, got ahold of this instance and called
blueString.setColor("Red");
You would suddenly, and probably unexpectedly, now have a "Red" string when you wanted a "Blue" one. Because of this, immutable objects are almost always preferred when passing instances of objects around. When you have a case where mutable objects are really necessary, then you would typically guard the objet by only passing copies out from your specific field of control.
To recap, in Java, java.lang.String is an immutable object (it cannot be changed once it's created) and java.lang.StringBuilder is a mutable object because it can be changed without creating a new instance.
The font sizes in your question are an example of what ratio each header should be in comparison to each other, rather than what size they should be themselves (in pixels).
So in response to your question "Is there a 'best practice' for these for mobile phones? - say iphone screen size?", yes there probably is - but you might find what someone says is "best practice" does not work for your layout.
However, to help get you on the right track, this article about building responsive layouts provides a good example of how to calculate the base font-size
in pixels in relation to device screen sizes.
The suggested font-sizes for screen resolutions suggested from that article are as follows:
@media (min-width: 858px) {
html {
font-size: 12px;
}
}
@media (min-width: 780px) {
html {
font-size: 11px;
}
}
@media (min-width: 702px) {
html {
font-size: 10px;
}
}
@media (min-width: 724px) {
html {
font-size: 9px;
}
}
@media (max-width: 623px) {
html {
font-size: 8px;
}
}
String[] tblHead={"Item Name","Price","Qty","Discount"};
DefaultTableModel dtm=new DefaultTableModel(tblHead,0);
JTable tbl=new JTable(dtm);
String[] item={"A","B","C","D"};
dtm.addRow(item);
Here;this is the solution.
To remove an item from a text file, first move all the text to a list and remove whichever item you want. Then write the text stored in the list into a text file:
List<string> quotelist=File.ReadAllLines(filename).ToList();
string firstItem= quotelist[0];
quotelist.RemoveAt(0);
File.WriteAllLines(filename, quotelist.ToArray());
return firstItem;
Definitely not the ideal solution, but it's easier for me to understand if I convert the list into tuples and then sort it.
mylist = [[1,2,3,4],[4,5,6,7]]
mylist2 = []
for thing in mylist:
thing = tuple(thing)
mylist2.append(thing)
set(mylist2)
My guess is that the folder you are trying to add already exists in SVN. You can confirm by checking out the files to a different folder and see if trunk already has the required folder.
I recently wrote this inline table valued function to solve this very problem. It's not limited in range other than memory and storage. It accesses no tables so there's no need for disk reads or writes generally. It adds joins values exponentially on each iteration so it's very fast even for very large ranges. It creates ten million records in five seconds on my server. It also works with negative values.
CREATE FUNCTION [dbo].[fn_ConsecutiveNumbers]
(
@start int,
@end int
) RETURNS TABLE
RETURN
select
x268435456.X
| x16777216.X
| x1048576.X
| x65536.X
| x4096.X
| x256.X
| x16.X
| x1.X
+ @start
X
from
(VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13),(14),(15)) as x1(X)
join
(VALUES (0),(16),(32),(48),(64),(80),(96),(112),(128),(144),(160),(176),(192),(208),(224),(240)) as x16(X)
on x1.X <= @end-@start and x16.X <= @end-@start
join
(VALUES (0),(256),(512),(768),(1024),(1280),(1536),(1792),(2048),(2304),(2560),(2816),(3072),(3328),(3584),(3840)) as x256(X)
on x256.X <= @end-@start
join
(VALUES (0),(4096),(8192),(12288),(16384),(20480),(24576),(28672),(32768),(36864),(40960),(45056),(49152),(53248),(57344),(61440)) as x4096(X)
on x4096.X <= @end-@start
join
(VALUES (0),(65536),(131072),(196608),(262144),(327680),(393216),(458752),(524288),(589824),(655360),(720896),(786432),(851968),(917504),(983040)) as x65536(X)
on x65536.X <= @end-@start
join
(VALUES (0),(1048576),(2097152),(3145728),(4194304),(5242880),(6291456),(7340032),(8388608),(9437184),(10485760),(11534336),(12582912),(13631488),(14680064),(15728640)) as x1048576(X)
on x1048576.X <= @end-@start
join
(VALUES (0),(16777216),(33554432),(50331648),(67108864),(83886080),(100663296),(117440512),(134217728),(150994944),(167772160),(184549376),(201326592),(218103808),(234881024),(251658240)) as x16777216(X)
on x16777216.X <= @end-@start
join
(VALUES (0),(268435456),(536870912),(805306368),(1073741824),(1342177280),(1610612736),(1879048192)) as x268435456(X)
on x268435456.X <= @end-@start
WHERE @end >=
x268435456.X
| isnull(x16777216.X, 0)
| isnull(x1048576.X, 0)
| isnull(x65536.X, 0)
| isnull(x4096.X, 0)
| isnull(x256.X, 0)
| isnull(x16.X, 0)
| isnull(x1.X, 0)
+ @start
GO
SELECT X FROM fn_ConsecutiveNumbers(5, 500);
It's handy for date and time ranges as well:
SELECT DATEADD(day,X, 0) DayX
FROM fn_ConsecutiveNumbers(datediff(day,0,'5/8/2015'), datediff(day,0,'5/31/2015'))
SELECT DATEADD(hour,X, 0) HourX
FROM fn_ConsecutiveNumbers(datediff(hour,0,'5/8/2015'), datediff(hour,0,'5/8/2015 12:00 PM'));
You could use a cross apply join on it to split records based on values in the table. So for example to create a record for every minute on a time range in a table you could do something like:
select TimeRanges.StartTime,
TimeRanges.EndTime,
DATEADD(minute,X, 0) MinuteX
FROM TimeRanges
cross apply fn_ConsecutiveNumbers(datediff(hour,0,TimeRanges.StartTime),
datediff(hour,0,TimeRanges.EndTime)) ConsecutiveNumbers
In the direction of Bradgonesurfing's answer, many times one doesn't really need to concatenate two vectors (O(n)), but instead just work with them as if they were concatenated (O(1)). If this is your case, it can be done without the need of Boost libraries.
The trick is to create a vector proxy: a wrapper class which manipulates references to both vectors, externally seen as a single, contiguous one.
USAGE
std::vector<int> A{ 1, 2, 3, 4, 5};
std::vector<int> B{ 10, 20, 30 };
VecProxy<int> AB(A, B); // ----> O(1). No copies performed.
for (size_t i = 0; i < AB.size(); ++i)
std::cout << AB[i] << " "; // 1 2 3 4 5 10 20 30
IMPLEMENTATION
template <class T>
class VecProxy {
private:
std::vector<T>& v1, v2;
public:
VecProxy(std::vector<T>& ref1, std::vector<T>& ref2) : v1(ref1), v2(ref2) {}
const T& operator[](const size_t& i) const;
const size_t size() const;
};
template <class T>
const T& VecProxy<T>::operator[](const size_t& i) const{
return (i < v1.size()) ? v1[i] : v2[i - v1.size()];
};
template <class T>
const size_t VecProxy<T>::size() const { return v1.size() + v2.size(); };
MAIN BENEFIT
It's O(1) (constant time) to create it, and with minimal extra memory allocation.
SOME STUFF TO CONSIDER
Depends what you mean by "post data". You can use the HTML target=""
attribute on a <form />
tag, so it could be as simple as:
<form action="do_stuff.aspx" method="post" target="my_iframe">
<input type="submit" value="Do Stuff!">
</form>
<!-- when the form is submitted, the server response will appear in this iframe -->
<iframe name="my_iframe" src="not_submitted_yet.aspx"></iframe>
If that's not it, or you're after something more complex, please edit your question to include more detail.
There is a known bug with Internet Explorer that only occurs when you're dynamically creating your iframes, etc. using Javascript (there's a work-around here), but if you're using ordinary HTML markup, you're fine. The target attribute and frame names isn't some clever ninja hack; although it was deprecated (and therefore won't validate) in HTML 4 Strict or XHTML 1 Strict, it's been part of HTML since 3.2, it's formally part of HTML5, and it works in just about every browser since Netscape 3.
I have verified this behaviour as working with XHTML 1 Strict, XHTML 1 Transitional, HTML 4 Strict and in "quirks mode" with no DOCTYPE specified, and it works in all cases using Internet Explorer 7.0.5730.13. My test case consist of two files, using classic ASP on IIS 6; they're reproduced here in full so you can verify this behaviour for yourself.
default.asp
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Form Iframe Demo</title>
</head>
<body>
<form action="do_stuff.asp" method="post" target="my_frame">
<input type="text" name="someText" value="Some Text">
<input type="submit">
</form>
<iframe name="my_frame" src="do_stuff.asp">
</iframe>
</body>
</html>
do_stuff.asp
<%@Language="JScript"%><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Form Iframe Demo</title>
</head>
<body>
<% if (Request.Form.Count) { %>
You typed: <%=Request.Form("someText").Item%>
<% } else { %>
(not submitted)
<% } %>
</body>
</html>
I would be very interested to hear of any browser that doesn't run these examples correctly.
You can do this with jQuery. Using their selectors, you can select by attributes, such as type. This does, however, require that your users have Javascript turned on, and an additional file to download, but if it works...
row=5
col=5
[[x]*col for x in [b for b in range(row)]]
The above will give you a 5x5 2D array
[[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4]]
It is using nested list comprehension. Breakdown as below:
[[x]*col for x in [b for b in range(row)]]
[x]*col --> final expression that is evaluated
for x in --> x will be the value provided by the iterator
[b for b in range(row)]] --> Iterator.
[b for b in range(row)]] this will evaluate to [0,1,2,3,4] since row=5
so now it simplifies to
[[x]*col for x in [0,1,2,3,4]]
This will evaluate to
[[0]*5 for x in [0,1,2,3,4]] --> with x=0 1st iteration
[[1]*5 for x in [0,1,2,3,4]] --> with x=1 2nd iteration
[[2]*5 for x in [0,1,2,3,4]] --> with x=2 3rd iteration
[[3]*5 for x in [0,1,2,3,4]] --> with x=3 4th iteration
[[4]*5 for x in [0,1,2,3,4]] --> with x=4 5th iteration
You need to do two things:
The code:
dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))
library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha = 0.35, linetype=0)+
geom_line(aes(linetype=model), size = 1) +
geom_point(aes(shape=model), size=4) +
theme(legend.position=c(.6,0.8)) +
theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
scale_linetype_discrete("Model 1") +
scale_shape_discrete("Model 1") +
scale_colour_discrete("Model 1")
However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha=0.2, colour=NA)+
geom_line() +
geom_point() +
facet_wrap(~model)
Very simple option in case you have many individual columns to delete in a data table and you want to avoid typing in all column names #careadviced
dt <- dt[, -c(1,4,6,17,83,104)]
This will remove columns based on column number instead.
It's obviously not as efficient because it bypasses data.table advantages but if you're working with less than say 500,000 rows it works fine
"+" does not mutate the list
.append() mutates the old list
Bundle extras = getIntent().getExtras();
Set<String> ks = extras.keySet();
Iterator<String> iterator = ks.iterator();
while (iterator.hasNext()) {
Log.d("KEY", iterator.next());
}
Just use
Dim Cell As Range
Columns("B:B").Select
Set cell = Selection.Find(What:="celda", After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If cell Is Nothing Then
'do it something
Else
'do it another thing
End If
I've always used the SimpleXML functions built in to PHP to parse XML documents. It's one of the few generic parsers out there that has an intuitive structure to it, which makes it extremely easy to build a meaningful class for something specific like an RSS feed. Additionally, it will detect XML warnings and errors, and upon finding any you could simply run the source through something like HTML Tidy (as ceejayoz mentioned) to clean it up and attempt it again.
Consider this very rough, simple class using SimpleXML:
class BlogPost
{
var $date;
var $ts;
var $link;
var $title;
var $text;
}
class BlogFeed
{
var $posts = array();
function __construct($file_or_url)
{
$file_or_url = $this->resolveFile($file_or_url);
if (!($x = simplexml_load_file($file_or_url)))
return;
foreach ($x->channel->item as $item)
{
$post = new BlogPost();
$post->date = (string) $item->pubDate;
$post->ts = strtotime($item->pubDate);
$post->link = (string) $item->link;
$post->title = (string) $item->title;
$post->text = (string) $item->description;
// Create summary as a shortened body and remove images,
// extraneous line breaks, etc.
$post->summary = $this->summarizeText($post->text);
$this->posts[] = $post;
}
}
private function resolveFile($file_or_url) {
if (!preg_match('|^https?:|', $file_or_url))
$feed_uri = $_SERVER['DOCUMENT_ROOT'] .'/shared/xml/'. $file_or_url;
else
$feed_uri = $file_or_url;
return $feed_uri;
}
private function summarizeText($summary) {
$summary = strip_tags($summary);
// Truncate summary line to 100 characters
$max_len = 100;
if (strlen($summary) > $max_len)
$summary = substr($summary, 0, $max_len) . '...';
return $summary;
}
}
1) imported all the JARS from POI folder 2) Imported all the JARS from ooxml folder which a subdirectory of POI folder 3) Imported all the JARS from lib folder which is a subdirectory of POI folder
String fileName = "C:/File raw.xlsx";
File file = new File(fileName);
FileInputStream fileInputStream;
Workbook workbook = null;
Sheet sheet;
Iterator<Row> rowIterator;
try {
fileInputStream = new FileInputStream(file);
String fileExtension = fileName.substring(fileName.indexOf("."));
System.out.println(fileExtension);
if(fileExtension.equals(".xls")){
workbook = new HSSFWorkbook(new POIFSFileSystem(fileInputStream));
}
else if(fileExtension.equals(".xlsx")){
workbook = new XSSFWorkbook(fileInputStream);
}
else {
System.out.println("Wrong File Type");
}
FormulaEvaluator evaluator workbook.getCreationHelper().createFormulaEvaluator();
sheet = workbook.getSheetAt(0);
rowIterator = sheet.iterator();
while(rowIterator.hasNext()){
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()){
Cell cell = cellIterator.next();
//Check the cell type after evaluating formulae
//If it is formula cell, it will be evaluated otherwise no change will happen
switch (evaluator.evaluateInCell(cell).getCellType()){
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + " ");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + " ");
break;
case Cell.CELL_TYPE_FORMULA:
Not again
break;
case Cell.CELL_TYPE_BLANK:
break;
}
}
System.out.println("\n");
}
//System.out.println(sheet);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}?
You can also try http://image.online-convert.com/convert-to-svg
I always use it for my needs.
here's a regex one for ya.
update table
set col1=null
where col1 not like '%[a-z,0-9]%'
essentially finds any columns that dont have letters or numbers in them and sets it to null. might have to update if you have columns with just special characters.
Ancient topic, if someone still stumbles over this--another workaround is to convert via .astype(str) to string before grouping. That will conserve the NaN's.
df = pd.DataFrame({'a': ['1', '2', '3'], 'b': ['4', np.NaN, '6']})
df['b'] = df['b'].astype(str)
df.groupby(['b']).sum()
a
b
4 1
6 3
nan 2
Based on Ray Nicholus's answer :
inputElement.onchange = function(event) {
var fileList = inputElement.files;
//TODO do something with fileList.
}
using this will also work :
inputElement.onchange = function(event) {
var fileList = event.target.files;
//TODO do something with fileList.
}
None of these answers worked for me. I'm now using:
document.addEventListener('dragleave', function(e){
var top = e.pageY;
var right = document.body.clientWidth - e.pageX;
var bottom = document.body.clientHeight - e.pageY;
var left = e.pageX;
if(top < 10 || right < 20 || bottom < 10 || left < 10){
console.log('Mouse has moved out of window');
}
});
I'm using this for a drag and drop file uploading widget. It's not absolutely accurate, being triggered when the mouse gets to a certain distance from the edge of the window.
Try using this code for v3:
gMap = new google.maps.Map(document.getElementById('map'));
gMap.setZoom(13); // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);
The answer is in the JavaDoc of the equals()
method:
Unlike
compareTo
, this method considers twoBigDecimal
objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).
In other words: equals()
checks if the BigDecimal
objects are exactly the same in every aspect. compareTo()
"only" compares their numeric value.
As to why equals()
behaves this way, this has been answered in this SO question.
One quick way to do this is to create a column with a formula that evaluates to true for the rows you care about and then filter for the value TRUE in that column.
Thought to add this here in case someone finds it useful. @ostrokach already mentioned how you can merge the data frames across rows which is
df_row_merged = pd.concat([df_a, df_b], ignore_index=True)
To merge across columns, you can use the following syntax:
df_col_merged = pd.concat([df_a, df_b], axis=1)
It is possible to handle these exceptions with Thread.setDefaultUncaughtExceptionHandler()
, however this appears to mess with Android's method of handling exceptions. I attempted to use a handler of this nature:
private class ExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread thread, Throwable ex){
Log.e(Constants.TAG, "uncaught_exception_handler: uncaught exception in thread " + thread.getName(), ex);
//hack to rethrow unchecked exceptions
if(ex instanceof RuntimeException)
throw (RuntimeException)ex;
if(ex instanceof Error)
throw (Error)ex;
//this should really never happen
Log.e(Constants.TAG, "uncaught_exception handler: unable to rethrow checked exception");
}
}
However, even with rethrowing the exceptions, I was unable to get the desired behavior, ie logging the exception while still allowing Android to shutdown the component it had happened it, so I gave up on it after a while.
Well, I added
<policy domain="coder" rights="read | write" pattern="PDF" />
just before </policymap>
in /etc/ImageMagick-7/policy.xml
and that makes it work again, but not sure about the security implications of that.
Function
CREATE FUNCTION dbo.SplitToRows (@column varchar(100), @separator varchar(10))
RETURNS @rtnTable TABLE
(
ID int identity(1,1),
ColumnA varchar(max)
)
AS
BEGIN
DECLARE @position int = 0
DECLARE @endAt int = 0
DECLARE @tempString varchar(100)
set @column = ltrim(rtrim(@column))
WHILE @position<=len(@column)
BEGIN
set @endAt = CHARINDEX(@separator,@column,@position)
if(@endAt=0)
begin
Insert into @rtnTable(ColumnA) Select substring(@column,@position,len(@column)-@position)
break;
end
set @tempString = substring(ltrim(rtrim(@column)),@position,@endAt-@position)
Insert into @rtnTable(ColumnA) select @tempString
set @position=@endAt+1;
END
return
END
Use case
select * from dbo.SplitToRows('T14; p226.0001; eee; 3554;', ';')
Or just a select with multiple result set
DECLARE @column varchar(max)= '1234; 4748;abcde; 324432'
DECLARE @separator varchar(10) = ';'
DECLARE @position int = 0
DECLARE @endAt int = 0
DECLARE @tempString varchar(100)
set @column = ltrim(rtrim(@column))
WHILE @position<=len(@column)
BEGIN
set @endAt = CHARINDEX(@separator,@column,@position)
if(@endAt=0)
begin
Select substring(@column,@position,len(@column)-@position)
break;
end
set @tempString = substring(ltrim(rtrim(@column)),@position,@endAt-@position)
select @tempString
set @position=@endAt+1;
END
It's because you're trying to assign an object by reference. Remove the ampersand and your script should work as intended.
I believe the approach:
is pretty standard, regardless of how you implement and other specific technical details.
If you really want to push the envelope, perhaps you could regard the client's https key in a temporarily invalid state until the credentials are validated, limit information if they never are, and grant access when they are validated, based again on expiration.
Hope this helps
str.isspace() returns False
for a valid and empty string
>>> tests = ['foo', ' ', '\r\n\t', '']
>>> print([s.isspace() for s in tests])
[False, True, True, False]
Therefore, checking with not
will also evaluate None
Type and ''
or ""
(empty string)
>>> tests = ['foo', ' ', '\r\n\t', '', None, ""]
>>> print ([not s or s.isspace() for s in tests])
[False, True, True, True, True, True]
Configuring a working email client from localhost
is quite a chore, I have spent hours of frustration attempting it. At last I have found this way to send mails (using WAMP, XAMPP, etc.):
Configure this hMailServer setting:
Configure your Gmail account, perform following modification:
If you want to send email from another computer you need to allow deliveries from External to External accounts by following steps:
Either You can use LinkedHashMap<K, V>
or you can implement you own CustomMap which maintains insertion order.
You can use the Following CustomHashMap
with the following features:
null
or empty strings are not allowed.HashMap
vs LinkedHashMap
vs CustomHashMap
interface CustomMap<K, V> extends Map<K, V> {
public boolean insertionRule(K key, V value);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public class CustomHashMap<K, V> implements CustomMap<K, V> {
private Map<K, V> entryMap;
// SET: Adds the specified element to this set if it is not already present.
private Set<K> entrySet;
public CustomHashMap() {
super();
entryMap = new LinkedHashMap<K, V>();
entrySet = new HashSet();
}
@Override
public boolean insertionRule(K key, V value) {
// KEY as null and EMPTY String is not allowed.
if (key == null || (key instanceof String && ((String) key).trim().equals("") ) ) {
return false;
}
// If key already available then, we are not overriding its value.
if (entrySet.contains(key)) { // Then override its value, but we are not allowing
return false;
} else { // Add the entry
entrySet.add(key);
entryMap.put(key, value);
return true;
}
}
public V put(K key, V value) {
V oldValue = entryMap.get(key);
insertionRule(key, value);
return oldValue;
}
public void putAll(Map<? extends K, ? extends V> t) {
for (Iterator i = t.keySet().iterator(); i.hasNext();) {
K key = (K) i.next();
insertionRule(key, t.get(key));
}
}
public void clear() {
entryMap.clear();
entrySet.clear();
}
public boolean containsKey(Object key) {
return entryMap.containsKey(key);
}
public boolean containsValue(Object value) {
return entryMap.containsValue(value);
}
public Set entrySet() {
return entryMap.entrySet();
}
public boolean equals(Object o) {
return entryMap.equals(o);
}
public V get(Object key) {
return entryMap.get(key);
}
public int hashCode() {
return entryMap.hashCode();
}
public boolean isEmpty() {
return entryMap.isEmpty();
}
public Set keySet() {
return entrySet;
}
public V remove(Object key) {
entrySet.remove(key);
return entryMap.remove(key);
}
public int size() {
return entryMap.size();
}
public Collection values() {
return entryMap.values();
}
}
Usage of CustomHashMap
:
public static void main(String[] args) {
System.out.println("== LinkedHashMap ==");
Map<Object, String> map2 = new LinkedHashMap<Object, String>();
addData(map2);
System.out.println("== CustomHashMap ==");
Map<Object, String> map = new CustomHashMap<Object, String>();
addData(map);
}
public static void addData(Map<Object, String> map) {
map.put(null, "1");
map.put("name", "Yash");
map.put("1", "1 - Str");
map.put("1", "2 - Str"); // Overriding value
map.put("", "1"); // Empty String
map.put(" ", "1"); // Empty String
map.put(1, "Int");
map.put(null, "2"); // Null
for (Map.Entry<Object, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
}
O/P:
== LinkedHashMap == | == CustomHashMap ==
null = 2 | name = Yash
name = Yash | 1 = 1 - Str
1 = 2 - Str | 1 = Int
= 1 |
= 1 |
1 = Int |
If you know the KEY's are fixed then you can use EnumMap. Get the values form Properties/XML files
EX:
enum ORACLE {
IP, URL, USER_NAME, PASSWORD, DB_Name;
}
EnumMap<ORACLE, String> props = new EnumMap<ORACLE, String>(ORACLE.class);
props.put(ORACLE.IP, "127.0.0.1");
props.put(ORACLE.URL, "...");
props.put(ORACLE.USER_NAME, "Scott");
props.put(ORACLE.PASSWORD, "Tiget");
props.put(ORACLE.DB_Name, "MyDB");
Bootstrap 4 removed .btn-group-justified. As a replacement you can use <div class="btn-group d-flex" role="group"></div>
as a wrapper around elements with .w-100.
Try this:
<div class="btn-group d-flex" role="group>
<button type="button" class="btn btn-primary w-100">Submit</button>
<button type="button" class="btn btn-primary w-100">Cancel</button>
</div>
If program name is always the first thing in (), and doesn't contain other )s than the one at end, then $yourstring -match "[(][^)]+[)]"
does the matching, result will be in $Matches[0]
In answer to your first question, there's no parameter substitution because you've put the delimiter in quotes - the bash manual says:
The format of here-documents is:
<<[-]word here-document delimiter
No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on word. If any characters in word are quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion. [...]
If you change your first example to use <<EOF
instead of << "EOF"
you'll find that it works.
In your second example, the shell invokes sudo
only with the parameter cat
, and the redirection applies to the output of sudo cat
as the original user. It'll work if you try:
sudo sh -c "cat > /path/to/outfile" <<EOT
my text...
EOT
Assumptions: x
is the horizontal axis, and increases when moving from left to right.
y
is the vertical axis, and increases from bottom to top. (touch_x, touch_y)
is the
point selected by the user. (center_x, center_y)
is the point at the center of the
screen. theta
is measured counter-clockwise from the +x
axis. Then:
delta_x = touch_x - center_x
delta_y = touch_y - center_y
theta_radians = atan2(delta_y, delta_x)
Edit: you mentioned in a comment that y increases from top to bottom. In that case,
delta_y = center_y - touch_y
But it would be more correct to describe this as expressing (touch_x, touch_y)
in polar coordinates relative to (center_x, center_y)
. As ChrisF mentioned,
the idea of taking an "angle between two points" is not well defined.
function first_last_day($string, $first_last, $format) {
$result = strtotime($string);
$year = date('Y',$result);
$month = date('m',$result);
$result = strtotime("{$year}-{$month}-01");
if ($first_last == 'last'){$result = strtotime('-1 second', strtotime('+1 month', $result)); }
if ($format == 'unix'){return $result; }
if ($format == 'standard'){return date('Y-m-d', $result); }
}
SELECT id, GROUP_CONCAT(name SEPARATOR ' ') FROM table GROUP BY id;
https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat
From the link above, GROUP_CONCAT
: This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values.
I suggest Oj as it is waaaaaay faster than the standard JSON library.
i've resolved with
sudo dpkg-reconfigure phpmyadmin
I had the same solution as gregpress answer, but my draggable items used a class instead of an id. It seems to work.
var $target = $(event.target);
if( $target.hasClass('draggable') ) {
event.preventDefault();
}
When you use a string literal the string can be interned, but when you use new String("...")
you get a new string object.
In this example both string literals refer the same object:
String a = "abc";
String b = "abc";
System.out.println(a == b); // true
Here, 2 different objects are created and they have different references:
String c = new String("abc");
String d = new String("abc");
System.out.println(c == d); // false
In general, you should use the string literal notation when possible. It is easier to read and it gives the compiler a chance to optimize your code.
usually i don't use for loop in R, but here is my solution using for loops and two packages : plyr and dostats
plyr is on cran and you can download dostats on https://github.com/halpo/dostats (may be using install_github from Hadley devtools package)
Assuming that i have your first two data.frame (Df.1 and Df.2) in csv files, you can do something like this.
require(plyr)
require(dostats)
files <- list.files(pattern = ".csv")
for (i in seq_along(files)) {
assign(paste("Df", i, sep = "."), read.csv(files[i]))
assign(paste(paste("Df", i, sep = ""), "summary", sep = "."),
ldply(get(paste("Df", i, sep = ".")), dostats, sum, min, mean, median, max))
}
Here is the output
R> Df1.summary
.id sum min mean median max
1 A 34 4 5.6667 5.5 8
2 B 22 1 3.6667 3.0 9
R> Df2.summary
.id sum min mean median max
1 A 21 1 3.5000 3.5 6
2 B 16 1 2.6667 2.5 5
For those using jQuery there's a convenient method: http://api.jquery.com/change/
According to this, you need to assign a height to the element in which the div is contained in order for 100% height to work. Does that work for you?
I won't write your code but what you looking for is something like a jquery dialog
take a look here
$(function() {
$( "#dialog-confirm" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Delete all items": function() {
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
<div id="dialog-confirm" title="Empty the recycle bin?">
<p>
<span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>
These items will be permanently deleted and cannot be recovered. Are you sure?
</p>
</div>
This is a mistake:
m.check(side);
That code has to go inside a function. Your class definition can only contain declarations and functions.
Classes don't "run", they provide a blueprint for how to make an object.
The line Message m;
means that an Orderbook
will contain Message
called m
, if you later create an Orderbook
.
If you need the context of A in B, you need to pass it to B, and you can do that by passing the Activity A as parameter as others suggested. I do not see much the problem of having the many instances of A having their own pointers to B, not sure if that would even be that much of an overhead.
But if that is the problem, a possibility is to keep the pointer to A as a sort of global, avariable of the Application
class, as @hasanghaforian suggested. In fact, depending on what do you need the context for, you could even use the context of the Application
instead.
I'd suggest reading this article about context to better figure it out what context you need.
Remove trailing \r
character that causes this error:
sed -i 's/\r$//' filename
Explanation:
Option -i
is for in-place editing, we delete the trailing \r
directly in the input file. Thus be careful to type the pattern correctly.
If you look at the PHP constant PATH_SEPARATOR, you will see it being ":" for you.
If you break apart your string ".:/usr/share/pear:/usr/share/php" using that character, you will get 3 parts.
Any attempts to include()/require() things, will look in these directories, in this order.
It is showing you that in the error message to let you know where it could NOT find the file you were trying to require()
For your first require, if that is being included from your index.php, then you dont need the dir stuff, just do...
require_once ( 'db/config.php');
"use strict";
Basically it enables the strict mode.
Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.
As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.
So, there will be no major difference how "use strict";
is interpreted by the Chrome browser and Node.js.
Please read what is strict mode in JavaScript.
For more information:
ECMAScript 6 Code & strict mode. Following is brief from the specification:
10.2.1 Strict Mode Code
An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:
- Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
- Module code is always strict mode code.
- All parts of a ClassDeclaration or a ClassExpression are strict mode code.
- Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
- Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
- Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.
Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).
For each Tensorflow's version, it requires different version of CuDnn. On www.tensorflow.org, they did not mentioned about that in installation guide!
My case use tensorflow version 1.3 which uses cuDNN 6. https://github.com/tensorflow/tensorflow/releases.
Please check your tensorfow version and cuDNN version if they are match together.
And please set path environment for cuDNN, if it still does not work, please check the answer from @Chris Han.
This is the answer:
numCols = objSheet.UsedRange.Columns.count
Here's a simple function that lets you do what you are looking for:
- (NSString *)getSubstring:(NSString *)value betweenString:(NSString *)separator
{
NSRange firstInstance = [value rangeOfString:separator];
NSRange secondInstance = [[value substringFromIndex:firstInstance.location + firstInstance.length] rangeOfString:separator];
NSRange finalRange = NSMakeRange(firstInstance.location + separator.length, secondInstance.location);
return [value substringWithRange:finalRange];
}
Usage:
NSString *myName = [self getSubstring:@"This is my :name:, woo!!" betweenString:@":"];
Generally, I'd prefer not using GoTo for bad readability. To me, it's a bad excuse for programming simple iterative functions instead of having to program recursive functions, or even better (if things like a Stack Overflow is feared), their true iterative alternatives (which may sometimes be complex).
Something like this would do:
while(true) {
alert("RINSE");
alert("LATHER");
}
That right there is an infinite loop. The expression ("true") inside the parantheses of the while clause is what the Javascript engine will check for - and if the expression is true, it'll keep the loop running. Writing "true" here always evaluates to true, hence an infinite loop.
According to the Apache Tomcat docs, you can change the application by creating a ROOT.xml file. See this for more info:
http://tomcat.apache.org/tomcat-6.0-doc/config/context.html
"The default web application may be defined by using a file called ROOT.xml."
What you're missing: Zero is a value
Hope this helps;
df1 = data.frame(CustomerId=c(1:10),
Hobby = c(rep("sing", 4), rep("pingpong", 3), rep("hiking", 3)),
Product=c(rep("Toaster",3),rep("Phone", 2), rep("Radio",3), rep("Stereo", 2)))
df2 = data.frame(CustomerId=c(2,4,6, 8, 10),State=c(rep("Alabama",2),rep("Ohio",1), rep("Cal", 2)),
like=c("sing", 'hiking', "pingpong", 'hiking', "sing"))
df3 = merge(df1, df2, by.x=c("CustomerId", "Hobby"), by.y=c("CustomerId", "like"))
Assuming df1$Hobby
and df2$like
mean the same thing.
Solutions:
Solution A:
com.oreilly.servlet.MultipartRequest
Solution B:
org.apache.commons.fileupload.MultipartStream
Solution C:
Solution D:
Use Struts. Struts 1.1 handles this automatically.
My suggestion would be
$value = $_POST["myfield"];
$Query = Database::Prepare("SELECT * FROM TABLE WHERE MYFIELD LIKE ?");
$Query->Execute(array("%".$value."%"));
There's also the rather low-tech solution of counting adding spaces by hand to make your messages line up. Nothing prevents you from including a few trailing spaces in your message strings.
I was able to get mine working using the following Client Credentials:
Authorized JavaScript origins
http://localhost
Authorized redirect URIs
http://localhost:8090/oauth2callback
Note: I used port 8090 instead of 8080, but that doesn't matter as long as your python script uses the same port as your client_secret.json file.
Reference: Python Quickstart
Try using input arrays:
<form action="try.php" method="post">
<div id="events_wrapper">
<div id="sub_events">
<input type="text" name="firstname[]" />
</div>
</div>
<input type="button" id="add_another_event" name="add_another_event" value="Add Another" />
<input type="submit" name="submit" value="submit" />
</form>
and add this script and jQuery, using foreach() to retrieve the data being $_POST'ed:
<script>
$(document).ready(function(){
$("#add_another_event").click(function(){
var $address = $('#sub_events');
var num = $('.clonedAddress').length; // there are 5 children inside each address so the prevCloned address * 5 + original
var newNum = num + 1;
var newElem = $address.clone().attr('id', 'address' + newNum).addClass('clonedAddress');
//set all div id's and the input id's
newElem.children('div').each (function (i) {
this.id = 'input' + (newNum*5 + i);
});
newElem.find('input').each (function () {
this.id = this.id + newNum;
this.name = this.name + newNum;
});
if (num > 0) {
$('.clonedAddress:last').after(newElem);
} else {
$address.after(newElem);
}
$('#btnDel').removeAttr('disabled');
});
$("#remove").click(function(){
});
});
</script>
If the images are generated via an ASP Response.Write()
, make sure you don't call Response.Close();
. Chrome doesn't like it.
Try using BindingExpression.UpdateTarget()
exec does not execute a command in your shell
try
Process p = Runtime.getRuntime().exec(new String[]{"csh","-c","cat /home/narek/pk.txt"});
instead.
EDIT:: I don't have csh on my system so I used bash instead. The following worked for me
Process p = Runtime.getRuntime().exec(new String[]{"bash","-c","ls /home/XXX"});
Dim filepath as string
Sheets("Sheet 1").ChartObjects("Chart 1").Chart.Export filepath & "Name.jpg"
Slimmed down the code to the absolute minimum if needed.
*Gradle Repository for the Facebook SDK.
dependencies {
compile 'com.facebook.android:facebook-android-sdk:4.4.0'
}
I guess I am coming late, but this info might be useful to anyone I found out something, which might be simple but important. if you use export on a function directly i.e
export const addPost = (id) =>{
...
}
Note while importing you need to wrap it in curly braces
i.e. import {addPost} from '../URL';
But when using export default i.e
const addPost = (id) =>{
...
}
export default addPost
,
Then you can import without curly braces i.e.
import addPost from '../url';
export default addPost
I hope this helps anyone who got confused as me.
Not clear where My_ConnectionString
is coming from in your example, but try this
System.Configuration.ConfigurationManager.ConnectionStrings("My_ConnectionString").ConnectionString
like this
Dim DBConnection As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("My_ConnectionString").ConnectionString)
public static int random_int(int Min, int Max)
{
return (int) (Math.random()*(Max-Min))+Min;
}
random_int(5, 9); // For example
Update: This will create a second context same as in applicationContext.xml
or you can add this code snippet to your web.xml
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
instead of
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
We can use following code
textBox1.DataBindings.Add("Text", model, "Name", false, DataSourceUpdateMode.OnPropertyChanged);
Where
"Text"
– the property of textbox model
– the model object enter code here "Name"
– the value of model which to bind the textbox.In macOS 10.14 this issue may also occur if you have two or more versions installed. If you like xCode GUI you can do it by going into preferences - CMD + ,
, selecting Locations
tab and choosing version of Command Line Tools. Please refer to the attached print screen.
You can use template module to copy if script exists on local machine to remote machine and execute it.
- name: Copy script from local to remote machine
hosts: remote_machine
tasks:
- name: Copy script to remote_machine
template: src=script.sh.2 dest=<remote_machine path>/script.sh mode=755
- name: Execute script on remote_machine
script: sh <remote_machine path>/script.sh
Your quotes only need to surround the value part of the attribute-equals selector, [attr='val']
, like this:
$('a#check_var').click(function() {
alert($("input:radio[name='r']:checked").val()+ ' '+
$("input:radio[name='s']:checked").val());
});?
For PHP7 and Apache2.4, this is all you need to do:
sudo vim /etc/httpd/conf/httpd.conf
Go to the very bottom and insert the following (all by itself):
<FilesMatch "\.*">
SetHandler application/x-httpd-php
</FilesMatch>
Then, restart Apache to load the new configuration:
sudo service httpd restart
Apache will now execute all HTTP/S requests with PHP. If all you have are html, css, and php files, then this will work fine for you. If you have other languages running, then you'll need to tailor the file matching to your situation. I've tested this with phpMyAdmin and it works fine.
None of that other stuff all the people are talking about here was necessary for me. When I put the "AddType Application....." thing in the correct spot, Apache just told me that that module was already loaded and skipped it.
More information can be found here: https://httpd.apache.org/docs/2.4/mod/core.html#filesmatch
My install was done as follows:
sudo yum install -y httpd24 php70 mysql56-server php70-mysqlnd
You should also read this, if you haven't: https://httpd.apache.org/docs/current/howto/htaccess.html#when
There is a library that will do all of this for you, check out mongoose-paginate-v2
This is a very late response, but adds some detail on the previous answers
When it comes to calling static methods in PHP from another static method on the same class, it is important to differentiate between self
and the class name.
Take for instance this code:
class static_test_class {
public static function test() {
echo "Original class\n";
}
public static function run($use_self) {
if($use_self) {
self::test();
} else {
$class = get_called_class();
$class::test();
}
}
}
class extended_static_test_class extends static_test_class {
public static function test() {
echo "Extended class\n";
}
}
extended_static_test_class::run(true);
extended_static_test_class::run(false);
The output of this code is:
Original class
Extended class
This is because self
refers to the class the code is in, rather than the class of the code it is being called from.
If you want to use a method defined on a class which inherits the original class, you need to use something like:
$class = get_called_class();
$class::function_name();
I know this is an older question but this past week I started to get a similar problem, so I leave here some notes regarding the solution that fits me.
This happened only in some Windows machines using even the last JRE to date (1.8.0_45).
The Java Web Start started to load but nothing happened and none of the previous solution attempts worked.
After some digging i've found this thread, which gives the same setup and a great explanation.
https://community.oracle.com/thread/3676876
So, in conclusion, it was a memory problem in x86 JRE and since our JNLP's max heap was defined as 1024MB, we changed to 780MB as suggested and it was fixed.
However, if you need more than 780MB, can always try launching in a x64 JRE version.
I found that my problem was that the server I've sent the cross request to had a certificate that was not trusted.
If you want to connect to a cross domain with https
, you have to add an exception for this certificate first.
You can do this by visiting the blocked link once and addibng the exception.
Due to the mixed comments about BuildConfig.DEBUG
, I used the following to disable crashlytics (and analytics) in debug mode :
update /app/build.gradle
android {
compileSdkVersion 25
buildToolsVersion "25.0.1"
defaultConfig {
applicationId "your.awesome.app"
minSdkVersion 16
targetSdkVersion 25
versionCode 100
versionName "1.0.0"
buildConfigField 'boolean', 'ENABLE_CRASHLYTICS', 'true'
}
buildTypes {
debug {
debuggable true
minifyEnabled false
buildConfigField 'boolean', 'ENABLE_CRASHLYTICS', 'false'
}
release {
debuggable false
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
then, in your code you detect the ENABLE_CRASHLYTICS
flag as follows:
if (BuildConfig.ENABLE_CRASHLYTICS)
{
// enable crashlytics and answers (Crashlytics by default includes Answers)
Fabric.with(this, new Crashlytics());
}
use the same concept in your app and rename ENABLE_CRASHLYTICS
to anything you want. I like this approach because I can see the flag in the configuration and I can control the flag.
You can use in this way using bootstrap css. Just remove the active class if already assinged to any row and reassign to the current row.
$(".table tr").each(function () {
$(this).attr("class", "");
});
$(this).attr("class", "active");
Maybe the best idea is to solve the problem while the data is in String format. If you have the data as String, you may parse it according to the decimal point. You extract the integral and decimal part as Substrings and then convert these substrings to actual integers.
A couple of relevant links:
For a while, I was following the development of Reia, which was initially going to have Python's indentation based syntax with Ruby blocks too, all on top of Erlang. But, the designer wound up giving up on indentation sensitivity, and this post he wrote about that decision includes a discussion about problems he ran into with indentation + multi-line blocks, and an increased appreciation he gained for Guido's design issues/decisions:
http://www.unlimitednovelty.com/2009/03/indentation-sensitivity-post-mortem.html
Also, here's an interesting proposal for Ruby-style blocks in Python I ran across where Guido posts a response w/o actually shooting it down (not sure whether there has been any subsequent shoot down, though):
Next up, I wanted to host node as a service, just like IIS. This way it’d start up with my machine, run in the background, restart automatically if it crashes and so forth.
This is where nssm, the non-sucking service manager, enters the picture. This tool lets you host a normal .exe as a Windows service.
Here are the commands I used to setup an instance of the your node application as a service, open your cmd like administrator and type following commands:
nssm.exe install service_name c:\your_nodejs_directory\node.exe c:\your_application_directory\server.js net start service_name
You can use jQuery change() function
$('input').change(function(){
//your codes
});
There are examples on how to use it on the API Page: http://api.jquery.com/change/
The answer shared by Paul is the best one. To expand more,
There can be only one default export per file. Whereas there can be more than one const exports. The default variable can be imported with any name, whereas const variable can be imported with it's particular name.
var message2 = 'I am exported';
export default message2;
export const message = 'I am also exported'
At the imports side we need to import it like this:
import { message } from './test';
or
import message from './test';
With the first import, the const variable is imported whereas, with the second one, the default one will be imported.
As you've noticed, you have no selectivity to your update statement so it is updating your entire table. If you want to update specific rows (ie where the IDs match) you probably want to do a coordinated subquery.
However, since you are using Oracle, it might be easier to create a materialized view for your query table and let Oracle's transaction mechanism handle the details. MVs work exactly like a table for querying semantics, are quite easy to set up, and allow you to specify the refresh interval.
You can do this if you use an <a>
tag instead of a button. I know it's not exactly what you asked for, but it might give you some other options if you cannot find a solution to this:
Borrowing from a demo from another answer here I produced this:
a {_x000D_
display: block;_x000D_
font-size: 18px;_x000D_
border: 2px solid gray;_x000D_
border-radius: 100px;_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
text-align: center;_x000D_
line-height: 100px;_x000D_
}_x000D_
_x000D_
a:active {_x000D_
font-size: 18px;_x000D_
border: 2px solid green;_x000D_
border-radius: 100px;_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
}_x000D_
_x000D_
a:target {_x000D_
font-size: 18px;_x000D_
border: 2px solid red;_x000D_
border-radius: 100px;_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
}
_x000D_
<a id="btn" href="#btn">Demo</a>
_x000D_
Notice the use of :target
; this will be the style applied when the element is targeted via the hash. Which also means your HTML will need to be this: <a id="btn" href="#btn">Demo</a>
a link targeting itself. and the demo http://jsfiddle.net/rlemon/Awdq5/4/
Thanks to @BenjaminGruenbaum here is a better demo: http://jsfiddle.net/agzVt/
Also, as a footnote: this should really be done with JavaScript and applying / removing CSS classes from the element. It would be much less convoluted.
http://gallery.technet.microsoft.com/scriptcenter/Invoke-Async-Allows-you-to-83b0c9f0
i created an invoke-async which allows you do run multiple script blocks/cmdlets/functions at the same time. this is great for small jobs (subnet scan or wmi query against 100's of machines) because the overhead for creating a runspace vs the startup time of start-job is pretty drastic. It can be used like so.
with scriptblock,
$sb = [scriptblock] {param($system) gwmi win32_operatingsystem -ComputerName $system | select csname,caption}
$servers = Get-Content servers.txt
$rtn = Invoke-Async -Set $server -SetParam system -ScriptBlock $sb
just cmdlet/function
$servers = Get-Content servers.txt
$rtn = Invoke-Async -Set $servers -SetParam computername -Params @{count=1} -Cmdlet Test-Connection -ThreadCount 50
You can try this it will recursively find all key values in a json object and constructs as a map . You can simply get which key you want from the Map .
public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
Iterator<String> keys = json.keys();
while(keys.hasNext()){
String key = keys.next();
String val = null;
try{
JSONObject value = json.getJSONObject(key);
parse(value,out);
}catch(Exception e){
val = json.getString(key);
}
if(val != null){
out.put(key,val);
}
}
return out;
}
public static void main(String[] args) throws JSONException {
String json = "{'ipinfo': {'ip_address': '131.208.128.15','ip_type': 'Mapped','Location': {'continent': 'north america','latitude': 30.1,'longitude': -81.714,'CountryData': {'country': 'united states','country_code': 'us'},'region': 'southeast','StateData': {'state': 'florida','state_code': 'fl'},'CityData': {'city': 'fleming island','postal_code': '32003','time_zone': -5}}}}";
JSONObject object = new JSONObject(json);
JSONObject info = object.getJSONObject("ipinfo");
Map<String,String> out = new HashMap<String, String>();
parse(info,out);
String latitude = out.get("latitude");
String longitude = out.get("longitude");
String city = out.get("city");
String state = out.get("state");
String country = out.get("country");
String postal = out.get("postal_code");
System.out.println("Latitude : " + latitude + " LongiTude : " + longitude + " City : "+city + " State : "+ state + " Country : "+country+" postal "+postal);
System.out.println("ALL VALUE " + out);
}
Output:
Latitude : 30.1 LongiTude : -81.714 City : fleming island State : florida Country : united states postal 32003
ALL VALUE {region=southeast, ip_type=Mapped, state_code=fl, state=florida, country_code=us, city=fleming island, country=united states, time_zone=-5, ip_address=131.208.128.15, postal_code=32003, continent=north america, longitude=-81.714, latitude=30.1}