check to make the field you are referencing to is an exact match with foreign key, in my case one was unsigned and the other was signed so i just changed them to match and this worked
ALTER TABLE customer_information
ADD CONSTRAINT fk_customer_information1
FOREIGN KEY (user_id
)
REFERENCES users
(id
)
ON DELETE CASCADE
ON UPDATE CASCADE
Error Code: 1005
I had a similar issue, so here are few things that I did try (not in any order, except for the solution :) )
Finally, I saw that I had two editors open. One that in PhpStorm (JetBrains) and the other MySQL workbench. It seems that the PhpStorm / MySQL Workbench creates some kind of edit lock.
I closed PhpStorm just to check if locking was the case (it could have been the other way around). This solved my problem.
Here maybe helpful answer for your problem using Rx Java & Rx Android.
Try using the success()
call back
$http.get('/Documents/DocumentsList/' + caseId).success(function (result) {
$scope.Documents = result;
});
But now since Documents
is an array and not a promise, remove the ()
<li ng-repeat="document in Documents" ng-class="IsFiltered(document.Filtered)"> <span>
<input type="checkbox" name="docChecked" id="doc_{{document.Id}}" ng-model="document.Filtered" />
</span>
<span>{{document.Name}}</span>
</li>
The difference is that the background
shorthand property sets several background-related properties. It sets them all, even if you only specify e.g. a color value, since then the other properties are set to their initial values, e.g. background-image
to none
.
This does not mean that it would always override any other settings for those properties. This depends on the cascade according to the usual, generally misunderstood rules.
In practice, the shorthand tends to be somewhat safer. It is a precaution (not complete, but useful) against accidentally getting some unexpected background properties, such as a background image, from another style sheet. Besides, it’s shorter. But you need to remember that it really means “set all background properties”.
For users that are not members of the sysadmin role on the SQL Server instance you need to do the following actions to grant access to the xp_cmdshell extended stored procedure. In addition if you forgot one of the steps I have listed the error that will be thrown.
Enable the xp_cmdshell procedure
Msg 15281, Level 16, State 1, Procedure xp_cmdshell, Line 1 SQL Server blocked access to procedure 'sys.xp_cmdshell' of component 'xp_cmdshell' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'xp_cmdshell' by using sp_configure. For more information about enabling 'xp_cmdshell', see "Surface Area Configuration" in SQL Server Books Online.*
Create a login for the non-sysadmin user that has public access to the master database
Msg 229, Level 14, State 5, Procedure xp_cmdshell, Line 1 The EXECUTE permission was denied on the object 'xp_cmdshell', database 'mssqlsystemresource', schema 'sys'.*
Grant EXEC permission on the xp_cmdshell stored procedure
Msg 229, Level 14, State 5, Procedure xp_cmdshell, Line 1 The EXECUTE permission was denied on the object 'xp_cmdshell', database 'mssqlsystemresource', schema 'sys'.*
Create a proxy account that xp_cmdshell will be run under using sp_xp_cmdshell_proxy_account
Msg 15153, Level 16, State 1, Procedure xp_cmdshell, Line 1 The xp_cmdshell proxy account information cannot be retrieved or is invalid. Verify that the '##xp_cmdshell_proxy_account##' credential exists and contains valid information.*
It would seem from your error that either step 2 or 3 was missed. I am not familiar with clusters to know if there is anything particular to that setup.
Generate a github oauth token here and export your github token as an environment variable:
export GITHUB_TOKEN=123
Set git config to use the basic auth url:
git config --global url."https://$GITHUB_TOKEN:[email protected]/".insteadOf "https://github.com/"
Now you can go get
your private repo.
Check All with uncheck/check controller if all items is/isnt checked
JS:
e = checkbox id t= checkbox (item) class n= checkbox check all class
function checkAll(e,t,n){jQuery("#"+e).click(function(e){if(this.checked){jQuery("."+t).each(function(){this.checked=true;jQuery("."+n).each(function(){this.checked=true})})}else{jQuery("."+t).each(function(){this.checked=false;jQuery("."+n).each(function(){this.checked=false})})}});jQuery("."+t).click(function(e){var r=jQuery("."+t).length;var i=0;var s=0;jQuery("."+t).each(function(){if(this.checked==true){i++}if(this.checked==false){s++}});if(r==i){jQuery("."+n).each(function(){this.checked=true})}if(i<r){jQuery("."+n).each(function(){this.checked=false})}})}
HTML:
Check ALL controle class : chkall_ctrl
<input type="checkbox"name="chkall" id="chkall_up" class="chkall_ctrl"/>
<br/>
1.<input type="checkbox" value="1" class="chkall" name="chk[]" id="chk1"/><br/>
2.<input type="checkbox" value="2" class="chkall" name="chk[]" id="chk2"/><br/>
3.<input type="checkbox" value="3" class="chkall" name="chk[]" id="chk3"/><br/>
<br/>
<input type="checkbox"name="chkall" id="chkall_down" class="chkall_ctrl"/>
<script>
jQuery(document).ready(function($)
{
checkAll('chkall_up','chkall','chkall_ctrl');
checkAll('chkall_down','chkall','chkall_ctrl');
});
</script>
Above many answers but doesn't work for me some of them no exception handling in correct way. here am adding a perfect solution work amazing for me sure also for you too.
//base64 decode string
String s = "ewoic2VydmVyIjoic2cuenhjLmx1IiwKInNuaSI6InRlc3RpbmciLAoidXNlcm5hbWUiOiJ0ZXN0
ZXIiLAoicGFzc3dvcmQiOiJ0ZXN0ZXIiLAoicG9ydCI6IjQ0MyIKfQ==";
String val = a(s) ;
Toast.makeText(this, ""+val, Toast.LENGTH_SHORT).show();
public static String a(String str) {
try {
return new String(Base64.decode(str, 0), "UTF-8");
} catch (UnsupportedEncodingException | IllegalArgumentException unused) {
return "This is not a base64 data";
}
}
%0|%0
is a fork bomb. It will spawn another process using a pipe |
which runs a copy of the same program asynchronously. This hogs the CPU and memory, slowing down the system to a near-halt (or even crash the system).
%0
refers to the command used to run the current program. For example, script.bat
A pipe |
symbol will make the output or result of the first command sequence as the input for the second command sequence. In the case of a fork bomb, there is no output, so it will simply run the second command sequence without any input.
Expanding the example, %0|%0
could mean script.bat|script.bat
. This runs itself again, but also creating another process to run the same program again (with no input).
You've just answered your own question :) You can do something like this:
$query = $this->db->get();
$ret = $query->row();
return $ret->campaign_id;
You can read more about it here: http://www.codeigniter.com/user_guide/database/results.html
The final
keyword indicates that a variable may only be initialized once. In your code you are only performing one initialization of final so the terms are satisfied. This statement performs the lone initialization of foo
. Note that final
!= immutable, it only means that the reference cannot change.
foo = new ArrayList();
When you declare foo
as static final
the variable must be initialized when the class is loaded and cannot rely on instantiation (aka call to constructor) to initialize foo
since static fields must be available without an instance of a class. There is no guarantee that the constructor will have been called prior to using the static field.
When you execute your method under the static final
scenario the Test
class is loaded prior to instantiating t
at this time there is no instantiation of foo
meaning it has not been initialized so foo
is set to the default for all objects which is null
. At this point I assume your code throws a NullPointerException
when you attempt to add an item to the list.
you can try
$(function()
{
$(window).bind('load', function()
{
// INSERT YOUR CODE THAT WILL BE EXECUTED AFTER THE PAGE COMPLETELY LOADED...
});
});
i had the same problem and this code worked for me. how it works for you too!
XOR is a binary operation, it stands for "exclusive or", that is to say the resulting bit evaluates to one if only exactly one of the bits is set.
This is its function table:
a | b | a ^ b
--|---|------
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 0
This operation is performed between every two corresponding bits of a number.
Example: 7 ^ 10
In binary: 0111 ^ 1010
0111
^ 1010
======
1101 = 13
Properties: The operation is commutative, associative and self-inverse.
It is also the same as addition modulo 2.
listview.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(final AdapterView<?> parent, View view,
final int position, long id) {
// TODO Auto-generated method stub
parent.getChildAt(position).setBackgroundColor(getResources().getColor(R.color.listlongclick_selection));
return false;
}
});
Find if the given number is a power of 2.
#include <math.h>
int main(void)
{
int n,logval,powval;
printf("Enter a number to find whether it is s power of 2\n");
scanf("%d",&n);
logval=log(n)/log(2);
powval=pow(2,logval);
if(powval==n)
printf("The number is a power of 2");
else
printf("The number is not a power of 2");
getch();
return 0;
}
You might want to do this.
input[type=checkbox] {
-ms-transform: scale(2); /* IE */
-moz-transform: scale(2); /* FF */
-webkit-transform: scale(2); /* Safari and Chrome */
-o-transform: scale(2); /* Opera */
padding: 10px;
}
Correct me if I am wrong, but getClass() will be useful when you want to make sure your instance is NOT a subclass of the class you are comparing with. If you use instanceof in that situation you can NOT know that because:
class A { }
class B extends A { }
Object oA = new A();
Object oB = new B();
oA instanceof A => true
oA instanceof B => false
oB instanceof A => true // <================ HERE
oB instanceof B => true
oA.getClass().equals(A.class) => true
oA.getClass().equals(B.class) => false
oB.getClass().equals(A.class) => false // <===============HERE
oB.getClass().equals(B.class) => true
You are asking palindrome in python. palindrome can be performed on strings, numbers and lists. However, I just posted a simple code to check palindrome of a string.
# Palindrome of string
str=raw_input("Enter the string\n")
ln=len(str)
for i in range(ln/2) :
if(str[ln-i-1]!=str[i]):
break
if(i==(ln/2)-1):
print "Palindrome"
else:
print "Not Palindrome"
Two very different types of Pipes Angular - Pipes and RxJS - Pipes
A pipe takes in data as input and transforms it to a desired output. In this page, you'll use pipes to transform a component's birthday property into a human-friendly date.
import { Component } from '@angular/core';
@Component({
selector: 'app-hero-birthday',
template: `<p>The hero's birthday is {{ birthday | date }}</p>`
})
export class HeroBirthdayComponent {
birthday = new Date(1988, 3, 15); // April 15, 1988
}
Observable operators are composed using a pipe method known as Pipeable Operators. Here is an example.
import {Observable, range} from 'rxjs';
import {map, filter} from 'rxjs/operators';
const source$: Observable<number> = range(0, 10);
source$.pipe(
map(x => x * 2),
filter(x => x % 3 === 0)
).subscribe(x => console.log(x));
The output for this in the console would be the following:
0
6
12
18
For any variable holding an observable, we can use the .pipe() method to pass in one or multiple operator functions that can work on and transform each item in the observable collection.
So this example takes each number in the range of 0 to 10, and multiplies it by 2. Then, the filter function to filter the result down to only the odd numbers.
I think that this below is accurate and it may help. Feel free to correct it if you find any errors. I'm new at C.
char str[]
including termination null character '\0'
&str
, &str[0]
and str
, all three represent the same location in memory which is address of the first element of the array str
char *strPtr = &str[0]; //declaration and initialization
alternatively, you can split this in two:
char *strPtr; strPtr = &str[0];
strPtr
is a pointer to a char
strPtr
points at array str
strPtr
is a variable with its own address in memorystrPtr
is a variable that stores value of address &str[0]
strPtr
own address in memory is different from the memory address that it stores (address of array in memory a.k.a &str[0])&strPtr
represents the address of strPtr itselfI think that you could declare a pointer to a pointer as:
char **vPtr = &strPtr;
declares and initializes with address of strPtr pointer
Alternatively you could split in two:
char **vPtr;
*vPtr = &strPtr
*vPtr
points at strPtr pointer*vPtr
is a variable with its own address in memory*vPtr
is a variable that stores value of address &strPtrstr++
, str
address is a const
, but
you can do strPtr++
It means you're passing the variable by reference.
In fact, in a declaration of a type, it means reference, just like:
int x = 42;
int& y = x;
declares a reference to x
, called y
.
Below is the structure of SQL that you may write. You can do multiple joins by using "AND" or "OR".
Select TableA.Col1, TableA.Col2, TableB.Val
FROM TableA,
INNER JOIN TableB
ON TableA.Col1 = TableB.Col1 OR TableA.Col2 = TableB.Col2
scan 0 MATCH * COUNT 1000 // it gets all the keys if return is "0" as first element then count is less than 1000 if more then it will return the pointer as first element and >scan pointer_val MATCH * COUNT 1000 to get the next set of keys it continues till the first value is "0".
According to official documentation https://keras.io/getting-started/faq/#how-can-i-install-hdf5-or-h5py-to-save-my-models-in-keras
you can do :
first test if you have h5py installed by running the
import h5py
if you dont have errors while importing h5py you are good to save:
from keras.models import load_model
model.save('my_model.h5') # creates a HDF5 file 'my_model.h5'
del model # deletes the existing model
# returns a compiled model
# identical to the previous one
model = load_model('my_model.h5')
If you need to install h5py http://docs.h5py.org/en/latest/build.html
Simply run the command:
C:>python .\file_name.py
Assuming the file name is within same folder and Python has already been added to environment variables.
I use $response->getBody()->getContents()
to get JSON from response.
Guzzle version 6.3.0.
I have just experienced this issue in one of my MySQL db's and I looked at the phpMyAdmin answer here. However the best way I fixed it in phpMyAdmin was in the affected table, drop the id column and make a fresh/new id column (adding A-I -autoincrement-). This restored my table id correctly-simples! Hope that helps (no MySQL code needed-I hope to learn to use that but later!) anyone else with this problem.
(1) list[...]<- I had posted this over a decade ago on r-help. Since then it has been added to the gsubfn package. It does not require a special operator but does require that the left hand side be written using list[...]
like this:
library(gsubfn) # need 0.7-0 or later
list[a, b] <- functionReturningTwoValues()
If you only need the first or second component these all work too:
list[a] <- functionReturningTwoValues()
list[a, ] <- functionReturningTwoValues()
list[, b] <- functionReturningTwoValues()
(Of course, if you only needed one value then functionReturningTwoValues()[[1]]
or functionReturningTwoValues()[[2]]
would be sufficient.)
See the cited r-help thread for more examples.
(2) with If the intent is merely to combine the multiple values subsequently and the return values are named then a simple alternative is to use with
:
myfun <- function() list(a = 1, b = 2)
list[a, b] <- myfun()
a + b
# same
with(myfun(), a + b)
(3) attach Another alternative is attach:
attach(myfun())
a + b
ADDED: with
and attach
Like this its work if you want to parse some string which is coming from mYearInDB.toString() =[2013] it will give 2013
Matcher n = MY_PATTERN.matcher("FOO[BAR]"+mYearInDB.toString());
while (n.find()) {
extracredYear = n.group(1);
// s now contains "BAR"
}
System.out.println("Extrated output is : "+extracredYear);
For me, to develop for web, works fine the following:
Image(
image: AssetImage('lib/images/portadaSchamann5.png'),
alignment: Alignment.center,
height: double.infinity,
width: double.infinity,
fit: BoxFit.fill,
),
if you want to be able to convert integer
back to corresponding enum
with selected value see Constants.forValue(...)
in below auto generated code but if not the answer of BlairHippo is best way to do it.
public enum Constants
{
SIGN_CREATE(0),
SIGN_CREATE(1),
HOME_SCREEN(2),
REGISTER_SCREEN(3);
public static final int SIZE = java.lang.Integer.SIZE;
private int intValue;
private static java.util.HashMap<Integer, Constants> mappings;
private static java.util.HashMap<Integer, Constants> getMappings()
{
if (mappings == null)
{
synchronized (Constants.class)
{
if (mappings == null)
{
mappings = new java.util.HashMap<Integer, Constants>();
}
}
}
return mappings;
}
private Constants(int value)
{
intValue = value;
getMappings().put(value, this);
}
public int getValue()
{
return intValue;
}
public static Constants forValue(int value)
{
return getMappings().get(value);
}
}
For straight HTML, with no JavaScript required:
<a href="#something">Add '#something' to URL</a>
Or, to take your question more literally, to just add '#' to the URL:
<a href="#">Add '#' to URL</a>
It depends what you want to do with VIM. It doesn't make sense to learn it only because many people cannot live without it.
When I was working a lot on UNIX environments, I couldn't live without it. Even when VIM was not installed on a UNIX machine, I could at least use vi. You could always count on it -- even if the machine is not yours (that from the customer).
Now I program in C# and mostly work on windows environment. I have installed VIM on my PC ... and I don't need it.
Evaluate if you really need VIM and if it supports you in your "flow of work". Try it out. Play with it. If you think you need it, stick to it ... the learning curve is very steep.
Looks like they were thinking about it for the CSS3 spec but it didn't make the cut.
:contains()
CSS3 selector http://www.w3.org/TR/css3-selectors/#content-selectors
thatLine = thatLine.replace('\n', '<br />')
str.replace() returns a copy of the string, it doesn't modify the string you pass in.
I had the "No module named PyQt4.QtCore" error and installing the python-qt4 package fixed it only partially: I could run
from PyQt4.QtCore import SIGNAL
from a python interpreter but only without activating my virtualenv.
The only solution I've found till now to use a virtualenv is to copy the PyQt4 folder and the sip.so file into my virtualenv as explained here: Is it possible to add PyQt4/PySide packages on a Virtualenv sandbox?
players
is a list which needs to be indexed by integers. You seem to be using it like a dictionary. Maybe you could use unpacking -- Something like:
name, score = player
(if the player
list is always a constant length).
There's not much more advice we can give you without knowing what query
is and how it works.
It's worth pointing out that the entire code you posted doesn't make a whole lot of sense. There's an IndentationError
on the second line. Also, your function is looping over some iterable, but unconditionally returning during the first iteration which isn't usually what you actually want to do.
This should do it:
expect($('[ng-show=saving].icon-spin').isDisplayed()).toBe(true);
Remember protractor's $
isn't jQuery and :visible
is not yet a part of available CSS selectors + pseudo-selectors
More info at https://stackoverflow.com/a/13388700/511069
Python accepts both " and ' as quote marks, so you could do this as:
>>> print '"A word that needs quotation marks"'
"A word that needs quotation marks"
Alternatively, just escape the inner "s
>>> print "\"A word that needs quotation marks\""
"A word that needs quotation marks"
FWIW, I had exactly the same question, but I could not find the answer here. It's probably not portable, but at least for gitolite, I can run the following to get what I want:
$ ssh [email protected] info
hello akim, this is gitolite 2.3-1 (Debian) running on git 1.7.10.4
the gitolite config gives you the following access:
R W android
R W bistro
R W checkpn
...
I'd say the minimum would be to
I've found an interesting way to solve this using only jQuery:
$("#element1").before($("#element2"));
or
$("#element1").after($("#element2"));
:)
Starting Python 3.8
, the standard library provides the NormalDist
object as part of the statistics
module:
from statistics import NormalDist
def confidence_interval(data, confidence=0.95):
dist = NormalDist.from_samples(data)
z = NormalDist().inv_cdf((1 + confidence) / 2.)
h = dist.stdev * z / ((len(data) - 1) ** .5)
return dist.mean - h, dist.mean + h
This:
Creates a NormalDist
object from the data sample (NormalDist.from_samples(data)
, which gives us access to the sample's mean and standard deviation via NormalDist.mean
and NormalDist.stdev
.
Compute the Z-score
based on the standard normal distribution (represented by NormalDist()
) for the given confidence using the inverse of the cumulative distribution function (inv_cdf
).
Produces the confidence interval based on the sample's standard deviation and mean.
This assumes the sample size is big enough (let's say more than ~100 points) in order to use the standard normal distribution rather than the student's t distribution to compute the z
value.
See question: How to find an item in a std::vector?
You'll also need to ensure you've implemented a suitable operator==()
for your object, if the default one isn't sufficient for a "deep" equality test.
I refer few writings.
reference:
This getMemorySize() method is returned MemorySize that has total and free memory size.
I don't believe this code perfectly.
This code is testing on LG G3 cat.6 (v5.0.1)
private MemorySize getMemorySize() {
final Pattern PATTERN = Pattern.compile("([a-zA-Z]+):\\s*(\\d+)");
MemorySize result = new MemorySize();
String line;
try {
RandomAccessFile reader = new RandomAccessFile("/proc/meminfo", "r");
while ((line = reader.readLine()) != null) {
Matcher m = PATTERN.matcher(line);
if (m.find()) {
String name = m.group(1);
String size = m.group(2);
if (name.equalsIgnoreCase("MemTotal")) {
result.total = Long.parseLong(size);
} else if (name.equalsIgnoreCase("MemFree") || name.equalsIgnoreCase("Buffers") ||
name.equalsIgnoreCase("Cached") || name.equalsIgnoreCase("SwapFree")) {
result.free += Long.parseLong(size);
}
}
}
reader.close();
result.total *= 1024;
result.free *= 1024;
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
private static class MemorySize {
public long total = 0;
public long free = 0;
}
I know that Pattern.compile() is expensive cost so You may move its code to class member.
UUID uses java.security.SecureRandom
, which is supposed to be "cryptographically strong". While the actual implementation is not specified and can vary between JVMs (meaning that any concrete statements made are valid only for one specific JVM), it does mandate that the output must pass a statistical random number generator test.
It's always possible for an implementation to contain subtle bugs that ruin all this (see OpenSSH key generation bug) but I don't think there's any concrete reason to worry about Java UUIDs's randomness.
if any(word in 'some one long two phrase three' for word in list_):
You can also cast (n,) to (n,1) by enclosing within brackets [ ].
e.g. Instead of np.append(b,a,axis=0)
use np.append(b,[a],axis=0)
a=[1,2]
b=[[5,6],[7,8]]
np.append(b,[a],axis=0)
returns
array([[5, 6],
[7, 8],
[1, 2]])
Simply use this method.
<?php
$_SESSION['foo'] = 'bar'; // set session
print $_SESSION['foo']; //print it
unset($_SESSION['foo']); //unset session
?>
https://www.w3.org/TR/html5/sec-forms.html#element-attrdef-form-novalidate
You can disable the validation in the form.
I know that my answer is kind of overlapping with some of the other answer, but this is a complete solution that has some advantages. This works on Tomcat 8:
This means that you only have to restart the tomcat once, and after updated war files can be deployed without a problem.
Step 1: In the server.xml file, find the connector entry and replace it with:
<Connector
port="8080"
protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
<Connector
port="80"
protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
Step 2:
Define contexts within the <Host ...>
tag:
<Context path="/" docBase="CAS">
<WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>
<Context path="/ROOT" docBase="ROOT">
<WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>
<Context path="/manager" docBase="manager" privileged="true">
<WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>
<Context path="/host-manager" docBase="host-manager" privileged="true">
<WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>
Note that I addressed all apps in the webapp folder. The first effectively switch the root and the main app from position. ROOT is now on http://example.com/ROOT
and the the main application is on http://example.com/
. The webapps that are password protected require the privileged="true"
attribute.
When you deploy a CAS.war file that matches with the root (<Context path="/" docBase="CAS">
you have to reload that one in the admin panel as it does not refresh with the deployment.
Do not include the <Context path="/CAS" docBase="CAS">
in your contexts as it disables the manager option to deploy war files. This means that you can access the app in two ways: http://example.com/
and http://example.com/APP/
Step 3:
In order to prevent unwanted access to the root and manager folder, add a valve
to those context tags like this:
<Context path="/manager" docBase="manager" privileged="true">
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
addConnectorPort="true"
allow="143\.21\.2\.\d+;8080|127\.0\.0\.1;8080|::1;8080|0:0:0:0:0:0:0:1;8080"/>
</Context>
This essentially limits access to the admin web app folder to people from my own domain (fake IP address) and localhost when they use the default port 8080 and maintains the ability to dynamically deploy the war files through the web interface.
If you want to use this for multiple apps that are using different IP addresses, you can add the IP address to the connector (address="143.21.2.1"
).
If you want to run multiple web apps from the root, you can duplicate the Service tag (use a different name for the second) and change the docbase of the <Context path="/" docBase="CAS">
to for example <Context path="/" docBase="ICR">
.
When the branch is no remote branch you can push your local branch direct to the remote.
git checkout master
git push origin master
or when you have a dev branch
git checkout dev
git push origin dev
or when the remote branch exists
git branch dev -t origin/dev
There are some other posibilites to push a remote branch.
Set the socket non-blocking, and use select()
(which takes a timeout parameter). If a non-blocking socket is trying to connect, then select()
will indicate that the socket is writeable when the connect()
finishes (either successfully or unsuccessfully). You then use getsockopt()
to determine the outcome of the connect()
:
int main(int argc, char **argv) {
u_short port; /* user specified port number */
char *addr; /* will be a pointer to the address */
struct sockaddr_in address; /* the libc network address data structure */
short int sock = -1; /* file descriptor for the network socket */
fd_set fdset;
struct timeval tv;
if (argc != 3) {
fprintf(stderr, "Usage %s <port_num> <address>\n", argv[0]);
return EXIT_FAILURE;
}
port = atoi(argv[1]);
addr = argv[2];
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr(addr); /* assign the address */
address.sin_port = htons(port); /* translate int2port num */
sock = socket(AF_INET, SOCK_STREAM, 0);
fcntl(sock, F_SETFL, O_NONBLOCK);
connect(sock, (struct sockaddr *)&address, sizeof(address));
FD_ZERO(&fdset);
FD_SET(sock, &fdset);
tv.tv_sec = 10; /* 10 second timeout */
tv.tv_usec = 0;
if (select(sock + 1, NULL, &fdset, NULL, &tv) == 1)
{
int so_error;
socklen_t len = sizeof so_error;
getsockopt(sock, SOL_SOCKET, SO_ERROR, &so_error, &len);
if (so_error == 0) {
printf("%s:%d is open\n", addr, port);
}
}
close(sock);
return 0;
}
Found an alternate solution over at DotNetPerls that I liked better because it doesn't require you to specify a path. Here's an example where I populated an array with the help of a custom method
// This custom method takes a path
// and adds all files and folder names to the 'files' array
string[] files = Utilities.FileList("C:\", "");
// Then for each array item...
foreach (string f in files)
{
// Here is the important line I used to ommit .DLL files:
if (!f.EndsWith(".dll", StringComparison.Ordinal))
// then populated a listBox with the array contents
myListBox.Items.Add(f);
}
The same problem error happened to me when I tried to present
a child view controller instead of its UINavigationViewController
parent
with hamcrest:
assertThat(s1, is(s2));
with plain assert:
assertEquals(s1, s2);
NB:t the equals() method of the concrete set class is used
(^\W$)
^ - start of the string, \W - match any non-word character [^a-zA-Z0-9_], $ - end of the string
Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.
This is wrong. It will just kill the session when the associated client (webbrowser) has not accessed the website for more than 15 minutes. The activity certainly counts, exactly as you initially expected, seeing your attempt to solve this.
The HttpSession#setMaxInactiveInterval()
doesn't change much here by the way. It does exactly the same as <session-timeout>
in web.xml
, with the only difference that you can change/set it programmatically during runtime. The change by the way only affects the current session instance, not globally (else it would have been a static
method).
To play around and experience this yourself, try to set <session-timeout>
to 1 minute and create a HttpSessionListener
like follows:
@WebListener
public class HttpSessionChecker implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent event) {
System.out.printf("Session ID %s created at %s%n", event.getSession().getId(), new Date());
}
public void sessionDestroyed(HttpSessionEvent event) {
System.out.printf("Session ID %s destroyed at %s%n", event.getSession().getId(), new Date());
}
}
(if you're not on Servlet 3.0 yet and thus can't use @WebListener
, then register in web.xml
as follows):
<listener>
<listener-class>com.example.HttpSessionChecker</listener-class>
</listener>
Note that the servletcontainer won't immediately destroy sessions after exactly the timeout value. It's a background job which runs at certain intervals (e.g. 5~15 minutes depending on load and the servletcontainer make/type). So don't be surprised when you don't see destroyed
line in the console immediately after exactly one minute of inactivity. However, when you fire a HTTP request on a timed-out-but-not-destroyed-yet session, it will be destroyed immediately.
Just to note that nginx has now support for Websockets on the release 1.3.13. Example of use:
location /websocket/ {
proxy_pass ?http://backend_host;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 86400;
}
You can also check the nginx changelog and the WebSocket proxying documentation.
The globals()
function returns a dictionary containing all your global variables.
>>> apple = 1
>>> banana = 'f'
>>> carrot = 3
>>> globals()
{'carrot': 3, 'apple': 1, '__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'banana': 'f'}
There is also a similar function called locals()
.
I realise this is probably not exactly what you want, but it may provide some insight into how Python provides access to your variables.
Edit: It sounds like your problem may be better solved by simply using a dictionary in the first place:
fruitdict = {}
fruitdict['apple'] = 1
fruitdict['banana'] = 'f'
fruitdict['carrot'] = 3
<form class="form-poll" id="poll-1225962377536" action="/cs/Satellite" target="_blank">
The ID always starts with 'post-' then the numbers are dynamic.
Please check your id names, "poll" and "post" are very different.
As already answered, you can use querySelector:
var selectors = '[id^="poll-"]';
element = document.querySelector(selectors).id;
but querySelector will not find "poll" if you keep querying for "post": '[id^="post-"]'
Currently (June 2016) typing in the link as http://www.example.com will only produce plain text.
You can now however put in an html anchor :
<a href="http://www.example.com">My Example Site</a>
from the command line type:
mvn eclipse:eclipse
this will add all the dependencies you have in your pom.xml into eclipse...
however, if you haven't done any of this before you may need to do one other, one time only step.
Close eclipse, then run the following command from the shell:
mvn -Declipse.workspace=<eclipse workspace> eclipse:add-maven-repo
sample:
mvn -Declipse.workspace=/home/ft/workspaces/wksp1/ eclipse:add-maven-repo
--- Shameless plug ---
I have added this function to a library I created
vanillajs-browser-helpers: https://github.com/Tokimon/vanillajs-browser-helpers/blob/master/inView.js
-------------------------------
Well BenM stated, you need to detect the height of the viewport + the scroll position to match up with your top position. The function you are using is ok and does the job, though its a bit more complex than it needs to be.
If you don't use jQuery
then the script would be something like this:
function posY(elm) {
var test = elm, top = 0;
while(!!test && test.tagName.toLowerCase() !== "body") {
top += test.offsetTop;
test = test.offsetParent;
}
return top;
}
function viewPortHeight() {
var de = document.documentElement;
if(!!window.innerWidth)
{ return window.innerHeight; }
else if( de && !isNaN(de.clientHeight) )
{ return de.clientHeight; }
return 0;
}
function scrollY() {
if( window.pageYOffset ) { return window.pageYOffset; }
return Math.max(document.documentElement.scrollTop, document.body.scrollTop);
}
function checkvisible( elm ) {
var vpH = viewPortHeight(), // Viewport Height
st = scrollY(), // Scroll Top
y = posY(elm);
return (y > (vpH + st));
}
Using jQuery is a lot easier:
function checkVisible( elm, evalType ) {
evalType = evalType || "visible";
var vpH = $(window).height(), // Viewport Height
st = $(window).scrollTop(), // Scroll Top
y = $(elm).offset().top,
elementHeight = $(elm).height();
if (evalType === "visible") return ((y < (vpH + st)) && (y > (st - elementHeight)));
if (evalType === "above") return ((y < (vpH + st)));
}
This even offers a second parameter. With "visible" (or no second parameter) it strictly checks whether an element is on screen. If it is set to "above" it will return true when the element in question is on or above the screen.
See in action: http://jsfiddle.net/RJX5N/2/
I hope this answers your question.
-- IMPROVED VERSION--
This is a lot shorter and should do it as well:
function checkVisible(elm) {
var rect = elm.getBoundingClientRect();
var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
return !(rect.bottom < 0 || rect.top - viewHeight >= 0);
}
with a fiddle to prove it: http://jsfiddle.net/t2L274ty/1/
And a version with threshold
and mode
included:
function checkVisible(elm, threshold, mode) {
threshold = threshold || 0;
mode = mode || 'visible';
var rect = elm.getBoundingClientRect();
var viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight);
var above = rect.bottom - threshold < 0;
var below = rect.top - viewHeight + threshold >= 0;
return mode === 'above' ? above : (mode === 'below' ? below : !above && !below);
}
and with a fiddle to prove it: http://jsfiddle.net/t2L274ty/2/
Path.GetFileName( Request.Url.AbsolutePath )
The job of interpreting the pipe symbol as an instruction to run multiple processes and pipe the output of one process into the input of another process is the responsibility of the shell (/bin/sh or equivalent).
In your example you can either choose to use your top level shell to perform the piping like so:
find -name 'file_*' -follow -type f -exec zcat {} \; | agrep -dEOE 'grep'
In terms of efficiency this results costs one invocation of find, numerous invocations of zcat, and one invocation of agrep.
This would result in only a single agrep process being spawned which would process all the output produced by numerous invocations of zcat.
If you for some reason would like to invoke agrep multiple times, you can do:
find . -name 'file_*' -follow -type f \
-printf "zcat %p | agrep -dEOE 'grep'\n" | sh
This constructs a list of commands using pipes to execute, then sends these to a new shell to actually be executed. (Omitting the final "| sh" is a nice way to debug or perform dry runs of command lines like this.)
In terms of efficiency this results costs one invocation of find, one invocation of sh, numerous invocations of zcat and numerous invocations of agrep.
The most efficient solution in terms of number of command invocations is the suggestion from Paul Tomblin:
find . -name "file_*" -follow -type f -print0 | xargs -0 zcat | agrep -dEOE 'grep'
... which costs one invocation of find, one invocation of xargs, a few invocations of zcat and one invocation of agrep.
Another (maybe faster for large directories) approach:
$ find dir1 | sed 's,^[^/]*/,,' | sort > dir1.txt && find dir2 | sed 's,^[^/]*/,,' | sort > dir2.txt
$ diff dir1.txt dir2.txt
The sed
command removes the first directory component thanks to Erik`s post)
You can completely control the execution of javascript functions (and pass variables between them) using custom jQuery events....I was told that this wasn't possible all over these forums, but I got something working that does exactly that (even using an ajax call).
Here's the answer (IMPORTANT: it's not the checked answer but rather the answer by me "Emile"):
How to get a variable returned across multiple functions - Javascript/jQuery
Just search
open_basedir =
in php.ini and disable it. That's the simplest solution to solve this issue.
Before Changes open_basedir =
After Changes ;open_basedir =
P.s - After changes don't forget to restart your server.
Enjoy ;)
Change these shortcuts in Visual Studio
Tools ? Options ? Environment ? Keyboard
and then change the command
"Edit.FormatDocument" or "Edit.FormatSelection"
assign the same shortcut alt + shift +f
as in visual studio code in order to not remember another one and confuse between each other.
As with everything in git there are multiple ways of doing it. The two commands you used are one way of doing it. Another thing you could have done is simply stash them with git stash -u
. The -u
makes sure that newly added files (untracked) are also included.
The handy thing about git stash -u
is that
git stash pop
(it's like deleting an email in gmail where you can just undo if you change your mind afterwards)As of your other question git reset --hard
won't remove the untracked files so you would still need the git clean -f
. But a git stash -u
might be the most convenient.
Nto sure which RDBMS you are using, but if it is SQL Server you could look at rather using a CASE statement
Evaluates a list of conditions and returns one of multiple possible result expressions.
The CASE expression has two formats:
The simple CASE expression compares an expression to a set of simple expressions to determine the result.
The searched CASE expression evaluates a set of Boolean expressions to determine the result.
Both formats support an optional ELSE argument.
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({`enter code here`
url: "TextFile.txt",
dataType: "text",
success: function (data) {
var text = $('#newCheckText').val();
var str = data;
var str_array = str.split('\n');
for (var i = 0; i < str_array.length; i++) {
// Trim the excess whitespace.
str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
// Add additional code here, such as:
alert(str_array[i]);
$('#checkboxes').append('<input type="checkbox" class="checkBoxClass" /> ' + str_array[i] + '<br />');
}
}
});
$("#ckbCheckAll").click(function () {
$(".checkBoxClass").prop('checked', $(this).prop('checked'));
});
});
</script>
</head>
<body>
<div id="checkboxes">
<input type="checkbox" id="ckbCheckAll" class="checkBoxClass"/> Select All<br />
</div>
</body>
</html>
If you use Microsoft Azure Storage Explorer, there is a "New Folder" button that allows you to create a folder in a container. This is actually a virtual folder:
<div class="overflow-auto p-3 mb-3 mb-md-0 mr-md-3 bg-light" style="max-width: 260px; max-height: 100px;">
<strong>Column 0 </strong><br>
<strong>Column 1</strong><br>
<strong>Column 2</strong><br>
<strong>Column 3</strong><br>
<strong>Column 4</strong><br>
<strong>Column 5</strong><br>
<strong>Column 6</strong><br>
<strong>Column 7</strong><br>
<strong>Column 8</strong><br>
<strong>Column 9</strong><br>
<strong>Column 10</strong><br>
<strong>Column 11</strong><br>
<strong>Column 12</strong><br>
<strong>Column 13</strong><br>
</div>
</div>
Passive event listeners are an emerging web standard, new feature shipped in Chrome 51 that provide a major potential boost to scroll performance. Chrome Release Notes.
It enables developers to opt-in to better scroll performance by eliminating the need for scrolling to block on touch and wheel event listeners.
Problem: All modern browsers have a threaded scrolling feature to permit scrolling to run smoothly even when expensive JavaScript is running, but this optimization is partially defeated by the need to wait for the results of any touchstart
and touchmove
handlers, which may prevent the scroll entirely by calling preventDefault()
on the event.
Solution: {passive: true}
By marking a touch or wheel listener as passive, the developer is promising the handler won't call preventDefault
to disable scrolling. This frees the browser up to respond to scrolling immediately without waiting for JavaScript, thus ensuring a reliably smooth scrolling experience for the user
.
document.addEventListener("touchstart", function(e) {
console.log(e.defaultPrevented); // will be false
e.preventDefault(); // does nothing since the listener is passive
console.log(e.defaultPrevented); // still false
}, Modernizr.passiveeventlisteners ? {passive: true} : false);
As written in PEP8:
Comparisons to singletons like None should always be done with 'is' or 'is not', never the equality operators.
Also, beware of writing "if x" when you really mean "if x is not None" -- e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!
It's the new feature in C# 6 called Interpolated Strings
.
The easiest way to understand it is: an interpolated string expression creates a string by replacing the contained expressions with the ToString representations of the expressions' results.
For more details about this, please take a look at MSDN.
Now, think a little bit more about it. Why this feature is great?
For example, you have class Point
:
public class Point
{
public int X { get; set; }
public int Y { get; set; }
}
Create 2 instances:
var p1 = new Point { X = 5, Y = 10 };
var p2 = new Point { X = 7, Y = 3 };
Now, you want to output it to the screen. The 2 ways that you usually use:
Console.WriteLine("The area of interest is bounded by (" + p1.X + "," + p1.Y + ") and (" + p2.X + "," + p2.Y + ")");
As you can see, concatenating string like this makes the code hard to read and error-prone. You may use string.Format()
to make it nicer:
Console.WriteLine(string.Format("The area of interest is bounded by({0},{1}) and ({2},{3})", p1.X, p1.Y, p2.X, p2.Y));
This creates a new problem:
For those reasons, we should use new feature:
Console.WriteLine($"The area of interest is bounded by ({p1.X},{p1.Y}) and ({p2.X},{p2.Y})");
The compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.
For the full post, please read this blog.
You can use the ternary operator easily:
{{ $usersType ? $usersType : '' }}
Correct ways in jQuery are -
$('#test').prop('scrollHeight')
OR$('#test')[0].scrollHeight
OR$('#test').get(0).scrollHeight
I use SQLYog at home and work. It turns out they DO have a free open-source version, though sadly they've been trying to hide that fact for the last few years.
You can download the open-source version from https://github.com/webyog/sqlyog-community - just click the "Download SQLyog Community Version" link.
From JDK 7 you can use Files.readAllBytes(Path)
.
Example:
import java.io.File;
import java.nio.file.Files;
File file;
// ...(file is initialised)...
byte[] fileContent = Files.readAllBytes(file.toPath());
css files do not support conditional statements.
If you want something to look one of two ways, depending on some condition, give it a suitable class using your server side scripting language or javascript. eg
<div class="oh-yes"></div>
<div class="hell-no"></div>
One way to resolve this would be to first add your user to the docker
group by running the following
sudo usermod -aG docker $USER
IMPORTANT: Remember to log out of your system (not just your terminal) and back in for this to take effect!
Here is how to kill one or more process from a .bat file.
Step 1. Open a preferred text editor and create a new file.
step 2. To kill one process use the 'taskkill' command, with the '/im' parameter that specifies the image name of the process to be terminated. Example:
taskkill /im examplename.exe
To 'force' kill a process use the '/f' parameter which specifies that processes be forcefully terminated. Example:
taskkill /f /im somecorporateprocess.exe
To kill more than one process you rinse and repeat the first part of step 2. Example:
taskkill /im examplename.exe
taskkill /im examplename1.exe
taskkill /im examplename2.exe
or
taskkill /f /im examplename.exe
taskkill /f /im examplename1.exe
taskkill /f /im examplename2.exe
step 3. Save your file to desired location with the .bat extension.
step 4. click newly created bat file to run it.
Funnily enough, adjusting the padding seems to do it.
.arrow {
border: solid rgb(2, 0, 0);
border-width: 0 3px 3px 0;
display: inline-block;
}
.first{
padding: 2vh;
}
.second{
padding: 4vh;
}
.left {
transform: rotate(135deg);
-webkit-transform: rotate(135deg);
}
_x000D_
<i class="arrow first left"></i>
<i class="arrow second left"></i>
_x000D_
/*Maximum value that can be entered is 2,147,483,647
* Program to convert entered number into string
* */
import java.util.Scanner;
public class NumberToWords
{
public static void main(String[] args)
{
double num;//for taking input number
Scanner obj=new Scanner(System.in);
do
{
System.out.println("\n\nEnter the Number (Maximum value that can be entered is 2,147,483,647)");
num=obj.nextDouble();
if(num<=2147483647)//checking if entered number exceeds maximum integer value
{
int number=(int)num;//type casting double number to integer number
splitNumber(number);//calling splitNumber-it will split complete number in pairs of 3 digits
}
else
System.out.println("Enter smaller value");//asking user to enter a smaller value compared to 2,147,483,647
}while(num>2147483647);
}
//function to split complete number into pair of 3 digits each
public static void splitNumber(int number)
{ //splitNumber array-contains the numbers in pair of 3 digits
int splitNumber[]=new int[4],temp=number,i=0,index;
//splitting number into pair of 3
if(temp==0)
System.out.println("zero");
while(temp!=0)
{
splitNumber[i++]=temp%1000;
temp/=1000;
}
//passing each pair of 3 digits to another function
for(int j=i-1;j>-1;j--)
{ //toWords function will split pair of 3 digits to separate digits
if(splitNumber[j]!=0)
{toWords(splitNumber[j]);
if(j==3)//if the number contained more than 9 digits
System.out.print("billion,");
else if(j==2)//if the number contained more than 6 digits & less than 10 digits
System.out.print("million,");
else if(j==1)
System.out.print("thousand,");//if the number contained more than 3 digits & less than 7 digits
}
}
}
//function that splits number into individual digits
public static void toWords(int number)
//splitSmallNumber array contains individual digits of number passed to this function
{ int splitSmallNumber[]=new int[3],i=0,j;
int temp=number;//making temporary copy of the number
//logic to split number into its constituent digits
while(temp!=0)
{
splitSmallNumber[i++]=temp%10;
temp/=10;
}
//printing words for each digit
for(j=i-1;j>-1;j--)
//{ if the digit is greater than zero
if(splitSmallNumber[j]>=0)
//if the digit is at 3rd place or if digit is at (1st place with digit at 2nd place not equal to zero)
{ if(j==2||(j==0 && (splitSmallNumber[1]!=1)))
{
switch(splitSmallNumber[j])
{
case 1:System.out.print("one ");break;
case 2:System.out.print("two ");break;
case 3:System.out.print("three ");break;
case 4:System.out.print("four ");break;
case 5:System.out.print("five ");break;
case 6:System.out.print("six ");break;
case 7:System.out.print("seven ");break;
case 8:System.out.print("eight ");break;
case 9:System.out.print("nine ");break;
}
}
//if digit is at 2nd place
if(j==1)
{ //if digit at 2nd place is 0 or 1
if(((splitSmallNumber[j]==0)||(splitSmallNumber[j]==1))&& splitSmallNumber[2]!=0 )
System.out.print("hundred ");
switch(splitSmallNumber[1])
{ case 1://if digit at 2nd place is 1 example-213
switch(splitSmallNumber[0])
{
case 1:System.out.print("eleven ");break;
case 2:System.out.print("twelve ");break;
case 3:System.out.print("thirteen ");break;
case 4:System.out.print("fourteen ");break;
case 5:System.out.print("fifteen ");break;
case 6:System.out.print("sixteen ");break;
case 7:System.out.print("seventeen ");break;
case 8:System.out.print("eighteen ");break;
case 9:System.out.print("nineteen ");break;
case 0:System.out.print("ten ");break;
}break;
//if digit at 2nd place is not 1
case 2:System.out.print("twenty ");break;
case 3:System.out.print("thirty ");break;
case 4:System.out.print("forty ");break;
case 5:System.out.print("fifty ");break;
case 6:System.out.print("sixty ");break;
case 7:System.out.print("seventy ");break;
case 8:System.out.print("eighty ");break;
case 9:System.out.print("ninety ");break;
//case 0: System.out.println("hundred ");break;
}
}
}
}
}
I used PathFindExtension() function to know whether it is a valid tif file or not.
#include <Shlwapi.h>
bool A2iAWrapperUtility::isValidImageFile(string imageFile)
{
char * pStrExtension = ::PathFindExtension(imageFile.c_str());
if (pStrExtension != NULL && strcmp(pStrExtension, ".tif") == 0)
{
return true;
}
return false;
}
If you're more into gaming you can use PyGame for GUIs.
@Michiel is correct to create a button but the code for ActionScript 3 it is a little different - where movieClipName is the name of your 'button'.
movieClipName.addEventListener(MouseEvent.CLICK, callLink);
function callLink:void {
var url:String = "http://site";
var request:URLRequest = new URLRequest(url);
try {
navigateToURL(request, '_blank');
} catch (e:Error) {
trace("Error occurred!");
}
}
source: http://scriptplayground.com/tutorials/as/getURL-in-Actionscript-3/
lepe - That works great for me thanks! I put your code in a plugin file, then used it in conjunction with an each statement so you can have multiple pre tags and multiple "Select all" links on one page and it picks out the correct pre to highlight:
<script type="text/javascript" src="../js/jquery.selecttext.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".selectText").each(function(indx) {
$(this).click(function() {
$('pre').eq(indx).selText().addClass("selected");
return false;
});
});
});
This process is simple, and follows the same flow as any git commit.
git pull
) git commit -m "nuke and start again"
git push
Here's some code I wrote after using the above posts. Thanks for all your help.
This code accepts a list of file paths and creates a zip file out of them.
public class Zip
{
private string _filePath;
public string FilePath { get { return _filePath; } }
/// <summary>
/// Zips a set of files
/// </summary>
/// <param name="filesToZip">A list of filepaths</param>
/// <param name="sZipFileName">The file name of the new zip (do not include the file extension, nor the full path - just the name)</param>
/// <param name="deleteExistingZip">Whether you want to delete the existing zip file</param>
/// <remarks>
/// Limitation - all files must be in the same location.
/// Limitation - must have read/write/edit access to folder where first file is located.
/// Will throw exception if the zip file already exists and you do not specify deleteExistingZip
/// </remarks>
public Zip(List<string> filesToZip, string sZipFileName, bool deleteExistingZip = true)
{
if (filesToZip.Count > 0)
{
if (File.Exists(filesToZip[0]))
{
// Get the first file in the list so we can get the root directory
string strRootDirectory = Path.GetDirectoryName(filesToZip[0]);
// Set up a temporary directory to save the files to (that we will eventually zip up)
DirectoryInfo dirTemp = Directory.CreateDirectory(strRootDirectory + "/" + DateTime.Now.ToString("yyyyMMddhhmmss"));
// Copy all files to the temporary directory
foreach (string strFilePath in filesToZip)
{
if (!File.Exists(strFilePath))
{
throw new Exception(string.Format("File {0} does not exist", strFilePath));
}
string strDestinationFilePath = Path.Combine(dirTemp.FullName, Path.GetFileName(strFilePath));
File.Copy(strFilePath, strDestinationFilePath);
}
// Create the zip file using the temporary directory
if (!sZipFileName.EndsWith(".zip")) { sZipFileName += ".zip"; }
string strZipPath = Path.Combine(strRootDirectory, sZipFileName);
if (deleteExistingZip == true && File.Exists(strZipPath)) { File.Delete(strZipPath); }
ZipFile.CreateFromDirectory(dirTemp.FullName, strZipPath, CompressionLevel.Fastest, false);
// Delete the temporary directory
dirTemp.Delete(true);
_filePath = strZipPath;
}
else
{
throw new Exception(string.Format("File {0} does not exist", filesToZip[0]));
}
}
else
{
throw new Exception("You must specify at least one file to zip.");
}
}
}
Use for...in
loop:
for (var key in obj) {
console.log(' name=' + key + ' value=' + obj[key]);
// do some more stuff with obj[key]
}
According to MSDN, the JavaScript Date object does not provide any specific date formatting methods (as you may see with other programming languages). However, you can use a few of the Date
methods and formatting to accomplish your goal:
function dateToString (date) {
// Use an array to format the month numbers
var months = [
"January",
"February",
"March",
...
];
// Use an object to format the timezone identifiers
var timeZones = {
"360": "EST",
...
};
var month = months[date.getMonth()];
var day = date.getDate();
var year = date.getFullYear();
var hours = date.getHours();
var minutes = date.getMinutes();
var time = (hours > 11 ? (hours - 11) : (hours + 1)) + ":" + minutes + (hours > 11 ? "PM" : "AM");
var timezone = timeZones[date.getTimezoneOffset()];
// Returns formatted date as string (e.g. January 28, 2011 - 7:30PM EST)
return month + " " + day + ", " + year + " - " + time + " " + timezone;
}
var date = new Date("2011-01-28T19:30:00-05:00");
alert(dateToString(date));
You could even take it one step further and override the Date.toString()
method:
function dateToString () { // No date argument this time
// Use an array to format the month numbers
var months = [
"January",
"February",
"March",
...
];
// Use an object to format the timezone identifiers
var timeZones = {
"360": "EST",
...
};
var month = months[*this*.getMonth()];
var day = *this*.getDate();
var year = *this*.getFullYear();
var hours = *this*.getHours();
var minutes = *this*.getMinutes();
var time = (hours > 11 ? (hours - 11) : (hours + 1)) + ":" + minutes + (hours > 11 ? "PM" : "AM");
var timezone = timeZones[*this*.getTimezoneOffset()];
// Returns formatted date as string (e.g. January 28, 2011 - 7:30PM EST)
return month + " " + day + ", " + year + " - " + time + " " + timezone;
}
var date = new Date("2011-01-28T19:30:00-05:00");
Date.prototype.toString = dateToString;
alert(date.toString());
First check to see if it can be cast.
if (readData is T) {
return (T)readData;
}
try {
return (T)Convert.ChangeType(readData, typeof(T));
}
catch (InvalidCastException) {
return default(T);
}
list = new List<ProcedureTime>(); sortedList = list.OrderByDescending(ProcedureTime=> ProcedureTime.EndTime).ToList();
Which works for me to show the time sorted in descending order.
try this : worked for me
rm -rf .git
You can use mv
instead of rm
if you don't want to loose your stashed commits
then copy .git from other clone
cp <pathofotherrepository>/.git . -r
then do
git init
this should solve your problem , ALL THE BEST
Suppose you want to write that in the same file, you can do as follows:
Set-Content -Path "C:\temp\Newtext.txt" -Value (get-content -Path "c:\Temp\Newtext.txt" | Select-String -Pattern 'H\|159' -NotMatch)
train_test_split
is part of the module sklearn.model_selection
, hence, you may need to import the module from model_selection
Code:
from sklearn.model_selection import train_test_split
While exporting your source into a jar, make sure you select runnable jar option from the options. Then select if you want to package all the dependency jars or just include them directly in the jar file. It depends on the project that you are working on.
You then run the jar directly by java -jar example.jar.
CREATE DEFINER=`yourfunctionname`@`%` FUNCTION `money`(
`betrag` DECIMAL(10,2)
)
RETURNS varchar(128) CHARSET latin1
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
return(
select replace(format(cast(betrag as char),2),',',"'") as betrag
)
will creating a MySql-Function with this Code:
select replace(format(cast(amount as char),2),',',"'") as amount_formated
Cmake from Windows terminal:
mkdir build
cd build/
cmake ..
cmake --build . --config Release
./Release/main.exe
Here's a command I think could be of some help :
apachectl -t -D DUMP_VHOSTS
You'll get a list of all the vhosts, you'll know which one is the default one and you'll make sure that your syntax is correct (same as apachectl configtest suggested by yojimbo87).
You'll also know where each vhost is declared. It can be handy if your config files are a mess. ;)
The +
operator returns the numeric representation of the object. So in your particular case, it would appear to be predicating the if on whether or not d
is a non-zero number.
Thanks for this post. I got this worked for using mustache templates in my asp.net mvc project I used the following, and it worked for me.
<system.webServer>
<staticContent>
<mimeMap fileExtension=".mustache" mimeType="text/html"/>
</staticContent>
</system.WebServer>
You want to look at the patch() function, and sneak in points for the start and end of the horizontal line:
x = 0:.1:2*pi;
y = sin(x)+rand(size(x))/2;
x2 = [0 x 2*pi];
y2 = [.1 y .1];
patch(x2, y2, [.8 .8 .1]);
If you only want the filled in area for a part of the data, you'll need to truncate the x and y vectors to only include the points you need.
Its only possible to get the WSDL if the webservice is configured to deliver it. Therefor you have to specify a serviceBehavior and enable httpGetEnabled:
<serviceBehaviors>
<behavior name="BindingBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
In case the webservice is only accessible via https you have to enable httpsGetEnabled instead of httpGetEnabled.
If you have Powershell remoting and CredSSP setup then you can update your code to the following:
$Session = New-PSSession -ComputerName $Computer1 -Authentication CredSSP
$NetbackupVersion1 = Invoke-Command -Session $Session -ScriptBlock { $(Get-ItemProperty hklm:\SOFTWARE\Veritas\NetBackup\CurrentVersion).PackageVersion}
Remove-PSSession $Session
Every time someone mentions SOAP/WSDL, I think of objects and classes defined in xml...
"You use SOAP just the same way that you would any PHP class. However, in this case the class does not exist in the local applications file system, but at a remote site accessed over http." ... "If we think of using a SOAP service as just another PHP class then the WSDL document is a list of all the available class methods and properties. "
..and whenever someone talks about REST I think of HTTP's commands (request methods) like POST, GET and DELETE
Easiest solution is to create the column using the correct data type: DATE
For example:
Create table:
create table test_date (mydate date);
Insert row:
insert into test_date values (to_date('01-01-2011','dd-mm-yyyy'));
To get the month and year, do as follows:
select to_char(mydate, 'MM-YYYY') from test_date;
Your result will be as follows: 01-2011
Another cool function to use is "EXTRACT"
select extract(year from mydate) from test_date;
This will return: 2011
If your CSS is constructed completely around ex
or em
units, then this might be possible and feasible. You'd just need to declare font-size: 150%
in your style for body
or html
. This should cause every other lengths to scale proportionally. You can't scale images this way, though, unless they get a style too.
But that's a very big if on most sites, anyway.
I'm adding a code snippet which shows on how to post a file to an API which has been exposed over DELETE http verb. This is not a common case to upload a file with DELETE http verb but it is allowed. I've assumed Windows NTLM authentication for authorizing the call.
The problem that one might face is that all the overloads of HttpClient.DeleteAsync
method have no parameters for HttpContent
the way we get it in PostAsync
method
var requestUri = new Uri("http://UrlOfTheApi");
using (var streamToPost = new MemoryStream("C:\temp.txt"))
using (var fileStreamContent = new StreamContent(streamToPost))
using (var httpClientHandler = new HttpClientHandler() { UseDefaultCredentials = true })
using (var httpClient = new HttpClient(httpClientHandler, true))
using (var requestMessage = new HttpRequestMessage(HttpMethod.Delete, requestUri))
using (var formDataContent = new MultipartFormDataContent())
{
formDataContent.Add(fileStreamContent, "myFile", "temp.txt");
requestMessage.Content = formDataContent;
var response = httpClient.SendAsync(requestMessage).GetAwaiter().GetResult();
if (response.IsSuccessStatusCode)
{
// File upload was successfull
}
else
{
var erroResult = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
throw new Exception("Error on the server : " + erroResult);
}
}
You need below namespaces at the top of your C# file:
using System;
using System.Net;
using System.IO;
using System.Net.Http;
P.S. Sorry about so many using blocks(IDisposable pattern) in my code. Unfortunately, the syntax of using construct of C# doesn't support initializing multiple variables in single statement.
A lot of answers already; wanted to jump on with a bit more.
docs:
For has_many, destroy and destroy_all will always call the destroy method of the record(s) being removed so that callbacks are run. However delete and delete_all will either do the deletion according to the strategy specified by the :dependent option, or if no :dependent option is given, then it will follow the default strategy. The default strategy is to do nothing (leave the foreign keys with the parent ids set), except for has_many :through, where the default strategy is delete_all (delete the join records, without running their callbacks).
The delete
verbage works differently for ActiveRecord::Association.has_many
and ActiveRecord::Base
. For the latter, delete will execute SQL DELETE
and bypass all validations/callbacks. The former will be executed based on the :dependent
option passed into the association. However, during testing, I found the following side effect where callbacks were only ran for delete
and not delete_all
dependent: :destroy
Example:
class Parent < ApplicationRecord
has_many :children,
before_remove: -> (_) { puts "before_remove callback" },
dependent: :destroy
end
class Child < ApplicationRecord
belongs_to :parent
before_destroy -> { puts "before_destroy callback" }
end
> child.delete # Ran without callbacks
Child Destroy (99.6ms) DELETE FROM "children" WHERE "children"."id" = $1 [["id", 21]]
> parent.children.delete(other_child) # Ran with callbacks
before_remove callback
before_destroy callback
Child Destroy (0.4ms) DELETE FROM "children" WHERE "children"."id" = $1 [["id", 22]]
> parent.children.delete_all # Ran without callbacks
Child Destroy (1.0ms) DELETE FROM "children" WHERE "children"."parent_id" = $1 [["parent_id", 1]]
The limitation of execl is that when executing a shell command or any other script that is not in the current working directory, then we have to pass the full path of the command or the script. Example:
execl("/bin/ls", "ls", "-la", NULL);
The workaround to passing the full path of the executable is to use the function execlp, that searches for the file (1st argument of execlp) in those directories pointed by PATH:
execlp("ls", "ls", "-la", NULL);
I had a hard time solving this issue. If none of the above work you can try this instead. I am using the create-react-app
Requirements
react-router-dom": "^4.3.1"
Solution
At the location where router is specified
<Route path="some/path" ..../>
Add the parameter name that you would want to pass in like this
<Route path="some/path/:id" .../>
At the page where you are rendering some/path you can specify this to view the parameter name call id like this
componentDidMount(){
console.log(this.props);
console.log(this.props.match.params.id);
}
At the end where you export default
export default withRouter(Component);
Remember to include import
import { withRouter } from 'react-router-dom'
When console.log(this.props) you would be able what has been passed down. Have fun!
You want to join on condition 1 AND condition 2, so simply use the AND keyword as below
ON a.userid = b.sourceid AND a.listid = b.destinationid;
copy the column paste it into notepad copy it again paste special as Text
It works correctly...
C:\>mysql>bin>mysql -u USERNAME DB_NAME < tableNameFile.sql
please note .sql file specified your current database..
Old question but still relevant. I've generated a dictionary that gets the appropriate datetime format for each region, here is the helper class I generated:
https://github.com/anakic/ExcelDateTimeFormatHelper/blob/master/FormatHelper.cs
FWIW this is how I went about it:
Yes.
var data = {_x000D_
'PropertyA': 1,_x000D_
'PropertyB': 2,_x000D_
'PropertyC': 3_x000D_
};_x000D_
_x000D_
data["PropertyD"] = 4;_x000D_
_x000D_
// dialog box with 4 in it_x000D_
alert(data.PropertyD);_x000D_
alert(data["PropertyD"]);
_x000D_
As of Gradle 2.4, you can use gradle wrapper --gradle-version X.X
to configure a specific version of the Gradle wrapper, without adding any tasks to your build.gradle
file. The next time you use the wrapper, it will download the appropriate Gradle distribution to match.
Ookii folder dialog can be found at Nuget.
PM> Install-Package Ookii.Dialogs.Wpf
And, example code is as below.
var dialog = new Ookii.Dialogs.Wpf.VistaFolderBrowserDialog();
if (dialog.ShowDialog(this).GetValueOrDefault())
{
textBoxFolderPath.Text = dialog.SelectedPath;
}
More information on how to use it: https://github.com/augustoproiete/ookii-dialogs-wpf
If you're talking about ASP.NET MVC then you should have a controller method that returns the following:
return Redirect("http://www.google.com");
Otherwise we need more info on the error you're getting in the redirect. I'd step through to make sure the url isn't empty.
You can use this for your purpose.
In parent form:
private void addCustomerToolStripMenuItem_Click(object sender, EventArgs e)
{
CustomerPage f = new CustomerPage();
f.LoadType = 1;
f.MdiParent = this;
f.Show();
f.Focus();
}
In child form:
public int LoadType{get;set;}
private void CustomerPage_Load(object sender, EventArgs e)
{
if (LoadType == 1)
{
this.button1.Visible = false;
}
}
Just use special `
var lyrics = 'Never gonna give you up';
var html = `<div>${lyrics}</div>`;
You can see more examples here.
I solve this problem with this code in NugetPackageConsole.and it works.The problem was in the version. i thikn it will help others.
In VS 2017, i have checked SQL Server Data Tools during the installation and it doesn't help. So I have downloaded and installed Microsoft.RdlcDesigner.vsix
Now it works.
UPDATE
Another way is to use Extensions and Updates.
Go to Tools > Extensions and Updates choose Online then search for Microsoft Rdlc Report Designer for Visual studio and click Download. It need to close VS to start installation. After installation you will be able to use rdlc designer.
Hope this helps!
You can use Pandas DataFrame to achieve this, with the following Example:
import pandas as pd
csv_file = pd.DataFrame(pd.read_csv("path/to/file.csv", sep = ",", header = 0, index_col = False))
csv_file.to_json("/path/to/new/file.json", orient = "records", date_format = "epoch", double_precision = 10, force_ascii = True, date_unit = "ms", default_handler = None)
If you want to automatically/periodically clean up exited containers and remove images and volumes that aren't in use by a running container you can download the Docker image meltwater/docker-cleanup
.
That way you don't need to go clean it up by hand.
Just run:
docker run -d -v /var/run/docker.sock:/var/run/docker.sock:rw -v /var/lib/docker:/var/lib/docker:rw --restart=unless-stopped meltwater/docker-cleanup:latest
It will run every 30 minutes (or however long you set it using DELAY_TIME=1800 option) and clean up exited containers and images.
More details: https://github.com/meltwater/docker-cleanup/blob/master/README.md
When you use setcookie
, you can either set the expiration time to 0
or simply omit the parametre - the cookie will then expire at the end of session (ie, when you close the browser).
I ran into this problem today and none of the solutions posted here worked. However, the code posted here worked for a POST request:
// HTTP POST request
private void sendPost() throws Exception {
String url = "https://selfsolve.apple.com/wcResults.do";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
It turns out that it's not the authorization that's the problem. In my case, it was an encoding problem. The content-type I needed was application/json but from the Java documentation:
static String encode(String s, String enc)
Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme.
The encode function translates the string into application/x-www-form-urlencoded.
Now if you don't set a Content-Type, you may get a 415 Unsupported Media Type error. If you set it to application/json or anything that's not application/x-www-form-urlencoded, you get an IOException. To solve this, simply avoid the encode method.
For this particular scenario, the following should work:
String data = "product[title]=" + title +
"&product[content]=" + content +
"&product[price]=" + price.toString() +
"&tags=" + tags;
Another small piece of information that might be helpful as to why the code breaks when creating the buffered reader is because the POST request actually only gets executed when conn.getInputStream() is called.
Are you always going to prepend a backslash? If so, try
import re
rx = re.compile('([&#])')
# ^^ fill in the characters here.
strs = rx.sub('\\\\\\1', strs)
It may not be the most efficient method but I think it is the easiest.
$ENV{FOO}
for usage, where FOO
is being picked up from the environment variable. otherwise use as ${FOO}
, where FOO
is some other variable. For setting, SET(FOO "foo")
would be used in CMake.
The problem is because you haven't set JDK version properly.You should use jdk 7 for major number 51. Like this:
JAVA_HOME=/usr/java/jdk1.7.0_79
kwargs is just a dictionary that is added to the parameters.
A dictionary can contain key, value pairs. And that are the kwargs. Ok, this is how.
The what for is not so simple.
For example (very hypothetical) you have an interface that just calls other routines to do the job:
def myDo(what, where, why):
if what == 'swim':
doSwim(where, why)
elif what == 'walk':
doWalk(where, why)
...
Now you get a new method "drive":
elif what == 'drive':
doDrive(where, why, vehicle)
But wait a minute, there is a new parameter "vehicle" -- you did not know it before. Now you must add it to the signature of the myDo-function.
Here you can throw kwargs into play -- you just add kwargs to the signature:
def myDo(what, where, why, **kwargs):
if what == 'drive':
doDrive(where, why, **kwargs)
elif what == 'swim':
doSwim(where, why, **kwargs)
This way you don't need to change the signature of your interface function every time some of your called routines might change.
This is just one nice example you could find kwargs helpful.
Maybe you can use WebView, but as you can see in the doc WebView doesn't support javascript and other stuff like widgets by default.
http://developer.android.com/reference/android/webkit/WebView.html
I think that you can enable javascript if you need it.
You may not have permission to dba_sequences. So you can always just do:
select * from user_sequences;
I think in your Angular-2 version directives are not supported in Component decorator, hence you have to register directive same as other component in @NgModule and then import in component as below and also remove directives: [ChildComponent]
from decorator.
import {myDirective} from './myDirective';
I had a similar problem when migrating an old database to a new version.
Switch the MySQL mode to not use STRICT.
SET @@global.sql_mode= 'NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
FXCop typically prefers OrdinalIgnoreCase
. But your requirements may vary.
For English there is very little difference. It is when you wander into languages that have different written language constructs that this becomes an issue. I am not experienced enough to give you more than that.
OrdinalIgnoreCase
The StringComparer returned by the OrdinalIgnoreCase property treats the characters in the strings to compare as if they were converted to uppercase using the conventions of the invariant culture, and then performs a simple byte comparison that is independent of language. This is most appropriate when comparing strings that are generated programmatically or when comparing case-insensitive resources such as paths and filenames. http://msdn.microsoft.com/en-us/library/system.stringcomparer.ordinalignorecase.aspx
InvariantCultureIgnoreCase
The StringComparer returned by the InvariantCultureIgnoreCase property compares strings in a linguistically relevant manner that ignores case, but it is not suitable for display in any particular culture. Its major application is to order strings in a way that will be identical across cultures. http://msdn.microsoft.com/en-us/library/system.stringcomparer.invariantcultureignorecase.aspx
The invariant culture is the CultureInfo object returned by the InvariantCulture property.
The InvariantCultureIgnoreCase property actually returns an instance of an anonymous class derived from the StringComparer class.
There is an appropriate index on column_having_index, and its use actually increase performance, but Oracle didn't use it...
You should gather statistics on your table to let optimizer see that index access can help. Using direct hint is not a good practice.
In addition to previous answers, in case of you need to validate a JSON format like "{}", you can use the following code:
const validateJSON = (str) => {
try {
const json = JSON.parse(str);
if (Object.prototype.toString.call(json).slice(8,-1) !== 'Object') {
return false;
}
} catch (e) {
return false;
}
return true;
}
Examples of usage:
validateJSON('{}')
true
validateJSON('[]')
false
validateJSON('')
false
validateJSON('2134')
false
validateJSON('{ "Id": 1, "Name": "Coke" }')
true
You need to declare disconnectFunc as a function pointer, not a void pointer. You also need to call it as a function (with parentheses), and no "*" is needed.
One use case is to make an ajax
call before the user closes the window or leaves the page. This would be like deleting some temporary records in the database before the user can navigate to another site or closes the browser.
$(window).unload(
function(){
$.ajax({
url: 'your url',
global: false,
type: 'POST',
data: {},
async: false, //blocks window close
success: function() {}
});
});
Use docstrings.
This is the built-in suggested convention in PyCharm for describing function using docstring comments:
def test_function(p1, p2, p3):
"""
test_function does blah blah blah.
:param p1: describe about parameter p1
:param p2: describe about parameter p2
:param p3: describe about parameter p3
:return: describe what it returns
"""
pass
As the error message indicates, you have an indentation error. It is probably caused by a mix of tabs and spaces.
The table normally contains multiple rows. Use a loop and use row.Field<string>(0)
to access the value of each row.
foreach(DataRow row in dt.Rows)
{
string file = row.Field<string>("File");
}
You can also access it via index:
foreach(DataRow row in dt.Rows)
{
string file = row.Field<string>(0);
}
If you expect only one row, you can also use the indexer of DataRowCollection
:
string file = dt.Rows[0].Field<string>(0);
Since this fails if the table is empty, use dt.Rows.Count
to check if there is a row:
if(dt.Rows.Count > 0)
file = dt.Rows[0].Field<string>(0);
Well in JavaScript you can check two strings for values same as integers so yo can do this:
"A" < "B"
"A" == "B"
"A" > "B"
And therefore you can make your own function that checks strings the same way as the strcmp()
.
So this would be the function that does the same:
function strcmp(a, b)
{
return (a<b?-1:(a>b?1:0));
}
My issue was having multiple AWS credentials; default and dev. Since I was trying to deploy to dev this worked:
$(aws ecr get-login --no-include-email --region eu-west-1 --profile dev | sed 's|https://||')
Suppose you run your program thus (using sh
syntax):
myprog arg1 arg2 'arg 3'
If you declared your main as int main(int argc, char *argv[])
, then (in most environments), your main()
will be called as if like:
p = { "myprog", "arg1", "arg2", "arg 3", NULL };
exit(main(4, p));
However, if you declared your main as int main()
, it will be called something like
exit(main());
and you don't get the arguments passed.
Two additional things to note:
main
. If a particular platform accepts extra arguments or a different return type, then that's an extension and should not be relied upon in a portable program.*argv[]
and **argv
are exactly equivalent, so you can write int main(int argc, char *argv[])
as int main(int argc, char **argv)
.I had the same problem, current update, but rendering failed because I need to update.
Try changing the update version you are on. The default is Stable, but there are 3 more options, Canary being the newest and potentially least stable. I chose to check for updates from the Dev Channel, which is a little more stable than Canary build. It fixed the problem and seems to work fine.
To change the version, Check for Updates, then click the Updates link on the popup that says you already have the latest version.
You can also use awk
for these purposes, since it allows you to perform more complex checks in a clearer way:
Lines not containing foo
:
awk '!/foo/'
Lines containing neither foo
nor bar
:
awk '!/foo/ && !/bar/'
Lines containing neither foo
nor bar
which contain either foo2
or bar2
:
awk '!/foo/ && !/bar/ && (/foo2/ || /bar2/)'
And so on.
You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.
Have you tried using System.Net.IPAddress just in case?
System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("127.0.0.1"); //127.0.0.1 as an example
The docs on Microsoft's site have a complete example which works fine on my machine.
How about this:
SELECT DISTINCT ON (name) *
FROM messages
ORDER BY name, id DESC;
I had similar issue (on postgresql tough) and on a 1M records table. This solution takes 1.7s vs 44s produced by the one with LEFT JOIN. In my case I had to filter the corrispondant of your name field against NULL values, resulting in even better performances by 0.2 secs
Pillow is new version
PIL-1.1.7.win-amd64-py2.x installers are available at
I realize this is an old question, and the OP is talking about using custom gx that aren't necessary 'checkbox'-looking, but there is a fantastic resource for generating custom colored assets here: http://kobroor.pl/
Just give it the relevant details and it spits out graphics, complete with xml resources, that you can just drop right in.
Below code works for me :
public void test() {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.freepdfconvert.com/pdf-word");
driver.findElement(By.id("clientUpload")).click();
driver.switchTo()
.activeElement()
.sendKeys(
"/home/likewise-open/GLOBAL/123/Documents/filename.txt");
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.findElement(By.id("convertButton"));
There are multiple remote linux machines, and I need to write a shell script which will execute the same set of commands in each machine. (Including some sudo operations). How can this be done using shell scripting?
You can do this with ssh, for example:
#!/bin/bash
USERNAME=someUser
HOSTS="host1 host2 host3"
SCRIPT="pwd; ls"
for HOSTNAME in ${HOSTS} ; do
ssh -l ${USERNAME} ${HOSTNAME} "${SCRIPT}"
done
When ssh'ing to the remote machine, how to handle when it prompts for RSA fingerprint authentication.
You can add the StrictHostKeyChecking=no
option to ssh:
ssh -o StrictHostKeyChecking=no -l username hostname "pwd; ls"
This will disable the host key check and automatically add the host key to the list of known hosts. If you do not want to have the host added to the known hosts file, add the option -o UserKnownHostsFile=/dev/null
.
Note that this disables certain security checks, for example protection against man-in-the-middle attack. It should therefore not be applied in a security sensitive environment.
Use DATESTR
>> datestr(40189)
ans =
12-Jan-0110
Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM
>> datenum(2010,1,11)
ans =
734149
>> datenum(2010,1,11)-40189
ans =
693960
>> datestr(40189+693960)
ans =
11-Jan-2010
In other words, to convert any serial Excel date, call
datestr(excelSerialDate + 693960)
EDIT
To get the date in mm/dd/yyyy format, call datestr
with the specified format
excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010
Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things
excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010
Google gave me this answer as result, so...
I actually needed to "save" a string as an integer, for a binding between C and JavaScript, so I convert the string into a integer value:
/*
Examples:
int2str( str2int("test") ) == "test" // true
int2str( str2int("t€st") ) // "t¬st", because "€".charCodeAt(0) is 8364, will be AND'ed with 0xff
Limitations:
max 4 chars, so it fits into an integer
*/
function str2int(the_str) {
var ret = 0;
var len = the_str.length;
if (len >= 1) ret += (the_str.charCodeAt(0) & 0xff) << 0;
if (len >= 2) ret += (the_str.charCodeAt(1) & 0xff) << 8;
if (len >= 3) ret += (the_str.charCodeAt(2) & 0xff) << 16;
if (len >= 4) ret += (the_str.charCodeAt(3) & 0xff) << 24;
return ret;
}
function int2str(the_int) {
var tmp = [
(the_int & 0x000000ff) >> 0,
(the_int & 0x0000ff00) >> 8,
(the_int & 0x00ff0000) >> 16,
(the_int & 0xff000000) >> 24
];
var ret = "";
for (var i=0; i<4; i++) {
if (tmp[i] == 0)
break;
ret += String.fromCharCode(tmp[i]);
}
return ret;
}
You can do this with jQuery:
var offset = $('.target').offset();
var scrollto = offset.top - 50; // fixed_top_bar_height = 50px
$('html, body').animate({scrollTop:scrollto}, 0);
I have found a good work-around for continue (love the break sample above). Here I do not want to list "agency". In PHP I'd "continue" but in twig, I came up with alternative:
{% for basename, perms in permsByBasenames %}
{% if basename == 'agency' %}
{# do nothing #}
{% else %}
<a class="scrollLink" onclick='scrollToSpot("#{{ basename }}")'>{{ basename }}</a>
{% endif %}
{% endfor %}
OR I simply skip it if it doesn't meet my criteria:
{% for tr in time_reports %}
{% if not tr.isApproved %}
.....
{% endif %}
{% endfor %}
You need to first transform data1, in your case by calling ToString()
on each element.
List<int> data1 = new List<int> {1,2,3,4,5};
List<string> data2 = new List<string>{"6","3"};
var newData = data1.Select(i => i.ToString()).Intersect(data2);
List<int> data1 = new List<int> {1,2,3,4,5};
List<string> data2 = new List<string>{"6","3"};
var newData = data1.Intersect(data2.Select(s => int.Parse(s));
Note that this will throw an exception if not all strings are numbers. So you could do the following first to check:
int temp;
if(data2.All(s => int.TryParse(s, out temp)))
{
// All data2 strings are int's
}
git log --all -- path/to/file
should work
Create a custom authorization attribute based on AuthorizeAttribute and override OnAuthorization to perform the check how you want it done. Normally, AuthorizeAttribute will set the filter result to HttpUnauthorizedResult if the authorization check fails. You could have it set it to a ViewResult (of your Error view) instead.
EDIT: I have a couple of blog posts that go into more detail:
Example:
[AttributeUsage( AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false )]
public class MasterEventAuthorizationAttribute : AuthorizeAttribute
{
/// <summary>
/// The name of the master page or view to use when rendering the view on authorization failure. Default
/// is null, indicating to use the master page of the specified view.
/// </summary>
public virtual string MasterName { get; set; }
/// <summary>
/// The name of the view to render on authorization failure. Default is "Error".
/// </summary>
public virtual string ViewName { get; set; }
public MasterEventAuthorizationAttribute()
: base()
{
this.ViewName = "Error";
}
protected void CacheValidateHandler( HttpContext context, object data, ref HttpValidationStatus validationStatus )
{
validationStatus = OnCacheAuthorization( new HttpContextWrapper( context ) );
}
public override void OnAuthorization( AuthorizationContext filterContext )
{
if (filterContext == null)
{
throw new ArgumentNullException( "filterContext" );
}
if (AuthorizeCore( filterContext.HttpContext ))
{
SetCachePolicy( filterContext );
}
else if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
// auth failed, redirect to login page
filterContext.Result = new HttpUnauthorizedResult();
}
else if (filterContext.HttpContext.User.IsInRole( "SuperUser" ))
{
// is authenticated and is in the SuperUser role
SetCachePolicy( filterContext );
}
else
{
ViewDataDictionary viewData = new ViewDataDictionary();
viewData.Add( "Message", "You do not have sufficient privileges for this operation." );
filterContext.Result = new ViewResult { MasterName = this.MasterName, ViewName = this.ViewName, ViewData = viewData };
}
}
protected void SetCachePolicy( AuthorizationContext filterContext )
{
// ** IMPORTANT **
// Since we're performing authorization at the action level, the authorization code runs
// after the output caching module. In the worst case this could allow an authorized user
// to cause the page to be cached, then an unauthorized user would later be served the
// cached page. We work around this by telling proxies not to cache the sensitive page,
// then we hook our custom authorization code into the caching mechanism so that we have
// the final say on whether a page should be served from the cache.
HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
cachePolicy.SetProxyMaxAge( new TimeSpan( 0 ) );
cachePolicy.AddValidationCallback( CacheValidateHandler, null /* data */);
}
}
With a newer VS Code version it's quite simple.
Open VS Code in your project's folder.
Then open Python Terminal
(Ctrl-Shift-P: Python: Create Terminal)
In the terminal:
python -m venv .venv
you'll then see the following dialog:
click Yes
Then Python: Select Interpreter
(via Ctrl-Shift-P)
and select the option (in my case towards the bottom)
Python 3.7 (venv)
./venv/Scripts/python.exe
If you see
Activate.ps1 is not digitally signed. You cannot run this script on the current system.
you'll need to do the following: https://stackoverflow.com/a/18713789/2705777
For more information see: https://code.visualstudio.com/docs/python/environments#_global-virtual-and-conda-environments
In addition to this, due to some recent website hacks we had to secure our sites more. In doing so, we discovered that file_get_contents failed to work, where curl still would work.
Not 100%, but I believe that this php.ini setting may have been blocking the file_get_contents request.
; Disable allow_url_fopen for security reasons
allow_url_fopen = 0
Either way, our code now works with curl.
select substr(orderno,1,2) from shipment;
You may want to have a look at the documentation too.
Quick Fix- This worked in Eclipse - Right Click on project -> Properties -> Java Build Path (Tab) -> Add External JARs -> locate the servlet api jar implementation (if Tomcat - its named servlet-api.jar) -> click OK. That's it !!
Server.UrlEncode() is there to provide backward compatibility with Classic ASP,
Server.UrlEncode(str);
Is equivalent to:
HttpUtility.UrlEncode(str, Response.ContentEncoding);
You seem to be misunderstanding how import
searches for modules. When you use an import statement it always searches the actual module path (and/or sys.modules
); it doesn't make use of module objects in the local namespace that exist because of previous imports. When you do:
import package.subpackage.module
from package.subpackage import module
from module import attribute1
The second line looks for a package called package.subpackage
and imports module
from that package. This line has no effect on the third line. The third line just looks for a module called module
and doesn't find one. It doesn't "re-use" the object called module
that you got from the line above.
In other words from someModule import ...
doesn't mean "from the module called someModule that I imported earlier..." it means "from the module named someModule that you find on sys.path...". There is no way to "incrementally" build up a module's path by importing the packages that lead to it. You always have to refer to the entire module name when importing.
It's not clear what you're trying to achieve. If you only want to import the particular object attribute1, just do from package.subpackage.module import attribute1
and be done with it. You need never worry about the long package.subpackage.module
once you've imported the name you want from it.
If you do want to have access to the module to access other names later, then you can do from package.subpackage import module
and, as you've seen you can then do module.attribute1
and so on as much as you like.
If you want both --- that is, if you want attribute1
directly accessible and you want module
accessible, just do both of the above:
from package.subpackage import module
from package.subpackage.module import attribute1
attribute1 # works
module.someOtherAttribute # also works
If you don't like typing package.subpackage
even twice, you can just manually create a local reference to attribute1:
from package.subpackage import module
attribute1 = module.attribute1
attribute1 # works
module.someOtherAttribute #also works
Bootstrap 3
Here is a working left sidebar example:
http://bootply.com/90936 (similar to the Bootstrap docs)
The trick is using the affix
component along with some CSS to position it:
#sidebar.affix-top {
position: static;
margin-top:30px;
width:228px;
}
#sidebar.affix {
position: fixed;
top:70px;
width:228px;
}
EDIT- Another example with footer and affix-bottom
Bootstrap 4
The Affix component has been removed in Bootstrap 4, so to create a sticky sidebar, you can use a 3rd party Affix plugin like this Bootstrap 4 sticky sidebar example, or use the sticky-top
class is explained in this answer.
Related: Create a responsive navbar sidebar "drawer" in Bootstrap 4?
You can use prettytable to render the table as text. The trick is to convert the data_frame to an in-memory csv file and have prettytable read it. Here's the code:
from StringIO import StringIO
import prettytable
output = StringIO()
data_frame.to_csv(output)
output.seek(0)
pt = prettytable.from_csv(output)
print pt
Try this:
class JSONListView(ListView):
queryset = Users.objects.all()
def get(self, request, *args, **kwargs):
data = {}
data["users"] = get_json_list(queryset)
return JSONResponse(data)
def get_json_list(query_set):
list_objects = []
for obj in query_set:
dict_obj = {}
for field in obj._meta.get_fields():
try:
if field.many_to_many:
dict_obj[field.name] = get_json_list(getattr(obj, field.name).all())
continue
dict_obj[field.name] = getattr(obj, field.name)
except AttributeError:
continue
list_objects.append(dict_obj)
return list_objects
There are many open source projects that can generate screenshots. For example PhantomJS, webkit2png etc
The big problem with these projects is that they are based on older browser technology and have problems rendering many sites, especially sites that use webfonts, flexbox, svg and various other additions to the HTML5 and CSS spec over the last couple of months/years.
I've tried a few of the third party services, and most are based on PhantomJS, meaning they also produce poor quality screenshots. The best third party service for generating website screenshots is urlbox.io. It is a paid service, although there is a free 7-day trial to test it out without committing to any paid plan.
Here is a link to the documentation, and below are simple steps to get it working in PHP with composer.
// 1 . Get the urlbox/screenshots composer package (on command line):
composer require urlbox/screenshots
// 2. Set up the composer package with Urlbox API credentials:
$urlbox = UrlboxRenderer::fromCredentials('API_KEY', 'API_SECRET');
// 3. Set your options (all options such as full page/full height screenshots, retina resolution, viewport dimensions, thumbnail width etc can be set here. See the docs for more.)
$options['url'] = 'example.com';
// 4. Generate the Urlbox url
$urlboxUrl = $urlbox->generateUrl($options);
// $urlboxUrl is now 'https://api.urlbox.io/v1/API_KEY/TOKEN/png?url=example.com'
// 5. Now stick it in an img tag, when the image is loaded in browser, the API call to urlbox will be triggered and a nice PNG screenshot will be generated!
<img src="$urlboxUrl" />
For e.g. here's a full height screenshot of this very page:
<body>
<div style="width:800px; margin:0 auto;">
centered content
</div>
</body>
First, your posted data isn't valid JSON. This would be:
{"value": "aériennes"}
Note the double quotes: They are required.
The Content-Type for JSON data should be application/json
. The actual JSON data (what we have above) should be encoded using UTF-8, UTF-16, or UTF-32 - I'd recommend using UTF-8.
You can use a tool like Wireshark to monitor network traffic and see how the data looks, you should see the bytes c3 89
for the é. I've never worked with Spring, but if it's doing the JSON encoding, this is probably taken care of properly, for you.
Once the JSON reaches the browser, it should good, if it is valid. However, how are you inserting the data from the JSON response into the webpage?
You are importing the module datetime, which doesn't have a strptime
function.
That module does have a datetime
object with that method though:
import datetime
dtDate = datetime.datetime.strptime(sDate, "%m/%d/%Y")
Alternatively you can import the datetime
object from the module:
from datetime import datetime
dtDate = datetime.strptime(sDate, "%m/%d/%Y")
Note that the strptime
method was added in python 2.5; if you are using an older version use the following code instead:
import datetime, time
dtDate = datetime.datetime(*time.strptime(sDate, "%m/%d/%Y")[:6])
Offering a quick answer for people using Ionic. I need to show a tooltip only once so I used the $localStorage to achieve this. This is for playing a track, so when they push play, it shows the tooltip once.
$scope.storage = $localStorage; //connects an object to $localstorage
$scope.storage.hasSeenPopup = "false"; // they haven't seen it
$scope.showPopup = function() { // popup to tell people to turn sound on
$scope.data = {}
// An elaborate, custom popup
var myPopup = $ionicPopup.show({
template: '<p class="popuptext">Turn Sound On!</p>',
cssClass: 'popup'
});
$timeout(function() {
myPopup.close(); //close the popup after 3 seconds for some reason
}, 2000);
$scope.storage.hasSeenPopup = "true"; // they've now seen it
};
$scope.playStream = function(show) {
PlayerService.play(show);
$scope.audioObject = audioObject; // this allow for styling the play/pause icons
if ($scope.storage.hasSeenPopup === "false"){ //only show if they haven't seen it.
$scope.showPopup();
}
}
A Runnable is basically a type of class (Runnable is an Interface) that can be put into a thread, describing what the thread is supposed to do.
The Runnable Interface requires of the class to implement the method run()
like so:
public class MyRunnableTask implements Runnable {
public void run() {
// do stuff here
}
}
And then use it like this:
Thread t = new Thread(new MyRunnableTask());
t.start();
If you did not have the Runnable
interface, the Thread class, which is responsible to execute your stuff in the other thread, would not have the promise to find a run()
method in your class, so you could get errors. That is why you need to implement the interface.
Note that you do not need to define a class as usual, you can do all of that inline:
Thread t = new Thread(new Runnable() {
public void run() {
// stuff here
}
});
t.start();
This is similar to the above, only you don't create another named class.
A handle is a sort of pointer in that it is typically a way of referencing some entity.
It would be more accurate to say that a pointer is one type of handle, but not all handles are pointers.
For example, a handle may also be some index into an in memory table, which corresponds to an entry that itself contains a pointer to some object.
The key thing is that when you have a "handle", you neither know nor care how that handle actually ends up identifying the thing that it identifies, all you need to know is that it does.
It should also be obvious that there is no single answer to "what exactly is a handle", because handles to different things, even in the same system, may be implemented in different ways "under the hood". But you shouldn't need to be concerned with those differences.
Well, there are plenty of database tutorials online for java (what you're looking for is called JDBC). But if you are using plain servlets, you will have a class that extends HttpServlet
and inside it you will have two methods that look like
public void doPost(HttpServletRequest req, HttpServletResponse resp){
}
and
public void doGet(HttpServletRequest req, HttpServletResponse resp){
}
One of them is called to handle GET
operations and another is used to handle POST
operations. You will then use the HttpServletRequest
object to get the parameters that were passed as part of the form like so:
String name = req.getParameter("name");
Then, once you have the data from the form, it's relatively easy to add it to a database using a JDBC tutorial that is widely available on the web. I also suggest searching for a basic Java servlet tutorial to get you started. It's very easy, although there are a number of steps that need to be configured correctly.
Also you can do something like that:
document.addEventListener("DOMContentLoaded", function(event) {
React.renderComponent(
CardBox({url: "/cards/?format=json", pollInterval: 2000}),
document.getElementById("content")
);
})
The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
I think the best way to handle this is the way python itself handles it. Python raises a TypeError. For example:
$ python -c 'print(sum())'
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: sum expected at least 1 arguments, got 0
Our junior dev just found this page in a google search for "python exception wrong arguments" and I'm surprised that the obvious (to me) answer wasn't ever suggested in the decade since this question was asked.
Yes, since some genius in the Java API creation committee decided that, even though certain classes have size()
members or length
attributes, they won't implement getSize()
or getLength()
which JSF and most other standards require, you can't do what you want.
There's a couple ways to do this.
One: add a function to your Bean that returns the length:
In class MyBean: public int getSomelistLength() { return this.somelist.length; } In your JSF page: #{MyBean.somelistLength}
Two: If you're using Facelets (Oh, God, why aren't you using Facelets!), you can add the fn namespace and use the length function
In JSF page: #{ fn:length(MyBean.somelist) }
echo
will normally output a newline, which is suppressed with -n
. Try this:
echo -n foobar | sha256sum
a = 'varname';
str = a+' = '+'123';
eval(str)
alert(varname);
Try this...
Here is the focus listener example.
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (hasFocus) {
Toast.makeText(getApplicationContext(), "Got the focus", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Lost the focus", Toast.LENGTH_LONG).show();
}
}
});
If you are calling from within Stored Procedure don't use @. In my case it returns 0
CALL SP_NAME(L_OUTPUT_PARAM)
The my.cnf file you should edit is the /etc/mysql/my.cnf file. Just:
sudo nano /etc/mysql/my.cnf
Then add:
[mysqld]
local-infile
[mysql]
local-infile
The headers [mysqld] and [mysql] are already given, just locate them in the file and add local-infile underneath each of them.
It works for me on MySQL 5.5 on Ubuntu 12.04 LTS.
Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.
They should be
server {
listen 80;
server_name www.domain1.com;
root /var/www/domain1;
}
server {
listen 80;
server_name www.domain2.com;
root /var/www/domain2;
}
Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.
You can't use placeholders for column names, table names, data type names, or basically anything that isn't data.
There is no global solution. For any given country it is at best rather tricky.
In the UK, the PostOffice controlls postal addresses, and can provide (at a cost) address information for validation purposes.
Government agencies also keep an extensive list of addresses, and these are centrally collated in the NLPG (National Land and Property Gazetteer).
Actually validating against these lists is very difficult. Most people don't even know exactly how their address as it is held by the PostOffice. Some businesses don't even know what number they are on a particular street.
Your best bet is to approach a company that specialises in this kind of thing.
Try that:
bool IsValidURL(string URL)
{
string Pattern = @"^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$";
Regex Rgx = new Regex(Pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
return Rgx.IsMatch(URL);
}
It will accept URL like that:
There's a function to find a substring within a string (find
), and a function to replace a particular range in a string with another string (replace
), so you can combine those to get the effect you want:
bool replace(std::string& str, const std::string& from, const std::string& to) {
size_t start_pos = str.find(from);
if(start_pos == std::string::npos)
return false;
str.replace(start_pos, from.length(), to);
return true;
}
std::string string("hello $name");
replace(string, "$name", "Somename");
In response to a comment, I think replaceAll
would probably look something like this:
void replaceAll(std::string& str, const std::string& from, const std::string& to) {
if(from.empty())
return;
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}
}
Following code works..
datePickerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showDialog(0);
}
});
@Override
@Deprecated
protected Dialog onCreateDialog(int id) {
return new DatePickerDialog(this, datePickerListener, year, month, day);
}
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
day = selectedDay;
month = selectedMonth;
year = selectedYear;
datePickerButton.setText(selectedDay + " / " + (selectedMonth + 1) + " / "
+ selectedYear);
}
};