You can, but the variable in your last include will overwrite the variable in your first one:
myfile.php
$var = 'test';
mysecondfile.php
$var = 'tester';
test.php
include 'myfile.php';
echo $var;
include 'mysecondfile.php';
echo $var;
Output:
test
tester
I suggest using different variable names.
Once you've done this
group p by p.SomeId into pg
you no longer have access to the range variables used in the initial from
. That is, you can no longer talk about p
or bp
, you can only talk about pg
.
Now, pg
is a group and so contains more than one product. All the products in a given pg
group have the same SomeId
(since that's what you grouped by), but I don't know if that means they all have the same BaseProductId
.
To get a base product name, you have to pick a particular product in the pg
group (As you are doing with SomeId
and CountryCode
), and then join to BaseProducts
.
var result = from p in Products
group p by p.SomeId into pg
// join *after* group
join bp in BaseProducts on pg.FirstOrDefault().BaseProductId equals bp.Id
select new ProductPriceMinMax {
SomeId = pg.FirstOrDefault().SomeId,
CountryCode = pg.FirstOrDefault().CountryCode,
MinPrice = pg.Min(m => m.Price),
MaxPrice = pg.Max(m => m.Price),
BaseProductName = bp.Name // now there is a 'bp' in scope
};
That said, this looks pretty unusual and I think you should step back and consider what you are actually trying to retrieve.
Please check this example here: Accessing Structure Members
There is explained that the right way to do it is like this:
strcpy(s1.name , "Egzona");
printf( "Name : %s\n", s1.name);
Here is how to bulk-create entities from column-separated file, leaving aside all unquoting and un-escaping routines:
SomeModel(Model):
@classmethod
def from_file(model, file_obj, headers, delimiter):
model.objects.bulk_create([
model(**dict(zip(headers, line.split(delimiter))))
for line in file_obj],
batch_size=None)
The setup:
List<int[]> intArrays=new ArrayList<>();
int anExample[]={1,2,3};
intArrays.add(anExample);
To retrieve a single int[] array in the ArrayList by index:
int[] anIntArray = intArrays.get(0); //'0' is the index
//iterate the retrieved array an print the individual elements
for (int aNumber : anIntArray ) {
System.out.println("Arraylist contains:" + aNumber );
}
To retrieve all int[] arrays in the ArrayList:
//iterate the ArrayList, get and print the elements of each int[] array
for(int[] anIntArray:intArrays) {
//iterate the retrieved array an print the individual elements
for (int aNumber : anIntArray) {
System.out.println("Arraylist contains:" + aNumber);
}
}
Output formatting can be performed based on this logic. Goodluck!!
public class Person{
String s;
Date d;
...
public Person clone(){
Person p = new Person();
p.s = this.s.clone();
p.d = this.d.clone();
...
return p;
}
}
In your executing code:
ArrayList<Person> clone = new ArrayList<Person>();
for(Person p : originalList)
clone.add(p.clone());
Git -> SVN with complete commit history
I had a Git project and had to move it to SVN. This is how I made it, keeping the whole commit history. The only thing that gets lost is the original commit time since libSVN will set the local time when we do git svn dcommit
.
Howto:
Have a SVN repository where we want to import our stuff to and clone it with git-svn:
git svn clone https://path.to/svn/repository repo.git-svn`
Go there:
cd repo.git-svn
Add the remote of the Git repository (in this example I'm using C:/Projects/repo.git). You want to push to SVN and give it the name old-git:
git remote add old-git file:///C/Projects/repo.git/
Fetch the information from the master branch from the old-git repository to the current repository:
git fetch old-git master
Checkout the master branch of the old-git remote into a new branch called old in the current repository:
git checkout -b old old-git/master`
Rebase to put the HEAD on top of old-git/master. This will maintain all your commits. What this does basically is to take all of your work done in Git and put it on top of the work you are accessing from SVN.
git rebase master
Now go back to your master branch:
git checkout master
And you can see that you have a clean commit history. This is what you want to push to SVN.
Push your work to SVN:
git svn dcommit
That's all. It is very clean, no hacking, and everything works perfectly out of the box. Enjoy.
map.get(myCode)
Create a new Item and go to the last you'll find option to copy from existing, just write your current job name and you will have clone of that project to work with.
class PushObjects {
testMethod(): Array<number> {
//declaration and initialisation of array onject
var objs: number[] = [1,2,3,4,5,7];
//push the elements into the array object
objs.push(100);
//pop the elements from the array
objs.pop();
return objs;
}
}
let pushObj = new PushObjects();
//create the button element from the dom object
let btn = document.createElement('button');
//set the text value of the button
btn.textContent = "Click here";
//button click event
btn.onclick = function () {
alert(pushObj.testMethod());
}
document.body.appendChild(btn);
While it is not possible to write a switch statement, it is possible to branch out to specific processing for each given type. One way of doing this is to use standard double dispatch mechanism. An example where we want to "switch" based on type is Jersey Exception mapper where we need to map multitude of exceptions to error responses. While for this specific case there is probably a better way (i.e. using a polymorphic method that translates each exception to an error response), using double dispatch mechanism is still useful and practical.
interface Processable {
<R> R process(final Processor<R> processor);
}
interface Processor<R> {
R process(final A a);
R process(final B b);
R process(final C c);
// for each type of Processable
...
}
class A implements Processable {
// other class logic here
<R> R process(final Processor<R> processor){
return processor.process(this);
}
}
class B implements Processable {
// other class logic here
<R> R process(final Processor<R> processor){
return processor.process(this);
}
}
class C implements Processable {
// other class logic here
<R> R process(final Processor<R> processor){
return processor.process(this);
}
}
Then where ever the "switch" is needed, you can do it as follows:
public class LogProcessor implements Processor<String> {
private static final Logger log = Logger.for(LogProcessor.class);
public void logIt(final Processable base) {
log.info("Logging for type {}", process(base));
}
// Processor methods, these are basically the effective "case" statements
String process(final A a) {
return "Stringifying A";
}
String process(final B b) {
return "Stringifying B";
}
String process(final C c) {
return "Stringifying C";
}
}
you should remove the vars from the function:
x = x * cs - y * sn; // now x is something different than original vector x
y = x * sn + y * cs;
create new coordinates becomes, to avoid calculation of x before it reaches the second line:
px = x * cs - y * sn;
py = x * sn + y * cs;
Cron jobs usually are stored in a per-user file under /var/spool/cron
The simplest thing for you to do is probably just create a text file with the job configured, then copy it to the cron spool folder and make sure it has the right permissions (600).
I tried your code, you didn't assign/bind a value to your formControlName.
In HTML file:
<form [formGroup]="form">
<label>
<input type="radio" value="Male" formControlName="gender">
<span>male</span>
</label>
<label>
<input type="radio" value="Female" formControlName="gender">
<span>female</span>
</label>
</form>
In the TS file:
form: FormGroup;
constructor(fb: FormBuilder) {
this.name = 'Angular2'
this.form = fb.group({
gender: ['', Validators.required]
});
}
Make sure you use Reactive form properly: [formGroup]="form"
and you don't need the name attribute.
In my sample. words male
and female
in span tags are the values display along the radio button and Male
and Female
values are bind to formControlName
To make it shorter:
<form [formGroup]="form">
<input type="radio" value='Male' formControlName="gender" >Male
<input type="radio" value='Female' formControlName="gender">Female
</form>
Hope it helps:)
The getPosts()
function seems to be expecting $con
to be global, but you're not declaring it as such.
A lot of programmers regard bald global variables as a "code smell". The alternative at the other end of the scale is to always pass around the connection resource. Partway between the two is a singleton call that always returns the same resource handle.
As I noticed, log4net locks their output files the whole time application is running, so you can't delete them. Otherwise they are similar.
So I prefer NLog.
This is an issue relating JRE.In my case (eclipse Luna with Maven plugin, JDK 7) I solved this by making following change in pom.xml and then Maven Update Project.
from:
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
to:
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
Screenshot showing problem in JRE:
Another feature is between:
Select * from table where date between '2009/01/30' and '2009/03/30'
You could query an LDAP server from the command line with ldap-utils: ldapsearch, ldapadd, ldapmodify
If you only have one reference to a string and you concatenate another string to the end, CPython now special cases this and tries to extend the string in place.
The end result is that the operation is amortized O(n).
e.g.
s = ""
for i in range(n):
s+=str(i)
used to be O(n^2), but now it is O(n).
From the source (bytesobject.c):
void
PyBytes_ConcatAndDel(register PyObject **pv, register PyObject *w)
{
PyBytes_Concat(pv, w);
Py_XDECREF(w);
}
/* The following function breaks the notion that strings are immutable:
it changes the size of a string. We get away with this only if there
is only one module referencing the object. You can also think of it
as creating a new string object and destroying the old one, only
more efficiently. In any case, don't use this if the string may
already be known to some other part of the code...
Note that if there's not enough memory to resize the string, the original
string object at *pv is deallocated, *pv is set to NULL, an "out of
memory" exception is set, and -1 is returned. Else (on success) 0 is
returned, and the value in *pv may or may not be the same as on input.
As always, an extra byte is allocated for a trailing \0 byte (newsize
does *not* include that), and a trailing \0 byte is stored.
*/
int
_PyBytes_Resize(PyObject **pv, Py_ssize_t newsize)
{
register PyObject *v;
register PyBytesObject *sv;
v = *pv;
if (!PyBytes_Check(v) || Py_REFCNT(v) != 1 || newsize < 0) {
*pv = 0;
Py_DECREF(v);
PyErr_BadInternalCall();
return -1;
}
/* XXX UNREF/NEWREF interface should be more symmetrical */
_Py_DEC_REFTOTAL;
_Py_ForgetReference(v);
*pv = (PyObject *)
PyObject_REALLOC((char *)v, PyBytesObject_SIZE + newsize);
if (*pv == NULL) {
PyObject_Del(v);
PyErr_NoMemory();
return -1;
}
_Py_NewReference(*pv);
sv = (PyBytesObject *) *pv;
Py_SIZE(sv) = newsize;
sv->ob_sval[newsize] = '\0';
sv->ob_shash = -1; /* invalidate cached hash value */
return 0;
}
It's easy enough to verify empirically.
$ python -m timeit -s"s=''" "for i in xrange(10):s+='a'" 1000000 loops, best of 3: 1.85 usec per loop $ python -m timeit -s"s=''" "for i in xrange(100):s+='a'" 10000 loops, best of 3: 16.8 usec per loop $ python -m timeit -s"s=''" "for i in xrange(1000):s+='a'" 10000 loops, best of 3: 158 usec per loop $ python -m timeit -s"s=''" "for i in xrange(10000):s+='a'" 1000 loops, best of 3: 1.71 msec per loop $ python -m timeit -s"s=''" "for i in xrange(100000):s+='a'" 10 loops, best of 3: 14.6 msec per loop $ python -m timeit -s"s=''" "for i in xrange(1000000):s+='a'" 10 loops, best of 3: 173 msec per loop
It's important however to note that this optimisation isn't part of the Python spec. It's only in the cPython implementation as far as I know. The same empirical testing on pypy or jython for example might show the older O(n**2) performance .
$ pypy -m timeit -s"s=''" "for i in xrange(10):s+='a'" 10000 loops, best of 3: 90.8 usec per loop $ pypy -m timeit -s"s=''" "for i in xrange(100):s+='a'" 1000 loops, best of 3: 896 usec per loop $ pypy -m timeit -s"s=''" "for i in xrange(1000):s+='a'" 100 loops, best of 3: 9.03 msec per loop $ pypy -m timeit -s"s=''" "for i in xrange(10000):s+='a'" 10 loops, best of 3: 89.5 msec per loop
So far so good, but then,
$ pypy -m timeit -s"s=''" "for i in xrange(100000):s+='a'" 10 loops, best of 3: 12.8 sec per loop
ouch even worse than quadratic. So pypy is doing something that works well with short strings, but performs poorly for larger strings.
Well... Huh. For years nobody mentioned one subtle thing.
Despite DROP TABLE IF EXISTS `bla`; CREATE TABLE `bla` ( ... );
seems reasonable, it leads to a situation when old table is already gone and new one has not been yet created: some client may try to access subject table right at this moment.
The better way is to create brand new table and swap it with an old one (table contents are lost):
CREATE TABLE `bla__new` (id int); /* if not ok: terminate, report error */
RENAME TABLE `bla__new` to `bla`; /* if ok: terminate, report success */
RENAME TABLE `bla` to `bla__old`, `bla__new` to `bla`;
DROP TABLE IF EXISTS `bla__old`;
CREATE ...
and do not continue in
case of error, because failure means that other thread didn't finish
the same script: either because it crashed in the middle or just
didn't finish yet -- it's a good idea to inspect things by yourself.RENAME ...
and do not
continue in case of success: whole operation is successfully
completed; even more, running next RENAME ...
can (and will) be
unsafe if another thread has already started same sequence (it's
better to cover this case than not to cover, see locking note below).RENAME ...
atomically replaces table definition, refer to
MySQL manual
for details.DROP ...
just cleans up the old table,
obviously.Wrapping all statements with something like SELECT GET_LOCK('__upgrade', -1); ... DO RELEASE_LOCK('__upgrade');
allows to just invoke all statements sequentially without error checking, but I don't think it's a good idea: complexity increases and locking functions in MySQL aren't safe for statement-based replication.
If the table data should survive table definition upgrade... For general case it's far more complex story about comparing table definitions to find out differences and produce proper ALTER ...
statement, which is not always possible automatically, e.g. when columns are renamed.
Side note 1:
You can deal with views using the same approach, in this case CREATE/DROP TABLE
merely transforms to CREATE/DROP VIEW
while RENAME TABLE
remains unchanged. In fact you can even turn table into view and vice versa.
CREATE VIEW `foo__new` as ...; /* if not ok: terminate, report error */
RENAME TABLE `foo__new` to `foo`; /* if ok: terminate, report success */
RENAME TABLE `foo` to `foo__old`, `foo__new` to `foo`;
DROP VIEW IF EXISTS `foo__old`;
Side note 2:
MariaDB users should be happy with CREATE OR REPLACE TABLE/VIEW
, which already cares about subject problem and it's fine points.
Generally, bash works better than python only in those environments where python is not available. :)
Seriously, I have to deal with both languages daily, and will take python instantly over bash if given the choice. Alas, I am forced to use bash on certain "small" platforms because someone has (mistakenly, IMHO) decided that python is "too large" to fit.
While it is true that bash might be faster than python for some select tasks, it can never be as quick to develop with, or as easy to maintain (at least after you get past 10 lines of code or so). Bash's sole strong point wrt python or ruby or lua, etc., is its ubiquity.
I've seen that problem when I'm writing to a filesystem which doesn't (properly) handle times -- I think SMB shares or FAT or something.
What is your target filesystem?
include and specify the node engine version to the latest, say at this time I did add version 8.
{
"name": "functions",
"dependencies": {
"firebase-admin": "~7.3.0",
"firebase-functions": "^2.2.1",
},
"engines": {
"node": "8"
},
"private": true
}
in the following file
package.json
int i = 0; // Counter used to determine when you're at the 3rd gun
for (Gun g : gunList) { // For each gun in your list
System.out.println(g); // Print out the gun
if (i == 2) { // If you're at the third gun
ArrayList<Bullet> bullets = g.getBullet(); // Get the list of bullets in the gun
for (Bullet b : bullets) { // Then print every bullet
System.out.println(b);
}
i++; // Don't forget to increment your counter so you know you're at the next gun
}
Simple:
var removedText = self.val().replace(/[^0-9]+/, '');
^ - means NOT
Just make it simple without third party libraries:
final String source = "FooBar";
final String target = "Foo";
final String replacement = "";
final String result = Pattern.compile(target, Pattern.LITERAL | Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE).matcher(source)
.replaceAll(Matcher.quoteReplacement(replacement));
... and Trick #3 Multiline entries in an Xtable
Generate some more data
moredata<-data.frame(Nominal=c(1:5), n=rep(5,5),
MeanLinBias=signif(rnorm(5, mean=0, sd=10), digits=4),
LinCI=paste("(",signif(rnorm(5,mean=-2, sd=5), digits=4),
", ", signif(rnorm(5, mean=2, sd=5), digits=4),")",sep=""),
MeanQuadBias=signif(rnorm(5, mean=0, sd=10), digits=4),
QuadCI=paste("(",signif(rnorm(5,mean=-2, sd=5), digits=4),
", ", signif(rnorm(5, mean=2, sd=5), digits=4),")",sep=""))
names(moredata)<-c("Nominal", "n","Linear Model \nBias","Linear \nCI", "Quadratic Model \nBias", "Quadratic \nCI")
Now produce our xtable, using the sanitize function to replace column names with the correct Latex newline commands (including double backslashes so R is happy)
<<label=multilinetable, results=tex, echo=FALSE>>=
foo<-xtable(moredata)
align(foo) <- c( rep('c',3),'p{1.8in}','p{2in}','p{1.8in}','p{2in}' )
print(foo,
floating=FALSE,
include.rownames=FALSE,
sanitize.text.function = function(str) {
str<-gsub("\n","\\\\", str, fixed=TRUE)
return(str)
},
sanitize.colnames.function = function(str) {
str<-c("Nominal", "n","\\centering Linear Model\\\\ \\% Bias","\\centering Linear \\\\ 95\\%CI", "\\centering Quadratic Model\\\\ \\%Bias", "\\centering Quadratic \\\\ 95\\%CI \\tabularnewline")
return(str)
})
@
(although this isn't perfect, as we need \tabularnewline so the table is formatted correctly, and Xtable still puts in a final \, so we end up with a blank line below the table header.)
A foreign key is a constraint, a relationship between two tables - that has nothing to do with an index per se.
But it is a known fact that it makes a lot of sense to index all the columns that are part of any foreign key relationship, because through a FK-relationship, you'll often need to lookup a relating table and extract certain rows based on a single value or a range of values.
So it makes good sense to index any columns involved in a FK, but a FK per se is not an index.
Check out Kimberly Tripp's excellent article "When did SQL Server stop putting indexes on Foreign Key columns?".
To parse JSON in VBA without adding a huge library to your workbook project, I created the following solution. It's extremely fast and stores all of the keys and values in a dictionary for easy access:
Function ParseJSON(json$, Optional key$ = "obj") As Object
p = 1
token = Tokenize(json)
Set dic = CreateObject("Scripting.Dictionary")
If token(p) = "{" Then ParseObj key Else ParseArr key
Set ParseJSON = dic
End Function
Function ParseObj(key$)
Do: p = p + 1
Select Case token(p)
Case "]"
Case "[": ParseArr key
Case "{"
If token(p + 1) = "}" Then
p = p + 1
dic.Add key, "null"
Else
ParseObj key
End If
Case "}": key = ReducePath(key): Exit Do
Case ":": key = key & "." & token(p - 1)
Case ",": key = ReducePath(key)
Case Else: If token(p + 1) <> ":" Then dic.Add key, token(p)
End Select
Loop
End Function
Function ParseArr(key$)
Dim e&
Do: p = p + 1
Select Case token(p)
Case "}"
Case "{": ParseObj key & ArrayID(e)
Case "[": ParseArr key
Case "]": Exit Do
Case ":": key = key & ArrayID(e)
Case ",": e = e + 1
Case Else: dic.Add key & ArrayID(e), token(p)
End Select
Loop
End Function
The code above does use a few helper functions, but the above is the meat of it.
The strategy used here is to employ a recursive tokenizer. I found it interesting enough to write an article about this solution on Medium. It explains the details.
Here is the full (yet surprisingly short) code listing, including all of the helper functions:
'-------------------------------------------------------------------
' VBA JSON Parser
'-------------------------------------------------------------------
Option Explicit
Private p&, token, dic
Function ParseJSON(json$, Optional key$ = "obj") As Object
p = 1
token = Tokenize(json)
Set dic = CreateObject("Scripting.Dictionary")
If token(p) = "{" Then ParseObj key Else ParseArr key
Set ParseJSON = dic
End Function
Function ParseObj(key$)
Do: p = p + 1
Select Case token(p)
Case "]"
Case "[": ParseArr key
Case "{"
If token(p + 1) = "}" Then
p = p + 1
dic.Add key, "null"
Else
ParseObj key
End If
Case "}": key = ReducePath(key): Exit Do
Case ":": key = key & "." & token(p - 1)
Case ",": key = ReducePath(key)
Case Else: If token(p + 1) <> ":" Then dic.Add key, token(p)
End Select
Loop
End Function
Function ParseArr(key$)
Dim e&
Do: p = p + 1
Select Case token(p)
Case "}"
Case "{": ParseObj key & ArrayID(e)
Case "[": ParseArr key
Case "]": Exit Do
Case ":": key = key & ArrayID(e)
Case ",": e = e + 1
Case Else: dic.Add key & ArrayID(e), token(p)
End Select
Loop
End Function
'-------------------------------------------------------------------
' Support Functions
'-------------------------------------------------------------------
Function Tokenize(s$)
Const Pattern = """(([^""\\]|\\.)*)""|[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?|\w+|[^\s""']+?"
Tokenize = RExtract(s, Pattern, True)
End Function
Function RExtract(s$, Pattern, Optional bGroup1Bias As Boolean, Optional bGlobal As Boolean = True)
Dim c&, m, n, v
With CreateObject("vbscript.regexp")
.Global = bGlobal
.MultiLine = False
.IgnoreCase = True
.Pattern = Pattern
If .TEST(s) Then
Set m = .Execute(s)
ReDim v(1 To m.Count)
For Each n In m
c = c + 1
v(c) = n.value
If bGroup1Bias Then If Len(n.submatches(0)) Or n.value = """""" Then v(c) = n.submatches(0)
Next
End If
End With
RExtract = v
End Function
Function ArrayID$(e)
ArrayID = "(" & e & ")"
End Function
Function ReducePath$(key$)
If InStr(key, ".") Then ReducePath = Left(key, InStrRev(key, ".") - 1)
End Function
Function ListPaths(dic)
Dim s$, v
For Each v In dic
s = s & v & " --> " & dic(v) & vbLf
Next
Debug.Print s
End Function
Function GetFilteredValues(dic, match)
Dim c&, i&, v, w
v = dic.keys
ReDim w(1 To dic.Count)
For i = 0 To UBound(v)
If v(i) Like match Then
c = c + 1
w(c) = dic(v(i))
End If
Next
ReDim Preserve w(1 To c)
GetFilteredValues = w
End Function
Function GetFilteredTable(dic, cols)
Dim c&, i&, j&, v, w, z
v = dic.keys
z = GetFilteredValues(dic, cols(0))
ReDim w(1 To UBound(z), 1 To UBound(cols) + 1)
For j = 1 To UBound(cols) + 1
z = GetFilteredValues(dic, cols(j - 1))
For i = 1 To UBound(z)
w(i, j) = z(i)
Next
Next
GetFilteredTable = w
End Function
Function OpenTextFile$(f)
With CreateObject("ADODB.Stream")
.Charset = "utf-8"
.Open
.LoadFromFile f
OpenTextFile = .ReadText
End With
End Function
Change this line
double *ptr = malloc(sizeof(double *) * TIME);
to
double *ptr = malloc(sizeof(double) * TIME);
Set display:inline-block
and then adjust your margins.
fiddle here: http://jsfiddle.net/Q2MrC/
Building off of @gnovice's answer, you can actually create filled plots with shading only in the area between the two curves. Just use fill
in conjunction with fliplr
.
Example:
x=0:0.01:2*pi; %#initialize x array
y1=sin(x); %#create first curve
y2=sin(x)+.5; %#create second curve
X=[x,fliplr(x)]; %#create continuous x value array for plotting
Y=[y1,fliplr(y2)]; %#create y values for out and then back
fill(X,Y,'b'); %#plot filled area
By flipping the x array and concatenating it with the original, you're going out, down, back, and then up to close both arrays in a complete, many-many-many-sided polygon.
(I know the question is old, but I think this might be good as a reference for people with similar questions)
If you want to load data from an ASCII/text file (which has the benefit or being more or less human-readable and easy to parse in other software), numpy.loadtxt is probably what you want:
If you just want to quickly save and load numpy arrays/matrices to and from a file, take a look at numpy.save and numpy.load:
In AVD Manager,
Go to Edit Icon on AVD Manager for selected Device.
Click on show advanced settings and increase ram size from 1500 mb to 2 GB.
Then it works.
NOTE: Some virtual devices do not allow you to update RAM, but if so, try installing Nexus 4. because it does.
NOTE2: If still doesnt work, dont give up. just uninstall and reinstall the device with changing RAM again. in some cases this is how it works
NOTE3: If still doesnt work, this means your pc doesnt have enough ram space. so increase the ram to 3gb. it might work but it will suffer
NOTE4: If still doesnt work, try it with multicore 2 instead of 4.
NOTE5: Still doesnt work. Close the Android Studio and NEVER open it back :)
try this:
grep -P '^(tomcat!?)' tst1.txt
It will search for specific word in txt file. Here we are trying to search word tomcat
You have several options:
Had a problem with Bootstrap tabs recently following their online guidelines, but there's currently an error in their markup example data-tabs="tabs
" is missing on <ul>
element. Without it using data-toggle
on links doesn't work.
In addition to the other answers, there is also the TimeUnit class which allows you to convert one time duration to another. For example, to find out how many milliseconds make up one day:
TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS); //gives 86400000
Note that this method takes a long
, so if you have a fraction of a day, you will have to multiply it by the number of milliseconds in one day.
I had the same problem, the solution for me is the following.
I had only install the junit.jar file from the web, but this library related with the hacrest-core.jar When I downloaded the hacrest-core.jar file and added it in my project everything works fine.
You can do this with css too.
just use position:fixed;
for what you want to be fixed when you scroll down.
you can have some examples here:
http://davidwalsh.name/demo/css-fixed-position.php
http://demo.tutorialzine.com/2010/06/microtut-how-css-position-works/demo.html
If somebody needs a recursive version of Owen's (and Eric's) answer, here it is:
/**
* Delete all null (or undefined) properties from an object.
* Set 'recurse' to true if you also want to delete properties in nested objects.
*/
function delete_null_properties(test, recurse) {
for (var i in test) {
if (test[i] === null) {
delete test[i];
} else if (recurse && typeof test[i] === 'object') {
delete_null_properties(test[i], recurse);
}
}
}
The problem I run into is I have an existing IIS machine. I then deploy a static React app to it. When you use router, the URL that displays is actually virtual, not real. If you hit F5 it goes to IIS, not index.js, and your return will be 404 file not found. How I resolved it was simple. I have a public folder in my react app. In that public folder I created the same folder name as the virtual routing. In this folder, I have an index.html with the following code:
<script>
{
localStorage.setItem("redirect", "/ansible/");
location.href = "/";
}
</script>
Now what this does is for this session, I'm adding the "routing" path I want it to go. Then inside my App.js I do this (Note ... is other code but too much to put here for a demo):
import React, { Component } from "react";
import { Route, Link } from "react-router-dom";
import { BrowserRouter as Router } from "react-router-dom";
import { Redirect } from 'react-router';
import Ansible from "./Development/Ansible";
import Code from "./Development/Code";
import Wood from "./WoodWorking";
import "./App.css";
class App extends Component {
render() {
const redirect = localStorage.getItem("redirect");
if(redirect) {
localStorage.removeItem("redirect");
}
return (
<Router>
{redirect ?<Redirect to={redirect}/> : ""}
<div className="App">
...
<Link to="/">
<li>Home</li>
</Link>
<Link to="/dev">
<li>Development</li>
</Link>
<Link to="/wood">
<li>Wood Working</li>
</Link>
...
<Route
path="/"
exact
render={(props) => (
<Home {...props} />
)}
/>
<Route
path="/dev"
render={(props) => (
<Code {...props} />
)}
/>
<Route
path="/wood"
render={(props) => (
<Wood {...props} />
)}
/>
<Route
path="/ansible/"
exact
render={(props) => (
<Ansible {...props} checked={this.state.checked} />
)}
/>
...
</Router>
);
}
}
export default App;
Actual usage: chizl.com
if exist yourfilename (
echo Yes
) else (
echo No
)
Replace yourfilename with the name of your file.
if exist yourfoldername\ (
echo Yes
) else (
echo No
)
Replace yourfoldername with the name of your folder.
A trailing backslash (\
) seems to be enough to distinguish between directories and ordinary files.
None of the answers worked for me. This is what worked Assuming you have anaconda python 3.7 installed
1) Dowload and install cmake(make sure to check the option to add cmake to system path during installation to avoid manually doing later) Download from this link cmake download
2) conda install -c conda-forge dlib
All answers so far use find
, so here's one with just the shell. No need for external tools in your case:
for dir in /tmp/*/ # list directories in the form "/tmp/dirname/"
do
dir=${dir%*/} # remove the trailing "/"
echo "${dir##*/}" # print everything after the final "/"
done
Use the name attribute selector:
$("input[name=nameGoesHere]").val();
I know that I'm too late for this party, but maybe - it will help to someone..
Here you can find my implementation of ObservableCollectionEx. It has some features:
Of course, any comments are appreciated ;)
It depends on the shell (and its configuration) in standard bash only the command is stored without the date and time (check .bash_history
if there is any timestamp there).
To have bash store the timestamp you need to set HISTTIMEFORMAT
before executing the commands, e.g. in .bashrc
or .bash_profile
. This will cause bash to store the timestamps in .bash_history
(see the entries starting with #
).
Use a binding, like in this example:
<a href="#new-search" data-bind="click:SearchManager.bind($data,'1')">
Search Manager
</a>
var ViewModelStructure = function () {
var self = this;
this.SearchManager = function (search) {
console.log(search);
};
}();
This is working for me,
# cat checking.sh
#!/bin/bash
echo "You have provided the following arguments $arg1 $arg2 $arg3"
if [ "$arg1" = "$arg2" ] && [ "$arg1" != "$arg3" ]
then
echo "Two of the provided args are equal."
exit 3
elif [ $arg1 == $arg2 ] && [ $arg1 = $arg3 ]
then
echo "All of the specified args are equal"
exit 0
else
echo "All of the specified args are different"
exit 4
fi
# ./checking.sh
You have provided the following arguments
All of the specified args are equal
You can add set -x
in script to troubleshoot the errors.
For those who are complining about Michael Tiptop's solution not working, here is the .Net4+ way of doing it:
public static string StripTags(this string markup)
{
try
{
StringReader sr = new StringReader(markup);
XPathDocument doc;
using (XmlReader xr = XmlReader.Create(sr,
new XmlReaderSettings()
{
ConformanceLevel = ConformanceLevel.Fragment
// for multiple roots
}))
{
doc = new XPathDocument(xr);
}
return doc.CreateNavigator().Value; // .Value is similar to .InnerText of
// XmlDocument or JavaScript's innerText
}
catch
{
return string.Empty;
}
}
You can try this:
if ($(#remember).is(':checked')){
alert('checked');
}else{
alert('not checked')
}
Here is my simple binary search tree implementation in Java SE 1.8:
public class BSTNode
{
int data;
BSTNode parent;
BSTNode left;
BSTNode right;
public BSTNode(int data)
{
this.data = data;
this.left = null;
this.right = null;
this.parent = null;
}
public BSTNode()
{
}
}
public class BSTFunctions
{
BSTNode ROOT;
public BSTFunctions()
{
this.ROOT = null;
}
void insertNode(BSTNode node, int data)
{
if (node == null)
{
node = new BSTNode(data);
ROOT = node;
}
else if (data < node.data && node.left == null)
{
node.left = new BSTNode(data);
node.left.parent = node;
}
else if (data >= node.data && node.right == null)
{
node.right = new BSTNode(data);
node.right.parent = node;
}
else
{
if (data < node.data)
{
insertNode(node.left, data);
}
else
{
insertNode(node.right, data);
}
}
}
public boolean search(BSTNode node, int data)
{
if (node == null)
{
return false;
}
else if (node.data == data)
{
return true;
}
else
{
if (data < node.data)
{
return search(node.left, data);
}
else
{
return search(node.right, data);
}
}
}
public void printInOrder(BSTNode node)
{
if (node != null)
{
printInOrder(node.left);
System.out.print(node.data + " - ");
printInOrder(node.right);
}
}
public void printPostOrder(BSTNode node)
{
if (node != null)
{
printPostOrder(node.left);
printPostOrder(node.right);
System.out.print(node.data + " - ");
}
}
public void printPreOrder(BSTNode node)
{
if (node != null)
{
System.out.print(node.data + " - ");
printPreOrder(node.left);
printPreOrder(node.right);
}
}
public static void main(String[] args)
{
BSTFunctions f = new BSTFunctions();
/**
* Insert
*/
f.insertNode(f.ROOT, 20);
f.insertNode(f.ROOT, 5);
f.insertNode(f.ROOT, 25);
f.insertNode(f.ROOT, 3);
f.insertNode(f.ROOT, 7);
f.insertNode(f.ROOT, 27);
f.insertNode(f.ROOT, 24);
/**
* Print
*/
f.printInOrder(f.ROOT);
System.out.println("");
f.printPostOrder(f.ROOT);
System.out.println("");
f.printPreOrder(f.ROOT);
System.out.println("");
/**
* Search
*/
System.out.println(f.search(f.ROOT, 27) ? "Found" : "Not Found");
System.out.println(f.search(f.ROOT, 10) ? "Found" : "Not Found");
}
}
And the output is:
3 - 5 - 7 - 20 - 24 - 25 - 27 -
3 - 7 - 5 - 24 - 27 - 25 - 20 -
20 - 5 - 3 - 7 - 25 - 24 - 27 -
Found
Not Found
SELECT SUM(Output.count),Output.attr
FROM
(
SELECT COUNT(column1 ) AS count,column1 AS attr FROM tab1 GROUP BY column1
UNION ALL
SELECT COUNT(column2) AS count,column2 AS attr FROM tab1 GROUP BY column2
UNION ALL
SELECT COUNT(column3) AS count,column3 AS attr FROM tab1 GROUP BY column3) AS Output
GROUP BY attr
dgv.Columns[0].HeaderText = "Your Header";
If you mean you want to delete a drop from a table if it exists, you can use the DELETE
command, for example:
DELETE FROM users WHERE user_login = 'foobar'
If no rows match, it's not an error.
You have to define public String toString()
method in your Student
class. For example:
public String toString() {
return "Student: " + studentName + ", " + studentNo;
}
String filepath="/tmp/employee.csv";
FileWriter sw = new FileWriter(new File(filepath));
CSVWriter writer = new CSVWriter(sw);
writer.writeAll(allRows);
String[] header= new String[]{"ErrorMessage"};
writer.writeNext(header);
List<String[]> errorData = new ArrayList<String[]>();
for(int i=0;i<1;i++){
String[] data = new String[]{"ErrorMessage"+i};
errorData.add(data);
}
writer.writeAll(errorData);
writer.close();
Also, never forget that an ID is unique. Once used, the ID value may not appear again anywhere in the document.
You may have many ID's, but all must have a unique value.
On the other hand, there is the class-element. Just like ID, it can appear many times, but the value may be used over and over again.
I'm aware that my solution is not the best, but it comes in handy when you want to split data in a simplistic way, especially when teaching data science to newbies!
def simple_split(descriptors, targets):
testX_indices = [i for i in range(descriptors.shape[0]) if i % 4 == 0]
validX_indices = [i for i in range(descriptors.shape[0]) if i % 4 == 1]
trainX_indices = [i for i in range(descriptors.shape[0]) if i % 4 >= 2]
TrainX = descriptors[trainX_indices, :]
ValidX = descriptors[validX_indices, :]
TestX = descriptors[testX_indices, :]
TrainY = targets[trainX_indices]
ValidY = targets[validX_indices]
TestY = targets[testX_indices]
return TrainX, ValidX, TestX, TrainY, ValidY, TestY
According to this code, data will be split into three parts - 1/4 for the test part, another 1/4 for the validation part, and 2/4 for the training set.
I think you can reset the invocations using Mockito.reset(mockLog). You should call this before every test, so inside @Before would be a good place.
window.location.origin+"/"+window.location.pathname.split('/')[1]+"/"+page+"/"+page+"_list.jsp"
almost same as Jenish answer but a little shorter.
I had this same problem after I dropped the special PhpMyAdmin controluser account from MySQL.
I had to update the config.inc.php file and replace the entries for 'controluser' and controlpass' with 'user' and 'password'.
So my file ended like this:
$cfg['Servers'][$i]['user'] = 'root'; $cfg['Servers'][$i]['password']='123456';
you have to add QT +=widgets in the .pro file before the first execution, if you execute before adding this line its not gonna working, so yo need to start file's creation from the beginning.
An alternative to substr
is the following, as a function:
substr_replace($string, "", -1)
Is it the fastest? I don't know, but I'm willing to bet these alternatives are all so fast that it just doesn't matter.
There is no direct way to do this - Java has no Map literals (yet - I think they were proposed for Java 8).
Some people like this:
Map<String,String> test = new HashMap<String, String>(){{
put("test","test"); put("test","test");}};
This creates an anonymous subclass of HashMap, whose instance initializer puts these values. (By the way, a map can't contain twice the same value, your second put will overwrite the first one. I'll use different values for the next examples.)
The normal way would be this (for a local variable):
Map<String,String> test = new HashMap<String, String>();
test.put("test","test");
test.put("test1","test2");
If your test
map is an instance variable, put the initialization in a constructor or instance initializer:
Map<String,String> test = new HashMap<String, String>();
{
test.put("test","test");
test.put("test1","test2");
}
If your test
map is a class variable, put the initialization in a static initializer:
static Map<String,String> test = new HashMap<String, String>();
static {
test.put("test","test");
test.put("test1","test2");
}
If you want your map to never change, you should after the initialization wrap your map by Collections.unmodifiableMap(...)
. You can do this in a static initializer too:
static Map<String,String> test;
{
Map<String,String> temp = new HashMap<String, String>();
temp.put("test","test");
temp.put("test1","test2");
test = Collections.unmodifiableMap(temp);
}
(I'm not sure if you can now make test
final ... try it out and report here.)
You need to use the scrollTop
property.
document.getElementById('box').scrollTop
you can use unlink in the folder where you have created your symlink
Intellij IDEA 15: File->Project Structure...->Project Settings->Libraries
Visual Studio 2012 (with ASP.NET and Web Tools 2012.2 RC installed) supports this natively.
Visual Studio 2013 onwards have this built-in.
(Image courtesy: robert.muehsig)
Extending from YaroslavGaponov's answer, the simplest implementation is just using Math.random()
.
Math.random()
Mathematically, the chances of fractions being the same in a real space [0, 1] is theoretically 0. Probability-wise it is approximately close to 0 for a default length of 16 decimals in node.js. And this implementation should also reduce arithmetic overflows as no operations are performed. Also, it is more memory efficient compared to a string as Decimals occupy less memory than strings.
I call this the "Fractional-Unique-ID".
Wrote code to generate 1,000,000 Math.random()
numbers and could not find any duplicates (at least for default decimal points of 16). See code below (please provide feedback if any):
random_numbers = []
for (i = 0; i < 1000000; i++) {
random_numbers.push(Math.random());
//random_numbers.push(Math.random().toFixed(13)) //depends decimals default 16
}
if (i === 1000000) {
console.log("Before checking duplicate");
console.log(random_numbers.length);
console.log("After checking duplicate");
random_set = new Set(random_numbers); // Set removes duplicates
console.log([...random_set].length); // length is still the same after removing
}
If you are using SQL*Plus try the following...
set long 8000
select ...
Using truncate()
, the solution could be
import re
#open the xml file for reading:
with open('path/test.xml','r+') as f:
#convert to string:
data = f.read()
f.seek(0)
f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>",data))
f.truncate()
This error is very weird.
I had this error with -ldAfnetworking and I only copy my project in other path and works.
You can use an svn changelist to keep track of a set of files that you want to commit together.
The linked page goes into lots of details, but here's an executive summary example:
$ svn changelist my-changelist mydir/dir1/file1.c mydir/dir2/myfile1.h
$ svn changelist my-changelist mydir/dir3/myfile3.c etc.
... (add all the files you want to commit together at your own rate)
$ svn commit -m"log msg" --changelist my-changelist
You can wrap it up to workaround the compiler but please remember that side effects in lambdas are discouraged.
To quote the javadoc
Side-effects in behavioral parameters to stream operations are, in general, discouraged, as they can often lead to unwitting violations of the statelessness requirement A small number of stream operations, such as forEach() and peek(), can operate only via side-effects; these should be used with care
Say your data set is in Columns A and B of the first sheet.
=Sheet1!$A$2:$B$5
.You can do this with multiple books too - as long as their "pages remaining" data points are tracked on the same dates (e.g. Book2 data would be in Column C, etc...) Books will be represented by additional series.
Yes, that is the definition of raw pointer equality: they both point to the same location (or are pointer aliases); usually in the virtual address space of the process running your application coded in C++ and managed by some operating system (but C++ can also be used for programming embedded devices with micro-controllers having a Harward architecture: on such microcontrollers some pointer casts are forbidden and makes no sense - since read only data could sit in code ROM)
For C++, read a good C++ programming book, see this C++ reference website, read the documentation of your C++ compiler (perhaps GCC or Clang) and consider coding with smart pointers. Maybe read also some draft C++ standard, like n4713 or buy the official standard from your ISO representative.
The concepts and terminology of garbage collection are also relevant when managing pointers and memory zones obtained by dynamic allocation (e.g. ::operator new
), so read perhaps the GC handbook.
For pointers on Linux machines, see also this.
The tutorial @Henrik mentioned is an excellent resource for learning how to create plots with the ggplot2
package.
An example with your data:
# transforming the data from wide to long
library(reshape2)
dfm <- melt(df, id = "TY")
# creating a scatterplot
ggplot(data = dfm, aes(x = TY, y = value, color = variable)) +
geom_point(size=5) +
labs(title = "Temperatures\n", x = "TY [°C]", y = "Txxx", color = "Legend Title\n") +
scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
theme_bw() +
theme(axis.text.x = element_text(size = 14), axis.title.x = element_text(size = 16),
axis.text.y = element_text(size = 14), axis.title.y = element_text(size = 16),
plot.title = element_text(size = 20, face = "bold", color = "darkgreen"))
this results in:
As mentioned by @user2739472 in the comments: If you only want to change the legend text labels and not the colours from ggplot's default palette, you can use scale_color_hue(labels = c("T999", "T888"))
instead of scale_color_manual()
.
That's a difficult problem to solve since visually similar PDFs may have a wildly differing structure depending on how they were produced. In the worst case the library would need to basically act like an OCR. On the other hand, the PDF may contain sufficient structure and metadata for easy removal of tables and figures, which the library can be tailored to take advantage of.
I'm pretty sure there are no open source tools which solve your problem for a wide variety of PDFs, but I remember having heard of commercial software claiming to do exactly what you ask for. I'm sure you'll run into them while googling.
gradle build -x test --parallel
If your machine has multiple cores. However, it is not recommended to use parallel clean.
I know this is an old stack but i will post this Multi-SQL select case
SELECT bp.bizid, bp.usrid, bp.website,
ROUND((SELECT SUM(rating) FROM ratings WHERE bizid=bp.bizid)/(SELECT COUNT(*) FROM ratings WHERE bizid=bp.bizid), 1) AS 'ratings',
(SELECT COUNT(*) FROM bzreviews WHERE bizid=bp.bizid) AS 'ttlreviews',
bp.phoneno, als.bizname,
(SELECT COUNT(*) FROM endorsment WHERE bizid=bp.bizid) AS 'endorses'
, als.imgname, bp.`location`, bp.`ownership`,
(SELECT COUNT(*) FROM follows WHERE bizid=bp.bizid) AS 'followers',
bp.categories, bp.openhours, bp.bizdecri FROM bizprofile AS bp
INNER JOIN alluser AS als ON bp.usrid=als.userid
WHERE als.usertype='Business'
I know that this is the wrong time to be answering this question but i just thought of something
i know it might be stressful but atleast it might still work
Now the trick is to create a lot of server side encoding scripts, they have to be decodable(for example a script that replaces all vowels with numbers and add the letter 'a' to every consonant so that the word 'bat' becomes ba1ta) then create a script that will randomize between the encoding scripts and create a cookie with the name of the encoding script being used (quick tip: try not to use the actual name of the encoding script for the cookie for example if our cookie is name 'encoding_script_being_used' and the randomizing script chooses an encoding script named MD10 try not to use MD10 as the value of the cookie but 'encoding_script4567656' just to prevent guessing) then after the cookie has been created another script will check for the cookie named 'encoding_script_being_used' and get the value, then it will determine what encoding script is being used.
Now the reason for randomizing between the encoding scripts was that the server side language will randomize which script to use to decode your javascript.js and then create a session or cookie to know which encoding scripts was used then the server side language will also encode your javascript .js and put it as a cookie
so people can't steal your code
but i would not advise this because
The androidmanifest.xml and policies.xml files on the sample page are invisible in my browser due to it trying to format the XML files as HTML. I'm only posting this for reference for the convenience of others, this is sourced from the sample page.
Thanks all for this helpful question!
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kns"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".LockScreenActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyAdmin"
android:permission="android.permission.BIND_DEVICE_ADMIN">
<meta-data android:name="android.app.device_admin"
android:resource="@xml/policies" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
</receiver>
</application>
</manifest>
policies.xml
<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
<uses-policies>
<limit-password />
<watch-login />
<reset-password />
<force-lock />
<wipe-data />
</uses-policies>
</device-admin>
You can map next and previous to function keys too, making cycling through buffers a breeze
map <F2> :bprevious<CR>
map <F3> :bnext<CR>
from my vimrc
What exactly are you planning on doing with it (what you want to do makes a difference with what you will need to call).
hashCode
, as defined in the JavaDocs, says:
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java™ programming language.)
So if you are using hashCode()
to find out if it is a unique object in memory that isn't a good way to do it.
System.identityHashCode
does the following:
Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode(). The hash code for the null reference is zero.
Which, for what you are doing, sounds like what you want... but what you want to do might not be safe depending on how the library is implemented.
You can set label's border via its underlying CALayer property:
#import <QuartzCore/QuartzCore.h>
myLabel.layer.borderColor = [UIColor greenColor].CGColor
myLabel.layer.borderWidth = 3.0
Swift 5:
myLabel.layer.borderColor = UIColor.darkGray.cgColor
myLabel.layer.borderWidth = 3.0
Execute
is sql*plus syntax .. try wrapping your call in begin .. end like this:
begin
temp_proc;
end;
(Although Jeffrey says this doesn't work in APEX .. but you're trying to get this to run in SQLDeveloper .. try the 'Run' menu there.)
There is a difference between .
and text()
, but this difference might not surface because of your input document.
If your input document looked like (the simplest document one can imagine given your XPath expressions)
Example 1
<html>
<a>Ask Question</a>
</html>
Then //a[text()="Ask Question"]
and //a[.="Ask Question"]
indeed return exactly the same result. But consider a different input document that looks like
Example 2
<html>
<a>Ask Question<other/>
</a>
</html>
where the a
element also has a child element other
that follows immediately after "Ask Question". Given this second input document, //a[text()="Ask Question"]
still returns the a
element, while //a[.="Ask Question"]
does not return anything!
This is because the meaning of the two predicates (everything between [
and ]
) is different. [text()="Ask Question"]
actually means: return true if any of the text nodes of an element contains exactly the text "Ask Question". On the other hand, [.="Ask Question"]
means: return true if the string value of an element is identical to "Ask Question".
In the XPath model, text inside XML elements can be partitioned into a number of text nodes if other elements interfere with the text, as in Example 2 above. There, the other
element is between "Ask Question" and a newline character that also counts as text content.
To make an even clearer example, consider as an input document:
Example 3
<a>Ask Question<other/>more text</a>
Here, the a
element actually contains two text nodes, "Ask Question" and "more text", since both are direct children of a
. You can test this by running //a/text()
on this document, which will return (individual results separated by ----
):
Ask Question
-----------------------
more text
So, in such a scenario, text()
returns a set of individual nodes, while .
in a predicate evaluates to the string concatenation of all text nodes. Again, you can test this claim with the path expression //a[.='Ask Questionmore text']
which will successfully return the a
element.
Finally, keep in mind that some XPath functions can only take one single string as an input. As LarsH has pointed out in the comments, if such an XPath function (e.g. contains()
) is given a sequence of nodes, it will only process the first node and silently ignore the rest.
I have run into this issue quite some times, so I made a JS solution for it. This basically adjust the height of the domElement according the width of the element by the ratio you specify. You could use it as followed:
<div ratio="4x3"></div>
Please be aware that since it is setting the height of the element, the element should be either a display:block
or display:inline-block
.
Seems pretty straightforward, according to the docs on the page you linked (emphasis mine).
requests.get(url, params=None, headers=None, cookies=None, auth=None, timeout=None)
Sends a GET request. Returns
Response
object.Parameters:
- url – URL for the new
Request
object.- params – (optional) Dictionary of GET Parameters to send with the
Request
.- headers – (optional) Dictionary of HTTP Headers to send with the
Request
.- cookies – (optional) CookieJar object to send with the
Request
.- auth – (optional) AuthObject to enable Basic HTTP Auth.
- timeout – (optional) Float describing the timeout of the request.
I guess you need to add a reference to the System.Configuration assembly if that have not already been added.
Also, you may need to insert the following line at the top of your code file:
using System.Configuration;
For anyone who has SQL 2012 or later, I was able to accomplish this with stored procedures that aren't dynamic and have the same columns output each time.
The general idea is I build the dynamic query to create, insert into, select from, and drop the temp table, and execute this after it's all generated. I dynamically generate the temp table by first retrieving column names and types from the stored procedure.
Note: there are much better, more universal solutions that will work with fewer lines of code if you're willing/able to update the SP or change configuration and use OPENROWSET
. Use the below if you have no other way.
DECLARE @spName VARCHAR(MAX) = 'MyStoredProc'
DECLARE @tempTableName VARCHAR(MAX) = '#tempTable'
-- might need to update this if your param value is a string and you need to escape quotes
DECLARE @insertCommand VARCHAR(MAX) = 'INSERT INTO ' + @tempTableName + ' EXEC MyStoredProc @param=value'
DECLARE @createTableCommand VARCHAR(MAX)
-- update this to select the columns you want
DECLARE @selectCommand VARCHAR(MAX) = 'SELECT col1, col2 FROM ' + @tempTableName
DECLARE @dropCommand VARCHAR(MAX) = 'DROP TABLE ' + @tempTableName
-- Generate command to create temp table
SELECT @createTableCommand = 'CREATE TABLE ' + @tempTableName + ' (' +
STUFF
(
(
SELECT ', ' + CONCAT('[', name, ']', ' ', system_type_name)
FROM sys.dm_exec_describe_first_result_set_for_object
(
OBJECT_ID(@spName),
NULL
)
FOR XML PATH('')
)
,1
,1
,''
) + ')'
EXEC( @createTableCommand + ' '+ @insertCommand + ' ' + @selectCommand + ' ' + @dropCommand)
Both are the same thing but many of the databases are not providing the varying char mainly postgreSQL is providing. So for the multi database like Oracle Postgre and DB2 it is good to use the Varchar
To take 6footunder's comment and turn it into an answer, HttpContent
is abstract so you need to use one of the derived classes:
The NSString
version (as opposed to Swift String) of replacingCharacters(in: NSRange, with: NSString)
accepts an NSRange
, so one simple solution is to convert String
to NSString
first. The delegate and replacement method names are slightly different in Swift 3 and 2, so depending on which Swift you're using:
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
let nsString = textField.text as NSString?
let newString = nsString?.replacingCharacters(in: range, with: string)
}
func textField(textField: UITextField,
shouldChangeCharactersInRange range: NSRange,
replacementString string: String) -> Bool {
let nsString = textField.text as NSString?
let newString = nsString?.stringByReplacingCharactersInRange(range, withString: string)
}
Into psql terminal put:
\i <path to contrib files>
in ubuntu it usually is /usr/share/postgreslq/<your pg version>/contrib/<contrib file>.sql
It works, just look at the bin/Debug folder, you are probably looking at app.config file inside project.
The vroom package provides a 'tidy' method of selecting / dropping columns by name during import. Docs: https://www.tidyverse.org/blog/2019/05/vroom-1-0-0/#column-selection
The vroom argument 'col_select' makes selecting columns to keep (or omit) more straightforward. The interface for col_select is the same as dplyr::select().
Select columns by namedata <- vroom("flights.tsv", col_select = c(year, flight, tailnum))
#> Observations: 336,776
#> Variables: 3
#> chr [1]: tailnum
#> dbl [2]: year, flight
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Drop columns by name
data <- vroom("flights.tsv", col_select = c(-dep_time, -air_time:-time_hour))
#> Observations: 336,776
#> Variables: 13
#> chr [4]: carrier, tailnum, origin, dest
#> dbl [9]: year, month, day, sched_dep_time, dep_delay, arr_time, sched_arr_time, arr...
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Use the selection helpers
data <- vroom("flights.tsv", col_select = ends_with("time"))
#> Observations: 336,776
#> Variables: 5
#> dbl [5]: dep_time, sched_dep_time, arr_time, sched_arr_time, air_time
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Or rename columns by name
data <- vroom("flights.tsv", col_select = list(plane = tailnum, everything()))
#> Observations: 336,776
#> Variables: 19
#> chr [ 4]: carrier, tailnum, origin, dest
#> dbl [14]: year, month, day, dep_time, sched_dep_time, dep_delay, arr_time, sched_arr...
#> dttm [ 1]: time_hour
#>
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
data
#> # A tibble: 336,776 x 19
#> plane year month day dep_time sched_dep_time dep_delay arr_time
#> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 N142… 2013 1 1 517 515 2 830
#> 2 N242… 2013 1 1 533 529 4 850
#> 3 N619… 2013 1 1 542 540 2 923
#> 4 N804… 2013 1 1 544 545 -1 1004
#> 5 N668… 2013 1 1 554 600 -6 812
#> 6 N394… 2013 1 1 554 558 -4 740
#> 7 N516… 2013 1 1 555 600 -5 913
#> 8 N829… 2013 1 1 557 600 -3 709
#> 9 N593… 2013 1 1 557 600 -3 838
#> 10 N3AL… 2013 1 1 558 600 -2 753
#> # … with 336,766 more rows, and 11 more variables: sched_arr_time <dbl>,
#> # arr_delay <dbl>, carrier <chr>, flight <dbl>, origin <chr>,
#> # dest <chr>, air_time <dbl>, distance <dbl>, hour <dbl>, minute <dbl>,
#> # time_hour <dttm>
var library = [_x000D_
{name: 'Steve', course:'WAP', courseID: 'cs452'}, _x000D_
{name: 'Rakesh', course:'WAA', courseID: 'cs545'},_x000D_
{name: 'Asad', course:'SWE', courseID: 'cs542'},_x000D_
];_x000D_
_x000D_
const sorted_by_name = library.sort( (a,b) => a.name > b.name );_x000D_
_x000D_
for(let k in sorted_by_name){_x000D_
console.log(sorted_by_name[k]);_x000D_
}
_x000D_
For installing pip with get-pip.py behind a proxy I went with the steps below. My server was even behind a jump server.
From the jump server:
ssh -R 18080:proxy-server:8080 my-python-server
On the "python-server"
export https_proxy=https://localhost:18080 ; export http_proxy=http://localhost:18080 ; export ftp_proxy=$http_proxy
python get-pip.py
Success.
If you paste the listing into your word processor instead of Notepad, (since each file name is in quotation marks with the full path name), you can highlight all the stuff you don't want on the first file, then use Find and Replace to replace every occurrence of that with nothing. Same with the ending quote (").
It makes a nice clean list of file names.
If you are working with Android-studio 1.3, Follow the below steps -
Go to File - Project Structure
Under modules- app-Properties tab, choose Source Compatibility -1.8 and
Target Compatibility - 1.8.
And you are good to go.
I tried the above methods, and no one can show the alert view, only when I put the presentViewController:
method in a dispatch_async
sentence:
dispatch_async(dispatch_get_main_queue(), ^ {
[self presentViewController:alert animated:YES completion:nil];
});
Refer to Alternative to UIAlertView for iOS 9?.
That turned out to be pretty simple. I've got it occasionally. To paste a text you simply need to right mouse button click anywhere in terminal window.
I started creating a Node.js/browserify application following the Cross Platform JavaScript blog post. And I ran into this issue, because my brand new Gruntfile didn't pass jshint.
Luckily I found an answer in the Leanpub book on Grunt:
If we try it now, we will scan our Gruntfile… and get some errors:
$ grunt jshint Running "jshint:all" (jshint) task Linting Gruntfile.js...ERROR [L1:C1] W097: Use the function form of "use strict". 'use strict'; Linting Gruntfile.js...ERROR [L3:C1] W117: 'module' is not defined. module.exports = function (grunt) { Warning: Task "jshint:all" failed. Use --force to continue.
Both errors are because the Gruntfile is a Node program, and by default JSHint does not recognise or allow the use of
module
and the string version ofuse strict
. We can set a JSHint rule that will accept our Node programs. Let’s edit our jshint task configuration and add an options key:jshint: { options: { node: true }, }
Adding node: true
to the jshint options
, to put jshint into "Node mode", removed both errors for me.
While Loop is an obsolete structure, I would recommend you to replace "While loop" to "Do While..loop", and you will able to use Exit clause.
check = 0
Do while not rs.EOF
if rs("reg_code") = rcode then
check = 1
Response.Write ("Found")
Exit do
else
rs.MoveNext
end if
Loop
if check = 0 then
Response.Write "Not Found"
end if}
public void getMyLocation() {
// create class object
gps = new GPSTracker(HomeActivity.this);
// check if GPS enabled
if (gps.canGetLocation()) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
postalCode = addresses.get(0).getPostalCode();
city = addresses.get(0).getLocality();
address = addresses.get(0).getAddressLine(0);
state = addresses.get(0).getAdminArea();
country = addresses.get(0).getCountryName();
knownName = addresses.get(0).getFeatureName();
Log.e("Location",postalCode+" "+city+" "+address+" "+state+" "+knownName);
} catch (IOException e) {
e.printStackTrace();
}
} else {
gps.showSettingsAlert();
}
}
The way Facebook does this is pretty interesting.
A common method of doing such notifications is to poll a script on the server (using AJAX) on a given interval (perhaps every few seconds), to check if something has happened. However, this can be pretty network intensive, and you often make pointless requests, because nothing has happened.
The way Facebook does it is using the comet approach, rather than polling on an interval, as soon as one poll completes, it issues another one. However, each request to the script on the server has an extremely long timeout, and the server only responds to the request once something has happened. You can see this happening if you bring up Firebug's Console tab while on Facebook, with requests to a script possibly taking minutes. It is quite ingenious really, since this method cuts down immediately on both the number of requests, and how often you have to send them. You effectively now have an event framework that allows the server to 'fire' events.
Behind this, in terms of the actual content returned from those polls, it's a JSON response, with what appears to be a list of events, and info about them. It's minified though, so is a bit hard to read.
In terms of the actual technology, AJAX is the way to go here, because you can control request timeouts, and many other things. I'd recommend (Stack overflow cliche here) using jQuery to do the AJAX, it'll take a lot of the cross-compability problems away. In terms of PHP, you could simply poll an event log database table in your PHP script, and only return to the client when something happens? There are, I expect, many ways of implementing this.
Implementing:
Server Side:
There appear to be a few implementations of comet libraries in PHP, but to be honest, it really is very simple, something perhaps like the following pseudocode:
while(!has_event_happened()) {
sleep(5);
}
echo json_encode(get_events());
The has_event_happened function would just check if anything had happened in an events table or something, and then the get_events function would return a list of the new rows in the table? Depends on the context of the problem really.
Don't forget to change your PHP max execution time, otherwise it will timeout early!
Client Side:
Take a look at the jQuery plugin for doing Comet interaction:
That said, the plugin seems to add a fair bit of complexity, it really is very simple on the client, perhaps (with jQuery) something like:
function doPoll() {
$.get("events.php", {}, function(result) {
$.each(result.events, function(event) { //iterate over the events
//do something with your event
});
doPoll();
//this effectively causes the poll to run again as
//soon as the response comes back
}, 'json');
}
$(document).ready(function() {
$.ajaxSetup({
timeout: 1000*60//set a global AJAX timeout of a minute
});
doPoll(); // do the first poll
});
The whole thing depends a lot on how your existing architecture is put together.
In addition of Stack: to avoid floating container on keyboard, use this
return Scaffold(
appBar: getAppBar(title),
resizeToAvoidBottomInset: false,
body:
None of yours are solved my problem. But, I found a good solution for me to work properly right now. In between tags write this code:
<div style="position: fixed; z-index: -99; width: 100%; height: 100%">
<iframe frameborder="0" height="100%" width="100%"
src="https://youtube.com/embed/**[CHANGE HERE WITH YOUR YOUTUBE VIDEO ID]**?autoplay=1&controls=0&showinfo=0&autohide=1">
</iframe>
</div>
- Make sure
session_start();
is called before any sessions are being called. So a safe bet would be to put it at the beginning of your page, immediately after the opening<?php
tag before anything else. Also ensure there are no whitespaces/tabs before the opening<?php
tag.- After the
header
redirect, end the current script usingexit();
(Others have also suggestedsession_write_close();
andsession_regenerate_id(true)
, you can try those as well, but I'd useexit();
).- Make sure cookies are enabled in the browser you are using to test it on.
- Ensure
register_globals
is off, you can check this on thephp.ini
file and also usingphpinfo()
. Refer to this as to how to turn it off.- Make sure you didn't delete or empty the session.
- Make sure the key in your
$_SESSION
superglobal array is not overwritten anywhere.- Make sure you redirect to the same domain. So redirecting from a
www.yourdomain.com
toyourdomain.com
doesn't carry the session forward.- Make sure your file extension is
.php
(it happens!).
You can use a full path with the fstream classes. The folowing code attempts to open the file demo.txt in the root of the C: drive. Note that as this is an input operation, the file must already exist.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream ifs( "c:/demo.txt" ); // note no mode needed
if ( ! ifs.is_open() ) {
cout <<" Failed to open" << endl;
}
else {
cout <<"Opened OK" << endl;
}
}
What does this code produce on your system?
In principle, you can pass any reformatting function to the labels
parameter:
+ scale_y_continuous(labels = function(x) paste0(x*100, "%")) # Multiply by 100 & add %
Or
+ scale_y_continuous(labels = function(x) paste0(x, "%")) # Add percent sign
Reproducible example:
library(ggplot2)
df = data.frame(x=seq(0,1,0.1), y=seq(0,1,0.1))
ggplot(df, aes(x,y)) +
geom_point() +
scale_y_continuous(labels = function(x) paste0(x*100, "%"))
Tag = a defined slice in time, usually used for releases
I think this is what one typically means by "tag". But in Subversion:
They don't really have any formal meaning. A folder is a folder to SVN.
which I find rather confusing: a revision control system that knows nothing about branches or tags. From an implementation point of view, I think the Subversion way of creating "copies" is very clever, but me having to know about it is what I'd call a leaky abstraction.
Or perhaps I've just been using CVS far too long.
Short version: by undoing the undo. If you undo, and then do a non-editing command such as C-f, then the next undo will undo the undo, resulting in a redo.
Longer version:
You can think of undo as operating on a stack of operations. If you perform some command (even a navigation command such as C-f) after a sequence of undo operations, all the undos are pushed on to the operation stack. So the next undo undoes the last command. Suppose you do have an operation sequence that looks like this:
Now, you undo. It undoes the last action, resulting in the following list:
If you do something other than undo at this point - say, C-f, the operation stack looks like this:
Now, when you undo, the first thing that is undone is the undo. Resulting in your original stack (and document state):
If you do a modifying command to break the undo sequence, that command is added after the undo and is thus the first thing to be undone afterwards. Suppose you backspaced over "bar" instead of hitting C-f. Then you would have had
This adding/re-adding happens ad infinitum. It takes a little getting used to, but it really does give Emacs a highly flexible and powerful undo/redo mechanism.
This Microsoft link allows you to select the SDK. When you run the install and only select Windows debugging tools it will only download 288mb and install the tool as stand alone.
https://developer.microsoft.com/en-us/windows/hardware/download-windbg
Use this, 100% guaranteed:-
vr {
margin-left: 20px;
margin-right: 20px;
height: 50px;
border: 0;
border-left: 1px solid #cccccc;
display: inline-block;
vertical-align: bottom;
}
You cannot do this in PHP. However, there are functional ways to accomplish this.
For more details please check this post: How to do a PHP nested class or nested methods?
This way of implementation is called fluent interface: http://en.wikipedia.org/wiki/Fluent_interface
This is a press down button example I've made:
<div>
<form id="forminput" action="action" method="POST">
...
</form>
<div style="right: 0px;bottom: 0px;position: fixed;" class="thumbnail">
<div class="image">
<a onclick="document.getElementById('forminput').submit();">
<img src="images/button.png" alt="Some awesome text">
</a>
</div>
</div>
</div>
the CSS file:
.thumbnail {
width: 128px;
height: 128px;
}
.image {
width: 100%;
height: 100%;
}
.image img {
-webkit-transition: all .25s ease; /* Safari and Chrome */
-moz-transition: all .25s ease; /* Firefox */
-ms-transition: all .25s ease; /* IE 9 */
-o-transition: all .25s ease; /* Opera */
transition: all .25s ease;
max-width: 100%;
max-height: 100%;
}
.image:hover img {
-webkit-transform:scale(1.05); /* Safari and Chrome */
-moz-transform:scale(1.05); /* Firefox */
-ms-transform:scale(1.05); /* IE 9 */
-o-transform:scale(1.05); /* Opera */
transform:scale(1.05);
}
.image:active img {
-webkit-transform:scale(.95); /* Safari and Chrome */
-moz-transform:scale(.95); /* Firefox */
-ms-transform:scale(.95); /* IE 9 */
-o-transform:scale(.95); /* Opera */
transform:scale(.95);
}
Enjoy it!
CSS3 has a box-shadow
property. Vendor prefixes are required at the moment for maximum browser compatibility.
div.box-shadow {
-webkit-box-shadow: 2px 2px 4px 1px #fff;
box-shadow: 2px 2px 4px 1px #fff;
}
There is a generator available at css3please.
Try your code like this:
var app = express();
app.get('/test', function(req, res) {
res.sendFile('views/test.html', {root: __dirname })
});
Use res.sendFile instead of reading the file manually so express can handle setting the content-type properly for you.
You don't need the app.engine
line, as that is handled internally by express.
we can easily stop the set interval by calling clear interval
var count = 0 , i = 5;
var vary = function intervalFunc() {
count++;
console.log(count);
console.log('hello boy');
if (count == 10) {
clearInterval(this);
}
}
setInterval(vary, 1500);
Another way to do it is using the StructField if you have multiple fields that needs to be modified.
Ex:
from pyspark.sql.types import StructField,IntegerType, StructType,StringType
newDF=[StructField('CLICK_FLG',IntegerType(),True),
StructField('OPEN_FLG',IntegerType(),True),
StructField('I1_GNDR_CODE',StringType(),True),
StructField('TRW_INCOME_CD_V4',StringType(),True),
StructField('ASIAN_CD',IntegerType(),True),
StructField('I1_INDIV_HHLD_STATUS_CODE',IntegerType(),True)
]
finalStruct=StructType(fields=newDF)
df=spark.read.csv('ctor.csv',schema=finalStruct)
Output:
Before
root
|-- CLICK_FLG: string (nullable = true)
|-- OPEN_FLG: string (nullable = true)
|-- I1_GNDR_CODE: string (nullable = true)
|-- TRW_INCOME_CD_V4: string (nullable = true)
|-- ASIAN_CD: integer (nullable = true)
|-- I1_INDIV_HHLD_STATUS_CODE: string (nullable = true)
After:
root
|-- CLICK_FLG: integer (nullable = true)
|-- OPEN_FLG: integer (nullable = true)
|-- I1_GNDR_CODE: string (nullable = true)
|-- TRW_INCOME_CD_V4: string (nullable = true)
|-- ASIAN_CD: integer (nullable = true)
|-- I1_INDIV_HHLD_STATUS_CODE: integer (nullable = true)
This is slightly a long procedure to cast , but the advantage is that all the required fields can be done.
It is to be noted that if only the required fields are assigned the data type, then the resultant dataframe will contain only those fields which are changed.
Rather than making a bunch of global variables, you might consider creating a class that has a bunch of public static constants. It's still global, but this way it's wrapped in a class so you know where the constant is coming from and that it's supposed to be a constant.
Constants.h
#ifndef CONSTANTS_H
#define CONSTANTS_H
class GlobalConstants {
public:
static const int myConstant;
static const int myOtherConstant;
};
#endif
Constants.cpp
#include "Constants.h"
const int GlobalConstants::myConstant = 1;
const int GlobalConstants::myOtherConstant = 3;
Then you can use this like so:
#include "Constants.h"
void foo() {
int foo = GlobalConstants::myConstant;
}
I was facing same issue not able to post form without ajax. but found solution , hope it can help and someones time.
<form name="paymentitrform" id="paymentitrform" class="payment"
method="post"
action="abc.php">
<input name="email" value="" placeholder="email" />
<input type="hidden" name="planamount" id="planamount" value="0">
<input type="submit" onclick="form_submit() " value="Continue Payment" class="action"
name="planform">
</form>
You can submit post form, from bootstrap modal using below javascript/jquery code : call the below function onclick of input submit button
function form_submit() {
document.getElementById("paymentitrform").submit();
}
# Initialize variables
new_list = []
i = 0
# Iterate through the list
for i in range(len(elements)):
# Does this element belong in the resulting list?
if i%2==0:
# Add this element to the resulting list
new_list.append(elements[i])
# Increment i
i +=2
return new_list
OP's solution to his problem, as he says, has dubious output. That code still shows confusion about representations of time. To clear up this confusion, and make code that won't lead to wrong times, consider this extension of what he did:
public static void _testDateFormatting() {
SimpleDateFormat sdfGMT1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdfGMT1.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat sdfGMT2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
sdfGMT2.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat sdfLocal1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
SimpleDateFormat sdfLocal2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
try {
Date d = new Date();
String s1 = d.toString();
String s2 = sdfLocal1.format(d);
// Store s3 or s4 in database.
String s3 = sdfGMT1.format(d);
String s4 = sdfGMT2.format(d);
// Retrieve s3 or s4 from database, using LOCAL sdf.
String s5 = sdfLocal1.parse(s3).toString();
//EXCEPTION String s6 = sdfLocal2.parse(s3).toString();
String s7 = sdfLocal1.parse(s4).toString();
String s8 = sdfLocal2.parse(s4).toString();
// Retrieve s3 from database, using GMT sdf.
// Note that this is the SAME sdf that created s3.
Date d2 = sdfGMT1.parse(s3);
String s9 = d2.toString();
String s10 = sdfGMT1.format(d2);
String s11 = sdfLocal2.format(d2);
} catch (Exception e) {
e.printStackTrace();
}
}
examining values in a debugger:
s1 "Mon Sep 07 06:11:53 EDT 2015" (id=831698113128)
s2 "2015.09.07 06:11:53" (id=831698114048)
s3 "2015.09.07 10:11:53" (id=831698114968)
s4 "2015.09.07 10:11:53 GMT+00:00" (id=831698116112)
s5 "Mon Sep 07 10:11:53 EDT 2015" (id=831698116944)
s6 -- omitted, gave parse exception
s7 "Mon Sep 07 10:11:53 EDT 2015" (id=831698118680)
s8 "Mon Sep 07 06:11:53 EDT 2015" (id=831698119584)
s9 "Mon Sep 07 06:11:53 EDT 2015" (id=831698120392)
s10 "2015.09.07 10:11:53" (id=831698121312)
s11 "2015.09.07 06:11:53 EDT" (id=831698122256)
sdf2 and sdfLocal2 include time zone, so we can see what is really going on. s1 & s2 are at 06:11:53 in zone EDT. s3 & s4 are at 10:11:53 in zone GMT -- equivalent to the original EDT time. Imagine we save s3 or s4 in a data base, where we are using GMT for consistency, so we can have times from anywhere in the world, without storing different time zones.
s5 parses the GMT time, but treats it as a local time. So it says "10:11:53" -- the GMT time -- but thinks it is 10:11:53 in local time. Not good.
s7 parses the GMT time, but ignores the GMT in the string, so still treats it as a local time.
s8 works, because now we include GMT in the string, and the local zone parser uses it to convert from one time zone to another.
Now suppose you don't want to store the zone, you want to be able to parse s3, but display it as a local time. The answer is to parse using the same time zone it was stored in -- so use the same sdf as it was created in, sdfGMT1. s9, s10, & s11 are all representations of the original time. They are all "correct". That is, d2 == d1. Then it is only a question of how you want to DISPLAY it. If you want to display what is stored in DB -- GMT time -- then you need to format it using a GMT sdf. Ths is s10.
So here is the final solution, if you don't want to explicitly store with " GMT" in the string, and want to display in GMT format:
public static void _testDateFormatting() {
SimpleDateFormat sdfGMT1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdfGMT1.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
Date d = new Date();
String s3 = sdfGMT1.format(d);
// Store s3 in DB.
// ...
// Retrieve s3 from database, using GMT sdf.
Date d2 = sdfGMT1.parse(s3);
String s10 = sdfGMT1.format(d2);
} catch (Exception e) {
e.printStackTrace();
}
}
In case you need the []
syntax, useful for "edit forms" when you need to pass parameters like id with the route, you would do something like:
[routerLink]="['edit', business._id]"
As for an "about page" with no parameters like yours,
[routerLink]="/about"
or
[routerLink]=['about']
will do the trick.
Is it really a function call on the action attribute? or it should be on the onSUbmit attribute, because by convention action attribute needs a page/URL.
I think you should use AJAX with that,
There are plenty PHP AJAX Frameworks to choose from
http://www.phplivex.com/example/submitting-html-forms-with-ajax
http://www.xajax-project.org/en/docs-tutorials/learn-xajax-in-10-minutes/
ETC.
Or the classic way
http://www.w3schools.com/php/php_ajax_php.asp
I hope these links help
I am using this on PHP 7.2.x, it's working fine for me:
public function make_hash($userStr){
try{
/**
* Used and tested on PHP 7.2x, Salt has been removed manually, it is now added by PHP
*/
return password_hash($userStr, PASSWORD_BCRYPT);
}catch(Exception $exc){
$this->tempVar = $exc->getMessage();
return false;
}
}
and then authenticate the hash with the following function:
public function varify_user($userStr,$hash){
try{
if (password_verify($userStr, $hash)) {
return true;
}
else {
return false;
}
}catch(Exception $exc){
$this->tempVar = $exc->getMessage();
return false;
}
}
Example:
//create hash from user string
$user_password = $obj->make_hash2($user_key);
and to authenticate this hash use the following code:
if($obj->varify_user($key, $user_key)){
//this is correct, you can proceed with
}
That's all.
Do this to launch the gallery and allow the user to pick an image:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, IMAGE_PICK);
Then in your onActivityResult()
use the URI of the image that is returned to set the image on your ImageView.
You shouldn't be looking at what happens around the call that creates the fiber but rather at what happens inside the fiber. Once you are inside the fiber you can program in sync style. For example:
function f1() { console.log('wait... ' + new Date); sleep(1000); console.log('ok... ' + new Date); } function f2() { f1(); f1(); } Fiber(function() { f2(); }).run();
Inside the fiber you call f1
, f2
and sleep
as if they were sync.
In a typical web application, you will create the Fiber in your HTTP request dispatcher. Once you've done that you can write all your request handling logic in sync style, even if it calls async functions (fs, databases, etc.).
I suggest to use sticky js it's have best option ever i have seen. nothing to do just ad this js on you
https://raw.githubusercontent.com/garand/sticky/master/jquery.sticky.js
and use below code :
<script>
$(document).ready(function(){
$("#sticker").sticky({topSpacing:0});
});
</script>
Its git repo: https://github.com/garand/sticky
requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
Log.w("a","")
}
})
You can use query
, i.e.:
b = df.query('a > 1 & a < 5')
Instead of this:
// [START refresh_token]
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
// String refreshedToken = FirebaseInstanceId.getInstance().getToken();
// Log.d(TAG, "Refreshed token: " + refreshedToken);
//
// TODO: Implement this method to send any registration to your app's servers.
// sendRegistrationToServer(refreshedToken);
//
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
}
// [END refresh_token]
Do this:
// [START refresh_token]
@Override
public void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.getInstance().getToken();
// Log.d(TAG, "Refreshed token: " + refreshedToken);
// Implement this method to send token to your app's server
sendRegistrationToServer(refreshedToken);
}
// [END refresh_token]
And one more thing:
You need to call
sendRegistrationToServer()
method which will update token on server, if you are sending push notifications from server.
UPDATE:
New Firebase token is generated (onTokenRefresh()
is called) when:
<head>
<script type="text/javascript">
function SetMaxLength () {
var input = document.getElementById ("myInput");
input.maxLength = 10;
}
</script>
</head>
<body>
<input id="myInput" type="text" size="20" />
</body>
In PyCharm go to
C:\Miniconda3\envs\my_env\python.exe
, where my_env is the environment you want to useAlternatively, in step 3 use C:\Miniconda3\python.exe
if you did not create any further environments (if you never invoked conda create -n my_env python=3
).
You can get a list of your current environments with conda info -e
and switch to one of them using activate my_env
.
All those special php expressions, in spirit of first day of ...
are great, though they go out of my head time and again.
So I decided to build a couple of basic datetime abstractions and tons of specific implementation which are auto-completed by any IDE. The point is to find what-kind of things. Like, today
, now
, the first day of a previous month
, etc. All of those things I've listed are datetimes. Hence, there is an interface or abstract class called ISO8601DateTime
, and specific datetimes which implement it.
The code in your particular case looks like that:
(new TheFirstDayOfThisMonth(new Now()))->value();
For more about this approach, take a look at this entry.
You need to create own PCH file
Add New file -> Other-> PCH file
Then add the path of this PCH file to your build setting->prefix header->path
($(SRCROOT)/filename.pch)
As Tmdean correctly pointed out you can use the Mid()
function. The MSDN Library also has a great reference section on VBScript which you can find here:
This works (pandas v'0.19.2'):
df.rename(columns=df.iloc[0])
You should be able to transfer the Application to another Username. You would need all your old user information to transfer it. The application would remove it's self from old account to new account. Also you could put a limit on how many times you where allowed to transfer it. If you transfer it to the application could expire after a year and force to buy update.
$uri = $_SERVER['REQUEST_URI'];
This will give you the requested directory and file name. If you use mod_rewrite, this is extremely useful because it tells you what page the user was looking at.
If you need the actual file name, you might want to try either $_SERVER['PHP_SELF']
, the magic constant __FILE__
, or $_SERVER['SCRIPT_FILENAME']
. The latter 2 give you the complete path (from the root of the server), rather than just the root of your website. They are useful for includes and such.
$_SERVER['PHP_SELF']
gives you the file name relative to the root of the website.
$relative_path = $_SERVER['PHP_SELF'];
$complete_path = __FILE__;
$complete_path = $_SERVER['SCRIPT_FILENAME'];
Remove all untracked files:
git clean -d -fx .
Caution: this will delete IDE files and any useful files as long as you donot track the files. Use this command with care
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private Context context;
private List<cardview_widgets> list;
public MyAdapter(Context context, List<cardview_widgets> list) {
this.context = context;
this.list = list;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(this.context).inflate(R.layout.fragment1_one_item,
viewGroup, false);
return new MyViewHolder(view);
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView txtValue;
TextView txtCategory;
ImageView imgInorEx;
ImageView imgCategory;
TextView txtDate;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
txtValue= itemView.findViewById(R.id.id_values);
txtCategory= itemView.findViewById(R.id.id_category);
imgInorEx= itemView.findViewById(R.id.id_inorex);
imgCategory= itemView.findViewById(R.id.id_imgcategory);
txtDate= itemView.findViewById(R.id.id_date);
}
}
@NonNull
@Override
public void onBindViewHolder(@NonNull final MyViewHolder myViewHolder, int i) {
myViewHolder.txtValue.setText(String.valueOf(list.get(i).getValuee()));
myViewHolder.txtCategory.setText(list.get(i).getCategory());
myViewHolder.imgInorEx.setBackgroundColor(list.get(i).getImg_inorex());
myViewHolder.imgCategory.setImageResource(list.get(i).getImg_category());
myViewHolder.txtDate.setText(list.get(i).getDate());
myViewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
list.remove(myViewHolder.getAdapterPosition());
notifyDataSetChanged();
return false;
}
});
}
@Override
public int getItemCount() {
return list.size();
}}
i hope this help you.
Putting the model dot property in strings worked for me: ModelState.AddModelError("Item1.Month", "This is not a valid date");
The Location directive system is
Like you want to forward all request which start /static
and your data present in /var/www/static
So a simple method is separated last folder from full path , that means
Full path : /var/www/static
Last Path : /static
and First path : /var/www
location <lastPath> {
root <FirstPath>;
}
So lets see what you did mistake and what is your solutions
Your Mistake :
location /static {
root /web/test.example.com/static;
}
Your Solutions :
location /static {
root /web/test.example.com;
}
BigDecimal a = new BigDecimal("12345.0789");
a = a.divide(new BigDecimal("1"), 2, BigDecimal.ROUND_HALF_UP);
//Also check other rounding modes
System.out.println("a >> "+a.toPlainString()); //Returns 12345.08
In my experience switching branches in the superproject or future checkouts will still cause detached HEADs of submodules regardless if the submodule is properly added and tracked (i.e. @djacobs7 and @Johnny Z answers).
And instead of manually checking out the correct branch manually or through a script git submodule foreach can be used.
This will check the submodule config file for the branch property and checkout the set branch.
git submodule foreach -q --recursive 'branch="$(git config -f <path>.gitmodules submodule.$name.branch)"; git checkout $branch'
The difference is the implicit conversion when using AddWithValue. If you know that your executing SQL query (stored procedure) is accepting a value of type int, nvarchar, etc, there's no reason in re-declaring it in your code.
For complex type scenarios (example would be DateTime, float), I'll probably use Add since it's more explicit but AddWithValue for more straight-forward type scenarios (Int to Int).
function createQuestionPanel() {
var element = document.createElement("Input");
element.setAttribute("type", "button");
element.setAttribute("value", "button");
element.setAttribute("name", "button");
var div = document.createElement("div"); <------- Create DIv Node
div.appendChild(element);<--------------------
document.body.appendChild(div) <------------- Then append it to body
}
function formvalidate() {
}
a:not([href]) { cursor: pointer; }
There's the global attribute called hidden
. But I'm green to all this and maybe there was a reason it wasn't mentioned yet?
var someCondition = true;_x000D_
_x000D_
if (someCondition == true){_x000D_
document.getElementById('hidden div').hidden = false;_x000D_
}
_x000D_
<div id="hidden div" hidden>_x000D_
stuff hidden by default_x000D_
</div>
_x000D_
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/hidden
First, a short description of $on()
, $broadcast()
and $emit()
:
.$on(name, listener)
- Listens for a specific event by a given name
.$broadcast(name, args)
- Broadcast an event down through the $scope
of all children.$emit(name, args)
- Emit an event up the $scope
hierarchy to all parents, including the $rootScope
Based on the following HTML (see full example here):
<div ng-controller="Controller1">
<button ng-click="broadcast()">Broadcast 1</button>
<button ng-click="emit()">Emit 1</button>
</div>
<div ng-controller="Controller2">
<button ng-click="broadcast()">Broadcast 2</button>
<button ng-click="emit()">Emit 2</button>
<div ng-controller="Controller3">
<button ng-click="broadcast()">Broadcast 3</button>
<button ng-click="emit()">Emit 3</button>
<br>
<button ng-click="broadcastRoot()">Broadcast Root</button>
<button ng-click="emitRoot()">Emit Root</button>
</div>
</div>
The fired events will traverse the $scopes
as follows:
$scope
$scope
then $rootScope
$scope
then Controller 3 $scope
$scope
then $rootScope
$scope
$scope
, Controller 2 $scope
then $rootScope
$rootScope
and $scope
of all the Controllers (1, 2 then 3) $rootScope
JavaScript to trigger events (again, you can see a working example here):
app.controller('Controller1', ['$scope', '$rootScope', function($scope, $rootScope){
$scope.broadcastAndEmit = function(){
// This will be seen by Controller 1 $scope and all children $scopes
$scope.$broadcast('eventX', {data: '$scope.broadcast'});
// Because this event is fired as an emit (goes up) on the $rootScope,
// only the $rootScope will see it
$rootScope.$emit('eventX', {data: '$rootScope.emit'});
};
$scope.emit = function(){
// Controller 1 $scope, and all parent $scopes (including $rootScope)
// will see this event
$scope.$emit('eventX', {data: '$scope.emit'});
};
$scope.$on('eventX', function(ev, args){
console.log('eventX found on Controller1 $scope');
});
$rootScope.$on('eventX', function(ev, args){
console.log('eventX found on $rootScope');
});
}]);
Please try following regex for remove double quotes from string .
$string = "I am here";
$string =~ tr/"//d;
print $string;
exit();
Another way to do this would be to respond to the UITableViewDelegate
method willDisplayHeaderView
. The passed view is actually an instance of a UITableViewHeaderFooterView
.
The example below changes the font, and also centers the title text vertically and horizontally within the cell. Note that you should also respond to heightForHeaderInSection
to have any changes to your header's height accounted for in the layout of the table view. (That is, if you decide to change the header height in this willDisplayHeaderView
method.)
You could then respond to the titleForHeaderInSection
method to reuse this configured header with different section titles.
Objective-C
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
header.textLabel.textColor = [UIColor redColor];
header.textLabel.font = [UIFont boldSystemFontOfSize:18];
CGRect headerFrame = header.frame;
header.textLabel.frame = headerFrame;
header.textLabel.textAlignment = NSTextAlignmentCenter;
}
Swift 1.2
(Note: if your view controller is a descendant of a UITableViewController
, this would need to be declared as override func
.)
override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
{
let header:UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
header.textLabel.textColor = UIColor.redColor()
header.textLabel.font = UIFont.boldSystemFontOfSize(18)
header.textLabel.frame = header.frame
header.textLabel.textAlignment = NSTextAlignment.Center
}
Swift 3.0
This code also ensures that the app doesn't crash if your header view is something other than a UITableViewHeaderFooterView:
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
guard let header = view as? UITableViewHeaderFooterView else { return }
header.textLabel?.textColor = UIColor.red
header.textLabel?.font = UIFont.boldSystemFont(ofSize: 18)
header.textLabel?.frame = header.frame
header.textLabel?.textAlignment = .center
}
Or, create a new table as temp with the extra column, copy the data to this new table while manipulating it as necessary to fill the non-nullable new column, and then swap the table via a two-step name change.
Yes, it is more complicated, but you may need to do it this way if you don't want a big UPDATE on a live table.
Ignacio Vazquez-Abrams is correct. But to elaborate, re.match()
will return either None
, which evaluates to False
, or a match object, which will always be True
as he said. Only if you want information about the part(s) that matched your regular expression do you need to check out the contents of the match object.
I just wanted to add some code here for people in the future since I was trying to export JSON to a CSV document and download it.
I use $.getJSON
to pull json data from an external page, but if you have a basic array, you can just use that.
This uses Christian Landgren's code to create the csv data.
$(document).ready(function() {
var JSONData = $.getJSON("GetJsonData.php", function(data) {
var items = data;
const replacer = (key, value) => value === null ? '' : value; // specify how you want to handle null values here
const header = Object.keys(items[0]);
let csv = items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','));
csv.unshift(header.join(','));
csv = csv.join('\r\n');
//Download the file as CSV
var downloadLink = document.createElement("a");
var blob = new Blob(["\ufeff", csv]);
var url = URL.createObjectURL(blob);
downloadLink.href = url;
downloadLink.download = "DataDump.csv"; //Name the file here
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
});
});
Edit: It's worth noting that JSON.stringify
will escape quotes in quotes by adding \"
. If you view the CSV in excel, it doesn't like that as an escape character.
You can add .replace(/\\"/g, '""')
to the end of JSON.stringify(row[fieldName], replacer)
to display this properly in excel (this will replace \"
with ""
which is what excel prefers).
Full Line: let csv = items.map(row => header.map(fieldName => (JSON.stringify(row[fieldName], replacer).replace(/\\"/g, '""'))).join(','));
I want to mention that in some win 10 systems, Microsoft pre-installed a python. Thus, in order to invoke the python installed in the anaconda, you should adjust the order of the environment variable to ensure that the anaconda has a higher priority.
I doubt that Subclipse and then SVN can use your Eclipse proxy settings. You'll probably need to set the proxy for your SVN program itself. Trying to check out the files using SVN from the command line should tell you if that works.
If SVN can't connect either then put the proxy settings in your servers file in your Subversion settings folder (in your home folder).
If it can't do it even with the proxy settings set, then your firewall is probably blocking the methods and protocols that Subversion needs to use to download the files.
I use:
used_features =[
"one",
"two",
"three"
]
df['is_duplicated'] = df.duplicated(used_features)
df['is_duplicated'].sum()
which gives count of duplicated rows, and then you can analyse them by a new column. I didn't see such solution here.
The key is to encapsulate the expression in parentheses after the @ delimiter. You can make any compound expression work this way.
Here is a React Hooks specific solution for
Warning: Can't perform a React state update on an unmounted component.
You can declare let isMounted = true
inside useEffect
, which will be changed in the cleanup callback, as soon as the component is unmounted. Before state updates, you now check this variable conditionally:
useEffect(() => {
let isMounted = true; // note this flag denote mount status
someAsyncOperation().then(data => {
if (isMounted) setState(data);
})
return () => { isMounted = false }; // use effect cleanup to set flag false, if unmounted
});
const Parent = () => {_x000D_
const [mounted, setMounted] = useState(true);_x000D_
return (_x000D_
<div>_x000D_
Parent:_x000D_
<button onClick={() => setMounted(!mounted)}>_x000D_
{mounted ? "Unmount" : "Mount"} Child_x000D_
</button>_x000D_
{mounted && <Child />}_x000D_
<p>_x000D_
Unmount Child, while it is still loading. It won't set state later on,_x000D_
so no error is triggered._x000D_
</p>_x000D_
</div>_x000D_
);_x000D_
};_x000D_
_x000D_
const Child = () => {_x000D_
const [state, setState] = useState("loading (4 sec)...");_x000D_
useEffect(() => {_x000D_
let isMounted = true; // note this mounted flag_x000D_
fetchData();_x000D_
return () => {_x000D_
isMounted = false;_x000D_
}; // use effect cleanup to set flag false, if unmounted_x000D_
_x000D_
// simulate some Web API fetching_x000D_
function fetchData() {_x000D_
setTimeout(() => {_x000D_
// drop "if (isMounted)" to trigger error again_x000D_
if (isMounted) setState("data fetched");_x000D_
}, 4000);_x000D_
}_x000D_
}, []);_x000D_
_x000D_
return <div>Child: {state}</div>;_x000D_
};_x000D_
_x000D_
ReactDOM.render(<Parent />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect, useState, useRef } = React</script>
_x000D_
useAsync
HookWe can encapsulate all the boilerplate into a custom Hook, that just knows, how to deal with and automatically abort async functions in case the component unmounts before:
function useAsync(asyncFn, onSuccess) {
useEffect(() => {
let isMounted = true;
asyncFn().then(data => {
if (isMounted) onSuccess(data);
});
return () => { isMounted = false };
}, [asyncFn, onSuccess]);
}
// use async operation with automatic abortion on unmount_x000D_
function useAsync(asyncFn, onSuccess) {_x000D_
useEffect(() => {_x000D_
let isMounted = true;_x000D_
asyncFn().then(data => {_x000D_
if (isMounted) onSuccess(data);_x000D_
});_x000D_
return () => {_x000D_
isMounted = false;_x000D_
};_x000D_
}, [asyncFn, onSuccess]);_x000D_
}_x000D_
_x000D_
const Child = () => {_x000D_
const [state, setState] = useState("loading (4 sec)...");_x000D_
useAsync(delay, setState);_x000D_
return <div>Child: {state}</div>;_x000D_
};_x000D_
_x000D_
const Parent = () => {_x000D_
const [mounted, setMounted] = useState(true);_x000D_
return (_x000D_
<div>_x000D_
Parent:_x000D_
<button onClick={() => setMounted(!mounted)}>_x000D_
{mounted ? "Unmount" : "Mount"} Child_x000D_
</button>_x000D_
{mounted && <Child />}_x000D_
<p>_x000D_
Unmount Child, while it is still loading. It won't set state later on,_x000D_
so no error is triggered._x000D_
</p>_x000D_
</div>_x000D_
);_x000D_
};_x000D_
_x000D_
const delay = () => new Promise(resolve => setTimeout(() => resolve("data fetched"), 4000));_x000D_
_x000D_
_x000D_
ReactDOM.render(<Parent />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>_x000D_
<div id="root"></div>_x000D_
<script>var { useReducer, useEffect, useState, useRef } = React</script>
_x000D_
I know this question already has an answer, but I found out an even simpler way of doing this.
Just add
<tr height = 20px></tr>
Into the table where you want to have an empty row. It works fine in my program and it's probably the quickest solution possible.
Here is my little utility helper for splitting paths int file, path tokens:
import os
# usage: file, path = splitPath(s)
def splitPath(s):
f = os.path.basename(s)
p = s[:-(len(f))-1]
return f, p
These examples are from php.net. Thanks to you, I also just learned about the new php hashing functions.
Read the php documentation to find out about the possibilities and best practices: http://www.php.net/manual/en/function.password-hash.php
Save a password hash:
$options = [
'cost' => 11,
];
// Get the password from post
$passwordFromPost = $_POST['password'];
$hash = password_hash($passwordFromPost, PASSWORD_BCRYPT, $options);
// Now insert it (with login or whatever) into your database, use mysqli or pdo!
Get the password hash:
// Get the password from the database and compare it to a variable (for example post)
$passwordFromPost = $_POST['password'];
$hashedPasswordFromDB = ...;
if (password_verify($passwordFromPost, $hashedPasswordFromDB)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
This tool creates the folders with the images in them automatically for you. All you have to do is supply your image then drag the generated folders to your res folder. http://romannurik.github.io/AndroidAssetStudio/
All the best.
#include <string.h>
#include <stdio.h>
int main()
{
int a,l;
char str[50],str1[50],str3[100];
printf("\nEnter a string: ");
scanf("%s",str);
str3[0]='\0';
printf("\nEnter the string which you want to concat with string one: ");
scanf("%s",str1);
strcat(str3,str);
strcat(str3,str1);
printf("\nThe string is %s\n",str3);
}
The answer may sound silly, but after wasting hours of time, this is how I got it to work
mysql -u root -p
I got the error message
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
Even though I was typing the correct password(the temporary password you get when you first install mysql)
I got it right when I typed in the password when the password prompt was blinking
For anyone that stumbles upon this page, none of the solutions here worked for me. I found this is the way to do it (in a batch file):
@for /f "skip=1" %%p in ('wmic cpu get loadpercentage /VALUE') do (
for /F "tokens=2 delims==" %%J in ("%%p") do echo %%J
)
Once the icon is in a .ICO format in visual studio I use
//This uses the file u give it to make an icon.
Icon icon = Icon.ExtractAssociatedIcon(String);//pulls icon from .ico and makes it then icon object.
//Assign icon to the icon property of the form
this.Icon = icon;
so in short
Icon icon = Icon.ExtractAssociatedIcon("FILE/Path");
this.Icon = icon;
Works everytime.
While there are several excellent answers, ranging from usual suspects to newer solutions, I would like to provide one more to the fray that addresses what you should do when you are working on a solution with multiple projects.
Before I arrived at this solution, I kept looking at bindingInformation
in the applicationhost.config of the solution, tirelessly looking for any hint of why things were simply not working.
Turns out, the simple thing that I overlooked was that different projects have individual settings too.
So, besides
Project > {Project-Name} Properties... > Web > Start Action
on my Backend Project, I also had to Go toWebsite > Start Options... > Start Action
on my Frontend Project. Once there, I selectedDon't open a page. Wait for a request from an external application
and have been happy ever since!
2018: CSS3
div{
position: absolute;
top: 50%;
left: 50%;
margin-right: -50%;
transform: translate(-50%, -50%);
}
This is even shorter. For more information see this: CSS: Centering Things
I use an alternative to the solution that wrote nifr.
$resultRows = $repository->fetchAll();
uasort($resultRows, function($a, $b){
if ($a->getProperty() == $b->getProperty()) {
return 0;
}
return ($a->getProperty()< $b->getProperty()) ? -1 : 1;
});
It's quicker than the ORDER BY clause, and without the overhead of the Iterator.
Description:
there are 3 steps to run PHP code inside post or page.
In functions.php
file (in your theme) add new function
In functions.php
file (in your theme) register new shortcode which call your function:
add_shortcode( 'SHORCODE_NAME', 'FUNCTION_NAME' );
Example #1: just display text.
In functions:
function simple_function_1() {
return "Hello World!";
}
add_shortcode( 'own_shortcode1', 'simple_function_1' );
In post/page:
[own_shortcode1]
Effect:
Hello World!
Example #2: use for loop.
In functions:
function simple_function_2() {
$output = "";
for ($number = 1; $number < 10; $number++) {
// Append numbers to the string
$output .= "$number<br>";
}
return "$output";
}
add_shortcode( 'own_shortcode2', 'simple_function_2' );
In post/page:
[own_shortcode2]
Effect:
1
2
3
4
5
6
7
8
9
Example #3: use shortcode with arguments
In functions:
function simple_function_3($name) {
return "Hello $name";
}
add_shortcode( 'own_shortcode3', 'simple_function_3' );
In post/page:
[own_shortcode3 name="John"]
Effect:
Hello John
Example #3 - without passing arguments
In post/page:
[own_shortcode3]
Effect:
Hello
I install go launcher on mine, (Windows 8)=> preferences => Screens => Screen orientation => vertical (disable QWE keyboard)
You can do it using the scrollTop method on DOM ready:
$(document).ready(function(){
$(this).scrollTop(0);
});
Use the command where
in prompt to find the current executable in path
C:\> where tsc
C:\Users\user\AppData\Roaming\npm\tsc
C:\Users\user\AppData\Roaming\npm\tsc.cmd
On docker with image php:7.2-apache
I just needed zip and unzip. No need for php-zip :
apt-get install zip unzip
or Dockerfile
RUN ["apt-get", "update"]
RUN ["apt-get", "install", "-y", "zip"]
RUN ["apt-get", "install", "-y", "unzip"]
To remove the first and last element of an array is by using the built-in method of an array i.e shift()
and pop()
the fruits.shift()
get the first element of the array as "Banana" while fruits.pop()
get the last element of the array as "Mango". so the remaining element of the array will be ["Orange", "Apple"]
THis method allows you to have more flexibility of styling your entire content. Effectivly creating two containers that you can style. THe HTML Body tag which serves as your background, and the div with an id of container which contains your content.
This then allows you to position your content within the page, while styling a background or other effects without issue. THink of it as a "Frame" for the content.
The easiest way would be using Substring
string str = "AM0122200204";
string substr = str.Substring(str.Length - 3);
Using the overload with one int
as I put would get the substring
of a string
, starting from the index int
. In your case being str.Length - 3
, since you want to get the last three chars.
Alternatively, you can use XPath query via XPathSelectElements
method:
var document = XDocument.Parse(yourXmlAsString);
var words = document.XPathSelectElements("//word[./category[text() = 'verb']]");
Apple Swift version 3.1 - Xcode Version 8.3 (8E162)
The handy way from Alexandre Cassagne's approach
let directions: [UISwipeGestureRecognizerDirection] = [.up, .down, .right, .left]
for direction in directions {
let gesture = UISwipeGestureRecognizer(target: self, action: #selector(YourClassName.handleSwipe(gesture:)))
gesture.direction = direction
self.view?.addGestureRecognizer(gesture)
}
func handleSwipe(gesture: UISwipeGestureRecognizer) {
print(gesture.direction)
switch gesture.direction {
case UISwipeGestureRecognizerDirection.down:
print("down swipe")
case UISwipeGestureRecognizerDirection.up:
print("up swipe")
case UISwipeGestureRecognizerDirection.left:
print("left swipe")
case UISwipeGestureRecognizerDirection.right:
print("right swipe")
default:
print("other swipe")
}
}
I strongly recommend Perlbrew. It lets you run multiple versions of Perl, install packages, hack Perl internals if you want to, all regular user permissions.
I use php
inside of var.js
file with this .htaccess
.
<Files var.js>
AddType application/x-httpd-php .js
</Files>
Then I write php code in the .js file
<?php
// This is a `.js` file but works with php
echo "var js_variable = '$php_variable';";
When I got the MIME type warning on Chrome, I fixed it by adding a Content-Type
header line in the .js(but php)
file.
<?php
header('Content-Type: application/javascript'); // <- Add this line
// This is a `.js` file but works with php
...
A browser won't execute .js
file because apache sends the Content-Type
header of the file as application/x-httpd-php
that is defined in .htaccess
. That's a security reason. But apache won't execute php as far as htaccess
commands the impersonation, it's necessary. So we need to overwrite apache's Content-Type
header with the php function header()
. I guess that apache stops sending its own header when php sends it instead of apache before.
FWIW, here's the dictionary thing. After setting a reference to MS Scripting. You can jack around with the array size of avInput to match your needs.
Sub somemacro()
Dim avInput As Variant
Dim uvals As Dictionary
Dim i As Integer
Dim rop As Range
avInput = Sheets("data").UsedRange
Set uvals = New Dictionary
For i = 1 To UBound(avInput, 1)
If uvals.Exists(avInput(i, 1)) = False Then
uvals.Add avInput(i, 1), 1
Else
uvals.Item(avInput(i, 1)) = uvals.Item(avInput(i, 1)) + 1
End If
Next i
ReDim avInput(1 To uvals.Count)
i = 1
For Each kv In uvals.Keys
avInput(i) = kv
i = i + 1
Next kv
Set rop = Sheets("sheet2").Range("a1")
rop.Resize(UBound(avInput, 1), 1) = Application.Transpose(avInput)
End Sub
To get the behavior you want you need to wait for the process to finish before you exit Main()
. To be able to tell when your process is done you need to return a Task
instead of a void
from your function, you should never return void
from a async
function unless you are working with events.
A re-written version of your program that works correctly would be
class Program { static void Main(string[] args) { Debug.WriteLine("Calling DoDownload"); var downloadTask = DoDownloadAsync(); Debug.WriteLine("DoDownload done"); downloadTask.Wait(); //Waits for the background task to complete before finishing. } private static async Task DoDownloadAsync() { WebClient w = new WebClient(); string txt = await w.DownloadStringTaskAsync("http://www.google.com/"); Debug.WriteLine(txt); } }
Because you can not await
in Main()
I had to do the Wait()
function instead. If this was a application that had a SynchronizationContext I would do await downloadTask;
instead and make the function this was being called from async
.
input type="submit"
is the best way to have a submit button in a form. The downside of this is that you cannot put anything other than text as its value. The button element can contain other HTML elements and content.
Try putting type="submit"
instead of type="button"
in your button
element (source).
Pay particular attention however to the following from that page:
If you use the button element in an HTML form, different browsers will submit different values. Internet Explorer will submit the text between the
<button>
and</button>
tags, while other browsers will submit the content of the value attribute. Use the input element to create buttons in an HTML form.
I just want to throw this answer in the mix, intended as a reminder that – given the right conditions – you sometimes don't need to overthink the issue at hand. What you want might be achievable with flex: wrap
and max-width
instead of :nth-child
.
ul {
display: flex;
flex-wrap: wrap;
justify-content: center;
max-width: 420px;
list-style-type: none;
background-color: tomato;
margin: 0 auto;
padding: 0;
}
li {
display: inline-block;
background-color: #ccc;
border: 1px solid #333;
width: 23px;
height: 23px;
text-align: center;
font-size: 1rem;
line-height: 1.5;
margin: 0.2rem;
flex-shrink: 0;
}
_x000D_
<div class="root">
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
<li>E</li>
<li>F</li>
<li>G</li>
<li>H</li>
<li>I</li>
<li>J</li>
<li>K</li>
<li>L</li>
<li>M</li>
<li>N</li>
<li>O</li>
<li>P</li>
<li>Q</li>
<li>R</li>
<li>S</li>
<li>T</li>
<li>U</li>
<li>V</li>
<li>W</li>
<li>X</li>
<li>Y</li>
<li>Z</li>
</ul>
</div>
_x000D_
Swift 5: You can create colors in Xcode as explained in the following two images:
You should name the color because you reference the color by the name. As shown in image 2: