bean.xhtml
<h:form enctype="multipart/form-data">
<p:outputLabel value="Choose your file" for="submissionFile" />
<p:fileUpload id="submissionFile"
value="#{bean.file}"
fileUploadListener="#{bean.uploadFile}" mode="advanced"
auto="true" dragDropSupport="false" update="messages"
sizeLimit="100000" fileLimit="1" allowTypes="/(\.|\/)(pdf)$/" />
</h:form>
Bean.java
@ManagedBean
@ViewScoped public class Submission implements Serializable {
private UploadedFile file;
//Gets
//Sets
public void uploadFasta(FileUploadEvent event) throws FileNotFoundException, IOException, InterruptedException {
String content = IOUtils.toString(event.getFile().getInputstream(), "UTF-8");
String filePath = PATH + "resources/submissions/" + nameOfMyFile + ".pdf";
MyFileWriter.writeFile(filePath, content);
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
event.getFile().getFileName() + " is uploaded.", null);
FacesContext.getCurrentInstance().addMessage(null, message);
}
}
web.xml
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
Any one looking for a swift solution
let url = NSURL(string: "http://www.apple.com/")
let request = NSMutableURLRequest(URL: url!)
request.HTTPBody = "company=Locassa&quality=AWESOME!".dataUsingEncoding(NSUTF8StringEncoding)
You can't have private
class but you can have second
class:
public class App14692708 {
public static void main(String[] args) {
PC pc = new PC();
System.out.println(pc);
}
}
class PC {
@Override
public String toString() {
return "I am PC instance " + super.toString();
}
}
Also remember that static
inner class is indistinguishable of separate class except it's name is OuterClass.InnerClass
. So if you don't want to use "closures", use static inner class.
Just like Nasser, I know this was a while ago but I wanted to post my solution for anyone who has this problem in the future.
I had my report setup so that it would use a data connection in a Data Connection library hosted on SharePoint. My issue was that I did not have the data connection 'approved' so that it was usable by other users.
Another thing to look for would to make sure that the permissions on that Data Connection library also allows read to the select users.
Hope this helps someone sooner or later!
Use SpecialCells to delete only the rows that are visible after autofiltering:
ActiveSheet.Range("$A$1:$I$" & lines).SpecialCells _
(xlCellTypeVisible).EntireRow.Delete
If you have a header row in your range that you don't want to delete, add an offset to the range to exclude it:
ActiveSheet.Range("$A$1:$I$" & lines).Offset(1, 0).SpecialCells _
(xlCellTypeVisible).EntireRow.Delete
"Knowing about sites which handles such massive traffic gives lots of pointers for architects etc. to keep in mind certain stuff while designing new sites"
I think you can probably learn a lot from the design of Facebook, just as you can from the design of any successful large software system. However, it seems to me that you should not keep the current design of Facebook in mind when designing new systems.
Why do you want to be able to handle the traffic that Facebook has to handle? Odds are that you will never have to, no matter how talented a programmer you may be. Facebook itself was not designed from the start for such massive scalability, which is perhaps the most important lesson to learn from it.
If you want to learn about a non-trivial software system I can recommend the book "Dissecting a C# Application" about the development of the SharpDevelop IDE. It is out of print, but it is available for free online. The book gives you a glimpse into a real application and provides insights about IDEs which are useful for a programmer.
using XML, you need to set the onclick listener yourself. First have your class implements OnClickListener
then add the variable Button button1;
then add this to your onCreate()
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);
when you implement OnClickListener you need to add the inherited method onClick()
where you will handle your clicks
For MS SQL 2016, passing ints into the in, it looks like it can handle close to 38,000 records.
select * from user where userId in (1,2,3,etc)
In my case it was:
Persist Security Info=True;
in my connection string that needed to be removed. Once I did that I no longer had issues.
List<Integer> listA = new ArrayList<>();
listA.add(1);
listA.add(5);
listA.add(3);
listA.add(4);
List<Integer> listB = new ArrayList<>();
listB.add(1);
listB.add(5);
listB.add(6);
listB.add(7);
System.out.println(listA.stream().filter(listB::contains).collect(Collectors.toList()));
Java 1.8 Stream API Solutions
Output [1, 5]
Windows->Preferences->Server
Server Timeout can be specified there.
or another method via the Servers tab here:
http://henneberke.wordpress.com/2009/09/28/fixing-eclipse-tomcat-timeout/
if you want put a input required if other is written:
<input type='text'
name='name'
ng-model='person.name'/>
<input type='text'
ng-model='person.lastname'
ng-required='person.name' />
Regards.
At least in python3, this works:
>>> datetime.strftime(datetime.utcnow(), "%s")
'1587503279'
List of Special Character codes in JavaScript:
Code Outputs
\' single quote
\" double quote
\\ backslash
\n new line
\r carriage return
\t tab
\b backspace
\f form feed
Instead of
var bottom = $(window).height() - link.height();
bottom = offset.top - bottom;
Why aren't you doing
var bottom = $(window).height() - top - link.height();
Edit: Your mistake is that you're doing
bottom = offset.top - bottom;
instead of
bottom = bottom - offset.top; // or bottom -= offset.top;
There is an issue with placing using statements inside the namespace when you wish to use aliases. The alias doesn't benefit from the earlier using
statements and has to be fully qualified.
Consider:
namespace MyNamespace
{
using System;
using MyAlias = System.DateTime;
class MyClass
{
}
}
versus:
using System;
namespace MyNamespace
{
using MyAlias = DateTime;
class MyClass
{
}
}
This can be particularly pronounced if you have a long-winded alias such as the following (which is how I found the problem):
using MyAlias = Tuple<Expression<Func<DateTime, object>>, Expression<Func<TimeSpan, object>>>;
With using
statements inside the namespace, it suddenly becomes:
using MyAlias = System.Tuple<System.Linq.Expressions.Expression<System.Func<System.DateTime, object>>, System.Linq.Expressions.Expression<System.Func<System.TimeSpan, object>>>;
Not pretty.
If you have the column it's very easy.
Using the designer, you could set the column as an identity (1,1): right click on the table ? design ? in part left (right click) ? properties ? in identity columns, select #column.
Properties:
Identity column:
Issue the following command to reseed mytable to start at 1:
DBCC CHECKIDENT (mytable, RESEED, 0)
Read about it in the Books on Line (BOL, SQL help). Also be careful that you don't have records higher than the seed you are setting.
You are using a wrong overload of the Html.ActionLink
helper. What you think is routeValues
is actually htmlAttributes
! Just look at the generated HTML, you will see that this anchor's href property doesn't look as you expect it to look.
Here's what you are using:
@Html.ActionLink(
"Reply", // linkText
"BlogReplyCommentAdd", // actionName
"Blog", // routeValues
new { // htmlAttributes
blogPostId = blogPostId,
replyblogPostmodel = Model,
captchaValid = Model.AddNewComment.DisplayCaptcha
}
)
and here's what you should use:
@Html.ActionLink(
"Reply", // linkText
"BlogReplyCommentAdd", // actionName
"Blog", // controllerName
new { // routeValues
blogPostId = blogPostId,
replyblogPostmodel = Model,
captchaValid = Model.AddNewComment.DisplayCaptcha
},
null // htmlAttributes
)
Also there's another very serious issue with your code. The following routeValue:
replyblogPostmodel = Model
You cannot possibly pass complex objects like this in an ActionLink. So get rid of it and also remove the BlogPostModel
parameter from your controller action. You should use the blogPostId
parameter to retrieve the model from wherever this model is persisted, or if you prefer from wherever you retrieved the model in the GET action:
public ActionResult BlogReplyCommentAdd(int blogPostId, bool captchaValid)
{
BlogPostModel model = repository.Get(blogPostId);
...
}
As far as your initial problem is concerned with the wrong overload I would recommend you writing your helpers using named parameters:
@Html.ActionLink(
linkText: "Reply",
actionName: "BlogReplyCommentAdd",
controllerName: "Blog",
routeValues: new {
blogPostId = blogPostId,
captchaValid = Model.AddNewComment.DisplayCaptcha
},
htmlAttributes: null
)
Now not only that your code is more readable but you will never have confusion between the gazillions of overloads that Microsoft made for those helpers.
I've had a go at putting together a multiprocessing example of file text searching. This is my first effort at using the multiprocessing module; and I'm a python n00b. Comments quite welcome. I'll have to wait until at work to test on really big files. It should be faster on multi core systems than single core searching. Bleagh! How do I stop the processes once the text has been found and reliably report line number?
import multiprocessing, os, time
NUMBER_OF_PROCESSES = multiprocessing.cpu_count()
def FindText( host, file_name, text):
file_size = os.stat(file_name ).st_size
m1 = open(file_name, "r")
#work out file size to divide up to farm out line counting
chunk = (file_size / NUMBER_OF_PROCESSES ) + 1
lines = 0
line_found_at = -1
seekStart = chunk * (host)
seekEnd = chunk * (host+1)
if seekEnd > file_size:
seekEnd = file_size
if host > 0:
m1.seek( seekStart )
m1.readline()
line = m1.readline()
while len(line) > 0:
lines += 1
if text in line:
#found the line
line_found_at = lines
break
if m1.tell() > seekEnd or len(line) == 0:
break
line = m1.readline()
m1.close()
return host,lines,line_found_at
# Function run by worker processes
def worker(input, output):
for host,file_name,text in iter(input.get, 'STOP'):
output.put(FindText( host,file_name,text ))
def main(file_name,text):
t_start = time.time()
# Create queues
task_queue = multiprocessing.Queue()
done_queue = multiprocessing.Queue()
#submit file to open and text to find
print 'Starting', NUMBER_OF_PROCESSES, 'searching workers'
for h in range( NUMBER_OF_PROCESSES ):
t = (h,file_name,text)
task_queue.put(t)
#Start worker processes
for _i in range(NUMBER_OF_PROCESSES):
multiprocessing.Process(target=worker, args=(task_queue, done_queue)).start()
# Get and print results
results = {}
for _i in range(NUMBER_OF_PROCESSES):
host,lines,line_found = done_queue.get()
results[host] = (lines,line_found)
# Tell child processes to stop
for _i in range(NUMBER_OF_PROCESSES):
task_queue.put('STOP')
# print "Stopping Process #%s" % i
total_lines = 0
for h in range(NUMBER_OF_PROCESSES):
if results[h][1] > -1:
print text, 'Found at', total_lines + results[h][1], 'in', time.time() - t_start, 'seconds'
break
total_lines += results[h][0]
if __name__ == "__main__":
main( file_name = 'testFile.txt', text = 'IPI1520' )
var el = document.getElementById('foo');
el.parentNode.innerHTML;
There are many ways to do this in R. Specifically, by
, aggregate
, split
, and plyr
, cast
, tapply
, data.table
, dplyr
, and so forth.
Broadly speaking, these problems are of the form split-apply-combine. Hadley Wickham has written a beautiful article that will give you deeper insight into the whole category of problems, and it is well worth reading. His plyr
package implements the strategy for general data structures, and dplyr
is a newer implementation performance tuned for data frames. They allow for solving problems of the same form but of even greater complexity than this one. They are well worth learning as a general tool for solving data manipulation problems.
Performance is an issue on very large datasets, and for that it is hard to beat solutions based on data.table
. If you only deal with medium-sized datasets or smaller, however, taking the time to learn data.table
is likely not worth the effort. dplyr
can also be fast, so it is a good choice if you want to speed things up, but don't quite need the scalability of data.table
.
Many of the other solutions below do not require any additional packages. Some of them are even fairly fast on medium-large datasets. Their primary disadvantage is either one of metaphor or of flexibility. By metaphor I mean that it is a tool designed for something else being coerced to solve this particular type of problem in a 'clever' way. By flexibility I mean they lack the ability to solve as wide a range of similar problems or to easily produce tidy output.
base
functionstapply
:
tapply(df$speed, df$dive, mean)
# dive1 dive2
# 0.5419921 0.5103974
aggregate
:
aggregate
takes in data.frames, outputs data.frames, and uses a formula interface.
aggregate( speed ~ dive, df, mean )
# dive speed
# 1 dive1 0.5790946
# 2 dive2 0.4864489
by
:
In its most user-friendly form, it takes in vectors and applies a function to them. However, its output is not in a very manipulable form.:
res.by <- by(df$speed, df$dive, mean)
res.by
# df$dive: dive1
# [1] 0.5790946
# ---------------------------------------
# df$dive: dive2
# [1] 0.4864489
To get around this, for simple uses of by
the as.data.frame
method in the taRifx
library works:
library(taRifx)
as.data.frame(res.by)
# IDX1 value
# 1 dive1 0.6736807
# 2 dive2 0.4051447
split
:
As the name suggests, it performs only the "split" part of the split-apply-combine strategy. To make the rest work, I'll write a small function that uses sapply
for apply-combine. sapply
automatically simplifies the result as much as possible. In our case, that means a vector rather than a data.frame, since we've got only 1 dimension of results.
splitmean <- function(df) {
s <- split( df, df$dive)
sapply( s, function(x) mean(x$speed) )
}
splitmean(df)
# dive1 dive2
# 0.5790946 0.4864489
data.table:
library(data.table)
setDT(df)[ , .(mean_speed = mean(speed)), by = dive]
# dive mean_speed
# 1: dive1 0.5419921
# 2: dive2 0.5103974
dplyr
:
library(dplyr)
group_by(df, dive) %>% summarize(m = mean(speed))
plyr
(the pre-cursor of dplyr
)
Here's what the official page has to say about plyr
:
It’s already possible to do this with
base
R functions (likesplit
and theapply
family of functions), butplyr
makes it all a bit easier with:
- totally consistent names, arguments and outputs
- convenient parallelisation through the
foreach
package- input from and output to data.frames, matrices and lists
- progress bars to keep track of long running operations
- built-in error recovery, and informative error messages
- labels that are maintained across all transformations
In other words, if you learn one tool for split-apply-combine manipulation it should be plyr
.
library(plyr)
res.plyr <- ddply( df, .(dive), function(x) mean(x$speed) )
res.plyr
# dive V1
# 1 dive1 0.5790946
# 2 dive2 0.4864489
reshape2:
The reshape2
library is not designed with split-apply-combine as its primary focus. Instead, it uses a two-part melt/cast strategy to perform a wide variety of data reshaping tasks. However, since it allows an aggregation function it can be used for this problem. It would not be my first choice for split-apply-combine operations, but its reshaping capabilities are powerful and thus you should learn this package as well.
library(reshape2)
dcast( melt(df), variable ~ dive, mean)
# Using dive as id variables
# variable dive1 dive2
# 1 speed 0.5790946 0.4864489
library(microbenchmark)
m1 <- microbenchmark(
by( df$speed, df$dive, mean),
aggregate( speed ~ dive, df, mean ),
splitmean(df),
ddply( df, .(dive), function(x) mean(x$speed) ),
dcast( melt(df), variable ~ dive, mean),
dt[, mean(speed), by = dive],
summarize( group_by(df, dive), m = mean(speed) ),
summarize( group_by(dt, dive), m = mean(speed) )
)
> print(m1, signif = 3)
Unit: microseconds
expr min lq mean median uq max neval cld
by(df$speed, df$dive, mean) 302 325 343.9 342 362 396 100 b
aggregate(speed ~ dive, df, mean) 904 966 1012.1 1020 1060 1130 100 e
splitmean(df) 191 206 249.9 220 232 1670 100 a
ddply(df, .(dive), function(x) mean(x$speed)) 1220 1310 1358.1 1340 1380 2740 100 f
dcast(melt(df), variable ~ dive, mean) 2150 2330 2440.7 2430 2490 4010 100 h
dt[, mean(speed), by = dive] 599 629 667.1 659 704 771 100 c
summarize(group_by(df, dive), m = mean(speed)) 663 710 774.6 744 782 2140 100 d
summarize(group_by(dt, dive), m = mean(speed)) 1860 1960 2051.0 2020 2090 3430 100 g
autoplot(m1)
As usual, data.table
has a little more overhead so comes in about average for small datasets. These are microseconds, though, so the differences are trivial. Any of the approaches works fine here, and you should choose based on:
plyr
is always worth learning for its flexibility; data.table
is worth learning if you plan to analyze huge datasets; by
and aggregate
and split
are all base R functions and thus universally available)But what if we have a big dataset? Let's try 10^7 rows split over ten groups.
df <- data.frame(dive=factor(sample(letters[1:10],10^7,replace=TRUE)),speed=runif(10^7))
dt <- data.table(df)
setkey(dt,dive)
m2 <- microbenchmark(
by( df$speed, df$dive, mean),
aggregate( speed ~ dive, df, mean ),
splitmean(df),
ddply( df, .(dive), function(x) mean(x$speed) ),
dcast( melt(df), variable ~ dive, mean),
dt[,mean(speed),by=dive],
times=2
)
> print(m2, signif = 3)
Unit: milliseconds
expr min lq mean median uq max neval cld
by(df$speed, df$dive, mean) 720 770 799.1 791 816 958 100 d
aggregate(speed ~ dive, df, mean) 10900 11000 11027.0 11000 11100 11300 100 h
splitmean(df) 974 1040 1074.1 1060 1100 1280 100 e
ddply(df, .(dive), function(x) mean(x$speed)) 1050 1080 1110.4 1100 1130 1260 100 f
dcast(melt(df), variable ~ dive, mean) 2360 2450 2492.8 2490 2520 2620 100 g
dt[, mean(speed), by = dive] 119 120 126.2 120 122 212 100 a
summarize(group_by(df, dive), m = mean(speed)) 517 521 531.0 522 532 620 100 c
summarize(group_by(dt, dive), m = mean(speed)) 154 155 174.0 156 189 321 100 b
autoplot(m2)
Then data.table
or dplyr
using operating on data.table
s is clearly the way to go. Certain approaches (aggregate
and dcast
) are beginning to look very slow.
If you have more groups, the difference becomes more pronounced. With 1,000 groups and the same 10^7 rows:
df <- data.frame(dive=factor(sample(seq(1000),10^7,replace=TRUE)),speed=runif(10^7))
dt <- data.table(df)
setkey(dt,dive)
# then run the same microbenchmark as above
print(m3, signif = 3)
Unit: milliseconds
expr min lq mean median uq max neval cld
by(df$speed, df$dive, mean) 776 791 816.2 810 828 925 100 b
aggregate(speed ~ dive, df, mean) 11200 11400 11460.2 11400 11500 12000 100 f
splitmean(df) 5940 6450 7562.4 7470 8370 11200 100 e
ddply(df, .(dive), function(x) mean(x$speed)) 1220 1250 1279.1 1280 1300 1440 100 c
dcast(melt(df), variable ~ dive, mean) 2110 2190 2267.8 2250 2290 2750 100 d
dt[, mean(speed), by = dive] 110 111 113.5 111 113 143 100 a
summarize(group_by(df, dive), m = mean(speed)) 625 630 637.1 633 644 701 100 b
summarize(group_by(dt, dive), m = mean(speed)) 129 130 137.3 131 142 213 100 a
autoplot(m3)
So data.table
continues scaling well, and dplyr
operating on a data.table
also works well, with dplyr
on data.frame
close to an order of magnitude slower. The split
/sapply
strategy seems to scale poorly in the number of groups (meaning the split()
is likely slow and the sapply
is fast). by
continues to be relatively efficient--at 5 seconds, it's definitely noticeable to the user but for a dataset this large still not unreasonable. Still, if you're routinely working with datasets of this size, data.table
is clearly the way to go - 100% data.table for the best performance or dplyr
with dplyr
using data.table
as a viable alternative.
Type in the command shell:
df -h
or
df -m
or
df -k
It will show the list of free disk spaces for each mount point.
You can show/view single column also.
Type:
df -m |awk '{print $3}'
Note: Here 3 is the column number. You can choose which column you need.
There is a small difference between both.
Second declaration assignates the reference associated to the constant SOME
to the variable str
First declaration creates a new String having for value the value of the constant SOME
and assignates its reference to the variable str
.
In the first case, a second String has been created having the same value that SOME
which implies more inititialization time. As a consequence, you should avoid it. Furthermore, at compile time, all constants SOME
are transformed into the same instance, which uses far less memory.
As a consequence, always prefer second syntax.
As stated in the other answers:
MOV
will grab the data at the address inside the brackets and place that data into the destination operand.LEA
will perform the calculation of the address inside the brackets and place that calculated address into the destination operand. This happens without actually going out to the memory and getting the data. The work done by LEA
is in the calculating of the "effective address".Because memory can be addressed in several different ways (see examples below), LEA
is sometimes used to add or multiply registers together without using an explicit ADD
or MUL
instruction (or equivalent).
Since everyone is showing examples in Intel syntax, here are some in AT&T syntax:
MOVL 16(%ebp), %eax /* put long at ebp+16 into eax */
LEAL 16(%ebp), %eax /* add 16 to ebp and store in eax */
MOVQ (%rdx,%rcx,8), %rax /* put qword at rcx*8 + rdx into rax */
LEAQ (%rdx,%rcx,8), %rax /* put value of "rcx*8 + rdx" into rax */
MOVW 5(%bp,%si), %ax /* put word at si + bp + 5 into ax */
LEAW 5(%bp,%si), %ax /* put value of "si + bp + 5" into ax */
MOVQ 16(%rip), %rax /* put qword at rip + 16 into rax */
LEAQ 16(%rip), %rax /* add 16 to instruction pointer and store in rax */
MOVL label(,1), %eax /* put long at label into eax */
LEAL label(,1), %eax /* put the address of the label into eax */
On platforms where they both have the same size the answer is nothing. They both represent signed 4 byte values.
However you cannot depend on this being true. The size of long and int are not definitively defined by the standard. It's possible for compilers to give the types different sizes and hence break this assumption.
You have at least two issues in your code:
ng-change="getScoreData(Score)
Angular doesn't see getScoreData
method that refers to defined service
getScoreData: function (Score, callback)
We don't need to use callback since GET
returns promise. Use then
instead.
Here is a working example (I used random address only for simulation):
HTML
<select ng-model="score"
ng-change="getScoreData(score)"
ng-options="score as score.name for score in scores"></select>
<pre>{{ScoreData|json}}</pre>
JS
var fessmodule = angular.module('myModule', ['ngResource']);
fessmodule.controller('fessCntrl', function($scope, ScoreDataService) {
$scope.scores = [{
name: 'Bukit Batok Street 1',
URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'
}, {
name: 'London 8',
URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, London 8&sensor=true'
}];
$scope.getScoreData = function(score) {
ScoreDataService.getScoreData(score).then(function(result) {
$scope.ScoreData = result;
}, function(result) {
alert("Error: No data returned");
});
};
});
fessmodule.$inject = ['$scope', 'ScoreDataService'];
fessmodule.factory('ScoreDataService', ['$http', '$q', function($http) {
var factory = {
getScoreData: function(score) {
console.log(score);
var data = $http({
method: 'GET',
url: score.URL
});
return data;
}
}
return factory;
}]);
Demo Fiddle
Marco13 already provided an excellent answer.
In case you are in search for a way to use the GPU without implementing CUDA/OpenCL kernels, I would like to add a reference to the finmath-lib-cuda-extensions (finmath-lib-gpu-extensions) http://finmath.net/finmath-lib-cuda-extensions/ (disclaimer: I am the maintainer of this project).
The project provides an implementation of "vector classes", to be precise, an interface called RandomVariable
, which provides arithmetic operations and reduction on vectors. There are implementations for the CPU and GPU. There are implementation using algorithmic differentiation or plain valuations.
The performance improvements on the GPU are currently small (but for vectors of size 100.000 you may get a factor > 10 performance improvements). This is due to the small kernel sizes. This will improve in a future version.
The GPU implementation use JCuda and JOCL and are available for Nvidia and ATI GPUs.
The library is Apache 2.0 and available via Maven Central.
Use GregorianCalendar
. Set the date of the object, and then use getActualMaximum(Calendar.DAY_IN_MONTH)
.
http://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html#getActualMaximum%28int%29 (but it was the same in Java 1.4)
I usually shy away from queries from sys* type tables, vendors tend to change these between releases, major or otherwise. What I have always done is to issue the DROP FUNCTION <name>
statement and not worry about any SQL error that might come back. I consider that standard procedure in the DBA realm.
Remove the function and check the output of:
var_dump(function_exists('parseDate'));
In which case, change the name of the function.
If you get false, you're including the file with that function twice, replace :
include
by
include_once
And replace :
require
by
require_once
EDIT : I'm just a little too late, post before beat me to it !
[print(a) for a in list]
will give a bunch of None types at the end though it prints out all the items
I would go as far as to say that it doesn't really matter if you use eval()
in javascript which is run in browsers.*(caveat)
All modern browsers have a developer console where you can execute arbitrary javascript anyway and any semi-smart developer can look at your JS source and put whatever bits of it they need to into the dev console to do what they wish.
*As long as your server endpoints have the correct validation & sanitisation of user supplied values, it should not matter what gets parsed and eval'd in your client side javascript.
If you were to ask if it's suitable to use eval()
in PHP however, the answer is NO, unless you whitelist any values which may be passed to your eval statement.
First off, if you want to extract count features and apply TF-IDF normalization and row-wise euclidean normalization you can do it in one operation with TfidfVectorizer
:
>>> from sklearn.feature_extraction.text import TfidfVectorizer
>>> from sklearn.datasets import fetch_20newsgroups
>>> twenty = fetch_20newsgroups()
>>> tfidf = TfidfVectorizer().fit_transform(twenty.data)
>>> tfidf
<11314x130088 sparse matrix of type '<type 'numpy.float64'>'
with 1787553 stored elements in Compressed Sparse Row format>
Now to find the cosine distances of one document (e.g. the first in the dataset) and all of the others you just need to compute the dot products of the first vector with all of the others as the tfidf vectors are already row-normalized.
As explained by Chris Clark in comments and here Cosine Similarity does not take into account the magnitude of the vectors. Row-normalised have a magnitude of 1 and so the Linear Kernel is sufficient to calculate the similarity values.
The scipy sparse matrix API is a bit weird (not as flexible as dense N-dimensional numpy arrays). To get the first vector you need to slice the matrix row-wise to get a submatrix with a single row:
>>> tfidf[0:1]
<1x130088 sparse matrix of type '<type 'numpy.float64'>'
with 89 stored elements in Compressed Sparse Row format>
scikit-learn already provides pairwise metrics (a.k.a. kernels in machine learning parlance) that work for both dense and sparse representations of vector collections. In this case we need a dot product that is also known as the linear kernel:
>>> from sklearn.metrics.pairwise import linear_kernel
>>> cosine_similarities = linear_kernel(tfidf[0:1], tfidf).flatten()
>>> cosine_similarities
array([ 1. , 0.04405952, 0.11016969, ..., 0.04433602,
0.04457106, 0.03293218])
Hence to find the top 5 related documents, we can use argsort
and some negative array slicing (most related documents have highest cosine similarity values, hence at the end of the sorted indices array):
>>> related_docs_indices = cosine_similarities.argsort()[:-5:-1]
>>> related_docs_indices
array([ 0, 958, 10576, 3277])
>>> cosine_similarities[related_docs_indices]
array([ 1. , 0.54967926, 0.32902194, 0.2825788 ])
The first result is a sanity check: we find the query document as the most similar document with a cosine similarity score of 1 which has the following text:
>>> print twenty.data[0]
From: [email protected] (where's my thing)
Subject: WHAT car is this!?
Nntp-Posting-Host: rac3.wam.umd.edu
Organization: University of Maryland, College Park
Lines: 15
I was wondering if anyone out there could enlighten me on this car I saw
the other day. It was a 2-door sports car, looked to be from the late 60s/
early 70s. It was called a Bricklin. The doors were really small. In addition,
the front bumper was separate from the rest of the body. This is
all I know. If anyone can tellme a model name, engine specs, years
of production, where this car is made, history, or whatever info you
have on this funky looking car, please e-mail.
Thanks,
- IL
---- brought to you by your neighborhood Lerxst ----
The second most similar document is a reply that quotes the original message hence has many common words:
>>> print twenty.data[958]
From: [email protected] (Robert Seymour)
Subject: Re: WHAT car is this!?
Article-I.D.: reed.1993Apr21.032905.29286
Reply-To: [email protected]
Organization: Reed College, Portland, OR
Lines: 26
In article <[email protected]> [email protected] (where's my
thing) writes:
>
> I was wondering if anyone out there could enlighten me on this car I saw
> the other day. It was a 2-door sports car, looked to be from the late 60s/
> early 70s. It was called a Bricklin. The doors were really small. In
addition,
> the front bumper was separate from the rest of the body. This is
> all I know. If anyone can tellme a model name, engine specs, years
> of production, where this car is made, history, or whatever info you
> have on this funky looking car, please e-mail.
Bricklins were manufactured in the 70s with engines from Ford. They are rather
odd looking with the encased front bumper. There aren't a lot of them around,
but Hemmings (Motor News) ususally has ten or so listed. Basically, they are a
performance Ford with new styling slapped on top.
> ---- brought to you by your neighborhood Lerxst ----
Rush fan?
--
Robert Seymour [email protected]
Physics and Philosophy, Reed College (NeXTmail accepted)
Artificial Life Project Reed College
Reed Solar Energy Project (SolTrain) Portland, OR
Steps that you should follow if you want the thread dump of your StandAlone Java Process
Step 1: Get the Process ID for the shell script calling the java program
linux$ ps -aef | grep "runABCD"
user1 **8535** 4369 0 Mar 25 ? 0:00 /bin/csh /home/user1/runABCD.sh
user1 17796 17372 0 08:15:41 pts/49 0:00 grep runABCD
Step 2: Get the Process ID for the Child which was Invoked by the runABCD. Use the above PID to get the childs.
linux$ ps -aef | grep **8535**
user1 **8536** 8535 0 Mar 25 ? 126:38 /apps/java/jdk/sun4/SunOS5/1.6.0_16/bin/java -cp /home/user1/XYZServer
user1 8535 4369 0 Mar 25 ? 0:00 /bin/csh /home/user1/runABCD.sh
user1 17977 17372 0 08:15:49 pts/49 0:00 grep 8535
Step 3: Get the JSTACK for the particular process. Get the Process id of your XYSServer process. i.e. 8536
linux$ jstack **8536** > threadDump.log
You can easily achieve this by using this code.
SELECT Convert(datetime, Convert(varchar(30),'10/15/2008 10:06:32 PM',102),102)
Here's a simple JS function to add commas to an integer number in string format. It will handle whole numbers or decimal numbers. You can pass it either a number or a string. It obviously returns a string.
function addCommas(str) {
var parts = (str + "").split("."),
main = parts[0],
len = main.length,
output = "",
first = main.charAt(0),
i;
if (first === '-') {
main = main.slice(1);
len = main.length;
} else {
first = "";
}
i = len - 1;
while(i >= 0) {
output = main.charAt(i) + output;
if ((len - i) % 3 === 0 && i > 0) {
output = "," + output;
}
--i;
}
// put sign back
output = first + output;
// put decimal part back
if (parts.length > 1) {
output += "." + parts[1];
}
return output;
}
Here's a set of test cases: http://jsfiddle.net/jfriend00/6y57j/
You can see it being used in this previous jsFiddle: http://jsfiddle.net/jfriend00/sMnjT/. You can find functions that will handle decimal numbers too with a simple Google search for "javascript add commas".
Converting a number to a string can be done many ways. The easiest is just to add it to a string:
var myNumber = 3;
var myStr = "" + myNumber; // "3"
Within, the context of your jsFiddle, you'd get commas into the counter by changing this line:
jTarget.text(current);
to this:
jTarget.text(addCommas(current));
You can see it working here: http://jsfiddle.net/jfriend00/CbjSX/
It's also worth checking out this bug report, which was closed with reason "Not a defect" and the following text:
"Autoboxing of entire arrays is not specified behavior, for good reason. It can be prohibitively expensive for large arrays."
Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.
That option could be useful when copying very large files over a potentially unstable connection.
Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.
In my case the error was caused by the insufficient memory allocated to the "test" lifecycle of maven. It was fixed by adding <argLine>-Xms3512m -Xmx3512m</argLine>
to:
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<configuration>
<argLine>-Xms3512m -Xmx3512m</argLine>
Thanks @crazycoder for pointing this out (and also that it is not related to IntelliJ; in this case).
If your tests are forked, they run in a new JVM that doesn't inherit Maven JVM options. Custom memory options must be provided via the test runner in pom.xml, refer to Maven documentation for details, it has very little to do with the IDE.
<script language="JavaScript" type="text/javascript">
<!--
function loopSelected()
{
var txtSelectedValuesObj = document.getElementById('txtSelectedValues');
var selectedArray = new Array();
var selObj = document.getElementById('selSeaShells');
var i;
var count = 0;
for (i=0; i<selObj.options.length; i++) {
if (selObj.options[i].selected) {
selectedArray[count] = selObj.options[i].value;
count++;
}
}
txtSelectedValuesObj.value = selectedArray;
}
function openInNewWindow(frm)
{
// open a blank window
var aWindow = window.open('', 'Tutorial004NewWindow',
'scrollbars=yes,menubar=yes,resizable=yes,toolbar=no,width=400,height=400');
// set the target to the blank window
frm.target = 'Tutorial004NewWindow';
// submit
frm.submit();
}
//-->
</script>
The HTML
<form action="tutorial004_nw.html" method="get">
<table border="1" cellpadding="10" cellspacing="0">
<tr>
<td valign="top">
<input type="button" value="Submit" onclick="openInNewWindow(this.form);" />
<input type="button" value="Loop Selected" onclick="loopSelected();" />
<br />
<select name="selSea" id="selSeaShells" size="5" multiple="multiple">
<option value="val0" selected>sea zero</option>
<option value="val1">sea one</option>
<option value="val2">sea two</option>
<option value="val3">sea three</option>
<option value="val4">sea four</option>
</select>
</td>
<td valign="top">
<input type="text" id="txtSelectedValues" />
selected array
</td>
</tr>
</table>
</form>
For Leaflet, I'm using
map.setView(markersLayer.getBounds().getCenter());
Looks like you forgot the @ in variable declaration. Also I remember having problems with SET
in MySql a long time ago.
Try
DECLARE @FOO varchar(7);
DECLARE @oldFOO varchar(7);
SELECT @FOO = '138';
SELECT @oldFOO = CONCAT('0', @FOO);
update mypermits
set person = @FOO
where person = @oldFOO;
NOTE: git whatchanged
is deprecated, use git log
instead
New users are encouraged to use git-log[1] instead. The
whatchanged
command is essentially the same as git-log[1] but defaults to show the raw format diff output and to skip merges.The command is kept primarily for historical reasons; fingers of many people who learned Git long before
git log
was invented by reading Linux kernel mailing list are trained to type it.
You can use the command git whatchanged --stat
to get a list of files that changed in each commit (along with the commit message).
This should work:
DECLARE db_cursor CURSOR FOR SELECT name, age, color FROM table;
DECLARE @myName VARCHAR(256);
DECLARE @myAge INT;
DECLARE @myFavoriteColor VARCHAR(40);
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
WHILE @@FETCH_STATUS = 0
BEGIN
--Do stuff with scalar values
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;
This should work...
JavaScriptSerializer ser = new JavaScriptSerializer();
var records = new ser.Deserialize<List<Record>>(jsonData);
public class Person
{
public string Name;
public int Age;
public string Location;
}
public class Record
{
public Person record;
}
Use this code. Change the 2nd line as you have your folder name. Where index.php file and folders application, system folder lie. Mostly problems happen due to second line. we don't configure the folder name where project is place. Important is 2nd line. This is simple to remove the index.php. RewriteEngine on RewriteBase /project_folder_name RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule .* index.php/$0 [PT,L]
#RewriteEngine on
#RewriteCond $1 !^(index\.php|images|robots\.txt)
#RewriteRule ^(.*)$ index.php/$1 [L]
Go to controller/config.php file.
config['index_url']='';
Reference for more study.
https://ellislab.com/expressionengine/user-guide/urls/remove_index.php.html
https://ellislab.com/blog/entry/fully-removing-index.php-from-urls
Is this a problem Only when you run ant -d or ant -verbose, but works other times
?
I noticed this error message line:
Could not load definitions from resource org/apache/tools/ant/antlib.xml. It could not be found.
The org/apache/tools/ant/antlib.xml
file is embedded in the ant.jar
. The ant
command is really a shell script called ant
or a batch script called ant.bat
. If the environment variable ANT_HOME is not set, it will figure out where it's located by looking to see where the ant
command itself is located.
Sometimes I've seen this where someone will move the ant
shell/batch script to put it in their path, and have ANT_HOME either not set, or set incorrectly.
What platform are you on? Is this Windows or Unix/Linux/MacOS? If you're on Windows, check to see if %ANT_HOME% is set. If it is, make sure it's the right directory. Make sure you have set your PATH to include %ANT_HOME%/bin
.
If you're on Unix, don't copy the ant shell script to an executable directory. Instead, make a symbolic link. I have a directory called /usr/local/bin
where I put the command I want to override the commands in /bin
and /usr/bin
. My Ant is installed in /opt/ant-1.9.2
, and I have a symbolic link from /opt/ant-1.9.2
to /opt/ant
. Then, I have symbolic links from all commands in /opt/ant/bin
to /usr/local/bin
. The Ant shell script can detect the symbolic links and find the correct Ant HOME location.
Next, go to your Ant installation directory and look under the lib directory to make sure ant.jar
is there, and that it contains org/apache/tools/ant/antlib.xml
. You can use the jar tvf ant.jar
command. The only thing I can emphasize is that you do have everything setup correctly. You have your Ant shell script in your PATH either because you included the bin directory of your Ant's HOME directory in your classpath, or (if you're on Unix/Linux/MacOS), you have that file symbolically linked to a directory in your PATH.
Make sure your JAVA_HOME is set correctly (on Unix, you can use the symbolic link trick to have the java
command set it for you), and that you're using Java 1.5 or higher. Java 1.4 will no longer work with newer versions of Ant.
Also run ant -version
and see what you get. You might get the same error as before which leads me to think you have something wrong.
Let me know what you find, and your OS, and I can give you directions on reinstalling Ant.
In the below mentioned link, ChromeDriver.exe for Windows 32 bit exist.
http://chromedriver.storage.googleapis.com/index.html?path=2.24/
It is working for me in Win7 64 bit.
This did the trick for me. It captures all the stdout output from the subprocess(For python 3.8):
from subprocess import check_output, STDOUT
cmd = "Your Command goes here"
try:
cmd_stdout = check_output(cmd, stderr=STDOUT, shell=True).decode()
except Exception as e:
print(e.output.decode()) # print out the stdout messages up to the exception
print(e) # To print out the exception message
import requests
r = requests.get("https://stackoverflow.com")
data = r.content # Content of response
print r.status_code # Status code of response
print data
It is only possible to do this cross domain if you have access to implement JS on both domains. If you have that, then here is a little library that solves all the problems with sizing iFrames to their contained content.
https://github.com/davidjbradshaw/iframe-resizer
It deals with the cross domain issue by using the post-message API, and also detects changes to the content of the iFrame in a few different ways.
Works in all modern browsers and IE8 upwards.
Ryan Stewart's answer was almost there. In the case where you actually don't want to delete your local changes, there's a workflow you can use to merge:
git status
. It will give you a list of unmerged files.git commit
Git will commit just the merges into a new commit. (In my case, I had additional added files on disk, which weren't lumped into that commit.)
Git then considers the merge successful and allows you to move forward.
On Windows 7,64 bit,the above solution (Onur Turhan's) worked for me with slight changes as below
C:\Users\MyName > heroku login
Enter email/password
C:\Users\MyName >ssh-keygen -t rsa -f id_rsa
This generated two files(id_rsa and id_rsa.pub) in my c:\Users\MyName directory (Not in .ssh directory)
heroku keys:add id_rsa.pub
git clone [email protected]:some-heiku-xxxx.git -o heroku
I guess adding the correct "id_rsa.pub" file is the most important.After generating the public key using keygen just verify that you are adding correct key by looking at the time-stamp when it was created.
You can rename classes or any file by hitting F2 on the filename in Eclipse. It will ask you if you want to update references. It's really as easy as that :)
For showing a particular trigger in a particular schema you can try the following:
select * from information_schema.triggers where
information_schema.triggers.trigger_name like '%trigger_name%' and
information_schema.triggers.trigger_schema like '%data_base_name%'
You can create a VBS script that will force the window to be hidden.
Set WshShell = WScript.CreateObject("WScript.Shell")
obj = WshShell.Run("""C:\Program Files (x86)\McKesson\HRS
Distributed\SwE.bat""", 0)
set WshShell = Nothing
Then, rather than executing the batch file, execute the script.
If you need support for serializing nested fields, similar to how PHP handles form fields, you can use the following function
function update(data, keys, value) {_x000D_
if (keys.length === 0) {_x000D_
// Leaf node_x000D_
return value;_x000D_
}_x000D_
_x000D_
let key = keys.shift();_x000D_
if (!key) {_x000D_
data = data || [];_x000D_
if (Array.isArray(data)) {_x000D_
key = data.length;_x000D_
}_x000D_
}_x000D_
_x000D_
// Try converting key to a numeric value_x000D_
let index = +key;_x000D_
if (!isNaN(index)) {_x000D_
// We have a numeric index, make data a numeric array_x000D_
// This will not work if this is a associative array _x000D_
// with numeric keys_x000D_
data = data || [];_x000D_
key = index;_x000D_
}_x000D_
_x000D_
// If none of the above matched, we have an associative array_x000D_
data = data || {};_x000D_
_x000D_
let val = update(data[key], keys, value);_x000D_
data[key] = val;_x000D_
_x000D_
return data;_x000D_
}_x000D_
_x000D_
function serializeForm(form) {_x000D_
return Array.from((new FormData(form)).entries())_x000D_
.reduce((data, [field, value]) => {_x000D_
let [_, prefix, keys] = field.match(/^([^\[]+)((?:\[[^\]]*\])*)/);_x000D_
_x000D_
if (keys) {_x000D_
keys = Array.from(keys.matchAll(/\[([^\]]*)\]/g), m => m[1]);_x000D_
value = update(data[prefix], keys, value);_x000D_
}_x000D_
data[prefix] = value;_x000D_
return data;_x000D_
}, {});_x000D_
}_x000D_
_x000D_
document.getElementById('output').textContent = JSON.stringify(serializeForm(document.getElementById('form')), null, 2);
_x000D_
<form id="form">_x000D_
<input name="field1" value="Field 1">_x000D_
<input name="field2[]" value="Field 21">_x000D_
<input name="field2[]" value="Field 22">_x000D_
<input name="field3[a]" value="Field 3a">_x000D_
<input name="field3[b]" value="Field 3b">_x000D_
<input name="field3[c]" value="Field 3c">_x000D_
<input name="field4[x][a]" value="Field xa">_x000D_
<input name="field4[x][b]" value="Field xb">_x000D_
<input name="field4[x][c]" value="Field xc">_x000D_
<input name="field4[y][a]" value="Field ya">_x000D_
<input name="field5[z][0]" value="Field z0">_x000D_
<input name="field5[z][]" value="Field z1">_x000D_
<input name="field6.z" value="Field 6Z0">_x000D_
<input name="field6.z" value="Field 6Z1">_x000D_
</form>_x000D_
_x000D_
<h2>Output</h2>_x000D_
<pre id="output">_x000D_
</pre>
_x000D_
If you're getting source in Content Use the following method
try
{
var response = restClient.Execute<List<EmpModel>>(restRequest);
var jsonContent = response.Content;
var data = JsonConvert.DeserializeObject<List<EmpModel>>(jsonContent);
foreach (EmpModel item in data)
{
listPassingData?.Add(item);
}
}
catch (Exception ex)
{
Console.WriteLine($"Data get mathod problem {ex} ");
}
3.681 billion is the current total in the year 2020.
there's nothing wrong with your file. xlrd does not yet support xlsx (excel 2007+) files although it's purported to have supported this for some time.
2-days ago they committed a pre-alpha version to their git which integrates xlsx support. Other forums suggest that you use a DOM parser for xlsx files since the xlsx file type is just a zip archive containing XML. I have not tried this. there is another package with similar functionality as xlrd and this is called openpyxl which you can get from easy_install or pip. I have not tried this either, however, its API is supposed to be similar to xlrd.
You've probably found the answer to this problem already but I've been looking on how to solve this and still can't really find exactly what I was looking for so I figured I'd post it here.
What I did was the following (this is very generalized, purpose is to give you an idea of how to proceed, copying and pasting all the code will not work O:D ):
First have the EditText and any other views you want in your program wrapped by a single view. In my case I used a LinearLayout to wrap everything.
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mainLinearLayout">
<EditText
android:id="@+id/editText"/>
<ImageView
android:id="@+id/imageView"/>
<TextView
android:id="@+id/textView"/>
</LinearLayout>
Then in your code you have to set a Touch Listener to your main LinearLayout.
final EditText searchEditText = (EditText) findViewById(R.id.editText);
mainLinearLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(searchEditText.isFocused()){
if(event.getY() >= 72){
//Will only enter this if the EditText already has focus
//And if a touch event happens outside of the EditText
//Which in my case is at the top of my layout
//and 72 pixels long
searchEditText.clearFocus();
InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
Toast.makeText(getBaseContext(), "Clicked", Toast.LENGTH_SHORT).show();
return false;
}
});
I hope this helps some people. Or at least helps them start solving their problem.
The following worked for me
const conString = "postgres://YourUserName:YourPassword@YourHostname:5432/YourDatabaseName";
Here is the full code with no errors
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
#map-canvas
{
height: 400px;
width: 500px;
}
</style>
</script>
<script type="text/javascript">
function initialize() {
var myLatLng = new google.maps.LatLng( 17.3850, 78.4867 ),
myOptions = {
zoom: 5,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map( document.getElementById( 'map-canvas' ), myOptions ),
marker = new google.maps.Marker( {icon: {
url: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png',
// This marker is 20 pixels wide by 32 pixels high.
size: new google.maps.Size(20, 32),
// The origin for this image is (0, 0).
origin: new google.maps.Point(0, 0),
// The anchor for this image is the base of the flagpole at (0, 32).
anchor: new google.maps.Point(0, 32)
}, position: myLatLng, map: map} );
marker.setMap( map );
moveBus( map, marker );
}
function moveBus( map, marker ) {
setTimeout(() => {
marker.setPosition( new google.maps.LatLng( 12.3850, 77.4867 ) );
map.panTo( new google.maps.LatLng( 17.3850, 78.4867 ) );
}, 1000)
};
</script>
</head>
<body onload="initialize()">
<script type="text/javascript">
//moveBus();
</script>
<script src="http://maps.googleapis.com/maps/api/js?sensor=AIzaSyB-W_sLy7VzaQNdckkY4V5r980wDR9ldP4"></script>
<div id="map-canvas" style="height: 500px; width: 500px;"></div>
</body>
</html>
In case you solve a more complex task of logging execution statistics in your code:
public void logExecutionMillis(LocalDateTime start, String callerMethodName) {
LocalDateTime end = getNow();
long difference = Duration.between(start, end).toMillis();
Logger logger = LoggerFactory.getLogger(ProfilerInterceptor.class);
long millisInDay = 1000 * 60 * 60 * 24;
long millisInHour = 1000 * 60 * 60;
long millisInMinute = 1000 * 60;
long millisInSecond = 1000;
long days = difference / millisInDay;
long daysDivisionResidueMillis = difference - days * millisInDay;
long hours = daysDivisionResidueMillis / millisInHour;
long hoursDivisionResidueMillis = daysDivisionResidueMillis - hours * millisInHour;
long minutes = hoursDivisionResidueMillis / millisInMinute;
long minutesDivisionResidueMillis = hoursDivisionResidueMillis - minutes * millisInMinute;
long seconds = minutesDivisionResidueMillis / millisInSecond;
long secondsDivisionResidueMillis = minutesDivisionResidueMillis - seconds * millisInSecond;
logger.info(
"\n************************************************************************\n"
+ callerMethodName
+ "() - "
+ difference
+ " millis ("
+ days
+ " d. "
+ hours
+ " h. "
+ minutes
+ " min. "
+ seconds
+ " sec."
+ secondsDivisionResidueMillis
+ " millis).");
}
P.S. Logger can be replaced with simple System.out.println() if you like.
If you are using JDK 6 then you might want to check out ConcurrentHashMap
Note the putIfAbsent method in that class.
Man, if you are using Windows, EOF is not reached by pressing enter, but by pressing Crtl+Z at the console. This will print "^Z", an indicator of EOF. The behavior of functions when reading this (the EOF or Crtl+Z):
Function: Output:
scanf(...) EOF
gets(<variable>) NULL
feof(stdin) 1
getchar() EOF
I am on OSX, this did not work for me:
code . --user-data-dir='.'
but this DID work:
code . -data-dir='.'
String string;
for (Datapoint d : dataPointList) {
Field[] fields = d.getFields();
for (Field f : fields) {
String value = (String) g.get(d);
if (value.equals(string)) {
//Do your stuff
}
}
}
This is what worked for me: it redirects a visitor if javascript is disabled
<noscript><meta http-equiv="refresh" content="0; url=whatyouwant.html" /></noscript>
From Stroustrup's speech at "Going Native 2012":
template<int M, int K, int S> struct Unit { // a unit in the MKS system
enum { m=M, kg=K, s=S };
};
template<typename Unit> // a magnitude with a unit
struct Value {
double val; // the magnitude
explicit Value(double d) : val(d) {} // construct a Value from a double
};
using Speed = Value<Unit<1,0,-1>>; // meters/second type
using Acceleration = Value<Unit<1,0,-2>>; // meters/second/second type
using Second = Unit<0,0,1>; // unit: sec
using Second2 = Unit<0,0,2>; // unit: second*second
constexpr Value<Second> operator"" s(long double d)
// a f-p literal suffixed by ‘s’
{
return Value<Second> (d);
}
constexpr Value<Second2> operator"" s2(long double d)
// a f-p literal suffixed by ‘s2’
{
return Value<Second2> (d);
}
Speed sp1 = 100m/9.8s; // very fast for a human
Speed sp2 = 100m/9.8s2; // error (m/s2 is acceleration)
Speed sp3 = 100/9.8s; // error (speed is m/s and 100 has no unit)
Acceleration acc = sp1/0.5s; // too fast for a human
mysqli in PHP 5 is an object with some good functions that will allow you to speed up the insertion time for the answer above:
$mysqli->autocommit(FALSE);
$mysqli->multi_query($sqlCombined);
$mysqli->autocommit(TRUE);
Turning off autocommit when inserting many rows greatly speeds up insertion, so turn it off, then execute as mentioned above, or just make a string (sqlCombined) which is many insert statements separated by semi-colons and multi-query will handle them fine.
KEYTOOL is in JAVAC SDK .So you must find it in inside the directory that contaijns javac
This should further clarify the points:
a = int(raw_input('Enter the index'))
str1 = 'Example'
leng = len(str1)
if (a < (len-1)) and (a > (-len)):
print str1[a]
else:
print('Index overflow')
Input 3 Output m
Input -3 Output p
you can also copy your JRE folder to eclipse directory and it will work corectly
It seems you might have a string, instead of a number. use this:
var num = document.getElementById('input').value,
replacement = num.replace(/^(\d)$/, '0$1');
document.getElementById('input').value = replacement;
Here's an example: http://jsfiddle.net/xtgFp/
So maybe you want to have this in your index.html to load the library, script, and initialize the app with a view:
<html>
<body ng-app="yourApp">
<div class="span12">
<div ng-view=""></div>
</div>
<script src="http://code.angularjs.org/1.2.0-rc.2/angular.js"></script>
<script src="script.js"></script>
</body>
</html>
Then yourView.html could just be:
<div>
<h1>{{ stuff.h1 }}</h1>
<p>{{ stuff.content }}</p>
</div>
scripts.js could have your controller with data $scope'd to it.
angular.module('yourApp')
.controller('YourCtrl', function ($scope) {
$scope.stuff = {
'h1':'Title',
'content':"A paragraph..."
};
});
Lastly, you'll have to config routes and assign the controller to view for it's $scope (i.e. your data object)
angular.module('yourApp', [])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/yourView.html',
controller: 'YourCtrl'
});
});
I haven't tested this, sorry if there's a bug but I think this is the Angularish way to get data
I think Pandas is the best way to go. There is already one answer here with Pandas using ExcelFile
function, but it did not work properly for me. From here I found the read_excel
function which works just fine:
import pandas as pd
dfs = pd.read_excel("your_file_name.xlsx", sheet_name="your_sheet_name")
print(dfs.head(10))
P.S. You need to have the xlrd
installed for read_excel
function to work
Update 21-03-2020: As you may see here, there are issues with the xlrd
engine and it is going to be deprecated. The openpyxl
is the best replacement. So as described here, the canonical syntax should be:
dfs = pd.read_excel("your_file_name.xlsx", sheet_name="your_sheet_name", engine="openpyxl")
You can use
function echo(content) {
var e = document.createElement("p");
e.innerHTML = content;
document.currentScript.parentElement.replaceChild(document.currentScript, e);
}
which will replace the currently executing script who called the echo function with the text in the content argument.
I think you are creating a project in the wrong way,I am going to post here in step by step
Step 1: File>>New>>Project>>Web>>Dynamic Web Project
Step 2: Enter Project Name>>Next>>Next>>
Step 3: Check the checkbox for Generate web.xml deployment descriptor
Step 4: Finish
Please follow this way you will get you web.xml file under WEB-INF folder
Check this out. The author provides a simple but elegant solution which doesn't require any 3rd party library. http://www.ksmpartners.com/2013/08/nicely-formatted-tabular-output-in-java/
try this:
Dim ws as Worksheet
Set ws = Thisworkbook.Sheets("Sheet2")
With ws
.Range("E2").Formula = "=VLOOKUP(D2,Sheet1!$A:$C,1,0)"
End With
End Sub
This just the simplified version of what you want.
No need to use Application
if you will just output the answer in the Range("E2")
.
If you want to stick with your logic, declare the variables.
See below for example.
Sub Test()
Dim rng As Range
Dim ws1, ws2 As Worksheet
Dim MyStringVar1 As String
Set ws1 = ThisWorkbook.Sheets("Sheet1")
Set ws2 = ThisWorkbook.Sheets("Sheet2")
Set rng = ws2.Range("D2")
With ws2
On Error Resume Next 'add this because if value is not found, vlookup fails, you get 1004
MyStringVar1 = Application.WorksheetFunction.VLookup(rng, ws1.Range("A1:C65536").Value, 1, False)
On Error GoTo 0
If MyStringVar1 = "" Then MsgBox "Item not found" Else MsgBox MyStringVar1
End With
End Sub
Hope this get's you started.
To initialize to current date, you could do something like:
Date firstDate = new Date();
To get it from String, you could use SimpleDateFormat like:
String dateInString = "10-Jan-2016";
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
//handle exception if date is not in "dd-MMM-yyyy" format
}
It subjects to architecture of the server on which PHP runs. For 64-bit,
print PHP_INT_MIN . ", ” . PHP_INT_MAX;
yields -9223372036854775808, 9223372036854775807
Since .NET 4.5 you can use combination of async and await with Progress for sending updates to UI thread:
private void Calculate(int i)
{
double pow = Math.Pow(i, i);
}
public void DoWork(IProgress<int> progress)
{
// This method is executed in the context of
// another thread (different than the main UI thread),
// so use only thread-safe code
for (int j = 0; j < 100000; j++)
{
Calculate(j);
// Use progress to notify UI thread that progress has
// changed
if (progress != null)
progress.Report((j + 1) * 100 / 100000);
}
}
private async void button1_Click(object sender, EventArgs e)
{
progressBar1.Maximum = 100;
progressBar1.Step = 1;
var progress = new Progress<int>(v =>
{
// This lambda is executed in context of UI thread,
// so it can safely update form controls
progressBar1.Value = v;
});
// Run operation in another thread
await Task.Run(() => DoWork(progress));
// TODO: Do something after all calculations
}
Tasks are currently the preferred way to implement what BackgroundWorker
does.
Tasks and
Progress
are explained in more detail here:
Hint: actively refused
sounds like somewhat deeper technical trouble, but...
...actually, this response (and also specifically errno:10061
) is also given, if one calls the bin/mongo executable and the mongodb service is simply not running on the target machine. This even applies to local machine instances (all happening on localhost).
? Always rule out for this trivial possibility first, i.e. simply by using the command line client to access your db.
Here is my reason:
before:
var path = "D:\xxx\util.s"
which \u
is a escape, I figured it out by using Codepen's analyze JS.
after:
var path = "D:\\xxx\\util.s"
and the error fixed
To clear things up a little, since some of the answers are providing incorrect information:
The jQuery .css() method allows the use of either DOM or CSS notation in many cases. So, both backgroundColor
and background-color
will get the job done.
Additionally, when you call .css()
with arguments you have two choices as to what the arguments can be. They can either be 2 comma separated strings representing a css property and its value, or it can be a Javascript object containing one or more key value pairs of CSS properties and values.
In conclusion the only thing wrong with your code is a missing }
. The line should read:
$("#myParagraph").css({"backgroundColor":"black","color":"white"});
You cannot leave the curly brackets out, but you may leave the quotes out from around backgroundColor
and color
. If you use background-color
you must put quotes around it because of the hyphen.
In general, it's a good habit to quote your Javascript objects, since problems can arise if you do not quote an existing keyword.
A final note is that about the jQuery .ready() method
$(handler);
is synonymous with:
$(document).ready(handler);
as well as with a third not recommended form.
This means that $(init)
is completely correct, since init
is the handler in that instance. So, init
will be fired when the DOM is constructed.
Stack views use intrinsic content size, so use layout constraints to define the dimensions of the views.
There is an easy way to add constraints quickly (example):
[view1.heightAnchor constraintEqualToConstant:100].active = true;
Complete Code:
- (void) setup {
//View 1
UIView *view1 = [[UIView alloc] init];
view1.backgroundColor = [UIColor blueColor];
[view1.heightAnchor constraintEqualToConstant:100].active = true;
[view1.widthAnchor constraintEqualToConstant:120].active = true;
//View 2
UIView *view2 = [[UIView alloc] init];
view2.backgroundColor = [UIColor greenColor];
[view2.heightAnchor constraintEqualToConstant:100].active = true;
[view2.widthAnchor constraintEqualToConstant:70].active = true;
//View 3
UIView *view3 = [[UIView alloc] init];
view3.backgroundColor = [UIColor magentaColor];
[view3.heightAnchor constraintEqualToConstant:100].active = true;
[view3.widthAnchor constraintEqualToConstant:180].active = true;
//Stack View
UIStackView *stackView = [[UIStackView alloc] init];
stackView.axis = UILayoutConstraintAxisVertical;
stackView.distribution = UIStackViewDistributionEqualSpacing;
stackView.alignment = UIStackViewAlignmentCenter;
stackView.spacing = 30;
[stackView addArrangedSubview:view1];
[stackView addArrangedSubview:view2];
[stackView addArrangedSubview:view3];
stackView.translatesAutoresizingMaskIntoConstraints = false;
[self.view addSubview:stackView];
//Layout for Stack View
[stackView.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor].active = true;
[stackView.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor].active = true;
}
Note: This was tested on iOS 9
The below example didnt quite work for me,this is the version that i made work!
HTML:
<div class="social-links">
<a href="#"><i class="fa fa-facebook fa-lg"></i></a>
<a href="#"><i class="fa fa-twitter fa-lg"></i></a>
<a href="#"><i class="fa fa-google-plus fa-lg"></i></a>
<a href="#"><i class="fa fa-pinterest fa-lg"></i></a>
</div>
CSS:
.social-links {
text-align:center;
}
.social-links a{
display: inline-block;
width:50px;
height: 50px;
border: 2px solid #909090;
border-radius: 50px;
margin-right: 15px;
}
.social-links a i{
padding: 18px 11px;
font-size: 20px;
color: #909090;
}
For reference—future Python possibilities:
Starting with Python 2.6 you can express binary literals using the prefix 0b or 0B:
>>> 0b101111
47
You can also use the new bin function to get the binary representation of a number:
>>> bin(173)
'0b10101101'
Development version of the documentation: What's New in Python 2.6
This may be the good solution for you: change the code like this very little change
.box{
position: relative;
}
.box:hover .hidden{
opacity: 1;
width:500px;
}
.box .hidden{
background: yellow;
height: 334px;
position: absolute;
top: 0;
left: 0;
width: 0;
opacity: 0;
transition: all 1s ease;
}
See demo here
The main benefit of "".equals(s)
is you don't need the null check (equals
will check its argument and return false
if it's null), which you seem to not care about. If you're not worried about s
being null (or are otherwise checking for it), I would definitely use s.isEmpty()
; it shows exactly what you're checking, you care whether or not s
is empty, not whether it equals the empty string
I got this issue trying some old format code in Swift3,
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(self.respond))
changing the action:"respond:"
to action: #selector(self.respond)
fixed the issue for me.
If you're using Xamarin and came here searching for a solution for this problem, here it's from Microsoft:
In some cases, you may see this error message: Java.Lang.IllegalStateException: Default FirebaseApp is not initialized in this process Make sure to call FirebaseApp.initializeApp(Context) first.
This is a known problem that you can work around by cleaning the solution and rebuilding the project (Build > Clean Solution, Build > Rebuild Solution).
I prefer to use
require_once('phpfile.php');
lots of options out there for you. and a good way to keep things clean.
Sometimes you need to see version of mongodb after making a connection from your project/application/code. In this case you can follow like this:
mongoose.connect(
encodeURI(DB_URL), {
keepAlive: true
},
(err) => {
if (err) {
console.log(err)
}else{
const con = new mongoose.mongo.Admin(mongoose.connection.db)
con.buildInfo( (err, db) => {
if(err){
throw err
}
// see the db version
console.log(db.version)
})
}
}
)
Hope this will be helpful for someone.
Two nitpicks. (1) Best not to use string literals for column alias - that is deprecated. (2) Just use style 120 to get the same value.
CASE
WHEN CreatedDate = '19000101' THEN ''
WHEN CreatedDate = '18000101' THEN ''
ELSE Convert(varchar(19), CreatedDate, 120)
END AS [Created Date]
This is what I found after a more specific Google search than just UTF-8 encode/decode. so for those who are looking for a converting library to convert between encodings, here you go.
https://github.com/inexorabletash/text-encoding
var uint8array = new TextEncoder().encode(str);
var str = new TextDecoder(encoding).decode(uint8array);
Paste from repo readme
All encodings from the Encoding specification are supported:
utf-8 ibm866 iso-8859-2 iso-8859-3 iso-8859-4 iso-8859-5 iso-8859-6 iso-8859-7 iso-8859-8 iso-8859-8-i iso-8859-10 iso-8859-13 iso-8859-14 iso-8859-15 iso-8859-16 koi8-r koi8-u macintosh windows-874 windows-1250 windows-1251 windows-1252 windows-1253 windows-1254 windows-1255 windows-1256 windows-1257 windows-1258 x-mac-cyrillic gb18030 hz-gb-2312 big5 euc-jp iso-2022-jp shift_jis euc-kr replacement utf-16be utf-16le x-user-defined
(Some encodings may be supported under other names, e.g. ascii, iso-8859-1, etc. See Encoding for additional labels for each encoding.)
I'd comment on matthieu's post, but I don't have the rep yet...
In MySQL, the auto increment counter gets reset with truncate, but not with delete.
This will not only change the max_retries but also enable a backoff strategy which makes requests to all http:// addresses sleep for a period of time before retrying (to a total of 5 times):
import requests
from urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
s = requests.Session()
retries = Retry(total=5,
backoff_factor=0.1,
status_forcelist=[ 500, 502, 503, 504 ])
s.mount('http://', HTTPAdapter(max_retries=retries))
s.get('http://httpstat.us/500')
As per documentation for Retry
: if the backoff_factor is 0.1, then sleep() will sleep for [0.1s, 0.2s, 0.4s, ...] between retries. It will also force a retry if the status code returned is 500, 502, 503 or 504.
Various other options to Retry
allow for more granular control:
MaxRetryError
, or to return a response with a response code in the 3xx range.NB: raise_on_status is relatively new, and has not made it into a release of urllib3 or requests yet. The raise_on_status keyword argument appears to have made it into the standard library at most in python version 3.6.
To make requests retry on specific HTTP status codes, use status_forcelist. For example, status_forcelist=[503] will retry on status code 503 (service unavailable).
By default, the retry only fires for these conditions:
TimeoutError
HTTPException
raised (from http.client in Python 3 else httplib).
This seems to be low-level HTTP exceptions, like URL or protocol not
formed correctly.SocketError
ProtocolError
Notice that these are all exceptions that prevent a regular HTTP response from being received. If any regular response is generated, no retry is done. Without using the status_forcelist, even a response with status 500 will not be retried.
To make it behave in a manner which is more intuitive for working with a remote API or web server, I would use the above code snippet, which forces retries on statuses 500, 502, 503 and 504, all of which are not uncommon on the web and (possibly) recoverable given a big enough backoff period.
EDITED: Import Retry
class directly from urllib3.
Good practice nowadays is to use CollectionUtils from either Apache Commons or Spring Framework.
CollectionUtils.isEmpty(list))
The code below can solve the NullPointerException.
@Id
@GeneratedValue
@Column(name = "STOCK_ID", unique = true, nullable = false)
public Integer getStockId() {
return this.stockId;
}
public void setStockId(Integer stockId) {
this.stockId = stockId;
}
If you add @Id
, then you can declare some more like as above declared method.
Only learning myself, but wrapping in a View may allow you to add styles around the button.
const Stack = StackNavigator({
Home: {
screen: HomeView,
navigationOptions: {
title: 'Home View'
}
},
CoolView: {
screen: CoolView,
navigationOptions: ({navigation}) => ({
title: 'Cool View',
headerRight: (<View style={{marginRight: 16}}><Button
title="Cool"
onPress={() => alert('cool')}
/></View>
)
})
}
})
A more general approach would be to set the UIView's appearance's tintColor.
UIColor *myColor = [UIColor purpleColor];
[[UIView appearance] setTintColor:myColor];
Makes sense if you're using many default UI elements.
** Update ** A scalars converter has been added to retrofit that allows for a String
response with less ceremony than my original answer below.
Example interface --
public interface GitHubService {
@GET("/users/{user}")
Call<String> listRepos(@Path("user") String user);
}
Add the ScalarsConverterFactory
to your retrofit builder. Note: If using ScalarsConverterFactory
and another factory, add the scalars factory first.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
// add other factories here, if needed.
.build();
You will also need to include the scalars converter in your gradle file --
implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'
--- Original Answer (still works, just more code) ---
I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject
land. I suspect your specific problem might be better solved using a custom gson TypeAdapter
or a retrofit Converter
if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -
First, if you are using Retrofit 2, you should start using the Call
API. Instead of sending an object to convert as the type parameter, use ResponseBody
from okhttp --
public interface GitHubService {
@GET("/users/{user}")
Call<ResponseBody> listRepos(@Path("user") String user);
}
then you can create and execute your call --
GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Response<ResponseBody> response) {
try {
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable t) {
e.printStackTrace();
}
});
Note The code above calls string()
on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream()
instead. See the ResponseBody
docs.
You should read up on the onclick
html attribute and the window.open()
documentation. Below is what you want.
<a href='#' onclick='window.open("http://www.google.com", "myWin", "scrollbars=yes,width=400,height=650"); return false;'>1</a>
_x000D_
JSFiddle: http://jsfiddle.net/TBcVN/
If you would like to auto format on save just with Javascript source, add this one into Users Setting
(press Cmd, or Ctrl,):
"[javascript]": { "editor.formatOnSave": true }
Found these docu on the google docu pages:
In your example, you would get (if you picked the 3rd row) "C3:O3", cause C --> O is 12 columns
edit
Using the example on the docu:
// The code below will get the number of columns for the range C2:G8
// in the active spreadsheet, which happens to be "4"
var count = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getNumColumns(); Browser.msgBox(count);
The values between brackets:
2: the starting row = 2
3: the starting col = C
6: the number of rows = 6 so from 2 to 8
4: the number of cols = 4 so from C to G
So you come to the range: C2:G8
In [1]: df
Out[1]:
Sp Mt Value count
0 MM1 S1 a 3
1 MM1 S1 n 2
2 MM1 S3 cb 5
3 MM2 S3 mk 8
4 MM2 S4 bg 10
5 MM2 S4 dgd 1
6 MM4 S2 rd 2
7 MM4 S2 cb 2
8 MM4 S2 uyi 7
In [2]: df.groupby(['Mt'], sort=False)['count'].max()
Out[2]:
Mt
S1 3
S3 8
S4 10
S2 7
Name: count
To get the indices of the original DF you can do:
In [3]: idx = df.groupby(['Mt'])['count'].transform(max) == df['count']
In [4]: df[idx]
Out[4]:
Sp Mt Value count
0 MM1 S1 a 3
3 MM2 S3 mk 8
4 MM2 S4 bg 10
8 MM4 S2 uyi 7
Note that if you have multiple max values per group, all will be returned.
Update
On a hail mary chance that this is what the OP is requesting:
In [5]: df['count_max'] = df.groupby(['Mt'])['count'].transform(max)
In [6]: df
Out[6]:
Sp Mt Value count count_max
0 MM1 S1 a 3 3
1 MM1 S1 n 2 3
2 MM1 S3 cb 5 8
3 MM2 S3 mk 8 8
4 MM2 S4 bg 10 10
5 MM2 S4 dgd 1 10
6 MM4 S2 rd 2 7
7 MM4 S2 cb 2 7
8 MM4 S2 uyi 7 7
For anyone using Windows 10, there's a request in Feedback Hub to get Microsoft to fix this issue. If you'd like to add a +1 to have it fixed, here's a link: https://aka.ms/Cryalp.
The link only works on Windows 10 as it needs to open Feedback Hub to get to the suggestion. The link was generated using the "Share" feature in Feedback Hub and aka.ms is an internal link shortening service used by Microsoft.
for an actual string object:
yourstring.length();
or
yourstring.size();
The documentation on CREATE EVENT is quite good, but it takes a while to get it right.
You have two problems, first, making the event recur, second, making it run at 13:00 daily.
This example creates a recurring event.
CREATE EVENT e_hourly
ON SCHEDULE
EVERY 1 HOUR
COMMENT 'Clears out sessions table each hour.'
DO
DELETE FROM site_activity.sessions;
When in the command-line MySQL client, you can:
SHOW EVENTS;
This lists each event with its metadata, like if it should run once only, or be recurring.
The second problem: pointing the recurring event to a specific schedule item.
By trying out different kinds of expression, we can come up with something like:
CREATE EVENT IF NOT EXISTS `session_cleaner_event`
ON SCHEDULE
EVERY 13 DAY_HOUR
COMMENT 'Clean up sessions at 13:00 daily!'
DO
DELETE FROM site_activity.sessions;
When you change attribute value like mentioned above the change
event is not triggered so if needed for some reasons you can trigger it like so
$('input[name=video_radio][value="' + r.data.video_radio + '"]')
.prop('checked', true)
.trigger('change');
Create a new directory layout-land
, then create xml
file with same name in layout-land
as it was layout
directory and align there your content for Landscape mode.
Note that id of content in both xml
is same.
If you go with the solution by @qiao, perhaps you would want to remove the appended child since the tab remains open and subsequent clicks would add more elements to the DOM.
// Code by @qiao
var a = document.createElement('a')
a.href = 'http://www.google.com'
a.target = '_blank'
document.body.appendChild(a)
a.click()
// Added code
document.body.removeChild(a)
Maybe someone could post a comment to his post, because I cannot.
you are thinking too much... Take a look at this [i think this is what you wanted - if not let me know]
css
.even{background: red; color:white;}
.odd{background: darkred; color:white;}
html
<div class="container">
<ul class="list-unstyled">
<li class="col-md-6 odd">Dumby Content</li>
<li class="col-md-6 odd">Dumby Content</li>
<li class="col-md-6 even">Dumby Content</li>
<li class="col-md-6 even">Dumby Content</li>
<li class="col-md-6 odd">Dumby Content</li>
<li class="col-md-6 odd">Dumby Content</li>
</ul>
</div>
DPAPI is just for this purpose. Use DPAPI to encrypt the password the first time the user enters is, store it in a secure location (User's registry, User's application data directory, are some choices). Whenever the app is launched, check the location to see if your key exists, if it does use DPAPI to decrypt it and allow access, otherwise deny it.
The two conditional statements you list here are not better than one another. Your usage depends on the situation. You have a typo by the way in the 2nd example. There should be only one equals sign after the exclamation mark.
The 1st example determines if the value in myVar is true and executes the code inside of the {...}
The 2nd example evaluates if myVar does not equal null and if that case is true it will execute your code inside of the {...}
I suggest taking a look into conditional statements for more techniques. Once you are familiar with them, you can decide when you need them.
You might want to have a look at joda time, which is a little easier to use than the java native date tools, and provides many common date patterns pre-built.
In response to comments, more detail:
To do this using Joda time, you need two DateTimeFormatters - one for your input format to parse your input and one for your output format to print your output. Your input format is an ISO standard format, so Joda time's ISODateTimeFormat class has a static method with a parser for it already: dateHourMinuteSecondMillis. Your output format isn't one they have a pre-built formatter for, so you'll have to make one yourself using DateTimeFormat. I think DateTimeFormat.forPattern("mm/dd/yyyy kk:mm:ss.SSS");
should do the trick. Once you have your two formatters, call the parseDateTime()
method on the input format and the print
method on the output format to get your result, as a string.
Putting it together should look something like this (warning, untested):
DateTimeFormatter input = ISODateTimeFormat.dateHourMinuteSecondMillis();
DateTimeFormatter output = DateTimeFormat.forPattern("mm/dd/yyyy kk:mm:ss.SSS");
String outputFormat = output.print( input.parseDate(inputFormat) );
setTimeout() function it's use to delay a process in JavaScript.
w3schools has an easy tutorial about this function.
I needed something along the lines of a simple string reduction function recently. Basically, the code looked something like this (C/C++ code ahead):
size_t ReduceString(char *Dest, size_t DestSize, const char *Src, size_t SrcSize, bool Normalize)
{
size_t x, x2 = 0, z = 0;
memset(Dest, 0, DestSize);
for (x = 0; x < SrcSize; x++)
{
Dest[x2] = (char)(((unsigned int)(unsigned char)Dest[x2]) * 37 + ((unsigned int)(unsigned char)Src[x]));
x2++;
if (x2 == DestSize - 1)
{
x2 = 0;
z++;
}
}
// Normalize the alphabet if it looped.
if (z && Normalize)
{
unsigned char TempChr;
y = (z > 1 ? DestSize - 1 : x2);
for (x = 1; x < y; x++)
{
TempChr = ((unsigned char)Dest[x]) & 0x3F;
if (TempChr < 10) TempChr += '0';
else if (TempChr < 36) TempChr = TempChr - 10 + 'A';
else if (TempChr < 62) TempChr = TempChr - 36 + 'a';
else if (TempChr == 62) TempChr = '_';
else TempChr = '-';
Dest[x] = (char)TempChr;
}
}
return (SrcSize < DestSize ? SrcSize : DestSize);
}
It probably has more collisions than might be desired but it isn't intended for use as a cryptographic hash function. You might try various multipliers (i.e. change the 37 to another prime number) if you get too many collisions. One of the interesting features of this snippet is that when Src is shorter than Dest, Dest ends up with the input string as-is (0 * 37 + value = value). If you want something "readable" at the end of the process, Normalize will adjust the transformed bytes at the cost of increasing collisions.
Source:
https://github.com/cubiclesoft/cross-platform-cpp/blob/master/sync/sync_util.cpp
This should do the trick for ASP.NET. The concept is the same as shown in the PHP example. Since the URL is different everytime the script is loaded, neither browser of proxy should cache the file. I'm used to put my JavaScript code into separate files, and wasted a significant amount of time with Visual Studio until I realized that it wouldn't reload the JavaScript files.
<script src="Scripts/main.js?version=<% =DateTime.Now.Ticks.ToString()%>" type="text/javascript"></script>
Full example:
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> <script src="Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script> <script src="Scripts/main.js?version=<% =DateTime.Now.Ticks.ToString()%>" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { myInit(); }); </script> </asp:Content>
Obvously, this solution should only be used during the development stage, and should be removed before posting the site.
git pull do below operation.
i.
git fetch
ii.
git merge
To undo pull do any operation:
i.
git reset --hard
--- its revert all local change alsoor
ii.
git reset --hard master@{5.days.ago}
(like10.minutes.ago
,1.hours.ago
,1.days.ago
..) to get local changes.or
iii.
git reset --hard commitid
Improvement:
Next time use git pull --rebase
instead of git pull
.. its sync server change by doing ( fetch & merge).
You can also set the environment variable to
CUDA_VISIBLE_DEVICES=""
without having to modify the source code.
You can add a random (or datetime string) as query string to the url that points to your script. Like so:
<script type="text/javascript" src="test.js?q=123"></script>
Every time you refresh the page you need to make sure the value of 'q' is changed.
Evidently, sometimes, the display properties of parent of the element containing the matter that shouldn't overflow should also be set to overflow:hidden
as well, e.g.:
<div style="overflow: hidden">
<div style="overflow: hidden">some text that should not overflow<div>
</div>
Why? I have no idea but it worked for me. See https://medium.com/@crrollyson/overflow-hidden-not-working-check-the-child-element-c33ac0c4f565 (ignore the sniping at stackoverflow!)
Try this
typeof(IFoo).IsAssignableFrom(typeof(BarClass));
This will tell you whether BarClass(Derived)
implements IFoo(SomeType)
or not
GUI-driven approach: Open the docker desktop tool (that usually comes with Docker):
You may also combine cut
and paste
:
paste <(cut -f2 file.txt) <(cut -f1 file.txt)
via comments: It's possible to avoid bashisms and remove one instance of cut by doing:
paste file.txt file.txt | cut -f2,3
This is for other people landing here. First of all you need a servlet. I used a @POST request. Now in your jsp file you have two ways to do this:
The complicated way with AJAX, in case you are new to jsp: You need to do a post with the javascript var that you want to use in you java class and use JSP to call your java function from inside your request:
$(document).ready(function() {
var sendVar = "hello";
$('#domId').click(function (e)
{
$.ajax({
type: "post",
url: "/", //or whatever your url is
data: "var=" + sendVar ,
success: function(){
console.log("success: " + sendVar );
<%
String received= request.getParameter("var");
if(received == null || received.isEmpty()){
received = "some default value";
}
MyJavaClass.processJSvar(received);
%>;
}
});
});
});
The easy way just with JSP:
<form id="myform" method="post" action="http://localhost:port/index.jsp">
<input type="hidden" name="inputName" value=""/>
<%
String pg = request.getParameter("inputName");
if(pg == null || pg.isEmpty()){
pg = "some default value";
}
DatasyncMain.changeToPage(pg);
%>;
</form>
Of course in this case you still have to load the input value from JS (so far I haven't figured out another way to load it).
My problem was that a Cloud Access Security Broker, NetSkope, was installed on my work laptop through a software update. This was altering the certificate chain and I was still not able to connect to the server through my java client after importing the entire chain to my cacerts keystore. I disabled NetSkope and was able to successfully connect.
Using parameter expansion (delete matched beginning):
args="$@"
last=${args##* }
It's also easy to get all before last:
prelast=${args% *}
This might be useful when you want to work in parallel and read only chunks of data but keep it clean with new lines.
def readInChunks(fileObj, chunkSize=1024):
while True:
data = fileObj.read(chunkSize)
if not data:
break
while data[-1:] != '\n':
data+=fileObj.read(1)
yield data
To do it in a simpler way, consider below:
JsonObject jsonObject = (new JsonParser()).parse(json).getAsJsonObject();
You can do this by using the following xml
<RelativeLayout
style="@style/GenericProgressBackground"
android:id="@+id/loadingPanel"
>
<ProgressBar
style="@style/GenericProgressIndicator"/>
</RelativeLayout>
With this style
<style name="GenericProgressBackground" parent="android:Theme">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">fill_parent</item>
<item name="android:background">#DD111111</item>
<item name="android:gravity">center</item>
</style>
<style name="GenericProgressIndicator" parent="@android:style/Widget.ProgressBar.Small">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:indeterminate">true</item>
</style>
To use this, you must hide your UI elements by setting the visibility value to GONE and whenever the data is loaded, call setVisibility(View.VISIBLE)
on all your views to restore them. Don't forget to call findViewById(R.id.loadingPanel).setVisiblity(View.GONE)
to hide the loading animation.
If you dont have a loading event/function but just want the loading panel to disappear after x seconds use a Handle to trigger the hiding/showing.
should you pass it in this way :
public ActionResult CreatePerson(int id) //controller
window.location.href = "@Url.Action("CreatePerson", "Person",new { @id = 1});
web2py has comet_messaging.py, which uses Tornado for websockets look at an example here: http://vimeo.com/18399381 and here vimeo . com / 18232653
Please add below jQuery Migrate Plugin
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://code.jquery.com/jquery-migrate-1.4.1.min.js"></script>
If you are sure there are no leading spaces, you can use bash parameter substitution:
$ string="word1 word2"
$ echo ${string/%\ */}
word1
Watch out for escaping the single space. See here for more examples of substitution patterns. If you have bash > 3.0, you could also use regular expression matching to cope with leading spaces - see here:
$ string=" word1 word2"
$ [[ ${string} =~ \ *([^\ ]*) ]]
$ echo ${BASH_REMATCH[1]}
word1
You can give a function expression a name that is actually private and is only visible from inside of the function ifself:
var factorial = function myself (n) {
if (n <= 1) {
return 1;
}
return n * myself(n-1);
}
typeof myself === 'undefined'
Here myself
is visible only inside of the function itself.
You can use this private name to call the function recursively.
See 13. Function Definition
of the ECMAScript 5 spec:
The Identifier in a FunctionExpression can be referenced from inside the FunctionExpression's FunctionBody to allow the function to call itself recursively. However, unlike in a FunctionDeclaration, the Identifier in a FunctionExpression cannot be referenced from and does not affect the scope enclosing the FunctionExpression.
Please note that Internet Explorer up to version 8 doesn't behave correctly as the name is actually visible in the enclosing variable environment, and it references a duplicate of the actual function (see patrick dw's comment below).
Alternatively you could use arguments.callee
to refer to the current function:
var factorial = function (n) {
if (n <= 1) {
return 1;
}
return n * arguments.callee(n-1);
}
The 5th edition of ECMAScript forbids use of arguments.callee() in strict mode, however:
(From MDN): In normal code arguments.callee refers to the enclosing function. This use case is weak: simply name the enclosing function! Moreover, arguments.callee substantially hinders optimizations like inlining functions, because it must be made possible to provide a reference to the un-inlined function if arguments.callee is accessed. arguments.callee for strict mode functions is a non-deletable property which throws when set or retrieved.
You can do this even in pure JavaScript by using the in built "filter" function for arrays:
Array.prototype.filterObjects = function(key, value) {
return this.filter(function(x) { return x[key] === value; })
}
So now simply pass "id" in place of key
and "45" in place of value
, and you will get the full object matching an id of 45. So that would be,
myArr.filterObjects("id", "45");
An alternative, I think for your purpose, is to use the round() function:
select round((10 * 1.5),2) // prints 15.00
You can try it here:
I did it this way: Just add the event to any control, set the control's tag, and add a conditional to handle the tooltip for the appropriate control/tag.
private void Info_MouseHover(object sender, EventArgs e)
{
Control senderObject = sender as Control;
string hoveredControl = senderObject.Tag.ToString();
// only instantiate a tooltip if the control's tag contains data
if (hoveredControl != "")
{
ToolTip info = new ToolTip
{
AutomaticDelay = 500
};
string tooltipMessage = string.Empty;
// add all conditionals here to modify message based on the tag
// of the hovered control
if (hoveredControl == "save button")
{
tooltipMessage = "This button will save stuff.";
}
info.SetToolTip(senderObject, tooltipMessage);
}
}
I based this solution on the comments of @jberger.
if git checkout master &&
git fetch origin master &&
[ `git rev-list HEAD...origin/master --count` != 0 ] &&
git merge origin/master
then
echo 'Updated!'
else
echo 'Not updated.'
fi
I really hate to put long HTML inside of the attribute, here is my solution, clear and simple (replace ? with whatever you want):
<a class="btn-lg popover-dismiss" data-placement="bottom" data-toggle="popover" title="Help">
<h2>Some title</h2>
Some text
</a>
then
var help = $('.popover-dismiss');
help.attr('data-content', help.html()).text(' ? ').popover({trigger: 'hover', html: true});
I find this issue in my centOS is caused by "Oracle Java is replace by gcj", after change default java to "Oracle Java", the issue is resolved.
alternatives --config java
There are 2 programs which provide 'java'.
Selection Command
-----------------------------------------------
* 1 /usr/lib/jvm/jre-1.5.0-gcj/bin/java
+ 2 /usr/java/jdk1.7.0_67/bin/java
SELECT field1,
field2,
'example' AS newfield
FROM TABLE1
This will add a column called "newfield" to the output, and its value will always be "example".
I'm not sure what happened in your case that fixed the issue, but your issue was on this line:
Caused by: java.lang.NoClassDefFoundError: javax/xml/rpc/handler/soap/SOAPMessageContext
You need to add jaxrpc-api.jar
to your /lib
s or add
<dependency>
<groupId>javax.xml</groupId>
<artifactId>jaxrpc-api</artifactId>
<version>x.x.x</version>
</dependency>
to your maven dependencies.
Angular's own website serves simplified content to search engines: http://docs.angularjs.org/?_escaped_fragment_=/tutorial/step_09
Say your Angular app is consuming a Node.js/Express-driven JSON api, like /api/path/to/resource
. Perhaps you could redirect any requests with ?_escaped_fragment_
to /api/path/to/resource.html
, and use content negotiation to render an HTML template of the content, rather than return the JSON data.
The only thing is, your Angular routes would need to match 1:1 with your REST API.
EDIT: I'm realizing that this has the potential to really muddy up your REST api and I don't recommend doing it outside of very simple use-cases where it might be a natural fit.
Instead, you can use an entirely different set of routes and controllers for your robot-friendly content. But then you're duplicating all of your AngularJS routes and controllers in Node/Express.
I've settled on generating snapshots with a headless browser, even though I feel that's a little less-than-ideal.
INADDR_ANY
instructs listening socket to bind to all available interfaces. It's the same as trying to bind to inet_addr("0.0.0.0")
.
For completeness I'll also mention that there is also IN6ADDR_ANY_INIT for IPv6 and it's the same as trying to bind to ::
address for IPv6 socket.
#include <netinet/in.h>
struct in6_addr addr = IN6ADDR_ANY_INIT;
Also, note that when you bind IPv6 socket to to IN6ADDR_ANY_INIT
your socket will bind to all IPv6 interfaces, and should be able to accept connections from IPv4 clients as well (though IPv6-mapped addresses).
It is a little complicated, but you can draw all the objects by the following code:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")
# draw cube
r = [-1, 1]
for s, e in combinations(np.array(list(product(r, r, r))), 2):
if np.sum(np.abs(s-e)) == r[1]-r[0]:
ax.plot3D(*zip(s, e), color="b")
# draw sphere
u, v = np.mgrid[0:2*np.pi:20j, 0:np.pi:10j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
ax.plot_wireframe(x, y, z, color="r")
# draw a point
ax.scatter([0], [0], [0], color="g", s=100)
# draw a vector
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d
class Arrow3D(FancyArrowPatch):
def __init__(self, xs, ys, zs, *args, **kwargs):
FancyArrowPatch.__init__(self, (0, 0), (0, 0), *args, **kwargs)
self._verts3d = xs, ys, zs
def draw(self, renderer):
xs3d, ys3d, zs3d = self._verts3d
xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
self.set_positions((xs[0], ys[0]), (xs[1], ys[1]))
FancyArrowPatch.draw(self, renderer)
a = Arrow3D([0, 1], [0, 1], [0, 1], mutation_scale=20,
lw=1, arrowstyle="-|>", color="k")
ax.add_artist(a)
plt.show()
CREATE TEMPORARY TABLE IF NOT EXISTS to_table_name AS (SELECT * FROM from_table_name)
If you intend to use the default VB6 Collection
, then the easiest you can do is:
col1.add array("first key", "first string"), "first key"
col1.add array("second key", "second string"), "second key"
col1.add array("third key", "third string"), "third key"
Then you can list all values:
Dim i As Variant
For Each i In col1
Debug.Print i(1)
Next
Or all keys:
Dim i As Variant
For Each i In col1
Debug.Print i(0)
Next
Problem is that your folder is not identified as a Source folder.
With SQL Server try:
SELECT TOP 1 *
FROM dbo.youTable
WHERE user_id = 'userid'
ORDER BY date_added desc
var duplicates = lst.GroupBy(s => s)
.SelectMany(grp => grp.Skip(1));
Note that this will return all duplicates, so if you only want to know which items are duplicated in the source list, you could apply Distinct
to the resulting sequence or use the solution given by Mark Byers.
I wanted to find the same and the UK Government Data Standards mentioned in the accepted answer sounded ideal. However none of these seemed to exist any more - after an extended search I found it in an archive here: http://webarchive.nationalarchives.gov.uk/+/http://www.cabinetoffice.gov.uk/govtalk/schemasstandards/e-gif/datastandards.aspx. Need to download the zip, extract it and then open default.htm in the html folder.
1 - You can set a timeout in your application :
var client = new YourServiceReference.YourServiceClass();
client.Timeout = 60; // or -1 for infinite
It is in milliseconds.
2 - Also you can increase timeout value in httpruntime tag in web/app.config :
<configuration>
<system.web>
<httpRuntime executionTimeout="<<**seconds**>>" />
...
</system.web>
</configuration>
For ASP.NET applications, the Timeout property value should always be less than the executionTimeout attribute of the httpRuntime element in Machine.config. The default value of executionTimeout is 90 seconds. This property determines the time ASP.NET continues to process the request before it returns a timed out error. The value of executionTimeout should be the proxy Timeout, plus processing time for the page, plus buffer time for queues. -- Source
Better approach may be a polyfill like this
jQuery.fn.load = function(callback){ $(window).on("load", callback) };
With this you can leave the legacy code untouched. If you use webpack be sure to use script-loader.
Here is my basic outline of REST. I tried to demonstrate the thinking behind each of the components in a RESTful architecture so that understanding the concept is more intuitive. Hopefully this helps demystify REST for some people!
REST (Representational State Transfer) is a design architecture that outlines how networked resources (i.e. nodes that share information) are designed and addressed. In general, a RESTful architecture makes it so that the client (the requesting machine) and the server (the responding machine) can request to read, write, and update data without the client having to know how the server operates and the server can pass it back without needing to know anything about the client. Okay, cool...but how do we do this in practice?
The most obvious requirement is that there needs to be a universal language of some sort so that the server can tell the client what it is trying to do with the request and for the server to respond.
But to find any given resource and then tell the client where that resource lives, there needs to be a universal way of pointing at resources. This is where Universal Resource Identifiers (URIs) come in; they are basically unique addresses to find the resources.
But the REST architecture doesn’t end there! While the above fulfills the basic needs of what we want, we also want to have an architecture that supports high volume traffic since any given server usually handles responses from a number of clients. Thus, we don’t want to overwhelm the server by having it remember information about previous requests.
Therefore, we impose the restriction that each request-response pair between the client and the server is independent, meaning that the server doesn’t have to remember anything about previous requests (previous states of the client-server interaction) to respond to a new request. This means that we want our interactions to be stateless.
To further ease the strain on our server from redoing computations that have already been recently done for a given client, REST also allows caching. Basically, caching means to take a snapshot of the initial response provided to the client. If the client makes the same request again, the server can provide the client with the snapshot rather than redo all of the computations that were necessary to create the initial response. However, since it is a snapshot, if the snapshot has not expired--the server sets an expiration time in advance--and the response has been updated since the initial cache (i.e. the request would give a different answer than the cached response), the client will not see the updates until the cache expires (or the cache is cleared) and the response is rendered from scratch again.
The last thing that you’ll often here about RESTful architectures is that they are layered. We have actually already been implicitly discussing this requirement in our discussion of the interaction between the client and server. Basically, this means that each layer in our system interacts only with adjacent layers. So in our discussion, the client layer interacts with our server layer (and vice versa), but there might be other server layers that help the primary server process a request that the client does not directly communicate with. Rather, the server passes on the request as necessary.
Now, if all of this sounds familiar, then great. The Hypertext Transfer Protocol (HTTP), which defines the communication protocol via the World Wide Web is an implementation of the abstract notion of RESTful architecture (or an implementation of the abstract REST class if you're an OOP fanatic like me). In this implementation of REST, the client and server interact via GET, POST, PUT, DELETE, etc., which are part of the universal language and the resources can be pointed to using URLs.
git cherry-pick <original commit sha>
Will make a copy of the original commit, essentially re-applying the commit
Reverting the revert will do the same thing, with a messier commit message:
git revert <commit sha of the revert>
Either of these ways will allow you to git push
without overwriting history, because it creates a new commit after the revert.
When typing the commit sha, you typically only need the first 5 or 6 characters:
git cherry-pick 6bfabc
In Oracle 12c and above, we have two types of databases:
If you want to create an user, you have two possibilities:
You can create a "container user" aka "common user".
Common users belong to CBDs as well as to current and future PDBs. It means they can perform operations in Container DBs or Pluggable DBs according to assigned privileges.
create user c##username identified by password;
You can create a "pluggable user" aka "local user".
Local users belong only to a single PDB. These users may be given administrative privileges, but only for that PDB inside which they exist. For that, you should connect to pluggable datable like that:
alter session set container = nameofyourpluggabledatabase;
and there, you can create user like usually:
create user username identified by password;
Don't forget to specify the tablespace(s) to use, it can be useful during import/export of your DBs. See this for more information about it https://docs.oracle.com/database/121/SQLRF/statements_8003.htm#SQLRF01503
There is an important bit that is not mentioned in the article to which you linked and that is flex-basis
. By default flex-basis
is auto
.
From the spec:
If the specified flex-basis is auto, the used flex basis is the value of the flex item’s main size property. (This can itself be the keyword auto, which sizes the flex item based on its contents.)
Each flex item has a flex-basis
which is sort of like its initial size. Then from there, any remaining free space is distributed proportionally (based on flex-grow
) among the items. With auto
, that basis is the contents size (or defined size with width
, etc.). As a result, items with bigger text within are being given more space overall in your example.
If you want your elements to be completely even, you can set flex-basis: 0
. This will set the flex basis to 0 and then any remaining space (which will be all space since all basises are 0) will be proportionally distributed based on flex-grow
.
li {
flex-grow: 1;
flex-basis: 0;
/* ... */
}
This diagram from the spec does a pretty good job of illustrating the point.
And here is a working example with your fiddle.
For Photoshop you need to download Photoshop portable.... Load image e press "w" click in image e suave as png or gif....
help.search()
is a handy function, e.g.
> help.search("concatenate")
will lead you to paste()
.
The guaranteed one that I had working was something along these lines:
myModule.config(['$httpProvider', function($httpProvider) {
if (!$httpProvider.defaults.headers.common) {
$httpProvider.defaults.headers.common = {};
}
$httpProvider.defaults.headers.common["Cache-Control"] = "no-cache";
$httpProvider.defaults.headers.common.Pragma = "no-cache";
$httpProvider.defaults.headers.common["If-Modified-Since"] = "Mon, 26 Jul 1997 05:00:00 GMT";
}]);
I had to merge 2 of the above solutions in order to guarantee the correct usage for all methods, but you can replace common
with get
or other method i.e. put
, post
, delete
to make this work for different cases.
Very simple, after defining args variable by 'args = parser.parse_args()' it contains all data of args subset variables too. To check if a variable is set or no assuming the 'action="store_true" is used...
if args.argument_name:
# do something
else:
# do something else
I had this problem. I had to make my class extend ListActivity rather than Activity, and rename my list in the XML to android:id="@android:id/list"
Here's another approach I use since I like n for easy switching between node versions.
On a new Ubuntu system, first install the 'system' node:
curl -sL https://deb.nodesource.com/setup | sudo bash -
Then install n module globally:
npm install -g n
Since the system node was installed first (above), the alternatives system can be used to cleanly point to the node provided by n. First make sure the alternatives system has nothing for node:
update-alternatives --remove-all node
Then add the node provided by n:
update-alternatives --install /usr/bin/node node /usr/local/bin/node 1
Next add node provided by the system (the one that was installed with curl):
update-alternatives --install /usr/bin/node node /usr/bin/nodejs 2
Now select the node provided by n using the interactive menu (select /usr/local/bin/node
from the menu presented by the following command):
update-alternatives --config node
Finally, since /usr/local/bin
usually has a higher precedence in PATH than /usr/bin
, the following alias must be created (enter in your .bashrc or .zshrc) if the alternatives system node is to be effective; otherwise the node installed with n in /usr/local/bin takes always precedence:
alias node='/usr/bin/node'
Now you can easily switch between node versions with n <desired node version number>
.
The function you need is CInt
.
ie CInt(PrinterLabel)
See Type Conversion Functions (Visual Basic) on MSDN
Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!
int rotation = getWindowManager().getDefaultDisplay().getRotation();
this will gives all orientation like normal and reverse
and handle it like
int angle = 0;
switch (rotation) {
case Surface.ROTATION_90:
angle = -90;
break;
case Surface.ROTATION_180:
angle = 180;
break;
case Surface.ROTATION_270:
angle = 90;
break;
default:
angle = 0;
break;
}
There is a builtin function all
:
all (x > limit for x in my_list)
Being limit the value greater than which all numbers must be.
Try using the downloadable DotNetVersionLister module (based on registry infos and some version-to-marketing-version lookup table).
Which would be used like this:
PS> Get-DotNetVersion -LocalHost -nosummary
ComputerName : localhost
>=4.x : 4.5.2
v4\Client : Installed
v4\Full : Installed
v3.5 : Installed
v3.0 : Installed
v2.0.50727 : Installed
v1.1.4322 : Not installed (no key)
Ping : True
Error :
Or like this if you just want to test it for some .NET framework >= 4.*:
PS> (Get-DotNetVersion -LocalHost -nosummary).">=4.x"
4.5.2
But it will not work (install/import) e.g. with PS v2.0 (Win 7, Win Server 2010 standard) due to incompatibility...
(You could skip reading this and use code below)
We had to work with PS 2.0 on some machines and could not install/import the above DotNetVersionLister.
On other machines we wanted to update (from PS 2.0) to PS 5.1 (which in turn needs .NET Framework >= 4.5) with the help of two company-custom Install-DotnetLatestCompany
and Install-PSLatestCompany
.
To guide admins nicely through the install/update process we would have to determine the .NET version in these functions on all machines and PS versions existing.
Thus we used also the below functions to determine them more safely in all environments...
So the following code and below (extracted) usage examples are useful here (based on other answers here):
function Get-DotNetVersionByFs {
<#
.SYNOPSIS
NOT RECOMMENDED - try using instead:
Get-DotNetVersion
from DotNetVersionLister module (https://github.com/EliteLoser/DotNetVersionLister),
but it is not usable/importable in PowerShell 2.0
Get-DotNetVersionByReg
reg(istry) based: (available herin as well) but it may return some wrong version or may not work reliably for versions > 4.5
(works in PSv2.0)
Get-DotNetVersionByFs (this):
f(ile) s(ystem) based: determines the latest installed .NET version based on $Env:windir\Microsoft.NET\Framework content
this is unreliable, e.g. if 4.0* is already installed some 4.5 update will overwrite content there without
renaming the folder
(works in PSv2.0)
.EXAMPLE
PS> Get-DotnetVersionByFs
4.0.30319
.EXAMPLE
PS> Get-DotnetVersionByFs -All
1.0.3705
1.1.4322
2.0.50727
3.0
3.5
4.0.30319
.NOTES
from https://stackoverflow.com/a/52078523/1915920
#>
[cmdletbinding()]
param(
[Switch]$All ## do not return only latest, but all installed
)
$list = ls $Env:windir\Microsoft.NET\Framework |
?{ $_.PSIsContainer -and $_.Name -match '^v\d.[\d\.]+' } |
%{ $_.Name.TrimStart('v') }
if ($All) { $list } else { $list | select -last 1 }
}
function Get-DotNetVersionByReg {
<#
.SYNOPSIS
NOT RECOMMENDED - try using instead:
Get-DotNetVersion
From DotNetVersionLister module (https://github.com/EliteLoser/DotNetVersionLister),
but it is not usable/importable in PowerShell 2.0.
Determines the latest installed .NET version based on registry infos under 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP'
.EXAMPLE
PS> Get-DotnetVersionByReg
4.5.51209
.EXAMPLE
PS> Get-DotnetVersionByReg -AllDetailed
PSChildName Version Release
----------- ------- -------
v2.0.50727 2.0.50727.5420
v3.0 3.0.30729.5420
Windows Communication Foundation 3.0.4506.5420
Windows Presentation Foundation 3.0.6920.5011
v3.5 3.5.30729.5420
Client 4.0.0.0
Client 4.5.51209 379893
Full 4.5.51209 379893
.NOTES
from https://stackoverflow.com/a/52078523/1915920
#>
[cmdletbinding()]
param(
[Switch]$AllDetailed ## do not return only latest, but all installed with more details
)
$Lookup = @{
378389 = [version]'4.5'
378675 = [version]'4.5.1'
378758 = [version]'4.5.1'
379893 = [version]'4.5.2'
393295 = [version]'4.6'
393297 = [version]'4.6'
394254 = [version]'4.6.1'
394271 = [version]'4.6.1'
394802 = [version]'4.6.2'
394806 = [version]'4.6.2'
460798 = [version]'4.7'
460805 = [version]'4.7'
461308 = [version]'4.7.1'
461310 = [version]'4.7.1'
461808 = [version]'4.7.2'
461814 = [version]'4.7.2'
}
$list = Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse |
Get-ItemProperty -name Version, Release -EA 0 |
# For One True framework (latest .NET 4x), change match to PSChildName -eq "Full":
Where-Object { $_.PSChildName -match '^(?!S)\p{L}'} |
Select-Object `
@{
name = ".NET Framework" ;
expression = {$_.PSChildName}},
@{ name = "Product" ;
expression = {$Lookup[$_.Release]}},
Version, Release
if ($AllDetailed) { $list | sort version } else { $list | sort version | select -last 1 | %{ $_.version } }
}
Example usage:
PS> Get-DotNetVersionByFs
4.0.30319
PS> Get-DotNetVersionByFs -All
1.0.3705
1.1.4322
2.0.50727
3.0
3.5
4.0.30319
PS> Get-DotNetVersionByReg
4.5.51209
PS> Get-DotNetVersionByReg -AllDetailed
.NET Framework Product Version Release
-------------- ------- ------- -------
v2.0.50727 2.0.50727.5420
v3.0 3.0.30729.5420
Windows Communication Foundation 3.0.4506.5420
Windows Presentation Foundation 3.0.6920.5011
v3.5 3.5.30729.5420
Client 4.0.0.0
Client 4.5.2 4.5.51209 379893
Full 4.5.2 4.5.51209 379893
You can use Matrix to resize your camera image ....
BitmapFactory.Options options=new BitmapFactory.Options();
InputStream is = getContentResolver().openInputStream(currImageURI);
bm = BitmapFactory.decodeStream(is,null,options);
int Height = bm.getHeight();
int Width = bm.getWidth();
int newHeight = 300;
int newWidth = 300;
float scaleWidth = ((float) newWidth) / Width;
float scaleHeight = ((float) newHeight) / Height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0,Width, Height, matrix, true);
BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);
I got this issue when I used an ajax call to retrieve data from the database. When the controller returned the array it converted it to a boolean. The problem was that I had "invalid characters" like ú (u with accent).
You can use this to paste from clipboard with Ctrlv:
set pastetoggle=<F10>
inoremap <C-v> <F10><C-r>+<F10>
And this for yanking visual selection into clipboard with Ctrlc:
vnoremap <C-c> "+y
If you also want to use clipboard by default for classic vim yanking/pasting (y/p) in normal mode, here is a config option that does it:
set clipboard=unnamedplus
With this configs you can e.g. yank first in normal mode and then paste with Ctrlv in insert mode. Also, you can paste text from different vim instances and different applications.
Another option is:
set clipboard=unnamed
Then you will be able to just select something by mouse dragging in your X environment and paste it into vim afterwards. But (for some reason) you won't be able to yank something (y) in Vim and shiftinsert it somewhere else afterwards, which is probably quite limiting.
Vim docs about this: http://vim.wikia.com/wiki/Accessing_the_system_clipboard
For pasting from custom registers you can follow the other answers :). This answer is mainly about integrating Vim with your system clipboard.
Note that for set clipboard=unnamedplus
and set clipboard=unnamed
to work, you need to use gvim or vimx (vim-X11
): Those are compiled with +xterm_clipboard
. You can optionally put this into your .bashrc
to alias vim
with vimx
:
if [ -e /usr/bin/vimx ]; then
alias vim='/usr/bin/vimx'; # vim with +xterm_clipboard
fi
You can find out whether or not your vim has the +xterm_clipboard
in the information provided by vim --version
.
typeof
is an operator to obtain a type known at compile-time (or at least a generic type parameter). The operand of typeof
is always the name of a type or type parameter - never an expression with a value (e.g. a variable). See the C# language specification for more details.
GetType()
is a method you call on individual objects, to get the execution-time type of the object.
Note that unless you only want exactly instances of TextBox
(rather than instances of subclasses) you'd usually use:
if (myControl is TextBox)
{
// Whatever
}
Or
TextBox tb = myControl as TextBox;
if (tb != null)
{
// Use tb
}
Right click-> generate getters and setters does the job well but if you want to create a keyboard shortcut in eclipse in windows, you can follow the following steps:
Hope this helps!
Using the Node.js readline module.
var fs = require('fs');
var readline = require('readline');
var filename = process.argv[2];
readline.createInterface({
input: fs.createReadStream(filename),
terminal: false
}).on('line', function(line) {
console.log('Line: ' + line);
});
Another cause for this might be case-insensitive file systems. If you have multiple folders in your repo on the same level whose names only differ by case, you will get hit by this. Browse the source repository using its web interface (e.g. GitHub or VSTS) to make sure.
For more information: https://stackoverflow.com/a/2016426/67824
compactitem
does the job.
\usepackage{paralist}
...
\begin{compactitem}[$\bullet$]
\item Element 1
\item Element 2
\end{compactitem}
\vspace{\baselineskip} % new line after list
When you execute a script without typing "python" in front, you need to know two things about how Windows invokes the program. First is to find out what kind of file Windows thinks it is:
C:\>assoc .py .py=Python.File
Next, you need to know how Windows is executing things with that extension. It's associated with the file type "Python.File", so this command shows what it will be doing:
C:\>ftype Python.File Python.File="c:\python26\python.exe" "%1" %*
So on my machine, when I type "blah.py foo", it will execute this exact command, with no difference in results than if I had typed the full thing myself:
"c:\python26\python.exe" "blah.py" foo
If you type the same thing, including the quotation marks, then you'll get results identical to when you just type "blah.py foo". Now you're in a position to figure out the rest of your problem for yourself.
(Or post more helpful information in your question, like actual cut-and-paste copies of what you see in the console. Note that people who do that type of thing get their questions voted up, and they get reputation points, and more people are likely to help them with good answers.)
Even if assoc and ftype display the correct information, it may happen that the arguments are stripped off. What may help in that case is directly fixing the relevant registry keys for Python. Set the
HKEY_CLASSES_ROOT\Applications\python26.exe\shell\open\command
key to:
"C:\Python26\python26.exe" "%1" %*
Likely, previously, %*
was missing. Similarly, set
HKEY_CLASSES_ROOT\py_auto_file\shell\open\command
to the same value. See http://eli.thegreenplace.net/2010/12/14/problem-passing-arguments-to-python-scripts-on-windows/
HKEY_CLASSES_ROOT\Applications\python.exe\shell\open\command
The registry path may vary, use python26.exe
or python.exe
or whichever is already in the registry.
This is a very simple RegEx for validating US Zipcode (not ZipCode Plus Four):
(?!([089])\1{4})\d{5}
Seems all five digit numeric are valid zipcodes except 00000
, 88888
& 99999
.
I have tested this RegEx with http://regexpal.com/
SP
all:
echo ${PATH}
Or change PATH just for one command:
all:
PATH=/my/path:${PATH} cmd
Your problem is that the indices returned by match.start()
correspond to the position of the character as it appeared in the original string when you matched it; however, as you rewrite the string c
every time, these indices become incorrect.
The best approach to solve this is to use replaceAll
, for example:
System.out.println(c.replaceAll("[^a-zA-Z0-9]", ""));
Go to the Properties - Files. The owner name must be blank. Just put "sa" in the user name and the issue will be resolved.
Just do a require('./yourfile.js');
Declare all the variables that you want outside access as global variables. So instead of
var a = "hello"
it will be
GLOBAL.a="hello"
or just
a = "hello"
This is obviously bad. You don't want to be polluting the global scope.
Instead the suggest method is to export
your functions/variables.
If you want the MVC pattern take a look at Geddy.
There are 3 access specifiers
for a class/struct/Union in C++. These access specifiers define how the members of the class can be accessed. Of course, any member of a class is accessible within that class(Inside any member function of that same class). Moving ahead to type of access specifiers, they are:
Public - The members declared as Public are accessible from outside the Class through an object of the class.
Protected - The members declared as Protected are accessible from outside the class BUT only in a class derived from it.
Private - These members are only accessible from within the class. No outside Access is allowed.
An Source Code Example:
class MyClass
{
public:
int a;
protected:
int b;
private:
int c;
};
int main()
{
MyClass obj;
obj.a = 10; //Allowed
obj.b = 20; //Not Allowed, gives compiler error
obj.c = 30; //Not Allowed, gives compiler error
}
Inheritance in C++ can be one of the following types:
Private
Inheritance Public
Inheritance Protected
inheritance Here are the member access rules with respect to each of these:
First and most important rule
Private
members of a class are never accessible from anywhere except the members of the same class.
All
Public
members of the Base Class becomePublic
Members of the derived class &
AllProtected
members of the Base Class becomeProtected
Members of the Derived Class.
i.e. No change in the Access of the members. The access rules we discussed before are further then applied to these members.
Code Example:
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:public Base
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Allowed
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
}
All
Public
members of the Base Class becomePrivate
Members of the Derived class &
AllProtected
members of the Base Class becomePrivate
Members of the Derived Class.
An code Example:
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:private Base //Not mentioning private is OK because for classes it defaults to private
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
class Derived2:public Derived
{
void doSomethingMore()
{
a = 10; //Not Allowed, Compiler Error, a is private member of Derived now
b = 20; //Not Allowed, Compiler Error, b is private member of Derived now
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Not Allowed, Compiler Error
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
}
All
Public
members of the Base Class becomeProtected
Members of the derived class &
AllProtected
members of the Base Class becomeProtected
Members of the Derived Class.
A Code Example:
Class Base
{
public:
int a;
protected:
int b;
private:
int c;
};
class Derived:protected Base
{
void doSomething()
{
a = 10; //Allowed
b = 20; //Allowed
c = 30; //Not Allowed, Compiler Error
}
};
class Derived2:public Derived
{
void doSomethingMore()
{
a = 10; //Allowed, a is protected member inside Derived & Derived2 is public derivation from Derived, a is now protected member of Derived2
b = 20; //Allowed, b is protected member inside Derived & Derived2 is public derivation from Derived, b is now protected member of Derived2
c = 30; //Not Allowed, Compiler Error
}
};
int main()
{
Derived obj;
obj.a = 10; //Not Allowed, Compiler Error
obj.b = 20; //Not Allowed, Compiler Error
obj.c = 30; //Not Allowed, Compiler Error
}
Remember the same access rules apply to the classes and members down the inheritance hierarchy.
- Access Specification is per-Class not per-Object
Note that the access specification C++ work on per-Class basis and not per-object basis.
A good example of this is that in a copy constructor or Copy Assignment operator function, all the members of the object being passed can be accessed.
- A Derived class can only access members of its own Base class
Consider the following code example:
class Myclass
{
protected:
int x;
};
class derived : public Myclass
{
public:
void f( Myclass& obj )
{
obj.x = 5;
}
};
int main()
{
return 0;
}
It gives an compilation error:
prog.cpp:4: error: ‘int Myclass::x’ is protected
Because the derived class can only access members of its own Base Class. Note that the object obj
being passed here is no way related to the derived
class function in which it is being accessed, it is an altogether different object and hence derived
member function cannot access its members.
friend
? How does friend
affect access specification rules?You can declare a function or class as friend
of another class. When you do so the access specification rules do not apply to the friend
ed class/function. The class or function can access all the members of that particular class.
So do
friend
s break Encapsulation?
No they don't, On the contrary they enhance Encapsulation!
friend
ship is used to indicate a intentional strong coupling between two entities.
If there exists a special relationship between two entities such that one needs access to others private
or protected
members but You do not want everyone to have access by using the public
access specifier then you should use friend
ship.
I think that you can do something like this:
let routeData = this.$router.resolve({name: 'routeName', query: {data: "someData"}});
window.open(routeData.href, '_blank');
It worked for me.
you don't need to pass the entire encoded string to atob method, you need to split the encoded string and pass the required string to atob method
const token= "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJob3NzYW0iLCJUb2tlblR5cGUiOiJCZWFyZXIiLCJyb2xlIjoiQURNSU4iLCJpc0FkbWluIjp0cnVlLCJFbXBsb3llZUlkIjoxLCJleHAiOjE2MTI5NDA2NTksImlhdCI6MTYxMjkzNzA1OX0.8f0EeYbGyxt9hjggYW1vR5hMHFVXL4ZvjTA6XgCCAUnvacx_Dhbu1OGh8v5fCsCxXQnJ8iAIZDIgOAIeE55LUw"
console.log(atob(token.split(".")[1]));
_x000D_
This is over simplifying it, but Express.js is to Node.js what Ruby on Rails or Sinatra is to Ruby.
Express 3.x is a light-weight web application framework to help organize your web application into an MVC architecture on the server side. You can use a variety of choices for your templating language (like EJS, Jade, and Dust.js).
You can then use a database like MongoDB with Mongoose (for modeling) to provide a backend for your Node.js application. Express.js basically helps you manage everything, from routes, to handling requests and views.
Redis is a key/value store -- commonly used for sessions and caching in Node.js applications. You can do a lot more with it, but that's what I'm using it for. I use MongoDB for more complex relationships, like line-item <-> order <-> user relationships. There are modules (most notably connect-redis) that will work with Express.js. You will need to install the Redis database on your server.
Here is a link to the Express 3.x guide: https://expressjs.com/en/3x/api.html
What? Floats are immutable? But can't I do
x = 5.0
x += 7.0
print x # 12.0
Doesn't that "mut" x?
Well you agree strings are immutable right? But you can do the same thing.
s = 'foo'
s += 'bar'
print s # foobar
The value of the variable changes, but it changes by changing what the variable refers to. A mutable type can change that way, and it can also change "in place".
Here is the difference.
x = something # immutable type
print x
func(x)
print x # prints the same thing
x = something # mutable type
print x
func(x)
print x # might print something different
x = something # immutable type
y = x
print x
# some statement that operates on y
print x # prints the same thing
x = something # mutable type
y = x
print x
# some statement that operates on y
print x # might print something different
Concrete examples
x = 'foo'
y = x
print x # foo
y += 'bar'
print x # foo
x = [1, 2, 3]
y = x
print x # [1, 2, 3]
y += [3, 2, 1]
print x # [1, 2, 3, 3, 2, 1]
def func(val):
val += 'bar'
x = 'foo'
print x # foo
func(x)
print x # foo
def func(val):
val += [3, 2, 1]
x = [1, 2, 3]
print x # [1, 2, 3]
func(x)
print x # [1, 2, 3, 3, 2, 1]
it will work if you put it as below:
AA='first line
\nsecond line
\nthird line'
echo $AA
output:
first line
second line
third line
if(MyGuid!=Guild.Empty)
{
//Valid Guild
}
else {
// Invalid Guild
}
ip route | grep rmnet_data0 | cut -d" " -f1 | cut -d"/" -f1
Change rmnet_data0
to the desired nic, in my case, rmnet_data0
represents the data nic.
To get a list of the available nic's you can use ip route