SEL is a type that represents a selector in Objective-C. The @selector() keyword returns a SEL that you describe. It's not a function pointer and you can't pass it any objects or references of any kind. For each variable in the selector (method), you have to represent that in the call to @selector. For example:
-(void)methodWithNoParameters;
SEL noParameterSelector = @selector(methodWithNoParameters);
-(void)methodWithOneParameter:(id)parameter;
SEL oneParameterSelector = @selector(methodWithOneParameter:); // notice the colon here
-(void)methodWIthTwoParameters:(id)parameterOne and:(id)parameterTwo;
SEL twoParameterSelector = @selector(methodWithTwoParameters:and:); // notice the parameter names are omitted
Selectors are generally passed to delegate methods and to callbacks to specify which method should be called on a specific object during a callback. For instance, when you create a timer, the callback method is specifically defined as:
-(void)someMethod:(NSTimer*)timer;
So when you schedule the timer you would use @selector to specify which method on your object will actually be responsible for the callback:
@implementation MyObject
-(void)myTimerCallback:(NSTimer*)timer
{
// do some computations
if( timerShouldEnd ) {
[timer invalidate];
}
}
@end
// ...
int main(int argc, const char **argv)
{
// do setup stuff
MyObject* obj = [[MyObject alloc] init];
SEL mySelector = @selector(myTimerCallback:);
[NSTimer scheduledTimerWithTimeInterval:30.0 target:obj selector:mySelector userInfo:nil repeats:YES];
// do some tear-down
return 0;
}
In this case you are specifying that the object obj be messaged with myTimerCallback every 30 seconds.
Float it with another wrapper without using display: table;
, it works:
<div style="float: right;">
<div style="display: table-cell; vertical-align: middle; width: 50%; height: 50%;">I am vertically aligned on your right! ^^</div>
</div>
On my side, this error came from the data type "INT' in the Null values column. The error is resolved by just changing the data a type to varchar.
An easier way would be to format the date directly in the MySQL query, instead of PHP. See the MySQL manual entry for DATE_FORMAT.
If you'd rather do it in PHP, then you need the date function, but you'll have to convert your database value into a timestamp first.
I believe there are different ways to do this based on what you need exactly, but one way would be to just put both Elements A and B inside Parent A.
<View style={{ position: 'absolute' }}> // parent of A
<View style={{ zIndex: 1 }} /> // element A
<View style={{ zIndex: 1 }} /> // element A
<View style={{ zIndex: 0, position: 'absolute' }} /> // element B
</View>
I'd use <article>
for a text block that is totally unrelated to the other blocks on the page.
<section>
, on the other hand, would be a divider to separate a document which have are related to each other.
Now, i'm not sure what you have in your videos, newsfeed etc, but here's an example (there's no REAL right or wrong, just a guideline of how I use these tags):
<article>
<h1>People</h1>
<p>text about people</p>
<section>
<h1>fat people</h1>
<p>text about fat people</p>
</section>
<section>
<h1>skinny people</p>
<p>text about skinny people</p>
</section>
</article>
<article>
<h1>Cars</h1>
<p>text about cars</p>
<section>
<h1>Fast Cars</h1>
<p>text about fast cars</p>
</section>
</article>
As you can see, the sections are still relevant to each other, but as long as they're inside a block that groups them. Sections DONT have to be inside articles. They can be in the body of a document, but i use sections in the body, when the whole document is one article.
e.g.
<body>
<h1>Cars</h1>
<p>text about cars</p>
<section>
<h1>Fast Cars</h1>
<p>text about fast cars</p>
</section>
</body>
Hope this makes sense.
An HTTP message may have a body of data sent after the header lines. In a response, this is where the requested resource is returned to the client (the most common use of the message body), or perhaps explanatory text if there's an error. In a request, this is where user-entered data or uploaded files are sent to the server.
Here's a good article on how to do it in a pretty rock-solid way, without any hacks and full cross-browser support. Works for me:
--> http://matthewjamestaylor.com/blog/beautiful-css-centered-menus-no-hacks-full-cross-browser-support
You will want to have a look at setInterval() and setTimeout().
Here is a decent tutorial article.
var yesterday = DateTime.Now.AddDays(-1);
I know question is already answered.
But let me add one point here. This is not only case of true or false. See below:
var val="Do";
Var c= (val == "Do" || val == "Done")
? 7
: 0
Here if val is Do or Done then c will be 7 else it will be zero. In this case c will be 7.
This is actually another perspective of this operator.
You don't need to set the value at all. ng-model takes care of it all:
Here's the fiddle for this: http://jsfiddle.net/terebentina/9mFpp/
First you must connect your device via USB
Then connect your device to WIFI and get the IP address. While still connect via usb type this in command line or via Android Studio Terminal
adb tcpip 5555
adb connect <device IP>:5555
You will see these messages:
restarting in TCP mode port: 5555
connected to 172.11.0.16:5555
Now remove the USB cable and you will still see your logcat as normal
Done. Enjoy
I did something like that:
HTML:
<p class='parent'>text text text</p>
<img class='child' src='idk.png'>
CSS:
.child {
visibility: hidden;
}
.parent:hover .child {
visibility: visible;
}
Since printArea is a jQuery plugin it is not included in jquery.d.ts.
You need to create a jquery.printArea.ts definition file.
If you create a complete definition file for the plugin you may want to submit it to DefinitelyTyped.
You can use:
os.execute("sleep 1") -- I think you can do every command of CMD using os.execute("command")
or you can use:
function wait(waitTime)
timer = os.time()
repeat until os.time() > timer + waitTime
end
wait(YourNumberHere)
Result of the IEnumerable.Count() function may be wrong. This is a very simple sample to test:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
namespace Test
{
class Program
{
static void Main(string[] args)
{
var test = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 };
var result = test.Split(7);
int cnt = 0;
foreach (IEnumerable<int> chunk in result)
{
cnt = chunk.Count();
Console.WriteLine(cnt);
}
cnt = result.Count();
Console.WriteLine(cnt);
Console.ReadLine();
}
}
static class LinqExt
{
public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> source, int chunkLength)
{
if (chunkLength <= 0)
throw new ArgumentOutOfRangeException("chunkLength", "chunkLength must be greater than 0");
IEnumerable<T> result = null;
using (IEnumerator<T> enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
result = GetChunk(enumerator, chunkLength);
yield return result;
}
}
}
static IEnumerable<T> GetChunk<T>(IEnumerator<T> source, int chunkLength)
{
int x = chunkLength;
do
yield return source.Current;
while (--x > 0 && source.MoveNext());
}
}
}
Result must be (7,7,3,3) but actual result is (7,7,3,17)
I used this lmp function quite a lot of times.
And at one point I decided to add new features to enhance data analysis. I am not in expert in R or statistics but people are usually looking at different information of a linear regression :
Let's have an example. You have here
Here a reproducible example with different variables:
Ex<-structure(list(X1 = c(-36.8598, -37.1726, -36.4343, -36.8644,
-37.0599, -34.8818, -31.9907, -37.8304, -34.3367, -31.2984, -33.5731
), X2 = c(64.26, 63.085, 66.36, 61.08, 61.57, 65.04, 72.69, 63.83,
67.555, 76.06, 68.61), Y1 = c(493.81544, 493.81544, 494.54173,
494.61364, 494.61381, 494.38717, 494.64122, 493.73265, 494.04246,
494.92989, 494.98384), Y2 = c(489.704166, 489.704166, 490.710962,
490.653212, 490.710612, 489.822928, 488.160904, 489.747776, 490.600579,
488.946738, 490.398958), Y3 = c(-19L, -19L, -19L, -23L, -30L,
-43L, -43L, -2L, -58L, -47L, -61L)), .Names = c("X1", "X2", "Y1",
"Y2", "Y3"), row.names = c(NA, 11L), class = "data.frame")
library(reshape2)
library(ggplot2)
Ex2<-melt(Ex,id=c("X1","X2"))
colnames(Ex2)[3:4]<-c("Y","Yvalue")
Ex3<-melt(Ex2,id=c("Y","Yvalue"))
colnames(Ex3)[3:4]<-c("X","Xvalue")
ggplot(Ex3,aes(Xvalue,Yvalue))+
geom_smooth(method="lm",alpha=0.2,size=1,color="grey")+
geom_point(size=2)+
facet_grid(Y~X,scales='free')
#Use the lmp function
lmp <- function (modelobject) {
if (class(modelobject) != "lm") stop("Not an object of class 'lm' ")
f <- summary(modelobject)$fstatistic
p <- pf(f[1],f[2],f[3],lower.tail=F)
attributes(p) <- NULL
return(p)
}
# create function to extract different informations from lm
lmtable<-function (var1,var2,data,signi=NULL){
#var1= y data : colnames of data as.character, so "Y1" or c("Y1","Y2") for example
#var2= x data : colnames of data as.character, so "X1" or c("X1","X2") for example
#data= data in dataframe, variables in columns
# if signi TRUE, round p-value with 2 digits and add *** if <0.001, ** if < 0.01, * if < 0.05.
if (class(data) != "data.frame") stop("Not an object of class 'data.frame' ")
Tabtemp<-data.frame(matrix(NA,ncol=6,nrow=length(var1)*length(var2)))
for (i in 1:length(var2))
{
Tabtemp[((length(var1)*i)-(length(var1)-1)):(length(var1)*i),1]<-var1
Tabtemp[((length(var1)*i)-(length(var1)-1)):(length(var1)*i),2]<-var2[i]
colnames(Tabtemp)<-c("Var.y","Var.x","p-value","a","b","r^2")
for (n in 1:length(var1))
{
Tabtemp[(((length(var1)*i)-(length(var1)-1))+n-1),3]<-lmp(lm(data[,var1[n]]~data[,var2[i]],data))
Tabtemp[(((length(var1)*i)-(length(var1)-1))+n-1),4]<-coef(lm(data[,var1[n]]~data[,var2[i]],data))[1]
Tabtemp[(((length(var1)*i)-(length(var1)-1))+n-1),5]<-coef(lm(data[,var1[n]]~data[,var2[i]],data))[2]
Tabtemp[(((length(var1)*i)-(length(var1)-1))+n-1),6]<-summary(lm(data[,var1[n]]~data[,var2[i]],data))$r.squared
}
}
signi2<-data.frame(matrix(NA,ncol=3,nrow=nrow(Tabtemp)))
signi2[,1]<-ifelse(Tabtemp[,3]<0.001,paste0("***"),ifelse(Tabtemp[,3]<0.01,paste0("**"),ifelse(Tabtemp[,3]<0.05,paste0("*"),paste0(""))))
signi2[,2]<-round(Tabtemp[,3],2)
signi2[,3]<-paste0(format(signi2[,2],digits=2),signi2[,1])
for (l in 1:nrow(Tabtemp))
{
Tabtemp$"p-value"[l]<-ifelse(is.null(signi),
Tabtemp$"p-value"[l],
ifelse(isTRUE(signi),
paste0(signi2[,3][l]),
Tabtemp$"p-value"[l]))
}
Tabtemp
}
# ------- EXAMPLES ------
lmtable("Y1","X1",Ex)
lmtable(c("Y1","Y2","Y3"),c("X1","X2"),Ex)
lmtable(c("Y1","Y2","Y3"),c("X1","X2"),Ex,signi=TRUE)
There is certainly a faster solution than this function but it works.
I like to do this with sed. In you case:
for x in DET01-*.dat; do
echo $x | sed -r 's/DET01-ABC-(.+)\.dat/mv -v "\0" "DET01-XYZ-\1.dat"/'
done | sh -e
It is best to omit the "sh -e" part first to see what will be executed.
puts false or true
--> prints: false
puts false || true
--> prints: true
Unless I am misunderstanding, you can just add height: 100%;
and overflow:hidden;
to #down
.
#down {
background:pink;
height:100%;
overflow:hidden;
}?
Edit: Since you do not want to use overflow:hidden;
, you can use display: table;
for this scenario; however, it is not supported prior to IE 8. (display: table;
support)
#container {
width: 300px;
height: 300px;
border:1px solid red;
display:table;
}
#up {
background: green;
display:table-row;
height:0;
}
#down {
background:pink;
display:table-row;
}?
Note: You have said that you want the #down
height to be #container
height minus #up
height. The display:table;
solution does exactly that and this jsfiddle will portray that pretty clearly.
void operator could be used here.
Instead of:
React.useEffect(() => {
async function fetchData() {
}
fetchData();
}, []);
or
React.useEffect(() => {
(async function fetchData() {
})()
}, []);
you could write:
React.useEffect(() => {
void async function fetchData() {
}();
}, []);
It is a little bit cleaner and prettier.
Async effects could cause memory leaks so it is important to perform cleanup on component unmount. In case of fetch this could look like this:
function App() {
const [ data, setData ] = React.useState([]);
React.useEffect(() => {
const abortController = new AbortController();
void async function fetchData() {
try {
const url = 'https://jsonplaceholder.typicode.com/todos/1';
const response = await fetch(url, { signal: abortController.signal });
setData(await response.json());
} catch (error) {
console.log('error', error);
}
}();
return () => {
abortController.abort(); // cancel pending fetch request on component unmount
};
}, []);
return <pre>{JSON.stringify(data, null, 2)}</pre>;
}
It does work indeed. Issue was with my less compiler. It was compiled in to:
.container {
min-height: calc(-51vh);
}
Fixed with the following code in less file:
.container {
min-height: calc(~"100vh - 150px");
}
Thanks to this link: Less Aggressive Compilation with CSS3 calc
MYSQL: To get column values as one comma separated value use GROUP_CONCAT( )
function as
GROUP_CONCAT( `column_name` )
for example
SELECT GROUP_CONCAT( `column_name` )
FROM `table_name`
WHERE 1
LIMIT 0 , 30
$dob = $this->dateOfBirth; //Datetime
$currentDate = new \DateTime();
$dateDiff = $dob->diff($currentDate);
$years = $dateDiff->y;
$months = $dateDiff->m;
$days = $dateDiff->d;
$age = $years .' Year(s)';
if($years === 0) {
$age = $months .' Month(s)';
if($months === 0) {
$age = $days .' Day(s)';
}
}
return $age;
You can see your current session settings by querying nls_session_parameters
:
select value
from nls_session_parameters
where parameter = 'NLS_NUMERIC_CHARACTERS';
VALUE
----------------------------------------
.,
That may differ from the database defaults, which you can see in nls_database_parameters
.
In this session your query errors:
select to_number('100,12') from dual;
Error report -
SQL Error: ORA-01722: invalid number
01722. 00000 - "invalid number"
I could alter my session, either directly with alter session
or by ensuring my client is configured in a way that leads to the setting the string needs (it may be inherited from a operating system or Java locale, for example):
alter session set NLS_NUMERIC_CHARACTERS = ',.';
select to_number('100,12') from dual;
TO_NUMBER('100,12')
-------------------
100,12
In SQL Developer you can set your preferred value in Tool->Preferences->Database->NLS.
But I can also override that session setting as part of the query, with the optional third nlsparam parameter to to_number()
; though that makes the optional second fmt parameter necessary as well, so you'd need to be able pick a suitable format:
alter session set NLS_NUMERIC_CHARACTERS = '.,';
select to_number('100,12', '99999D99', 'NLS_NUMERIC_CHARACTERS='',.''')
from dual;
TO_NUMBER('100,12','99999D99','NLS_NUMERIC_CHARACTERS='',.''')
--------------------------------------------------------------
100.12
By default the result is still displayed with my session settings, so the decimal separator is still a period.
BreedId
in the Dog
table is obviously a foreign key to the corresponding row in the Breed
table. If you've got your database set up properly, LINQ to SQL should automatically create an association between the two tables. The resulting Dog class will have a Breed property, and the Breed class should have a Dogs collection. Setting it up this way, you can still return IEnumerable<Dog>
, which is an object that includes the breed property. The only caveat is that you need to preload the breed object along with dog objects in the query so they can be accessed after the data context has been disposed, and (as another poster has suggested) execute a method on the collection that will cause the query to be performed immediately (ToArray in this case):
public IEnumerable<Dog> GetDogs()
{
using (var db = new DogDataContext(ConnectString))
{
db.LoadOptions.LoadWith<Dog>(i => i.Breed);
return db.Dogs.ToArray();
}
}
It is then trivial to access the breed for each dog:
foreach (var dog in GetDogs())
{
Console.WriteLine("Dog's Name: {0}", dog.Name);
Console.WriteLine("Dog's Breed: {0}", dog.Breed.Name);
}
To disable inputting password:
sudo visudo
Then add a new line like below and save then:
# The user can run installer as root without inputting password
yourusername ALL=(root) NOPASSWD: /usr/sbin/installer
Then you run installer without password:
sudo installer -pkg ...
Use the CSS property border on the <td>
s following the <tr>
s you do not want to have the border.
In my example I made a class noBorder
that I gave to one <tr>
. Then I use a simple selector tr.noBorder td
to make the border go away for all the <td>
s that are inside of <tr>
s with the noBorder
class by assigning border: 0
.
Note that you do not need to provide the unit (i.e. px
) if you set something to 0
as it does not matter anyway. Zero is just zero.
table, tr, td {_x000D_
border: 3px solid red;_x000D_
}_x000D_
tr.noBorder td {_x000D_
border: 0;_x000D_
}
_x000D_
<table>_x000D_
<tr>_x000D_
<td>A1</td>_x000D_
<td>B1</td>_x000D_
<td>C1</td>_x000D_
</tr>_x000D_
<tr class="noBorder">_x000D_
<td>A2</td>_x000D_
<td>B2</td>_x000D_
<td>C2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>A3</td>_x000D_
<td>A3</td>_x000D_
<td>A3</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Here's the output as an image:
if you want get all values from form in simple array you may be do something like this.
function getValues(form) {
var listvalues = new Array();
var datastring = $("#" + form).serializeArray();
var data = "{";
for (var x = 0; x < datastring.length; x++) {
if (data == "{") {
data += "\"" + datastring[x].name + "\": \"" + datastring[x].value + "\"";
}
else {
data += ",\"" + datastring[x].name + "\": \"" + datastring[x].value + "\"";
}
}
data += "}";
data = JSON.parse(data);
listvalues.push(data);
return listvalues;
};
This seems to explain it.
The definition of
order
is thata[order(a)]
is in increasing order. This works with your example, where the correct order is the fourth, second, first, then third element.You may have been looking for
rank
, which returns the rank of the elements
R> a <- c(4.1, 3.2, 6.1, 3.1)
R> order(a)
[1] 4 2 1 3
R> rank(a)
[1] 3 2 4 1
sorank
tells you what order the numbers are in,order
tells you how to get them in ascending order.
plot(a, rank(a)/length(a))
will give a graph of the CDF. To see whyorder
is useful, though, tryplot(a, rank(a)/length(a),type="S")
which gives a mess, because the data are not in increasing orderIf you did
oo<-order(a)
plot(a[oo],rank(a[oo])/length(a),type="S")
or simply
oo<-order(a)
plot(a[oo],(1:length(a))/length(a)),type="S")
you get a line graph of the CDF.
I'll bet you're thinking of rank.
Without reloading, using HTML and PHP only it is not possible, but this can be very similar to what you want, but you have to reload:
<?php
function test() {
echo $_POST["user"];
}
if (isset($_POST[])) { // If it is the first time, it does nothing
test();
}
?>
<form action="test.php" method="post">
<input type="text" name="user" placeholder="enter a text" />
<input type="submit" value="submit" onclick="test()" />
</form>
modification for the code above:
$scope.$on('$locationChangeStart',function(evt, absNewUrl, absOldUrl) {
console.log('prev path: ' + absOldUrl.$$route.originalPath);
});
Give this mother a chance:
dependencies {
classpath 'com.android.tools.build:gradle:1.4.0-beta6'
}
Don't forget to bookmark this.
Instead of subclassing threading.Thread
, one can modify the function to allow
stopping by a flag.
We need an object, accessible to running function, to which we set the flag to stop running.
We can use threading.currentThread()
object.
import threading
import time
def doit(arg):
t = threading.currentThread()
while getattr(t, "do_run", True):
print ("working on %s" % arg)
time.sleep(1)
print("Stopping as you wish.")
def main():
t = threading.Thread(target=doit, args=("task",))
t.start()
time.sleep(5)
t.do_run = False
t.join()
if __name__ == "__main__":
main()
The trick is, that the running thread can have attached additional properties. The solution builds on assumptions:
True
False
.Running the code, we get following output:
$ python stopthread.py
working on task
working on task
working on task
working on task
working on task
Stopping as you wish.
Other alternative is to use threading.Event
as function argument. It is by
default False
, but external process can "set it" (to True
) and function can
learn about it using wait(timeout)
function.
We can wait
with zero timeout, but we can also use it as the sleeping timer (used below).
def doit(stop_event, arg):
while not stop_event.wait(1):
print ("working on %s" % arg)
print("Stopping as you wish.")
def main():
pill2kill = threading.Event()
t = threading.Thread(target=doit, args=(pill2kill, "task"))
t.start()
time.sleep(5)
pill2kill.set()
t.join()
Edit: I tried this in Python 3.6. stop_event.wait()
blocks the event (and so the while loop) until release. It does not return a boolean value. Using stop_event.is_set()
works instead.
Advantage of pill to kill is better seen, if we have to stop multiple threads at once, as one pill will work for all.
The doit
will not change at all, only the main
handles the threads a bit differently.
def main():
pill2kill = threading.Event()
tasks = ["task ONE", "task TWO", "task THREE"]
def thread_gen(pill2kill, tasks):
for task in tasks:
t = threading.Thread(target=doit, args=(pill2kill, task))
yield t
threads = list(thread_gen(pill2kill, tasks))
for thread in threads:
thread.start()
time.sleep(5)
pill2kill.set()
for thread in threads:
thread.join()
It's about the ABI, in order to let both C and C++ application use C interfaces without any issue.
Since C language is very easy, code generation was stable for many years for different compilers, such as GCC, Borland C\C++, MSVC etc.
While C++ becomes more and more popular, a lot things must be added into the new C++ domain (for example finally the Cfront was abandoned at AT&T because C could not cover all the features it needs). Such as template feature, and compilation-time code generation, from the past, the different compiler vendors actually did the actual implementation of C++ compiler and linker separately, the actual ABIs are not compatible at all to the C++ program at different platforms.
People might still like to implement the actual program in C++ but still keep the old C interface and ABI as usual, the header file has to declare extern "C" {}, it tells the compiler generate compatible/old/simple/easy C ABI for the interface functions if the compiler is C compiler not C++ compiler.
This can be achieved purely with JavaScript.
I see the answer I wanted to write has been answered by lynx in comments to the question.
But I'm going to write answer anyway because just like me, people sometimes forget to read the comments.
So, if you just want to get an element's distance (in Pixels) from the top of your screen window, here is what you need to do:
// Fetch the element
var el = document.getElementById("someElement");
// Use the 'top' property of 'getBoundingClientRect()' to get the distance from top
var distanceFromTop = el.getBoundingClientRect().top;
Thats it!
Hope this helps someone :)
You could either explicitly name the columns you want to keep, like so:
keep = [a.id, a.julian_date, a.user_id, b.quan_created_money, b.quan_created_cnt]
Or in a more general approach you'd include all columns except for a specific one via a list comprehension. For example like this (excluding the id
column from b
):
keep = [a[c] for c in a.columns] + [b[c] for c in b.columns if c != 'id']
Finally you make a selection on your join result:
d = a.join(b, a.id==b.id, 'outer').select(*keep)
On Android 5.1 Lollipop for my device, click on the Google Settings
icon > Security
> Scan device for security threats
.
Note that Google Settings
is separated from the Settings
app itself.
If you used a raw socket (SOCK_RAW
) and re-implemented TCP in userland, I think the answer is limited in this case only by the number of (local address, source port, destination address, destination port)
tuples (~2^64 per local address).
It would of course take a lot of memory to keep the state of all those connections, and I think you would have to set up some iptables rules to keep the kernel TCP stack from getting upset &/or responding on your behalf.
You can also use rdp/specific_install gem:
gem install specific_install
gem specific_install https://github.com/capistrano/drupal-deploy.git
Now there is the pandas_profiling
package, which is a more complete alternative to df.describe()
.
If your pandas dataframe is df
, the below will return a complete analysis including some warnings about missing values, skewness, etc. It presents histograms and correlation plots as well.
import pandas_profiling
pandas_profiling.ProfileReport(df)
See the example notebook detailing the usage.
Com = commercial application (just like .com, most people register their app as a com app)
First level = always the publishing entity's' name
Second level (optional) = sub-devison, group, or project name
Final level = product name
For example he android launcher (home screen) is Com.Google.android.launcher
You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace); CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession); CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);
//Resolved
const fetchPromise1 = fetch(url);
fetchPromise1.then(response => {
console.log(response);
});
//Pending
const fetchPromise = fetch(url);
console.log(fetchPromise);
Here's a solution:
dates <- c("14.01.2013", "26.03.2014")
# Date format:
dates2 <- strptime(dates, format = "%d.%m.%Y")
dif <- diff(as.numeric(dates2)) # difference in seconds
dif/(60 * 60 * 24 * 7) # weeks
[1] 62.28571
dif/(60 * 60 * 24 * 30) # months
[1] 14.53333
dif/(60 * 60 * 24 * 30 * 3) # quartes
[1] 4.844444
dif/(60 * 60 * 24 * 365) # years
[1] 1.194521
I had this problem while generating 1000+ graphs through VBA
. I generated the graphs and assigned a range to their series. However, when the sheet recalculated the graphs wouldn't update as the data ranges changed values.
Solution --> I turned WrapText off before the For...Next Loop that generates the graphs and then turned it on again after the loop.
Workbooks(x).Worksheets(x).Cells.WrapText=False
and after...
Workbooks(x).Worksheets(x).Cells.WrapText=True
This a great solution because it updates 1000+ graphs at once without looping through them all and changing something individually.
Also, I'm not really sure why this works; I suppose when WrapText changes one property of the data range it makes the graph update, although I have no documentation on this.
Just setting json
option to true
, the body will contain the parsed json:
request({
url: 'http://...',
json: true
}, function(error, response, body) {
console.log(body);
});
Check the Debug
class. http://developer.android.com/reference/android/os/Debug.html
i.e. Debug.getNativeHeapAllocatedSize()
It has methods to get the used native heap, which is i.e. used by external bitmaps in your app. For the heap that the app is using internally, you can see that in the DDMS tool that comes with the Android SDK and is also available via Eclipse.
The native heap + the heap as indicated in the DDMS make up the total heap that your app is allocating.
For CPU usage I'm not sure if there's anything available via API/SDK.
If your array is not initialized then it contains randoms values and cannot be checked !
To initialize your array with 0 values:
int array[5] = {0};
Then you can check if the value is 0:
array[4] == 0;
When you compare to NULL, it compares to 0 as the NULL is defined as integer value 0 or 0L.
If you have an array of pointers, better use the nullptr
value to check:
char* array[5] = {nullptr}; // we defined an array of char*, initialized to nullptr
if (array[4] == nullptr)
// do something
I don't see either MacPorts or Homebrew mentioned in other answers here, but since I do see them mentioned elsewhere on Stack Overflow for related questions, I'll add my own US$0.02 that many folks seem to consider MacPorts as not only a package manager for packages in general (as of today they list 16311 packages/ports, 2931 matching "python", albeit only for Macs), but also as a decent (maybe better) package manager for Python packages/modules:
"...what is the method that Mac python developers use to manage their modules?"
I'm still debating on whether or not to use MacPorts myself, but at the moment I'm leaning in that direction.
delete from t
where id in (1, 4, 6, 7)
Per the JQuery documentation, .get()
only takes the url
, data
(content), dataType
, and success
callback as its parameters. What you're really looking to do here is modify the jqXHR object before it gets sent. With .ajax()
, this is done with the beforeSend()
method. But since .get()
is a shortcut, it doesn't allow it.
It should be relatively easy to switch your .ajax()
calls to .get()
calls though. After all, .get()
is just a subset of .ajax()
, so you can probably use all the default values for .ajax()
(except, of course, for beforeSend()
).
Edit:
::Looks at Jivings' answer::
Oh yeah, forgot about the cache
parameter! While beforeSend()
is useful for adding other headers, the built-in cache
parameter is far simpler here.
Not an exact answer because you're using xml data and there is currently no pd.read_xml()
function (as of v0.23.4), but pandas (starting with v0.21.0) can uncompress the file for you! Thanks Wes!
import pandas as pd
import os
fn = '../data/file_to_load.json.gz'
print(os.path.isfile(fn))
df = pd.read_json(fn, lines=True, compression='gzip')
df.tail()
If a collection is iterable, then it can be iterated using an iterator (and consequently can be used in a for each loop.) The iterator is the actual object that will iterate through the collection.
If you're using the express library, as many node.js developers do, there is an easier way. Check the Express.js documentation page for more information.
The parsing example above works but express gives you a nice function to take care of that:
app.use(express.cookieParser());
To set a cookie:
res.cookie('cookiename', 'cookievalue', { maxAge: 900000, httpOnly: true });
To clear the cookie:
res.clearCookie('cookiename');
You can use input type="reset"
<form action="/action_page.php">
text: <input type="text" name="email" /><br />
<input type="reset" defaultValue="Reset" />
</form>
1) Wait for the popup balloon to appear.
2) Open a new tab.
3) Close the a new tab. The popup will be gone from the original tab.
A small Chrome extension can automate these steps:
manifest.json
{
"name": "Open and close tab",
"description": "After Chrome starts, open and close a new tab.",
"version": "1.0",
"manifest_version": 2,
"permissions": ["tabs"],
"background": {
"scripts": ["background.js"],
"persistent": false
}
}
background.js
// This runs when Chrome starts up
chrome.runtime.onStartup.addListener(function() {
// Execute the inner function after a few seconds
setTimeout(function() {
// Open new tab
chrome.tabs.create({url: "about:blank"});
// Get tab ID of newly opened tab, then close the tab
chrome.tabs.query({'currentWindow': true}, function(tabs) {
var newTabId = tabs[1].id;
chrome.tabs.remove(newTabId);
});
}, 5000);
});
With this extension installed, launch Chrome and immediately switch apps before the popup appears... a few seconds later, the popup will be gone and you won't see it when you switch back to Chrome.
I thinks it is vary helpful way.
models.py
from django.db import models
class User(models.Model):
user_name = models.CharField(max_length=100)
password = models.CharField(max_length=32)
forms.py
from django import forms
from Admin.models import *
class User_forms(forms.ModelForm):
class Meta:
model= User
fields=[
'user_name',
'password'
]
widgets = {
'password': forms.PasswordInput()
}
To convert back from tensor to numpy array you can simply run .eval()
on the transformed tensor.
This may help you find what you're looking for... Batch script loop
My answer is as follows:
@echo off
:start
set /a var+=1
if %var% EQU 100 goto end
:: Code you want to run goes here
goto start
:end
echo var has reached %var%.
pause
exit
The first set of commands under the start label loops until a variable, %var% reaches 100. Once this happens it will notify you and allow you to exit. This code can be adapted to your needs by changing the 100 to 17 and putting your code or using a call command followed by the batch file's path (Shift+Right Click on file and select "Copy as Path") where the comment is placed.
It would seem overkill but Spring Forms handles this elegantly. That is of course if you are already using Spring MVC and you want to take advantage of the Spring Forms feature.
// jsp form
<form:select path="friendlyNumber" items="${friendlyNumberItems}" />
// the command class
public class NumberCmd {
private String[] friendlyNumber;
}
// in your Spring MVC controller submit method
@RequestMapping(method=RequestMethod.POST)
public String manageOrders(@ModelAttribute("nbrCmd") NumberCmd nbrCmd){
String[] selectedNumbers = nbrCmd.getFriendlyNumber();
}
You can use something like this whit array and for loop.
<p id='fisrt'>??????</p>
<p id='second'>??????</p>
<p id='third'>??????</p>
<p id='forth'>??????</p>
<p id='fifth'>??????</p>
<button id="change" onclick="changeColor()">color red</button>
<script>
var ids = ['fisrt','second','third','forth','fifth'];
function changeColor() {
for (var i = 0; i < ids.length; i++) {
document.getElementById(ids[i]).style.color='red';
}
}
</script>
Here's a version using the excellent requests library:
from requests import session
payload = {
'action': 'login',
'username': USERNAME,
'password': PASSWORD
}
with session() as c:
c.post('http://example.com/login.php', data=payload)
response = c.get('http://example.com/protected_page.php')
print(response.headers)
print(response.text)
Since none of the above solve my issue, I will post my solution
WARNING: if you just installed TensorFlow using conda, you have to restart your command prompt!
Solution: restart terminal ENTIRELY and restart conda environment
This worked for me:
First, go to
and make the changes in nginx.conf and make the default port to listen from 80 to any of your choice 85 or something.
Then use this command to bind that port type for nginx to use it:
where PORT_TYPE is one of the following: http_cache_port_t, http_port_t, jboss_management_port_t, jboss_messaging_port_t, ntop_port_t, puppet_port_t.
Then run:
[you should see active status]; #sudo systemctl enable nginx
I found a solution for this problem try to run this command in terminal
ps -ef | grep postgres
kill process by this command
sudo kill -9 PID
As another anwsers told, you can change in a Session Listener. But you can change it directly in your servlet, for example.
getRequest().getSession().setMaxInactiveInterval(123);
You can try jquery-collision. Full disclosure: I just wrote this and released it. I didn't find a solution, so I wrote it myself.
It allows you to do:
var hit_list = $("#ball").collision("#someobject0");
which will return all the "#someobject0"'s that overlap with "#ball".
If you try to enter a negative number, the onkeyup event blocks this and if you use the arrow on the input number, the onblur event resolves that part.
<input type="number" _x000D_
onkeyup="if(this.value<0)this.value=1"_x000D_
onblur="if(this.value<0)this.value=1"_x000D_
>
_x000D_
There are a few different ways to accomplish this, I'll outline my favourites.
Use a ToggleButton and apply a custom style to it. I suggest this because your required control is "like a toggle button" but just looks different from the default toggle button styling.
My preferred method is to define a graphic for the button in css:
.toggle-button {
-fx-graphic: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Pizza-icon.png');
}
.toggle-button:selected {
-fx-graphic: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Piece-of-cake-icon.png');
}
OR use the attached css to define a background image.
// file imagetogglebutton.css deployed in the same package as ToggleButtonImage.class
.toggle-button {
-fx-background-image: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Pizza-icon.png');
-fx-background-repeat: no-repeat;
-fx-background-position: center;
}
.toggle-button:selected {
-fx-background-image: url('http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Piece-of-cake-icon.png');
}
I prefer the -fx-graphic specification over the -fx-background-* specifications as the rules for styling background images are tricky and setting the background does not automatically size the button to the image, whereas setting the graphic does.
And some sample code:
import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.StackPaneBuilder;
import javafx.stage.Stage;
public class ToggleButtonImage extends Application {
public static void main(String[] args) throws Exception { launch(args); }
@Override public void start(final Stage stage) throws Exception {
final ToggleButton toggle = new ToggleButton();
toggle.getStylesheets().add(this.getClass().getResource(
"imagetogglebutton.css"
).toExternalForm());
toggle.setMinSize(148, 148); toggle.setMaxSize(148, 148);
stage.setScene(new Scene(
StackPaneBuilder.create()
.children(toggle)
.style("-fx-padding:10; -fx-background-color: cornsilk;")
.build()
));
stage.show();
}
}
Some advantages of doing this are:
An alternate is to not use css and still use a ToggleButton, but set the image graphic in code:
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.scene.*;
import javafx.scene.control.ToggleButton;
import javafx.scene.image.*;
import javafx.scene.layout.StackPaneBuilder;
import javafx.stage.Stage;
public class ToggleButtonImageViaGraphic extends Application {
public static void main(String[] args) throws Exception { launch(args); }
@Override public void start(final Stage stage) throws Exception {
final ToggleButton toggle = new ToggleButton();
final Image unselected = new Image(
"http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Pizza-icon.png"
);
final Image selected = new Image(
"http://icons.iconarchive.com/icons/aha-soft/desktop-buffet/128/Piece-of-cake-icon.png"
);
final ImageView toggleImage = new ImageView();
toggle.setGraphic(toggleImage);
toggleImage.imageProperty().bind(Bindings
.when(toggle.selectedProperty())
.then(selected)
.otherwise(unselected)
);
stage.setScene(new Scene(
StackPaneBuilder.create()
.children(toggle)
.style("-fx-padding:10; -fx-background-color: cornsilk;")
.build()
));
stage.show();
}
}
The code based approach has the advantage that you don't have to use css if you are unfamilar with it.
For best performance and ease of porting to unsigned applet and webstart sandboxes, bundle the images with your app and reference them by relative path urls rather than downloading them off the net.
Since the version 22.1.0, the class ActionBarActivity
is deprecated. You should use AppCompatActivity
.
Here is how you can do it in Swift:
let vc = UIViewController()
self.presentViewController(vc, animated: true, completion: nil)
function DeleteJob() {
if (confirm("Do you really want to delete selected job/s?"))
window.location.href = "/{controller}/{action}/{params}";
else
return false;
}
Great answer thanks. Small improvement to support Windows phone and Zune:
if (navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/webOS/i) ||
navigator.userAgent.match(/iPhone/i) ||
navigator.userAgent.match(/iPad/i) ||
navigator.userAgent.match(/iPod/i) ||
navigator.userAgent.match(/BlackBerry/) ||
navigator.userAgent.match(/Windows Phone/i) ||
navigator.userAgent.match(/ZuneWP7/i)
) {
// some code
self.location = "top.htm";
}
When using guava (See doc) there is Iterators.forEnumeration
. Given an Enumeration x
you can do the following:
to get a immutable Set:
ImmutableSet.copyOf(Iterators.forEnumeration(x));
to get a immutable List:
ImmutableList.copyOf(Iterators.forEnumeration(x));
to get a hashSet:
Sets.newHashSet(Iterators.forEnumeration(x));
Add this line
AddHandler application/x-httpd-php .html
to httpd.conf
file for what you want to do.
But remember, if you do this then your web server will be very slow, because it will be parsing even static code which will not contain php code.
So the better way will be to make the file extension .phtml
instead of just .html
.
Right now, you're creating an instance of every type defined in the assembly. You only need to create a single instance of Class1
in order to call the method:
class Program
{
static void Main(string[] args)
{
var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");
var theType = DLL.GetType("DLL.Class1");
var c = Activator.CreateInstance(theType);
var method = theType.GetMethod("Output");
method.Invoke(c, new object[]{@"Hello"});
Console.ReadLine();
}
}
The clearest answer. Does “X& const x” make any sense?
No, it is nonsense
To find out what the above declaration means, read it right-to-left: “x is a const reference to a X”. But that is redundant — references are always const, in the sense that you can never reseat a reference to make it refer to a different object. Never. With or without the const.
In other words, “X& const x” is functionally equivalent to “X& x”. Since you’re gaining nothing by adding the const after the &, you shouldn’t add it: it will confuse people — the const will make some people think that the X is const, as if you had said “const X& x”.
It is possible using ogr2ogr:
C:\Program Files\PostgreSQL\12\bin\ogr2ogr.exe -f "PostgreSQL" PG:"host=someip user=someuser dbname=somedb password=somepw" C:/folder/excelfile.xlsx -nln newtablenameinpostgres -oo AUTODETECT_TYPE=YES
(Not sure if ogr2ogr is included in postgres installation or if I got it with postgis extension.)
I was having this issue while running a SpringBoot project (Maven)
In my POM file I changed the java version from 11 to 8 and it worked:
<properties>
<java.version>8</java.version> //The default was 11
</properties>
Make sure to Load maven changes
else the change won't reflect.
In case, you are using PHP7 already, the formerly deprecated functions mysql_*
were removed entirely, so you should update your code using the PDO-functions or mysqli_*
functions instead.
If that's not possible, as a workaround, I created a small PHP include file, that recreates the old mysql_*
functions with mysqli_*()
-functions: fix_mysql.inc.php
I don't know how to break it to you, but I have a PhD from Cambridge, and I'm using 2.8 just fine.
More seriously, I hardly spent any time with 2.7 (it won't inter-op with a Java library I am using) and started using Scala just over a month ago. I have some experience with Haskell (not much), but just ignored the stuff you're worried about and looked for methods that matched my experience with Java (which I use for a living).
So: I am a "new user" and I wasn't put off - the fact that it works like Java gave me enough confidence to ignore the bits I didn't understand.
(However, the reason I was looking at Scala was partly to see whether to push it at work, and I am not going to do so yet. Making the documentation less intimidating would certainly help, but what surprised me is how much it is still changing and being developed (to be fair what surprised me most was how awesome it is, but the changes came a close second). So I guess what I am saying is that I'd rather prefer the limited resources were put into getting it into a final state - I don't think they were expecting to be this popular this soon.)
How about this?
if (window.location.protocol !== 'https:') {
window.location = 'https://' + window.location.hostname + window.location.pathname + window.location.hash;
}
Ideally you'd do it on the server side, though.
Thank you guys for this answers. But I think the accepted answer needs more clarity, As i found difficulty in getting the solution.
We may set the environment variable as mentioned in the answer by w0rldart .
In this case(after seting envmnt var) we may run the phpFile by opening start >> CMD and typing commands like,
php.exe <path to file location>
or
php <path to file location>
example:
php.exe C:\xampp\htdocs\test.php
you can open Start >> CMD as administrator and write like
<path to php.exe in xampp's php folder> <path to file location>
example:
C:\xampp\php\php.exe C:\xampp\htdocs\test.php
or
C:\xampp\php\php C:\xampp\htdocs\test.php
Hopes this will help somebody.
You can also unpack the axes in the subplots call
And set whether you want to share the x and y axes between the subplots
Like this:
import matplotlib.pyplot as plt
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True)
ax1.plot(range(10), 'r')
ax2.plot(range(10), 'b')
ax3.plot(range(10), 'g')
ax4.plot(range(10), 'k')
plt.show()
First of all, it has to do with usability. If you use inheritance, the Team
class will expose behavior (methods) that are designed purely for object manipulation. For example, AsReadOnly()
or CopyTo(obj)
methods make no sense for the team object. Instead of the AddRange(items)
method you would probably want a more descriptive AddPlayers(players)
method.
If you want to use LINQ, implementing a generic interface such as ICollection<T>
or IEnumerable<T>
would make more sense.
As mentioned, composition is the right way to go about it. Just implement a list of players as a private variable.
The code below also solves otherwise
.on("change", function(e) {
var lastValue = e.currentTarget.value;
var lastText = e.currentTarget.textContent;
});
(WINDOWS)
If you have installed Android Studio already go to File
>> Project Structure...
>> SDK Location.
Go to that location + \cmdline-tools\latest\bin
Copy the Path into Environment Variables
than it is OK to use the command line tool.
Actually I don't know you want to this.
try this
INSERT INTO my_table (my_column)
SELECT
(random() * 10) + 1
;
Please always check your certificate expiry date first because most of the certificates have an expiry date. In my case certificate has expired and I was trying to build project.
SELECT CONVERT(varchar(11),Getdate(),105)
I got this as root when as a non-root user I was getting permissions errors trying to connect to custom recovery (Philz). so I killed adb server, copied the .android subdirectory of my user account into /root, chowned -R to root.root, and restarted adb server. I'm in!
I think people in this post are missing the most important point for anyone who has never used a functional programming language: expanding your mind. If you are new to functional programming then Haskell will make you think in ways you've never thought before. As a result your programming in other areas and other languages will improve. How much? Hard to quantify.
Simply check the var/lib/cloud/instance
symlink, it should point to /var/lib/cloud/instances/{instance-id}
where {instance_id}
is your instance-id.
Well , it might help someone. i just got the same error while my json file is like this
{"id":"1101010","city_id":"1101","name":"TEUPAH SELATAN"}
{"id":"1101020","city_id":"1101","name":"SIMEULUE TIMUR"}
and i found it malformed, so i changed it into somekind of
{
"datas":[
{"id":"1101010","city_id":"1101","name":"TEUPAH SELATAN"},
{"id":"1101020","city_id":"1101","name":"SIMEULUE TIMUR"}
]
}
An artifact can be any result of your build process. The important thing is that it doesn't matter on which client it was built it will be tranfered from the workspace back to the master (server) and stored there with a link to the build. The advantage is that it is versionized this way, you only have to setup backup on your master and that all artifacts are accesible via the web interface even if all build clients are offline.
It is possible to define a regular expression as the artifact name. In my case I zipped all the files I wanted to store in one file with a constant name during the build.
Their are two methods you can use to pass an integer. One is as shown below.
A.class
Intent myIntent = new Intent(A.this, B.class);
myIntent.putExtra("intVariableName", intValue);
startActivity(myIntent);
B.class
Intent intent = getIntent();
int intValue = intent.getIntExtra("intVariableName", 0);
The other method converts the integer to a string and uses the following code.
A.class
Intent intent = new Intent(A.this, B.class);
Bundle extras = new Bundle();
extras.putString("StringVariableName", intValue + "");
intent.putExtras(extras);
startActivity(intent);
The code above will pass your integer value as a string to class B. On class B, get the string value and convert again as an integer as shown below.
B.class
Bundle extras = getIntent().getExtras();
String stringVariableName = extras.getString("StringVariableName");
int intVariableName = Integer.parseInt(stringVariableName);
After discussion posting updated answer:
Option Explicit
Sub test()
Dim wk As String, yr As String
Dim fname As String, fpath As String
Dim owb As Workbook
With Application
.DisplayAlerts = False
.ScreenUpdating = False
.EnableEvents = False
End With
wk = ComboBox1.Value
yr = ComboBox2.Value
fname = yr & "W" & wk
fpath = "C:\Documents and Settings\jammil\Desktop\AutoFinance\ProjectControl\Data"
On Error GoTo ErrorHandler
Set owb = Application.Workbooks.Open(fpath & "\" & fname)
'Do Some Stuff
With owb
.SaveAs fpath & Format(Date, "yyyymm") & "DB" & ".xlsx", 51
.Close
End With
With Application
.DisplayAlerts = True
.ScreenUpdating = True
.EnableEvents = True
End With
Exit Sub
ErrorHandler: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then
Else: Call Clear
End Sub
Error Handling:
You could try something like this to catch a specific error:
On Error Resume Next
Set owb = Application.Workbooks.Open(fpath & "\" & fname)
If Err.Number = 1004 Then
GoTo FileNotFound
Else
End If
...
Exit Sub
FileNotFound: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then
Else: Call Clear
VERY IMPORTANT Additional info on difference between .text() and .html():
If your selector selects more than one item, e.g you have two spans like so
<span class="foo">bar1</span>
<span class="foo">bar2</span>
,
then
$('.foo').text();
appends the two texts and give you that; whereas
$('.foo').html();
gives you only one of those.
More input types and details found here on google website
If you want to just go with the default large size you can add 'modal-lg':
var modal = $modal.open({
templateUrl: "/partials/welcome",
controller: "welcomeCtrl",
backdrop: "static",
scope: $scope,
windowClass: 'modal-lg'
});
The following simple fix worked for me, bypassing possible permissions issues with the socket.
In your nginx config, set fastcgi_pass to:
fastcgi_pass 127.0.0.1:9000;
Instead of
fastcgi_pass /var/run/php5-fpm.sock;
This must match the listen = parameter in /etc/php5/fpm/pool.d/www.conf, so also set this to:
listen = 127.0.0.1:9000;
Then restart php5-fpm and nginx
service php5-fpm restart
And
service nginx restart
For more info, see: https://wildlyinaccurate.com/solving-502-bad-gateway-with-nginx-php-fpm/
Use waitpid() like this:
pid_t childPid; // the child process that the execution will soon run inside of.
childPid = fork();
if(childPid == 0) // fork succeeded
{
// Do something
exit(0);
}
else if(childPid < 0) // fork failed
{
// log the error
}
else // Main (parent) process after fork succeeds
{
int returnStatus;
waitpid(childPid, &returnStatus, 0); // Parent process waits here for child to terminate.
if (returnStatus == 0) // Verify child process terminated without error.
{
printf("The child process terminated normally.");
}
if (returnStatus == 1)
{
printf("The child process terminated with an error!.");
}
}
Just out of interest, if you want to center two or more divs (so they're side by side in the center), then here's how to do it:
<div style="text-align:center;">
<div style="border:1px solid #000; display:inline-block;">Div 1</div>
<div style="border:1px solid red; display:inline-block;">Div 2</div>
</div>
I tried the code of William, Thanks brother.
but it's not working as a simple button I have to add form with method="post". Also I have to write submit instead of button.
here is my code below..
<form method="post">
<input type="submit" name="test" id="test" value="RUN" /><br/>
</form>
<?php
function testfun()
{
echo "Your test function on button click is working";
}
if(array_key_exists('test',$_POST)){
testfun();
}
?>
Be aware that the path under src/main/resources must match the package path of your .class files wishing to access the resource. See my answer here.
I was searching for a solution to get the last foldername where the file is located, I just used split
two times, to get the right part. It's not the question but google transfered me here.
pathname = "/folderA/folderB/folderC/folderD/filename.py"
head, tail = os.path.split(os.path.split(pathname)[0])
print(head + " " + tail)
You can also get this exception when your application target .NET Framework 4.5 (for example) and you have the following app.config :
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v2.0.50727" />
<supportedRuntime version="v4.0" />
</startup>
</configuration>
When trying to launch the debug of the application you will get the BadImageFormatException.
Removing the line declaring the v2.0 version will clear the error.
I had this issue recently when I tried to change the target platform from an old .NET 2.0 project to .NET 4.5.
Bonus: why do people seemingly always use big-oh when talking informally?
Because in big-oh, this loop:
for i = 1 to n do
something in O(1) that doesn't change n and i and isn't a jump
is O(n), O(n^2), O(n^3), O(n^1423424)
. big-oh is just an upper bound, which makes it easier to calculate because you don't have to find a tight bound.
The above loop is only big-theta(n)
however.
What's the complexity of the sieve of eratosthenes? If you said O(n log n)
you wouldn't be wrong, but it wouldn't be the best answer either. If you said big-theta(n log n)
, you would be wrong.
How do I get the text value of a selected option
Select elements typically have two values that you want to access.
First there's the value to be sent to the server, which is easy:
$( "#myselect" ).val();
// => 1
The second is the text value of the select.
For example, using the following select box:
<select id="myselect">
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
<option value="4">Dr</option>
<option value="5">Prof</option>
</select>
If you wanted to get the string "Mr" if the first option was selected (instead of just "1") you would do that in the following way:
$( "#myselect option:selected" ).text();
// => "Mr"
As the other answers state, you need to select an active scheme to something that is not a simulator, i.e. a device that's connected to your mac.
If you have no device connected to the mac then selecting "Generic IOS Device" works also.
I often have this problem with sequences (as opposed to discrete values). If I have a sequence of ints, and I want to SUM them, when the list is empty I'll receive the error "InvalidOperationException: The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.".
I find I can solve this by casting the sequence to a nullable type. SUM and the other aggregate operators don't throw this error if a sequence of nullable types is empty.
So for example something like this
MySum = MyTable.Where(x => x.SomeCondtion).Sum(x => x.AnIntegerValue);
becomes
MySum = MyTable.Where(x => x.SomeCondtion).Sum(x => (int?) x.AnIntegerValue);
The second one will return 0 when no rows match the where clause. (the first one throws an exception when no rows match).
A random value?
If you want a random value, try
<?php
$value = mt_rand($min, $max);
mt_rand() will run a bit more random if you are using many random numbers in a row, or if you might ever execute the script more than once a second. In general, you should use mt_rand() over rand() if there is any doubt.
The default to open/add rows to a table is Edit Top 200 Rows. If you have more than 200 rows, like me now, then you need to change the default setting. Here's what I did to change the edit default to 300:
I did not know that even with the "Allow Installation of non-Marked application", I still needed to sign the application.
I self-signed my application, following this link self-sign and release application, It only took 5 minutes, then I emailed the signed-APK file to myself and downloaded it to SD-card and then installed it without any problem.
If you are working on Linux and want to use several processes and only have to do read operations on one or more large objects use makeForkCluster
instead of a makePSOCKcluster
. This also saves you the time sending the large object to the other processes.
They are called ifdef or include guards.
If writing a small program it might seems that it is not needed, but as the project grows you could intentionally or unintentionally include one file many times, which can result in compilation warning like variable already declared.
#ifndef checks whether HEADERFILE_H is not declared.
#define will declare HEADERFILE_H once #ifndef generates true.
#endif is to know the scope of #ifndef i.e end of #ifndef
If it is not declared which means #ifndef generates true then only the part between #ifndef and #endif executed otherwise not. This will prevent from again declaring the identifiers, enums, structure, etc...
You Could Do The same as abatishchev but without the UAC
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
</requestedPrivileges>
</security>
</trustInfo>
</assembly>
If you like 'Mike Sherrill' solution but don't want to use psql, I used this query to get the missing information:
select column_name,
case
when domain_name is not null then domain_name
when data_type='character varying' THEN 'varchar('||character_maximum_length||')'
when data_type='numeric' THEN 'numeric('||numeric_precision||','||numeric_scale||')'
else data_type
end as myType
from information_schema.columns
where table_name='test'
with result:
column_name | myType
-------------+-------------------
test_id | test_domain
test_vc | varchar(15)
test_n | numeric(15,3)
big_n | bigint
ip_addr | inet
If I may suggest a safer approach:
Declare a buffer big enough to hold the string:
char user_input[255];
Get the user input in a safe way:
fgets(user_input, 255, stdin);
A safe way to get the input, the first argument being a pointer to a buffer where the input will be stored, the second the maximum input the function should read and the third is a pointer to the standard input - i.e. where the user input comes from.
Safety in particular comes from the second argument limiting how much will be read which prevents buffer overruns. Also, fgets
takes care of null-terminating the processed string.
More info on that function here.
EDIT: If you need to do any formatting (e.g. convert a string to a number), you can use atoi once you have the input.
thing_index = thing_list.index(elem) if elem in thing_list else -1
One line. Simple. No exceptions.
It's recommended not to use the <Button>
tag. Use the <Input type='Button' onclick='return false;'>
tag instead. (Using the "return false" should indeed not send the form.)
Some reference material
I think this only happens when you have 'Preserve log' checked and you are trying to view the response data of a previous request after you have navigated away.
For example, I viewed the Response to loading this Stack Overflow question. You can see it.
The second time, I reloaded this page but didn't look at the Headers or Response. I navigated to a different website. Now when I look at the response, it shows 'Failed to load response data'.
This is a known issue, that's been around for a while, and debated a lot. However, there is a workaround, in which you pause on onunload
, so you can view the response before it navigates away, and thereby doesn't lose the data upon navigating away.
window.onunload = function() { debugger; }
You should not include folder node_modules in your .gitignore file (or rather you should include folder node_modules in your source deployed to Heroku).
If folder node_modules:
npm install
will use those vendored libraries and will rebuild any binary dependencies with npm rebuild
.npm install
will have to fetch all dependencies itself which adds time to the slug compile step.See the Node.js buildpack source for these exact steps.
However, the original error looks to be an incompatibility between the versions of npm and Node.js. It is a good idea to always explicitly set the engines
section of your packages.json file according to this guide to avoid these types of situations:
{
"name": "myapp",
"version": "0.0.1",
"engines": {
"node": "0.8.x",
"npm": "1.1.x"
}
}
This will ensure development/production parity and reduce the likelihood of such situations in the future.
Below query is appropriate for the last 30 days records
Here, I have used a review table and review_date
is a column from the review table
SELECT * FROM reviews WHERE DATE(review_date) >= DATE(NOW()) - INTERVAL 30 DAY
A little update to Evan Mulawski answer to make it shorter
List<string> allLinesText = File.ReadAllLines(fileName).ToList()
It can't parse that string because "UTC" is not a valid time zone designator.
UTC time is denoted by adding a 'Z' to the end of the time string, so your parsing code should look like this:
DateTime.Parse("Tue, 1 Jan 2008 00:00:00Z");
From the Wikipedia article on ISO 8601
If the time is in UTC, add a 'Z' directly after the time without a space. 'Z' is the zone designator for the zero UTC offset. "09:30 UTC" is therefore represented as "09:30Z" or "0930Z". "14:45:15 UTC" would be "14:45:15Z" or "144515Z".
UTC time is also known as 'Zulu' time, since 'Zulu' is the NATO phonetic alphabet word for 'Z'.
As pointed out already, most standard implementations of List
are serializable. However you have to ensure that the objects referenced/contained within the list are also serializable.
You can declare multiple variables, and initialize multiple variables, but not both at the same time:
String one,two,three;
one = two = three = "";
However, this kind of thing (especially the multiple assignments) would be frowned upon by most Java developers, who would consider it the opposite of "visually simple".
Don’t Repeat Your CSS
a.abc, a.xyz{
margin-left:20px;
}
OR
a{
margin-left:20px;
}
This is such a common problem, especially in GUI applications, that I'm surprised there isn't a BCL class to do this out of the box. Here's how I do it.
public static class ReflectiveEnumerator
{
static ReflectiveEnumerator() { }
public static IEnumerable<T> GetEnumerableOfType<T>(params object[] constructorArgs) where T : class, IComparable<T>
{
List<T> objects = new List<T>();
foreach (Type type in
Assembly.GetAssembly(typeof(T)).GetTypes()
.Where(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof(T))))
{
objects.Add((T)Activator.CreateInstance(type, constructorArgs));
}
objects.Sort();
return objects;
}
}
A few notes:
Assembly.GetAssembly(typeof(T))
because your base class might be in a different assembly. type.IsClass
and !type.IsAbstract
because it'll throw an exception if you try to instantiate an interface or abstract class.IComparable
so that they can be sorted.With 500k documents, there is no reason to scale whatsoever. A typical laptop with an SSD and 8GB of ram can easily do 10s of millions of records, so if you are trying to pick because of scaling your choice doesn't really matter. I would suggest you pick what you like the most, and perhaps where you can find the most online support with.
What's the difference between Perl's backticks (`
), system
, and exec
?
exec -> exec "command"; ,
system -> system("command"); and
backticks -> print `command`;
exec
exec
executes a command and never resumes the Perl script. It's to a script like a return
statement is to a function.
If the command is not found, exec
returns false. It never returns true, because if the command is found, it never returns at all. There is also no point in returning STDOUT
, STDERR
or exit status of the command. You can find documentation about it in perlfunc, because it is a function.
E.g.:
#!/usr/bin/perl
print "Need to start exec command";
my $data2 = exec('ls');
print "Now END exec command";
print "Hello $data2\n\n";
In above code, there are three print
statements, but due to exec
leaving the script, only the first print statement is executed. Also, the exec
command output is not being assigned to any variable.
Here, only you're only getting the output of the first print
statement and of executing the ls
command on standard out.
system
system
executes a command and your Perl script is resumed after the command has finished. The return value is the exit status of the command. You can find documentation about it in perlfunc.
E.g.:
#!/usr/bin/perl
print "Need to start system command";
my $data2 = system('ls');
print "Now END system command";
print "Hello $data2\n\n";
In above code, there are three print
statements. As the script is resumed after the system
command, all three print statements are executed.
Also, the result of running system
is assigned to data2
, but the assigned value is 0
(the exit code from ls
).
Here, you're getting the output of the first print
statement, then that of the ls
command, followed by the outputs of the final two print
statements on standard out.
`
)Like system
, enclosing a command in backticks executes that command and your Perl script is resumed after the command has finished. In contrast to system
, the return value is STDOUT
of the command. qx//
is equivalent to backticks. You can find documentation about it in perlop, because unlike system and exec
, it is an operator.
E.g.:
#!/usr/bin/perl
print "Need to start backticks command";
my $data2 = `ls`;
print "Now END system command";
print "Hello $data2\n\n";
In above code, there are three print
statements and all three are being executed. The output of ls
is not going to standard out directly, but assigned to the variable data2
and then printed by the final print statement.
Sample: My package is com.example.mypc.f01, to fix error you add line below to Activity:
import com.example.mypc.f01.R;
The best practice for this sort of situation is to create a method that hold all the logics, and call the method in both events, rather than calling an event from another event;
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
LogicMethod()
End Sub
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
LogicMethod()
End Sub
Private Sub LogicMethod()
// All your logic goes here
End Sub
In case you need the properties of the EventArgs (e), you can easily pass it through parameters in your method, that will avoid errors if ever the sender is of different types. But that won't be a problem in your case, as both senders are of type Button.
The headers only remain fixed when the UITableViewStyle
property of the table is set to UITableViewStylePlain
. If you have it set to UITableViewStyleGrouped
, the headers will scroll up with the cells.
For both device as well as simulators, Create a new swift file with name UIDevice.swift
Add the below code
import UIKit
public extension UIDevice {
var modelName: String {
#if (arch(i386) || arch(x86_64)) && os(iOS)
let DEVICE_IS_SIMULATOR = true
#else
let DEVICE_IS_SIMULATOR = false
#endif
var machineString : String = ""
if DEVICE_IS_SIMULATOR == true
{
if let dir = NSProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] {
machineString = dir
}
}
else {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
machineString = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8 where value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
}
switch machineString {
case "iPod5,1": return "iPod Touch 5"
case "iPod7,1": return "iPod Touch 6"
case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4"
case "iPhone4,1": return "iPhone 4s"
case "iPhone5,1", "iPhone5,2": return "iPhone 5"
case "iPhone5,3", "iPhone5,4": return "iPhone 5c"
case "iPhone6,1", "iPhone6,2": return "iPhone 5s"
case "iPhone7,2": return "iPhone 6"
case "iPhone7,1": return "iPhone 6 Plus"
case "iPhone8,1": return "iPhone 6s"
case "iPhone8,2": return "iPhone 6s Plus"
case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3"
case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4"
case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air"
case "iPad5,3", "iPad5,4": return "iPad Air 2"
case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini"
case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2"
case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3"
case "iPad5,1", "iPad5,2": return "iPad Mini 4"
case "iPad6,7", "iPad6,8": return "iPad Pro"
case "AppleTV5,3": return "Apple TV"
default: return machineString
}
}
}
Then in your viewcontroller,
let deviceType = UIDevice.currentDevice().modelName
if deviceType.lowercaseString.rangeOfString("iphone 4") != nil {
print("iPhone 4 or iphone 4s")
}
else if deviceType.lowercaseString.rangeOfString("iphone 5") != nil {
print("iPhone 5 or iphone 5s or iphone 5c")
}
else if deviceType.lowercaseString.rangeOfString("iphone 6") != nil {
print("iPhone 6 Series")
}
Try below solution
ng-if="details.Payment[0].Status != '0'"
Use below condition(! prefix with true condition) instead of above
ng-if="!details.Payment[0].Status == '0'"
jezrael's answer is good, but did not answer a question I had: Will getting the "sort" flag wrong mess up my data in any way? The answer is apparently "no", you are fine either way.
from pandas import DataFrame, concat
a = DataFrame([{'a':1, 'c':2,'d':3 }])
b = DataFrame([{'a':4,'b':5, 'd':6,'e':7}])
>>> concat([a,b],sort=False)
a c d b e
0 1 2.0 3 NaN NaN
0 4 NaN 6 5.0 7.0
>>> concat([a,b],sort=True)
a b c d e
0 1 NaN 2.0 3 NaN
0 4 5.0 NaN 6 7.0
I would try the following:
~/.bashrc
file
SSH_ENV=$HOME/.ssh/environment
# start the ssh-agent
function start_agent {
echo "Initializing new SSH agent..."
# spawn ssh-agent
/usr/bin/ssh-agent | sed 's/^echo/#echo/' > ${SSH_ENV}
echo succeeded
chmod 600 ${SSH_ENV}
. ${SSH_ENV} > /dev/null
/usr/bin/ssh-add
}
if [ -f "${SSH_ENV}" ]; then
. ${SSH_ENV} > /dev/null
ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
start_agent;
}
else
start_agent;
fi
I tried the above solution, but it didn't work. Try this, it works:
git fetch origin 'remote_branch':'local_branch_name'
This will fetch the remote branch and create a new local branch (if not exists already) with name local_branch_name
and track the remote one in it.
You can use splash screen in your first loading Activity like this:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread welcomeThread = new Thread() {
@Override
public void run() {
try {
super.run();
sleep(10000); //Delay of 10 seconds
} catch (Exception e) {
} finally {
Intent i = new Intent(SplashActivity.this,
MainActivity.class);
startActivity(i);
finish();
}
}
};
welcomeThread.start();
}
Hope this code helps you.
This can be done with MySQL, although it's highly unintuitive:
CREATE PROCEDURE p25 (OUT return_val INT)
BEGIN
DECLARE a,b INT;
DECLARE cur_1 CURSOR FOR SELECT s1 FROM t;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET b = 1;
OPEN cur_1;
REPEAT
FETCH cur_1 INTO a;
UNTIL b = 1
END REPEAT;
CLOSE cur_1;
SET return_val = a;
END;//
Check out this guide: mysql-storedprocedures.pdf
The nicest solution I have found is to do the following in the first view controller.
Objective-C
- (void)viewWillAppear:(BOOL)animated {
[self.navigationController setNavigationBarHidden:YES animated:animated];
[super viewWillAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
[self.navigationController setNavigationBarHidden:NO animated:animated];
[super viewWillDisappear:animated];
}
Swift
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.setNavigationBarHidden(true, animated: animated)
super.viewWillAppear(animated)
}
override func viewWillDisappear(_ animated: Bool) {
self.navigationController?.setNavigationBarHidden(false, animated: animated)
super.viewWillDisappear(animated)
}
This will cause the navigation bar to animate in from the left (together with the next view) when you push the next UIViewController
on the stack, and animate away to the left (together with the old view), when you press the back button on the UINavigationBar
.
Please note also that these are not delegate methods, you are overriding UIViewController
's implementation of these methods, and according to the documentation you must call the super's implementation somewhere in your implementation.
I'm triggering my notifications from FCM console and through HTTP/JSON ... with the same result.
I can handle the title, full message, but the icon is always a default white circle:
Instead of my custom icon in the code (setSmallIcon or setSmallIcon) or default icon from the app:
Intent intent = new Intent(this, MainActivity.class);
// use System.currentTimeMillis() to have a unique ID for the pending intent
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
if (Build.VERSION.SDK_INT < 16) {
Notification n = new Notification.Builder(this)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true).getNotification();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//notificationManager.notify(0, n);
notificationManager.notify(id, n);
} else {
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
Notification n = new Notification.Builder(this)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setLargeIcon(bm)
.setContentIntent(pIntent)
.setAutoCancel(true).build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//notificationManager.notify(0, n);
notificationManager.notify(id, n);
}
The issue HttpServletRequest.login does not set authentication state in session has been fixed in 3.0.1. Update glassfish to the latest version and you're done.
Updating is quite straightforward:
glassfishv3/bin/pkg set-authority -P dev.glassfish.org
glassfishv3/bin/pkg image-update
When it comes to areal device, the behavior of devices seem different to a different group of devices.
Some of the strange collection of the opinion I heard form different people is:
./adb install ~Application_path
android:installLocation="preferExternal"
I hope one of them is relevant to you! ;)
I was getting the same problem on Spring Tool Suite 3.2 and changed the version of jstl to 1.2 (from 1.1.2) manually when adding it to the dependency list, and the error got disappeared.
[contains(text(),'')]
only returns true or false. It won't return any element results.
I came up with the same problem, and I work it out !
<img :src='book.images.small' v-on:mouseenter="hoverImg">
_x000D_
The changed value will be in event.target.value
const app = new Vue({_x000D_
el: "#app",_x000D_
data: function() {_x000D_
return {_x000D_
message: "Vue"_x000D_
}_x000D_
},_x000D_
methods: {_x000D_
onChange(event) {_x000D_
console.log(event.target.value);_x000D_
}_x000D_
}_x000D_
})
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
<select name="LeaveType" @change="onChange" class="form-control">_x000D_
<option value="1">Annual Leave/ Off-Day</option>_x000D_
<option value="2">On Demand Leave</option>_x000D_
</select>_x000D_
</div>
_x000D_
As an addition to @C??? answer, make sure the title of the tooltip has not already been set manually in the HTML element. In my case, the span class for the tooltip already had a fixed tittle text, because of this my JQuery function $('[data-toggle="tooltip"]').prop('title', 'your new title');
did not work.
When I removed the title attribute in the HTML span class, the jQuery was working.
So:
<span class="showTooltip" data-target="#showTooltip" data-id="showTooltip">
<span id="MyTooltip" class="fas fa-info-circle" data-toggle="tooltip" data-placement="top" title="this is my pre-set title text"></span>
</span>
Should becode:
<span class="showTooltip" data-target="#showTooltip" data-id="showTooltip">
<span id="MyTooltip" class="fas fa-info-circle" data-toggle="tooltip" data-placement="top"></span>
</span>
What about using the ×-mark (the multiplication symbol), ×
in HTML, for that?
"x" (letter) should not be used to represent anything else other than the letter X.
To read binary ASCII characters with great speed using only your head:
Letters start with leading bits 01. Bit 3 is on (1) for lower case, off (0) for capitals. Scan the following bits 4–8 for the first that is on, and select the starting letter from the same index in this string: “PHDBA” (think P.H.D., Bachelors in Arts). E.g. 1xxxx = P, 01xxx = H, etc. Then convert the remaining bits to an integer value (e.g. 010 = 2), and count that many letters up from your starting letter. E.g. 01001010 => H+2 = J.
The saga continues with the Windows 10 version. I had to install Win Debug Tools on clean Windows 10 OS with Visual Studio 2015.
To make a long story short, just follow the instructions in the link provided by David Black. After downloading the files, instead of running the SDK installer, browse to the installers directory and execute the msi files directly.
I wonder how many man hours have been lost through the last decade because of MS sloppiness in regards to WDK/SDK installation?
Easy Solution. You can use the following function to convert your Enum to an array of objects.
buildGoalProgressMeasurementsArray(): Object[] {
return Object.keys(GoalProgressMeasurements)
.map(key => ({ id: GoalProgressMeasurements[key], name: key }))
}
If you needed to strip that underscore off, we could use regex as follows:
buildGoalProgressMeasurementsArray(): Object[] {
return Object.keys(GoalProgressMeasurements)
.map(key => ({ id: GoalProgressMeasurements[key], name: key.replace(/_/g, ' ') }))
}
Here is brilliant quotes from Apple Developer Forums described delicious details:
unowned
vs unowned(safe)
vs unowned(unsafe)
unowned(safe)
is a non-owning reference that asserts on access that the object is still alive. It's sort of like a weak optional reference that's implicitly unwrapped withx!
every time it's accessed.unowned(unsafe)
is like__unsafe_unretained
in ARC—it's a non-owning reference, but there's no runtime check that the object is still alive on access, so dangling references will reach into garbage memory.unowned
is always a synonym forunowned(safe)
currently, but the intent is that it will be optimized tounowned(unsafe)
in-Ofast
builds when runtime checks are disabled.
unowned
vs weak
unowned
actually uses a much simpler implementation thanweak
. Native Swift objects carry two reference counts, andunowned
references bump the unowned reference count instead of the strong reference count. The object is deinitialized when its strong reference count reaches zero, but it isn't actually deallocated until the unowned reference count also hits zero. This causes the memory to be held onto slightly longer when there are unowned references, but that isn't usually a problem whenunowned
is used because the related objects should have near-equal lifetimes anyway, and it's much simpler and lower-overhead than the side-table based implementation used for zeroing weak references.
Update: In modern Swift weak
internally uses the same mechanism as unowned
does. So this comparison is incorrect because it compares Objective-C weak
with Swift unonwed
.
What is the purpose of keeping the memory alive after owning references reach 0? What happens if code attempts to do something with the object using an unowned reference after it is deinitialized?
The memory is kept alive so that its retain counts are still available. This way, when someone attempts to retain a strong reference to the unowned object, the runtime can check that the strong reference count is greater than zero in order to ensure that it is safe to retain the object.
What happens to owning or unowned references held by the object? Is their lifetime decoupled from the object when it is deinitialized or is their memory also retained until the object is deallocated after the last unowned reference is released?
All resources owned by the object are released as soon as the object's last strong reference is released, and its deinit is run. Unowned references only keep the memory alive—aside from the header with the reference counts, its contents is junk.
Excited, huh?
// This one has print statement so you can see the result at every stage if you would like. They are not needed
function crop(image, width, height)
{
image.width = width;
image.height = height;
//print ("in function", image, image.getWidth(), image.getHeight());
return image;
}
var image = new SimpleImage("name of your image here");
//print ("original", image, image.getWidth(), image.getHeight());
//crop(image,200,300);
print ("final", image, image.getWidth(), image.getHeight());
I created a DefaultableDictionary to do exactly what you are asking for!
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace DefaultableDictionary {
public class DefaultableDictionary<TKey, TValue> : IDictionary<TKey, TValue> {
private readonly IDictionary<TKey, TValue> dictionary;
private readonly TValue defaultValue;
public DefaultableDictionary(IDictionary<TKey, TValue> dictionary, TValue defaultValue) {
this.dictionary = dictionary;
this.defaultValue = defaultValue;
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() {
return dictionary.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
public void Add(KeyValuePair<TKey, TValue> item) {
dictionary.Add(item);
}
public void Clear() {
dictionary.Clear();
}
public bool Contains(KeyValuePair<TKey, TValue> item) {
return dictionary.Contains(item);
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) {
dictionary.CopyTo(array, arrayIndex);
}
public bool Remove(KeyValuePair<TKey, TValue> item) {
return dictionary.Remove(item);
}
public int Count {
get { return dictionary.Count; }
}
public bool IsReadOnly {
get { return dictionary.IsReadOnly; }
}
public bool ContainsKey(TKey key) {
return dictionary.ContainsKey(key);
}
public void Add(TKey key, TValue value) {
dictionary.Add(key, value);
}
public bool Remove(TKey key) {
return dictionary.Remove(key);
}
public bool TryGetValue(TKey key, out TValue value) {
if (!dictionary.TryGetValue(key, out value)) {
value = defaultValue;
}
return true;
}
public TValue this[TKey key] {
get
{
try
{
return dictionary[key];
} catch (KeyNotFoundException) {
return defaultValue;
}
}
set { dictionary[key] = value; }
}
public ICollection<TKey> Keys {
get { return dictionary.Keys; }
}
public ICollection<TValue> Values {
get
{
var values = new List<TValue>(dictionary.Values) {
defaultValue
};
return values;
}
}
}
public static class DefaultableDictionaryExtensions {
public static IDictionary<TKey, TValue> WithDefaultValue<TValue, TKey>(this IDictionary<TKey, TValue> dictionary, TValue defaultValue ) {
return new DefaultableDictionary<TKey, TValue>(dictionary, defaultValue);
}
}
}
This project is a simple decorator for an IDictionary object and an extension method to make it easy to use.
The DefaultableDictionary will allow for creating a wrapper around a dictionary that provides a default value when trying to access a key that does not exist or enumerating through all the values in an IDictionary.
Example: var dictionary = new Dictionary<string, int>().WithDefaultValue(5);
Blog post on the usage as well.
Let us see the difference between the two HTTP authentication using Wireshark
(Tool to analyse packets sent or received) .
1. Http Basic Authentication
As soon as the client types in the correct username:password,as requested by the Web-server, the Web-Server checks in the Database if the credentials are correct and gives the access to the resource .
Here is how the packets are sent and received :
In the first packet the Client fill the credentials using the POST method at the resource - lab/webapp/basicauth
.In return the server replies back with http response code 200 ok ,i.e, the username:password were correct .
Now , In the Authorization
header it shows that it is Basic Authorization followed by some random string .This String is the encoded (Base64) version of the credentials admin:aadd
(including colon ) .
2 . Http Digest Authentication(rfc 2069)
So far we have seen that the Basic Authentication sends username:password in plaintext over the network .But the Digest Auth sends a HASH of the Password using Hash algorithm.
Here are packets showing the requests made by the client and response from the server .
As soon as the client types the credentials requested by the server , the Password is converted to a response
using an algorithm and then is sent to the server , If the server Database has same response as given by the client the server gives the access to the resource , otherwise a 401 error .
In the above Authorization
, the response
string is calculated using the values of Username
,Realm
,Password
,http-method
,URI
and Nonce
as shown in the image :
Hence , we can see that the Digest Authentication is more Secure as it involve Hashing (MD5 encryption) , So the packet sniffer tools cannot sniff the Password although in Basic Auth the exact Password was shown on Wireshark.
Intel's picture is helpful, as shown by Tortuga's best answer. Here's a caption for it.
Processor: One semiconductor chip, the CPU (central processing unit) seated in one socket, circa 1950s-2010s. Over time, more functions have been packed onto the CPU chip. Prior to the 1950s releases of single-chip processors, one processor might have spread across multiple chips. In the mid 2010s the system-on-a-chip chips made it slightly more sketchy to equate one processor to one chip, though that's generally what people mean by processor, as in "this computer has an i7 processor" or "this computer system has four processors."
Core: One block of a CPU, executing one instruction at a time. (You'll see people say one instruction per clock cycle, but some CPUs use multiple clock cycles for some instructions.)
You will need wrapper classes:
public class SomeIntInfo
{
[XmlAttribute]
public int Value { get; set; }
}
public class SomeStringInfo
{
[XmlAttribute]
public string Value { get; set; }
}
public class SomeModel
{
[XmlElement("SomeStringElementName")]
public SomeStringInfo SomeString { get; set; }
[XmlElement("SomeInfoElementName")]
public SomeIntInfo SomeInfo { get; set; }
}
or a more generic approach if you prefer:
public class SomeInfo<T>
{
[XmlAttribute]
public T Value { get; set; }
}
public class SomeModel
{
[XmlElement("SomeStringElementName")]
public SomeInfo<string> SomeString { get; set; }
[XmlElement("SomeInfoElementName")]
public SomeInfo<int> SomeInfo { get; set; }
}
And then:
class Program
{
static void Main()
{
var model = new SomeModel
{
SomeString = new SomeInfo<string> { Value = "testData" },
SomeInfo = new SomeInfo<int> { Value = 5 }
};
var serializer = new XmlSerializer(model.GetType());
serializer.Serialize(Console.Out, model);
}
}
will produce:
<?xml version="1.0" encoding="ibm850"?>
<SomeModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SomeStringElementName Value="testData" />
<SomeInfoElementName Value="5" />
</SomeModel>
For a small number of variables, you can build the plot manually yourself:
ggplot(test_data, aes(date)) +
geom_line(aes(y = var0, colour = "var0")) +
geom_line(aes(y = var1, colour = "var1"))
Instead of getopt()
, you may also consider using argp_parse()
(an alternative interface to the same library).
From libc manual:
getopt
is more standard (the short-option only version of it is a part of the POSIX standard), but usingargp_parse
is often easier, both for very simple and very complex option structures, because it does more of the dirty work for you.
But I was always happy with the standard getopt
.
N.B. GNU getopt
with getopt_long
is GNU LGPL.
To check array is null:
int arr[] = null;
if (arr == null) {
System.out.println("array is null");
}
To check array is empty:
arr = new int[0];
if (arr.length == 0) {
System.out.println("array is empty");
}
cmd /k cd c:\ is the right answer
I found that ie browser have problem to vertically align inner containers, when only the min-height style is set or when height style is missing at all. What I did was to add height style with some value and that fix the issue for me.
for example :
.outer
{
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
/* Center vertically */
align-items: center;
/*Center horizontaly */
justify-content: center;
/*Center horizontaly ie */
-ms-flex-pack: center;
min-height: 220px;
height:100px;
}
So now we have height style, but the min-height will overwrite it. That way ie is happy and we still can use min-height.
Hope this is helpful for someone.
Count all the DISTINCT program names by program type and push number
SELECT COUNT(DISTINCT program_name) AS Count,
program_type AS [Type]
FROM cm_production
WHERE push_number=@push_number
GROUP BY program_type
DISTINCT COUNT(*)
will return a row for each unique count. What you want is COUNT(DISTINCT <expression>)
: evaluates expression for each row in a group and returns the number of unique, non-null values.
It is not enough in case of PHP fpm. It was one more configuration file which can enable display_error
. You should find www.conf. In my case it is in directory /etc/php/7.1/fpm/pool.d/
You should find php_flag[display_errors] = on
and disable it, php_flag[display_errors] = off
. This should solve the issue.
Make sure there is no whitespace before your php tag
// whitespace
<?php
namespace HelloWorld
?>
Remove the white space before your php tag starts
<?php
namespace HelloWorld
?>
ActiveX resolved in Chrome!
Hello all this is not the solution but the successful workaround and I have implemented as well.
This required some implementation on client machine as well that why is most suitable for intranet environment and not recommended for public sites. Even though one can implement it for public sites as well the only problem is end user has to download/implement solution.
Lets understand the key problem
Chrome cannot communicate with ActiceX
Solution: Since Chorme cannot communicate with ActiveX but still it can communicate with the API hosted on the client machine. So develop API using .Net MVC or any other technology so that through Ajax call it can communicate with the API and API communicate with the ActiveX object situated on the client machine. Since API also resides in Client machine that why there is no problem in communication. This API works as mediator between Chrome browser and ActiveX.
During API implementation you might encounter CORS issues, Use JSONP to deal with it.
Pictorial view of the solution
Other solution : Use URI Scheme like MailTo: or MS-Word to deal with outlook and word application. If your requirement is different then you can implement your customized URI Scheme.
Write "LogCat" in Quick Access edit box in your eclipse window (top right corner, just before Open Prospective button). And just select LogCat it will open-up the LogCat window in your current prospect
You can implement a Comparator
which compares two Person
objects, and you can examine as many of the fields as you like. You can put in a variable in your comparator that tells it which field to compare to, although it would probably be simpler to just write multiple comparators.
Isolation level defines how the changes made to some data repository by one transaction affect other simultaneous concurrent transactions, and also how and when that changed data becomes available to other transactions. When we define a transaction using the Spring framework we are also able to configure in which isolation level that same transaction will be executed.
@Transactional(isolation=Isolation.READ_COMMITTED)
public void someTransactionalMethod(Object obj) {
}
READ_UNCOMMITTED isolation level states that a transaction may read data that is still uncommitted by other transactions.
READ_COMMITTED isolation level states that a transaction can't read data that is not yet committed by other transactions.
REPEATABLE_READ isolation level states that if a transaction reads one record from the database multiple times the result of all those reading operations must always be the same.
SERIALIZABLE isolation level is the most restrictive of all isolation levels. Transactions are executed with locking at all levels (read, range and write locking) so they appear as if they were executed in a serialized way.
Propagation is the ability to decide how the business methods should be encapsulated in both logical or physical transactions.
Spring REQUIRED behavior means that the same transaction will be used if there is an already opened transaction in the current bean method execution context.
REQUIRES_NEW behavior means that a new physical transaction will always be created by the container.
The NESTED behavior makes nested Spring transactions to use the same physical transaction but sets savepoints between nested invocations so inner transactions may also rollback independently of outer transactions.
The MANDATORY behavior states that an existing opened transaction must already exist. If not an exception will be thrown by the container.
The NEVER behavior states that an existing opened transaction must not already exist. If a transaction exists an exception will be thrown by the container.
The NOT_SUPPORTED behavior will execute outside of the scope of any transaction. If an opened transaction already exists it will be paused.
The SUPPORTS behavior will execute in the scope of a transaction if an opened transaction already exists. If there isn't an already opened transaction the method will execute anyway but in a non-transactional way.
Do it in the controller ( controller as syntax below)
controller:
vm.question= {};
vm.question.active = true;
form
<input ng-model="vm.question.active" type="checkbox" id="active" name="active">
No longer works for spreadsheets Protected with Excel 2013 or later -- they improved the pw hash. So now need to unzip .xlsx and hack the internals.
Here's a generator that does what you requested. In this case, using rstrip is sufficient and slightly faster than strip.
lines = (line.rstrip('\n') for line in open(filename))
However, you'll most likely want to use this to get rid of trailing whitespaces too.
lines = (line.rstrip() for line in open(filename))
Most Easy Solution will be using Apache http client library. refer following sample code.. this code uses basic security for authenticating.
Add following Dependency.
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.4</version> </dependency>
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
Credentials credentials = new UsernamePasswordCredentials("username", "password");
credentialsProvider.setCredentials(AuthScope.ANY, credentials);
HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
HttpPost request = new HttpPost("https://api.plivo.com/v1/Account/MAYNJ3OT/Message/");HttpResponse response = client.execute(request);
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
textView = textView + line;
}
System.out.println(textView);
If you're looking for a particular string, put quotes around it:
awk '$1 == "findtext" {print $3}'
Otherwise, awk will assume it's a variable name.
Or alternatively, you could use this:
WHERE CHARINDEX(N'Apples', someColumn) = 0
Not sure which one performs better - you gotta test it! :-)
Marc
UPDATE: the performance seems to be pretty much on a par with the other solution (WHERE someColumn NOT LIKE '%Apples%') - so it's really just a question of your personal preference.
If you can avoid the need for concurrent writes to a single file, it sounds like you do not need a database to store the chat messages.
Just append the conversation to a text file (1 file per user\conversation). and have a directory/ file structure
Here's a simplified view of the file structure:
chat-1-bob.txt
201101011029, hi
201101011030, fine thanks.
chat-1-jen.txt
201101011030, how are you?
201101011035, have you spoken to bill recently?
chat-2-bob.txt
201101021200, hi
201101021222, about 12:22
chat-2-bill.txt
201101021201, Hey Bob,
201101021203, what time do you call this?
You would then only need to store the userid, conversation id (guid ?) & a reference to the file name.
I think you will find it hard to get a more simple scaleable solution.
You can use LOAD_FILE
to get the data too see: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html
If you have a requirement to rebuild a conversation you will need to put a value (date time) alongside your sent chat message (in the file) to allow you to merge & sort the files, but at this point it is probably a good idea to consider using a database.
1. First should understand the error meaning
Error not enough values to unpack (expected 3, got 2)
means:
a 2 part tuple, but assign to 3 values
and I have written demo code to show for you:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Function: Showing how to understand ValueError 'not enough values to unpack (expected 3, got 2)'
# Author: Crifan Li
# Update: 20191212
def notEnoughUnpack():
"""Showing how to understand python error `not enough values to unpack (expected 3, got 2)`"""
# a dict, which single key's value is two part tuple
valueIsTwoPartTupleDict = {
"name1": ("lastname1", "email1"),
"name2": ("lastname2", "email2"),
}
# Test case 1: got value from key
gotLastname, gotEmail = valueIsTwoPartTupleDict["name1"] # OK
print("gotLastname=%s, gotEmail=%s" % (gotLastname, gotEmail))
# gotLastname, gotEmail, gotOtherSomeValue = valueIsTwoPartTupleDict["name1"] # -> ValueError not enough values to unpack (expected 3, got 2)
# Test case 2: got from dict.items()
for eachKey, eachValues in valueIsTwoPartTupleDict.items():
print("eachKey=%s, eachValues=%s" % (eachKey, eachValues))
# same as following:
# Background knowledge: each of dict.items() return (key, values)
# here above eachValues is a tuple of two parts
for eachKey, (eachValuePart1, eachValuePart2) in valueIsTwoPartTupleDict.items():
print("eachKey=%s, eachValuePart1=%s, eachValuePart2=%s" % (eachKey, eachValuePart1, eachValuePart2))
# but following:
for eachKey, (eachValuePart1, eachValuePart2, eachValuePart3) in valueIsTwoPartTupleDict.items(): # will -> ValueError not enough values to unpack (expected 3, got 2)
pass
if __name__ == "__main__":
notEnoughUnpack()
using VSCode
debug effect:
2. For your code
for name, email, lastname in unpaidMembers.items():
but error
ValueError: not enough values to unpack (expected 3, got 2)
means each item(a tuple value) in unpaidMembers
, only have 1 parts:email
, which corresponding above code
unpaidMembers[name] = email
so should change code to:
for name, email in unpaidMembers.items():
to avoid error.
But obviously you expect extra lastname
, so should change your above code to
unpaidMembers[name] = (email, lastname)
and better change to better syntax:
for name, (email, lastname) in unpaidMembers.items():
then everything is OK and clear.
Because fs.writefile
is a traditional asynchronous callback - you need to follow the promise spec and return a new promise wrapping it with a resolve and rejection handler like so:
return new Promise(function(resolve, reject) {
fs.writeFile("<filename.type>", data, '<file-encoding>', function(err) {
if (err) reject(err);
else resolve(data);
});
});
So in your code you would use it like so right after your call to .then()
:
.then(function(results) {
return new Promise(function(resolve, reject) {
fs.writeFile(ASIN + '.json', JSON.stringify(results), function(err) {
if (err) reject(err);
else resolve(data);
});
});
}).then(function(results) {
console.log("results here: " + results)
}).catch(function(err) {
console.log("error here: " + err);
});
The short answer is that you can't do it using JavaScript alone. You'd need a server-side handler to connect with the SMTP server to actually send the mail. There are many simple mail scripts online, such as this one for PHP:
Using a script like that, you'd POST the contents of your web form to the script, using a function like this:
And then the script would take those values, plus a username and password for the mail server, and connect to the server to send the mail.
Seems to work
$(".selector").change(function() {
var $value = $(this).val();
var $title = $(this).children('option[value='+$value+']').html();
$('#bacon').val($title);
});
Just check with your firebug. And don't put css on hidden input.
There may be another reason when your application will not update when you either change/add/remove shareId in AndroidManifiest.
"android:sharedUserId"
Please check that also.
To prevent would recommend to use sharedUserId in your application despite in your current requirement you need or now.
From what I've read, this error means that you're not referencing the table name correctly. One common reason is that the table is defined with a mixed-case spelling, and you're trying to query it with all lower-case.
In other words, the following fails:
CREATE TABLE "SF_Bands" ( ... );
SELECT * FROM sf_bands; -- ERROR!
Use double-quotes to delimit identifiers so you can use the specific mixed-case spelling as the table is defined.
SELECT * FROM "SF_Bands";
Re your comment, you can add a schema to the "search_path" so that when you reference a table name without qualifying its schema, the query will match that table name by checked each schema in order. Just like PATH
in the shell or include_path
in PHP, etc. You can check your current schema search path:
SHOW search_path
"$user",public
You can change your schema search path:
SET search_path TO showfinder,public;
See also http://www.postgresql.org/docs/8.3/static/ddl-schemas.html
update mytable
set myfield = replace (myfield, ' ', ' ')
where charindex(' ', myfield) > 0
Replace will work on all the double spaces, no need to put in multiple replaces. This is the set-based solution.
Have a look into the start
command. It should do what you're trying to achieve.
Also, you might be able to leave out path to chrome. The following works on Windows 7:
start chrome "site1.com" "site2.com"
What you are trying to do can almost certainly be achieved with a set.
>>> x = set([1,2,3])
>>> x.add(2)
>>> x
set([1, 2, 3])
>>> x.add(4)
>>> x.add(4)
>>> x
set([1, 2, 3, 4])
>>>
using a set's add method you can build your unique set of ids very quickly. Or if you already have a list
unique_ids = set(id_list)
as for getting your inputs in numeric form you can do something like
>>> ids = [int(n) for n in '350882 348521 350166\r\n'.split()]
>>> ids
[350882, 348521, 350166]
Wrong syntax. Here you are:
insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');
or:
insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');
The second one is normally used for case-sensitive column names.
So, it turns out that X11 wasn't actually installed on the centOS. There didn't seem to be any indication anywhere of it not being installed. I did the following command and now firefox opens:
yum groupinstall 'X Window System'
Hope this answer will help others that are confused :)
SOAP (Simple Object Access Protocol) is the communication protocol in the web service scenario.
One benefit of SOAP is that it allowas RPC to execute through a firewall. But to pass through a firewall, you will probably want to use 80. it uses port no.8084 To the firewall, a SOAP conversation on 80 looks like a POST to a web page. However, there are extensions in SOAP which are specifically aimed at the firewall. In the future, it may be that firewalls will be configured to filter SOAP messages. But as of today, most firewalls are SOAP ignorant.
so exclusively open SOAP Port in Firewalls
I think you want
output <- do.call(rbind,lapply(z,matrix,ncol=10,byrow=TRUE))
i.e. combining @BlueMagister's use of do.call(rbind,...)
with an lapply
statement to convert the individual list elements into 11*10 matrices ...
Benchmarks (showing @flodel's unlist
solution is 5x faster than mine, and 230x faster than the original approach ...)
n <- 1000
z <- replicate(n,matrix(1:110,ncol=10,byrow=TRUE),simplify=FALSE)
library(rbenchmark)
origfn <- function(z) {
output <- NULL
for(i in 1:length(z))
output<- rbind(output,matrix(z[[i]],ncol=10,byrow=TRUE))
}
rbindfn <- function(z) do.call(rbind,lapply(z,matrix,ncol=10,byrow=TRUE))
unlistfn <- function(z) matrix(unlist(z), ncol = 10, byrow = TRUE)
## test replications elapsed relative user.self sys.self
## 1 origfn(z) 100 36.467 230.804 34.834 1.540
## 2 rbindfn(z) 100 0.713 4.513 0.708 0.012
## 3 unlistfn(z) 100 0.158 1.000 0.144 0.008
If this scales appropriately (i.e. you don't run into memory problems), the full problem would take about 130*0.2 seconds = 26 seconds on a comparable machine (I did this on a 2-year-old MacBook Pro).
String[] result = "hi i'm paul".split("\\s+");
to split across one or more cases.
Or you could take a look at Apache Common StringUtils. It has StringUtils.split(String str)
method that splits string using white space as delimiter. It also has other useful utility methods