openssl
allows to generate self-signed certificate by a single command (-newkey
instructs to generate a private key and -x509
instructs to issue a self-signed
certificate instead of a signing request)::
openssl req -x509 -newkey rsa:4096 \
-keyout my.key -passout pass:123456 -out my.crt \
-days 365 \
-subj /CN=localhost/O=home/C=US/[email protected] \
-addext "subjectAltName = DNS:localhost,DNS:web.internal,email:[email protected]" \
-addext keyUsage=digitalSignature -addext extendedKeyUsage=serverAuth
You can generate a private key and construct a self-signing certificate in separate steps::
openssl genrsa -out my.key -passout pass:123456 2048
openssl req -x509 \
-key my.key -passin pass:123456 -out my.csr \
-days 3650 \
-subj /CN=localhost/O=home/C=US/[email protected] \
-addext "subjectAltName = DNS:localhost,DNS:web.internal,email:[email protected]" \
-addext keyUsage=digitalSignature -addext extendedKeyUsage=serverAuth
Review the resulting certificate::
openssl x509 -text -noout -in my.crt
Java keytool
creates PKCS#12 store::
keytool -genkeypair -keystore my.p12 -alias master \
-storetype pkcs12 -keyalg RSA -keysize 2048 -validity 3650 \
-storepass 123456 \
-dname "CN=localhost,O=home,C=US" \
-ext 'san=dns:localhost,dns:web.internal,email:[email protected]'
To export the self-signed certificate::
keytool -exportcert -keystore my.p12 -file my.crt \
-alias master -rfc -storepass 123456
Review the resulting certificate::
keytool -printcert -file my.crt
certtool
from GnuTLS doesn't allow passing different attributes from CLI. I don't like to mess with config files ((
The Z stands for 'Zulu' - your times are in UTC. From Wikipedia:
The UTC time zone is sometimes denoted by the letter Z—a reference to the equivalent nautical time zone (GMT), which has been denoted by a Z since about 1950. The letter also refers to the "zone description" of zero hours, which has been used since 1920 (see time zone history). Since the NATO phonetic alphabet and amateur radio word for Z is "Zulu", UTC is sometimes known as Zulu time. This is especially true in aviation, where Zulu is the universal standard.
If you add -chain to your command line, it will export any chained certificates.
With your private key and public certificate, you need to create a PKCS12 keystore first, then convert it into a JKS.
# Create PKCS12 keystore from private key and public certificate.
openssl pkcs12 -export -name myservercert -in selfsigned.crt -inkey server.key -out keystore.p12
# Convert PKCS12 keystore into a JKS keystore
keytool -importkeystore -destkeystore mykeystore.jks -srckeystore keystore.p12 -srcstoretype pkcs12 -alias myservercert
To verify the contents of the JKS, you can use this command:
keytool -list -v -keystore mykeystore.jks
If this was not a self-signed certificate, you would probably want to follow this step with importing the certificate chain leading up to the trusted CA cert.
The original order is in fact backwards. Certs should be followed by the issuing cert until the last cert is issued by a known root per IETF's RFC 5246 Section 7.4.2
This is a sequence (chain) of certificates. The sender's certificate MUST come first in the list. Each following certificate MUST directly certify the one preceding it.
See also SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch for troubleshooting techniques.
But I still don't know why they wrote the spec so that the order matters.
Can someone help me with the exact syntax?
It's a three-step process, and it involves modifying the openssl.cnf
file. You might be able to do it with only command line options, but I don't do it that way.
Find your openssl.cnf
file. It is likely located in /usr/lib/ssl/openssl.cnf
:
$ find /usr/lib -name openssl.cnf
/usr/lib/openssl.cnf
/usr/lib/openssh/openssl.cnf
/usr/lib/ssl/openssl.cnf
On my Debian system, /usr/lib/ssl/openssl.cnf
is used by the built-in openssl
program. On recent Debian systems it is located at /etc/ssl/openssl.cnf
You can determine which openssl.cnf
is being used by adding a spurious XXX
to the file and see if openssl
chokes.
First, modify the req
parameters. Add an alternate_names
section to openssl.cnf
with the names you want to use. There are no existing alternate_names
sections, so it does not matter where you add it.
[ alternate_names ]
DNS.1 = example.com
DNS.2 = www.example.com
DNS.3 = mail.example.com
DNS.4 = ftp.example.com
Next, add the following to the existing [ v3_ca ]
section. Search for the exact string [ v3_ca ]
:
subjectAltName = @alternate_names
You might change keyUsage
to the following under [ v3_ca ]
:
keyUsage = digitalSignature, keyEncipherment
digitalSignature
and keyEncipherment
are standard fare for a server certificate. Don't worry about nonRepudiation
. It's a useless bit thought up by computer science guys/gals who wanted to be lawyers. It means nothing in the legal world.
In the end, the IETF (RFC 5280), browsers and CAs run fast and loose, so it probably does not matter what key usage you provide.
Second, modify the signing parameters. Find this line under the CA_default
section:
# Extension copying option: use with caution.
# copy_extensions = copy
And change it to:
# Extension copying option: use with caution.
copy_extensions = copy
This ensures the SANs are copied into the certificate. The other ways to copy the DNS names are broken.
Third, generate your self-signed certificate:
$ openssl genrsa -out private.key 3072
$ openssl req -new -x509 -key private.key -sha256 -out certificate.pem -days 730
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
...
Finally, examine the certificate:
$ openssl x509 -in certificate.pem -text -noout
Certificate:
Data:
Version: 3 (0x2)
Serial Number: 9647297427330319047 (0x85e215e5869042c7)
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
Validity
Not Before: Feb 1 05:23:05 2014 GMT
Not After : Feb 1 05:23:05 2016 GMT
Subject: C=US, ST=MD, L=Baltimore, O=Test CA, Limited, CN=Test CA/[email protected]
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (3072 bit)
Modulus:
00:e2:e9:0e:9a:b8:52:d4:91:cf:ed:33:53:8e:35:
...
d6:7d:ed:67:44:c3:65:38:5d:6c:94:e5:98:ab:8c:
72:1c:45:92:2c:88:a9:be:0b:f9
Exponent: 65537 (0x10001)
X509v3 extensions:
X509v3 Subject Key Identifier:
34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
X509v3 Authority Key Identifier:
keyid:34:66:39:7C:EC:8B:70:80:9E:6F:95:89:DB:B5:B9:B8:D8:F8:AF:A4
X509v3 Basic Constraints: critical
CA:FALSE
X509v3 Key Usage:
Digital Signature, Non Repudiation, Key Encipherment, Certificate Sign
X509v3 Subject Alternative Name:
DNS:example.com, DNS:www.example.com, DNS:mail.example.com, DNS:ftp.example.com
Signature Algorithm: sha256WithRSAEncryption
3b:28:fc:e3:b5:43:5a:d2:a0:b8:01:9b:fa:26:47:8e:5c:b7:
...
71:21:b9:1f:fa:30:19:8b:be:d2:19:5a:84:6c:81:82:95:ef:
8b:0a:bd:65:03:d1
Try this:
//using System.Security.Cryptography.X509Certificates;
public static X509Certificate2 selectCert(StoreName store, StoreLocation location, string windowTitle, string windowMsg)
{
X509Certificate2 certSelected = null;
X509Store x509Store = new X509Store(store, location);
x509Store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection col = x509Store.Certificates;
X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection(col, windowTitle, windowMsg, X509SelectionFlag.SingleSelection);
if (sel.Count > 0)
{
X509Certificate2Enumerator en = sel.GetEnumerator();
en.MoveNext();
certSelected = en.Current;
}
x509Store.Close();
return certSelected;
}
So far, I've seen this issue happen within corporate networks because of two reasons, one or both of which may be happening in your case:
As a side note, No. 2 above may make you feel uneasy about your supposedly secure TLS traffic being scanned. That's the corporate world for you.
I will also add my experience here in case it helps someone:
At work we commonly use the following two commands to enable IntelliJ IDEA to talk to various servers, for example our internal maven repositories:
[Elevated]C:\Program Files\JetBrains\IntelliJ IDEA {version}\jre64>bin\keytool
-printcert -rfc -sslserver maven.services.{our-company}.com:443 > public.crt
[Elevated]C:\Program Files\JetBrains\IntelliJ IDEA {version}\jre64>bin\keytool
-import -storepass changeit -noprompt -trustcacerts -alias services.{our-company}.com
-keystore lib\security\cacerts -file public.crt
Now, what sometimes happens is that the keytool -printcert
command is unable to communicate with the outside world due to temporary connectivity issues, such as the firewall preventing it, the user forgot to start his VPN, whatever. It is a fact of life that this may happen. This is not actually the problem.
The problem is that when the stupid tool encounters such an error, it does not emit the error message to the standard error device, it emits it to the standard output device!
So here is what ends up happening:
public.crt
file now contains an error message saying keytool error: java.lang.Exception: No certificate from the SSL server
.public.crt
, so it fails, saying keytool error: java.lang.Exception: Input not an X.509 certificate
.Bottom line is: after keytool -printcert ... > public.crt
always dump the contents of public.crt
to make sure it is actually a key and not an error message before proceeding to run keytool -import ... -file public.crt
When generating CSR is possible to specify -ext attribute again to have it inserted in the CSR
keytool -certreq -file test.csr -keystore test.jks -alias testAlias -ext SAN=dns:test.example.com
complete example here: How to create CSR with SANs using keytool
If you want to use an older version of .net, create your own flag and cast it.
//
// Summary:
// Specifies the security protocols that are supported by the Schannel security
// package.
[Flags]
private enum MySecurityProtocolType
{
//
// Summary:
// Specifies the Secure Socket Layer (SSL) 3.0 security protocol.
Ssl3 = 48,
//
// Summary:
// Specifies the Transport Layer Security (TLS) 1.0 security protocol.
Tls = 192,
//
// Summary:
// Specifies the Transport Layer Security (TLS) 1.1 security protocol.
Tls11 = 768,
//
// Summary:
// Specifies the Transport Layer Security (TLS) 1.2 security protocol.
Tls12 = 3072
}
public Session()
{
System.Net.ServicePointManager.SecurityProtocol = (SecurityProtocolType)(MySecurityProtocolType.Tls12 | MySecurityProtocolType.Tls11 | MySecurityProtocolType.Tls);
}
Create an array of Views and apply it to: container.addView(viewarr[position]);
public class Layoutes extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
Layoutes(Context context){
this.context=context;
}
int layoutes[]={R.layout.one,R.layout.two,R.layout.three};
@Override
public int getCount() {
return layoutes.length;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return (view==(LinearLayout)object);
}
@Override
public Object instantiateItem(ViewGroup container, int position){
layoutInflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View one=layoutInflater.inflate(R.layout.one,container,false);
View two=layoutInflater.inflate(R.layout.two,container,false);
View three=layoutInflater.inflate(R.layout.three,container,false);
View viewarr[]={one,two,three};
container.addView(viewarr[position]);
return viewarr[position];
}
@Override
public void destroyItem(ViewGroup container, int position, Object object){
container.removeView((LinearLayout) object);
}
}
Old tread...? Well, someone may bump into this...
Please check out http://telamenta.com/techarticle/php-explode-newlines-and-you
Rather than using:
$values = explode("\n", $value_string);
Use a safer method like:
$values = preg_split('/[\n\r]+/', $value_string);
This will for most of the objects for outputting in nodejs console
var util = require('util')_x000D_
function print (data){_x000D_
console.log(util.inspect(data,true,12,true))_x000D_
_x000D_
}_x000D_
_x000D_
print({name : "Your name" ,age : "Your age"})
_x000D_
On the actual behavior, there is no difference. They all return None
and that's it. However, there is a time and place for all of these.
The following instructions are basically how the different methods should be used (or at least how I was taught they should be used), but they are not absolute rules so you can mix them up if you feel necessary to.
return None
This tells that the function is indeed meant to return a value for later use, and in this case it returns None
. This value None
can then be used elsewhere. return None
is never used if there are no other possible return values from the function.
In the following example, we return person
's mother
if the person
given is a human. If it's not a human, we return None
since the person
doesn't have a mother
(let's suppose it's not an animal or something).
def get_mother(person):
if is_human(person):
return person.mother
else:
return None
return
This is used for the same reason as break
in loops. The return value doesn't matter and you only want to exit the whole function. It's extremely useful in some places, even though you don't need it that often.
We've got 15 prisoners
and we know one of them has a knife. We loop through each prisoner
one by one to check if they have a knife. If we hit the person with a knife, we can just exit the function because we know there's only one knife and no reason the check rest of the prisoners
. If we don't find the prisoner
with a knife, we raise an alert. This could be done in many different ways and using return
is probably not even the best way, but it's just an example to show how to use return
for exiting a function.
def find_prisoner_with_knife(prisoners):
for prisoner in prisoners:
if "knife" in prisoner.items:
prisoner.move_to_inquisition()
return # no need to check rest of the prisoners nor raise an alert
raise_alert()
Note: You should never do var = find_prisoner_with_knife()
, since the return value is not meant to be caught.
return
at allThis will also return None
, but that value is not meant to be used or caught. It simply means that the function ended successfully. It's basically the same as return
in void
functions in languages such as C++ or Java.
In the following example, we set person's mother's name and then the function exits after completing successfully.
def set_mother(person, mother):
if is_human(person):
person.mother = mother
Note: You should never do var = set_mother(my_person, my_mother)
, since the return value is not meant to be caught.
Like this:
if (str.indexOf("Yes") >= 0)
...or you can use the tilde operator:
if (~str.indexOf("Yes"))
This works because indexOf()
returns -1
if the string wasn't found at all.
Note that this is case-sensitive.
If you want a case-insensitive search, you can write
if (str.toLowerCase().indexOf("yes") >= 0)
Or:
if (/yes/i.test(str))
Just create a data.frame
with 0 length variables
eg
nodata <- data.frame(x= numeric(0), y= integer(0), z = character(0))
str(nodata)
## 'data.frame': 0 obs. of 3 variables:
## $ x: num
## $ y: int
## $ z: Factor w/ 0 levels:
or to create a data.frame with 5 columns named a,b,c,d,e
nodata <- as.data.frame(setNames(replicate(5,numeric(0), simplify = F), letters[1:5]))
Another interesting way when you use ES6 arrow function syntax:
x = ['a', 'a', 'a', 'a']
!x.filter(e=>e!==x[0])[0] // true
x = ['a', 'a', 'b', 'a']
!x.filter(e=>e!==x[0])[0] // false
x = []
!x.filter(e=>e!==x[0])[0] // true
And when you don't want to reuse the variable for array (x):
!['a', 'a', 'a', 'a'].filter((e,i,a)=>e!==a[0])[0] // true
IMO previous poster who used array.every(...) has the cleanest solution.
Here is my answer. This function will help you to find out whether B is a sub-list of A. Time complexity is O(n).
`def does_A_contain_B(A, B): #remember now A is the larger list
b_size = len(B)
for a_index in range(0, len(A)):
if A[a_index : a_index+b_size]==B:
return True
else:
return False`
Based on antoinepairet's comment/example:
Using uib-collapse
attribute provides animations: http://plnkr.co/edit/omyoOxYnCdWJP8ANmTc6?p=preview
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<!-- note the ng-init and ng-click here: -->
<button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</div>
<div class="collapse navbar-collapse" uib-collapse="navCollapsed">
<ul class="nav navbar-nav">
...
</ul>
</div>
</nav>
I see that the question is framed around BS2, but I thought I'd pitch in with a solution for Bootstrap 3 using ng-class solution based on suggestions in ui.bootstrap issue 394:
The only variation from the official bootstrap example is the addition of ng-
attributes noted by comments, below:
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-header">
<!-- note the ng-init and ng-click here: -->
<button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</div>
<!-- note the ng-class here -->
<div class="collapse navbar-collapse" ng-class="{'in':!navCollapsed}">
<ul class="nav navbar-nav">
...
Here is an updated working example: http://plnkr.co/edit/OlCCnbGlYWeO7Nxwfj5G?p=preview (hat tip Lars)
This seems to works for me in simple use cases, but you'll note in the example that the second dropdown is cut off… good luck!
I found this example also tricky. Why that in the 2nd loop at the last iteration nothing happens ($v stays 'two'), is that $v points to $a[3] (and vice versa), so it cannot assign value to itself, so it keeps the previous assigned value :)
.style1 {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
Works in:
In addition you can try this for an IE solution
filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";
zoom: 1;
Credit to this article by Chris Coyier http://css-tricks.com/perfect-full-page-background-image/
Here it is using Swift
/* Distance from a point (p1) to line l1 l2 */
func distanceFromPoint(p: CGPoint, toLineSegment l1: CGPoint, and l2: CGPoint) -> CGFloat {
let A = p.x - l1.x
let B = p.y - l1.y
let C = l2.x - l1.x
let D = l2.y - l1.y
let dot = A * C + B * D
let len_sq = C * C + D * D
let param = dot / len_sq
var xx, yy: CGFloat
if param < 0 || (l1.x == l2.x && l1.y == l2.y) {
xx = l1.x
yy = l1.y
} else if param > 1 {
xx = l2.x
yy = l2.y
} else {
xx = l1.x + param * C
yy = l1.y + param * D
}
let dx = p.x - xx
let dy = p.y - yy
return sqrt(dx * dx + dy * dy)
}
In my case the contents of my cell is HTML as result of a formatter. I want the value inside anchor tag. By fetching the cell contents and then creating an element out of the html via jQuery I am able to then access the raw value by calling .text() on my newly created element.
var cellContents = grid.getCell(rowid, 'ColNameHere');
console.log($(cellContents));
//in my case logs <h3><a href="#">The Value I'm After</a></h3>
var cellRawValue = $(cellContents).text();
console.log(cellRawValue); //outputs "The Value I'm After!"
my answer is based on @LLQ answer, but since in my case my cellContents isn't an input I needed to use .text()
instead of .val()
to access the raw value so I thought I'd post this in case anyone else is looking for a way to access the raw value of a formatted jqGrid cell.
This answer is based on the following answer by @YuSolution https://stackoverflow.com/a/44622211/4567504.
In my case Installing MySQL changed my path variable and even after reinstalling @angular/cli globally many times I was not able to fix the issue.
Solution:
In command prompt, run the following command
npm config get prefix
A path will be returned like
C:\Users{{Your_Username}}\AppData\Roaming\npm
Copy this path and go to ControlPanel > System and Security > System, Click on Advanced System settings, go to advanced tab and select environment variable button like
Now in User Variables box click on Path row and edit and in variable value box paste your copied path.
Restart the command prompt and it will work
The fault occurs here:
C[i][j]+=A[i][k]*B[k][j]
It crashes when k=2. This is because the tuple A[i]
has only 2 values, and therefore you can only call it up to A[i][1] before it errors.
EDIT: Listen to Gerard's answer too, your C is wrong. It should be C=[[0 for row in range(len(A))] for col in range(len(A[0]))]
.
Just a tip: you could replace the first loop with a multiplication, so it would be C=[[0]*len(A) for col in range(len(A[0]))]
The list()
function [docs] will convert a string into a list of single-character strings.
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:
>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'
You can also loop over the characters in the string as you can loop over the elements of a list:
>>> for c in 'hello':
... print c + c,
...
hh ee ll ll oo
a.button:hover{
background: #383; }
works for me but in my case
#buttonClick:hover {
background-color:green; }
All 3 of them represent the end of a line. But...
\r
(Carriage Return) → moves the cursor to the beginning of the line without advancing to the next line\n
(Line Feed) → moves the cursor down to the next line without returning to the beginning of the line — In a *nix environment \n
moves to the beginning of the line.\r\n
(End Of Line) → a combination of \r
and \n
Simple javascript document navigation to "#" will do it.
window.onload = function()
{
document.location.href = "#";
}
This will force the navigation bar to remove itself on load.
It worked for me.
if (Build.VERSION.SDK_INT < 16) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
} else {
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
}
You can have any length, but of course, there can be a memory issue on the computer if the String input is too long. The output is always 32 characters.
Easier alternative to above answers
If Object(Model Class/POJO) contains the date in String datatype.
private void sortArray(ArrayList<myObject> arraylist) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); //your own date format
if (reports != null) {
Collections.sort(arraylist, new Comparator<myObject>() {
@Override
public int compare(myObject o1, myObject o2) {
try {
return simpleDateFormat.parse(o2.getCreated_at()).compareTo(simpleDateFormat.parse(o1.getCreated_at()));
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
}
});
}
If Object(Model Class/POJO) contains date in Date datatype
private void sortArray(ArrayList<myObject> arrayList) {
if (arrayList != null) {
Collections.sort(arrayList, new Comparator<myObject>() {
@Override
public int compare(myObject o1, myObject o2) {
return o2.getCreated_at().compareTo(o1.getCreated_at()); }
});
} }
The above code is for sorting the array in descending order of date, swap o1 and o2 for ascending order.
I had the same problem when I deployed my application to test PC. The problem was development PC had msvcp110d.dll
and msvcr110d.dll
but not the test PC.
I added "Visual Studio C++ 11.0 DebugCRT (x86)" merge module in InstalledSheild and it worked. Hope this will be helpful for someone else.
brilliant example Jonathan Leffler, to make your code work on SLES, I needed to add an additional header to allow the pid_t object :)
#include <sys/types.h>
This one is simplier :)
dataview dataview1;
this.dataview1= dataset.tables[0].defaultview;
this.dataview1.sort = "[ColumnName] ASC, [ColumnName] DESC";
this.datagridview.datasource = dataview1;
well, char *
means a pointer point to char, it is different from char array.
char amessage[] = "this is an array"; /* define an array*/
char *pmessage = "this is a pointer"; /* define a pointer*/
And, char **
means a pointer point to a char pointer.
You can look some books about details about pointer and array.
I think it is much more simple solution:
window.location = (""+window.location).replace(/#[A-Za-z0-9_]*$/,'')+"#myAnchor"
This method does not reload the website, and sets the focus on the anchors which are needed for screen reader.
Since this answer still gets voted up, I want to point out that you should almost never need to look in the header files. If you want to write reliable code, you're much better served by looking in the standard. A better question than "how is off_t
defined on my machine" is "how is off_t
defined by the standard?". Following the standard means that your code will work today and tomorrow, on any machine.
In this case, off_t
isn't defined by the C standard. It's part of the POSIX standard, which you can browse here.
Unfortunately, off_t
isn't very rigorously defined. All I could find to define it is on the page on sys/types.h
:
blkcnt_t
andoff_t
shall be signed integer types.
This means that you can't be sure how big it is. If you're using GNU C, you can use the instructions in the answer below to ensure that it's 64 bits. Or better, you can convert to a standards defined size before putting it on the wire. This is how projects like Google's Protocol Buffers work (although that is a C++ project).
So, I think "where do I find the definition in my header files" isn't the best question. But, for completeness here's the answer:
On my machine (and most machines using glibc) you'll find the definition in bits/types.h
(as a comment says at the top, never directly include this file), but it's obscured a bit in a bunch of macros. An alternative to trying to unravel them is to look at the preprocessor output:
#include <stdio.h>
#include <sys/types.h>
int main(void) {
off_t blah;
return 0;
}
And then:
$ gcc -E sizes.c | grep __off_t
typedef long int __off_t;
....
However, if you want to know the size of something, you can always use the sizeof()
operator.
Edit: Just saw the part of your question about the __
. This answer has a good discussion. The key point is that names starting with __
are reserved for the implementation (so you shouldn't start your own definitions with __
).
Try using the net use
command in your script to map the share first, because you can provide it credentials. Then, your copy command should use those credentials.
net use \\<network-location>\<some-share> password /USER:username
Don't leave a trailing \ at the end of the
Instead of
<item name="android:statusBarColor">@android:color/transparent</item>
Use the following:
<item name="android:windowTranslucentStatus">true</item>
And make sure to remove the top padding (which is added by default) on your 'MainActivity' layout.
Note that this does not make the status bar fully transparent, and there will still be a "faded black" overlay over your status bar.
For my style, I always use @ModelAttribute to catch object from spring form jsp. for example, I design form on jsp page, that form exist with commandName
<form:form commandName="Book" action="" methon="post">
<form:input type="text" path="title"></form:input>
</form:form>
and I catch the object on controller with follow code
public String controllerPost(@ModelAttribute("Book") Book book)
and every field name of book must be match with path in sub-element of form
you can use the below method to extract all numbers from a string.
def extract_numbers_from_string(string):
number = ''
for i in string:
try:
number += str(int(i))
except:
pass
return number
(OR) you could use i.isdigit()
or i.isnumeric
(in Python 3.6.5 or above)
def extract_numbers_from_string(string):
number = ''
for i in string:
if i.isnumeric():
number += str(int(i))
return number
a = '343fdfd3'
print (extract_numbers_from_string(a))
# 3433
You can use the dir step, example:
dir("folder") {
sh "pwd"
}
The folder
can be relative or absolute path.
If you got here because a search engine told you this is how to get the Unix timestamp, stop reading this answer. Scroll down one.
If you want to reverse time.gmtime()
, you want calendar.timegm()
.
>>> calendar.timegm(time.gmtime())
1293581619.0
You can turn your string into a time tuple with time.strptime()
, which returns a time tuple that you can pass to calendar.timegm()
:
>>> import calendar
>>> import time
>>> calendar.timegm(time.strptime('Jul 9, 2009 @ 20:02:58 UTC', '%b %d, %Y @ %H:%M:%S UTC'))
1247169778
More information about calendar module here
You'll want something like this to increase the message size quotas, in the App.config or Web.config file:
<bindings>
<basicHttpBinding>
<binding name="basicHttp" allowCookies="true"
maxReceivedMessageSize="20000000"
maxBufferSize="20000000"
maxBufferPoolSize="20000000">
<readerQuotas maxDepth="32"
maxArrayLength="200000000"
maxStringContentLength="200000000"/>
</binding>
</basicHttpBinding>
</bindings>
And use the binding name in your endpoint configuration e.g.
...
bindingConfiguration="basicHttp"
...
The justification for the values is simple, they are sufficiently large to accommodate most messages. You can tune that number to fit your needs. The low default value is basically there to prevent DOS type attacks. Making it 20000000 would allow for a distributed DOS attack to be effective, the default size of 64k would require a very large number of clients to overpower most servers these days.
Add the following lines to your ~/.bash_profile
or ~/.zshrc
file(s).
export LC_CTYPE=C
export LANG=C
I found that this worked perfectly for me:
.jumbotron {
background-image: url(/img/Jumbotron.jpg);
background-size: cover;
height: 100%;}
You can resize your screen and it will always take up 100% of the window.
char *a = new char[10];
My question is that how can I get the length of a char *
It is very simply.:) It is enough to add only one statement
size_t N = 10;
char *a = new char[N];
Now you can get the size of the allocated array
std::cout << "The size is " << N << std::endl;
Many mentioned here C standard function std::strlen. But it does not return the actual size of a character array. It returns only the size of stored string literal.
The difference is the following. if to take your code snippet as an example
char a[] = "aaaaa";
int length = sizeof(a)/sizeof(char); // length=6
then std::strlen( a ) will return 5 instead of 6 as in your code.
So the conclusion is simple: if you need to dynamically allocate a character array consider usage of class std::string
. It has methof size and its synonym length that allows to get the size of the array at any time.
For example
std::string s( "aaaaa" );
std::cout << s.length() << std::endl;
or
std::string s;
s.resize( 10 );
std::cout << s.length() << std::endl;
setInterval(function()
{
$.ajax({
type:"post",
url:"myurl.html",
datatype:"html",
success:function(data)
{
//do something with response data
}
});
}, 10000);//time in milliseconds
I don't know on which Windows version it exists, but on Windows Vista and later this runs:
Function Is64Bit As Boolean
Dim x64 As Boolean = System.Environment.Is64BitOperatingSystem
If x64 Then
Return true
Else
Return false
End If
End Function
For Debian Jessie (which is the current default for the PHP image on Docker Hub):
apt-get install --yes zip unzip php-pclzip
You can omit the --yes, but it's useful when you're RUN-ing it in a Dockerfile.
Since you are the only user:
git reset --hard HEAD@{1}
git push -f
git reset --hard HEAD@{1}
( basically, go back one commit, force push to the repo, then go back again - remove the last step if you don't care about the commit )
Without doing any changes to your local repo, you can also do something like:
git push -f origin <sha_of_previous_commit>:master
Generally, in published repos, it is safer to do git revert
and then git push
Please use datatable if you want to get result from json object. Datatable also works in the same manner of converting the json result into table format with the facility of searchable and sortable columns automatically.
If you are creating a new table, you can use the inline shortcut:
def change
create_table :posts do |t|
t.string :title, null: false, index: { unique: true }
t.timestamps
end
end
This worked for me:
.ui-panelgrid td, .ui-panelgrid tr { border-style: none !important }
I use Pipes in Angular 2+ to filter arrays of objects. The following takes multiple filter arguments but you can send just one if that suits your needs. Here is a StackBlitz Example. It will find the keys you want to filter by and then filters by the value you supply. It's actually quite simple, if it sounds complicated it's not, check out the StackBlitz Example.
Here is the Pipe being called in an *ngFor directive,
<div *ngFor='let item of items | filtermulti: [{title:"mr"},{last:"jacobs"}]' >
Hello {{item.first}} !
</div>
Here is the Pipe,
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filtermulti'
})
export class FiltermultiPipe implements PipeTransform {
transform(myobjects: Array<object>, args?: Array<object>): any {
if (args && Array.isArray(myobjects)) {
// copy all objects of original array into new array of objects
var returnobjects = myobjects;
// args are the compare oprators provided in the *ngFor directive
args.forEach(function (filterobj) {
let filterkey = Object.keys(filterobj)[0];
let filtervalue = filterobj[filterkey];
myobjects.forEach(function (objectToFilter) {
if (objectToFilter[filterkey] != filtervalue && filtervalue != "") {
// object didn't match a filter value so remove it from array via filter
returnobjects = returnobjects.filter(obj => obj !== objectToFilter);
}
})
});
// return new array of objects to *ngFor directive
return returnobjects;
}
}
}
And here is the Component containing the object to filter,
import { Component } from '@angular/core';
import { FiltermultiPipe } from './pipes/filtermulti.pipe';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
items = [{ title: "mr", first: "john", last: "jones" }
,{ title: "mr", first: "adrian", last: "jacobs" }
,{ title: "mr", first: "lou", last: "jones" }
,{ title: "ms", first: "linda", last: "hamilton" }
];
}
GitHub Example: Fork a working copy of this example here
*Please note that in an answer provided by Gunter, Gunter states that arrays are no longer used as filter interfaces but I searched the link he provides and found nothing speaking to that claim. Also, the StackBlitz example provided shows this code working as intended in Angular 6.1.9. It will work in Angular 2+.
Happy Coding :-)
for mac :- take checkout from server side and a new window will open to select directory from your local machine than put your all code in selected folder then open svn local side and add and commit the project
Judging from the comments, you are looking for:
mongoose.mongo.BSONPure.ObjectID.isValid
Or
mongoose.Types.ObjectId.isValid
Have you tried Advanced Filter? Using your short list as the 'Criteria' and long list as the 'List Range'. Use the options: 'Filter in Place' and 'Unique Values'.
You should be presented with the list of unique values that only appear in your short list.
Alternatively, you can paste your Unique list to another location (on the same sheet), if you prefer. Choose the option 'Copy to another Location' and in the 'Copy to' box enter the cell reference (say F1) where you want the Unique list.
Note: this will work with the two columns (name/ID) too, if you select the two columns as both 'Criteria' and 'List Range'.
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate localDate = LocalDate.now();
System.out.println("Formatted Date: " + formatter.format(localDate));
Java 8 LocalDate
simply used the +
operator. Javascript concats strings with +
I have experienced the same problem as well. The reason was, that the functions.php
was configured wrongly.
I did the following to solve the problem:
style.css
page.On reloading my functions.php I found it was the culprit. I rewrote the php and it was fine.
Converting a range to a table as described in this answer:
Sub CreateTable() ActiveSheet.ListObjects.Add(xlSrcRange, Range("$B$1:$D$16"), , xlYes).Name = _ "Table1" 'No go in 2003 ActiveSheet.ListObjects("Table1").TableStyle = "TableStyleLight2" End Sub
You can also do it using netrw
The explore command opens up netrw in the directory of the open file
:E
Move the cursor over the file you want to rename:
R
Type in the new name, press enter, press y.
declare -a arr
echo "-------------------------------------"
echo "Here another example with arr numeric"
echo "-------------------------------------"
arr=( 10 200 3000 40000 500000 60 700 8000 90000 100000 )
echo -e "\n Elements in arr are:\n ${arr[0]} \n ${arr[1]} \n ${arr[2]} \n ${arr[3]} \n ${arr[4]} \n ${arr[5]} \n ${arr[6]} \n ${arr[7]} \n ${arr[8]} \n ${arr[9]}"
echo -e " \n Total elements in arr are : ${arr[*]} \n"
echo -e " \n Total lenght of arr is : ${#arr[@]} \n"
for (( i=0; i<10; i++ ))
do echo "The value in position $i for arr is [ ${arr[i]} ]"
done
for (( j=0; j<10; j++ ))
do echo "The length in element $j is ${#arr[j]}"
done
for z in "${!arr[@]}"
do echo "The key ID is $z"
done
~
const absolutePath = path.join(__dirname, some, dir);
vs.
const absolutePath = path.resolve(__dirname, some, dir);
path.join
will concatenate __dirname
which is the directory name of the current file concatenated with values of some
and dir
with platform-specific separator.
Whereas
path.resolve
will process __dirname
, some
and dir
i.e. from right to left prepending it by processing it.
If any of the values of some
or dir
corresponds to a root path then the previous path will be omitted and process rest by considering it as root
In order to better understand the concept let me explain both a little bit more detail as follows:-
The path.join
and path.resolve
are two different methods or functions of the path module provided by nodejs.
Where both accept a list of paths but the difference comes in the result i.e. how they process these paths.
path.join
concatenates all given path segments together using the platform-specific separator as a delimiter, then normalizes the resulting path. While the path.resolve()
process the sequence of paths from right to left, with each subsequent path prepended until an absolute path is constructed.
When no arguments supplied
The following example will help you to clearly understand both concepts:-
My filename is index.js
and the current working directory is E:\MyFolder\Pjtz\node
const path = require('path');
console.log("path.join() : ", path.join());
// outputs .
console.log("path.resolve() : ", path.resolve());
// outputs current directory or equivalent to __dirname
Result
? node index.js
path.join() : .
path.resolve() : E:\MyFolder\Pjtz\node
path.resolve()
method will output the absolute path whereas the path.join()
returns . representing the current working directory if nothing is provided
When some root path is passed as arguments
const path=require('path');
console.log("path.join() : " ,path.join('abc','/bcd'));
console.log("path.resolve() : ",path.resolve('abc','/bcd'));
Result i
? node index.js
path.join() : abc\bcd
path.resolve() : E:\bcd
path.join()
only concatenates the input list with platform-specific separator while the path.resolve()
process the sequence of paths from right to left, with each subsequent path prepended until an absolute path is constructed.
remote show
shows all the branches on the remote, including those that are not tracked locally and even those that have not yet been fetched.
git remote show <remote-name>
It also tries to show the status of the branches relative to your local repository:
> git remote show origin
* remote origin
Fetch URL: C:/git/.\remote_repo.git
Push URL: C:/git/.\remote_repo.git
HEAD branch: master
Remote branches:
branch_that_is_not_even_fetched new (next fetch will store in remotes/origin)
branch_that_is_not_tracked tracked
branch_that_is_tracked tracked
master tracked
Local branches configured for 'git pull':
branch_that_is_tracked merges with remote branch_that_is_tracked
master merges with remote master
Local refs configured for 'git push':
branch_that_is_tracked pushes to branch_that_is_tracked (fast-forwardable)
master pushes to master (up to date)
In perl, for an input of 1 (A), 27 (AA), etc.
sub excel_colname {
my ($idx) = @_; # one-based column number
--$idx; # zero-based column index
my $name = "";
while ($idx >= 0) {
$name .= chr(ord("A") + ($idx % 26));
$idx = int($idx / 26) - 1;
}
return scalar reverse $name;
}
Updated Answer There is no convenient way to do this using Dynamo DB Queries with predictable throughput. One (sub optimal) option is to use a GSI with an artificial HashKey & CreatedAt. Then query by HashKey alone and mention ScanIndexForward to order the results. If you can come up with a natural HashKey (say the category of the item etc) then this method is a winner. On the other hand, if you keep the same HashKey for all items, then it will affect the throughput mostly when when your data set grows beyond 10GB (one partition)
Original Answer: You can do this now in DynamoDB by using GSI. Make the "CreatedAt" field as a GSI and issue queries like (GT some_date). Store the date as a number (msecs since epoch) for this kind of queries.
Details are available here: Global Secondary Indexes - Amazon DynamoDB : http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html#GSI.Using
This is a very powerful feature. Be aware that the query is limited to (EQ | LE | LT | GE | GT | BEGINS_WITH | BETWEEN) Condition - Amazon DynamoDB : http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Condition.html
Define it in your init file and call by M-x reload-user-init-file
(defun reload-user-init-file()
(interactive)
(load-file user-init-file))
If you want to remove the file from the remote repo, first remove it from your project with --cache option and then push it:
git rm --cache /path/to/file
git commit -am "Remove file"
git push
(This works even if the file was added to the remote repo some commits ago) Remember to add to .gitignore the file extensions that you don't want to push.
Your empList
is object type but you are trying to push strings
Try this
this.empList.push({this.name,this.empoloyeeID});
You need to add assembly redirects:
<configuration>
....
<runtime>
<assemblyBinding>
<dependentAssembly>
<assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.5.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
...
</configuration>
Most likely you have to do this for a few more assemblies like webhosting, etc.
There is actually a media query for that:
@media (hover: none) { … }
Apart from Firefox, it's fairly well supported. Safari and Chrome being the most common browsers on mobile devices, it might suffice untill greater adoption.
You can use the following one-liner to always ask the user before leaving the page.
window.onbeforeunload = s => "";
To ask the user when something on the page has been modified, see this answer.
Short and simple
import os
directory_path = '/home/xyz/'
No_of_files = len(os.listdir(directory_path))
Use format string
intNum = 123
print "0x%x"%(intNum)
or hex
function.
intNum = 123
print hex(intNum)
Here is a version of B. Clay Shannon's code not static for excel-files:
class ExcelSearcher
{
private List<string> _fileNames;
public ExcelSearcher(List<string> filenames)
{
_fileNames = filenames;
}
public List<string> GetExcelFiles(string dir, List<string> filenames = null)
{
string dirName = dir;
var dirNames = new List<string>();
if (filenames != null)
{
_fileNames.Concat(filenames);
}
try
{
foreach (string f in Directory.GetFiles(dirName))
{
if (f.ToLower().EndsWith(".xls") || f.ToLower().EndsWith(".xlsx"))
{
_fileNames.Add(f);
}
}
dirNames = Directory.GetDirectories(dirName).ToList();
foreach (string d in dirNames)
{
GetExcelFiles(d, _fileNames);
}
}
catch (Exception ex)
{
//Bam
}
return _fileNames;
}
Updated to work with MarkerClustererPlus.
google.maps.event.trigger(mc, "click", cClusterIcon.cluster_);
google.maps.event.trigger(mc, "clusterclick", cClusterIcon.cluster_); // deprecated name
// BEGIN MODIFICATION
var zoom = mc.getMap().getZoom();
// Trying to pull this dynamically made the more zoomed in clusters not render
// when then kind of made this useless. -NNC @ BNB
// var maxZoom = mc.getMaxZoom();
var maxZoom = 15;
// if we have reached the maxZoom and there is more than 1 marker in this cluster
// use our onClick method to popup a list of options
if (zoom >= maxZoom && cClusterIcon.cluster_.markers_.length > 1) {
var markers = cClusterIcon.cluster_.markers_;
var a = 360.0 / markers.length;
for (var i=0; i < markers.length; i++)
{
var pos = markers[i].getPosition();
var newLat = pos.lat() + -.00004 * Math.cos((+a*i) / 180 * Math.PI); // x
var newLng = pos.lng() + -.00004 * Math.sin((+a*i) / 180 * Math.PI); // Y
var finalLatLng = new google.maps.LatLng(newLat,newLng);
markers[i].setPosition(finalLatLng);
markers[i].setMap(cClusterIcon.cluster_.map_);
}
cClusterIcon.hide();
return ;
}
// END MODIFICATION
Question Iam coming from was marked as [duplicate] to this question but I havent seen the answer i needed here.
adb server version (41) doesn't match this client (36); killing... ADB server didn't ACK.
Look at this: https://stackoverflow.com/a/47797366/8187578
Another method that has not been mentioned yet is std::vector
.
std::vector<std::string> line;
while(file >> mystr)
{
line.push_back(mystr);
}
Then you can simply iterate over the vector and modify/extract what you need/
This code works:
$(".ui-button-text").live(
'hover',
function (ev) {
if (ev.type == 'mouseover') {
$(this).addClass("ui-state-hover");
}
if (ev.type == 'mouseout') {
$(this).removeClass("ui-state-hover");
}
});
I think some background backup solutions like Google Backup and Sync block access to the index file. I closed the application and Sourcetree had no issues at all. Seems that Dropbox does the same (@tonymayoral).
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class ErrorDialog {
public static void main(String argv[]) {
String message = "\"The Comedy of Errors\"\n"
+ "is considered by many scholars to be\n"
+ "the first play Shakespeare wrote";
JOptionPane.showMessageDialog(new JFrame(), message, "Dialog",
JOptionPane.ERROR_MESSAGE);
}
}
You can use split(" ")
method of the String
class and can get each word as code given below:
String s = "I want to walk my dog";
String []strArray=s.split(" ");
for(int i=0; i<strArray.length;i++) {
System.out.println(strArray[i]);
}
First, change your directory:
cd your_project name
Then run:
python manage.py runserver
This sounds like a ClassLoader conflict. I'd bet you have the javax.persistence api 1.x on the classpath somewhere, whereas Spring is trying to access ValidationMode
, which was only introduced in JPA 2.0.
Since you use Maven, do mvn dependency:tree
, find the artifact:
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
And remove it from your setup. (See Excluding Dependencies)
AFAIK there is no such general distribution for JPA 2, but you can use this Hibernate-specific version:
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
OK, since that doesn't work, you still seem to have some JPA-1 version in there somewhere. In a test method, add this code:
System.out.println(EntityManager.class.getProtectionDomain()
.getCodeSource()
.getLocation());
See where that points you and get rid of that artifact.
Ahh, now I finally see the problem. Get rid of this:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jpa</artifactId>
<version>2.0.8</version>
</dependency>
and replace it with
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
On a different note, you should set all test libraries (spring-test, easymock etc.) to
<scope>test</scope>
Two native solutions
performance.now
--> Call to ... took 6.414999981643632
milliseconds.console.time
--> Call to ... took 5.815
millisecondsThe difference between both is precision.
For usage and explanation read on.
Performance.now
(For microsecond precision use)
var t0 = performance.now();
doSomething();
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
function doSomething(){
for(i=0;i<1000000;i++){var x = i*i;}
}
_x000D_
Unlike other timing data available to JavaScript (for example Date.now), the timestamps returned by Performance.now() are not limited to one-millisecond resolution. Instead, they represent times as floating-point numbers with up to microsecond precision.
Also unlike Date.now(), the values returned by Performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like NTP). Otherwise, performance.timing.navigationStart + performance.now() will be approximately equal to Date.now().
console.time
Example: (timeEnd
wrapped in setTimeout
for simulation)
console.time('Search page');
doSomething();
console.timeEnd('Search page');
function doSomething(){
for(i=0;i<1000000;i++){var x = i*i;}
}
_x000D_
You can change the Timer-Name for different operations.
Be nice if there was a Javascript API version. That way can integrate w/ other AJAX apps or browser extensions/gadgets/widgets.
Right now, current APIs restrict to web app technologies that support Java, .NET, or Python, more for server side, unless may use Google Web Toolkit to translate Java code to Javascript.
Array.filter is not implemented in many browsers,It is better to define this function if it does not exist.
The source code for Array.prototype is posted in MDN
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisp */)
{
"use strict";
if (this == null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var res = [];
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in t)
{
var val = t[i]; // in case fun mutates this
if (fun.call(thisp, val, i, t))
res.push(val);
}
}
return res;
};
}
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter for more details
Don't forget to take into consideration the global flag in your regexp :
var reg = /abc/g;
!!'abcdefghi'.match(reg); // => true
!!'abcdefghi'.match(reg); // => true
reg.test('abcdefghi'); // => true
reg.test('abcdefghi'); // => false <=
This is because Regexp keeps track of the lastIndex when a new match is found.
Here is a list of all http-headers: http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
And here is a list of all apache-logformats: http://httpd.apache.org/docs/2.0/mod/mod_log_config.html#formats
As you did write correctly, the code for logging a specific header is %{foobar}i where foobar is the name of the header. So, the only solution is to create a specific format string. When you expect a non-standard header like x-my-nonstandard-header, then use %{x-my-nonstandard-header}i
. If your server is going to ignore this non-standard-header, why should you want to write it to your logfile? An unknown header has absolutely no effect to your system.
First Step:-
Select Project Target -> Build Setting -> Search('Define') -> Define Module update value No to Yes
"Defines Module": YES.
"Always Embed Swift Standard Libraries" : YES.
"Install Objective-C Compatibility Header" : YES.
Second Step:-
Add Swift file Class in Objective C ".h" File as below
#import <UIKit/UIKit.h>
@class TestViewController(Swift File);
@interface TestViewController(Objective C File) : UIViewController
@end
Import 'ProjectName(Your Project Name)-Swift.h' in Objective C ".m" file
//TestViewController.m
#import "TestViewController.h"
/*import ProjectName-Swift.h file to access Swift file here*/
#import "ProjectName-Swift.h"
Which SQL was not specified, SQL 2005 / 2008
SELECT yourfields from yourTable WHERE yourfieldWithDate > dateadd(dd,-1,getdate())
If you are on the 2008 increased accuracy date types, then use the new sysdatetime() function instead, equally if using UTC times internally swap to the UTC calls.
try
.insertAfter()
here
$(content).insertAfter('#bla');
If you don't wish to use 3rd party classes then the following is how you set the post body...
NSURL *aUrl = [NSURL URLWithString:@"http://www.apple.com/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
NSString *postString = @"company=Locassa&quality=AWESOME!";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request
delegate:self];
Simply append your key/value pair to the post string
In RunCommand
write "MSINFO32"
and hit enter
It will show All information related to system
dataString = [];
$.ajax({
type: "POST",
url: "script.php",
data:{data: $(dataString).serializeArray()},
cache: false,
success: function(){
alert("OK");
}
});
My version
$ sqlplus -s username/password@host:port/service <<< "select 1 from dual;"
1
----------
1
EDIT:
For multiline you can use this
$ echo -e "select 1 from dual; \n select 2 from dual;" | sqlplus -s username/password@host:port/service
1
----------
1
2
----------
2
There is nothing wrong in concatenating two strings with +
. Indeed it's easier to read than ''.join([a, b])
.
You are right though that concatenating more than 2 strings with +
is an O(n^2) operation (compared to O(n) for join
) and thus becomes inefficient. However this has not to do with using a loop. Even a + b + c + ...
is O(n^2), the reason being that each concatenation produces a new string.
CPython2.4 and above try to mitigate that, but it's still advisable to use join
when concatenating more than 2 strings.
python -c 'import os; print (os.path.getsize("... filename ..."))'
portable, all flavours of python, avoids variation in stat dialects
if you want to access table cell
WebElement thirdCell = driver.findElement(By.Xpath("//table/tbody/tr[2]/td[1]"));
If you want to access nested table cell -
WebElement thirdCell = driver.findElement(By.Xpath("//table/tbody/tr[2]/td[2]"+//table/tbody/tr[1]/td[2]));
For more details visit this Tutorial
If you aren't worried about generating the extra elements using the split then filter could handle the issue you mention of the trailing slash (Assuming you have browser support for filter).
url.split('/').filter(function (s) { return !!s }).pop()
A referral is sent by an AD server when it doesn't have the information requested itself, but know that another server have the info. It usually appears in trust environment where a DC can refer to a DC in trusted domain.
In your case you are only specifying a domain, relying on automatic lookup of what domain controller to use. I think that you should try to find out what domain controller is used for the query and look if that one really holds the requested information.
If you provide more information on your AD setup, including any trusts/subdomains, global catalogues and the DNS resource records for the domain controllers it will be easier to help you.
You need to fill the value for Website with Facebook Login with the value http://localhost/OfferDrive/
to allow Facebook to authenticate that the requests from JavaScript SDK are coming from right place
mixin gives a way to add functionality in a class, i.e you can interact with methods defined in a module by including the module inside the desired class. Though ruby doesn't supports multiple inheritance but provides mixin as an alternative to achieve that.
here is an example that explains how multiple inheritance is achieved using mixin.
module A # you create a module
def a1 # lets have a method 'a1' in it
end
def a2 # Another method 'a2'
end
end
module B # let's say we have another module
def b1 # A method 'b1'
end
def b2 #another method b2
end
end
class Sample # we create a class 'Sample'
include A # including module 'A' in the class 'Sample' (mixin)
include B # including module B as well
def S1 #class 'Sample' contains a method 's1'
end
end
samp = Sample.new # creating an instance object 'samp'
# we can access methods from module A and B in our class(power of mixin)
samp.a1 # accessing method 'a1' from module A
samp.a2 # accessing method 'a2' from module A
samp.b1 # accessing method 'b1' from module B
samp.b2 # accessing method 'a2' from module B
samp.s1 # accessing method 's1' inside the class Sample
You could just define a new xml background in the drawables folder
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="enter_your_desired_color_here" />
<corners android:radius="enter_your_desired_radius_the_corners" />
</shape>
After this just include it in your TextView or EditText by defining it in the background.
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="80dp"
android:background="YOUR_FILE_HERE"
Android:layout_weight="1"
android:gravity="center"
android:text="TEXT_HERE"
android:textSize="40sp" />
Split the string in to string array and write using above method (I assume your text contains \n to get new line)
String[] test = test.split("\n");
and the inside a loop
bufferedWriter.write(test[i]);
bufferedWriter.newline();
If you upgrade to numpy 1.7 (where datetime is still labeled as experimental) the following should work.
dates/np.timedelta64(1,'Y')
What I do in my projects is to activate the following option in the "Constant conditions & exceptions" code inspection:
Suggest @Nullable annotation for methods that may possibly return null and report nullable values passed to non-annotated parameters
When activated, all non-annotated parameters will be treated as non-null and thus you will also see a warning on your indirect call:
clazz.indirectPathToA(null);
For even stronger checks the Checker Framework may be a good choice (see this nice tutorial.
Note: I have not used that yet and there may be problems with the Jack compiler: see this bugreport
self.tableView.tableHeaderView = segmentedControl;
If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.
use this for target path for uploading
<?php
$file_name = $_FILES["csvFile"]["name"];
$target_path = $dir = plugin_dir_path( __FILE__ )."\\upload\\". $file_name;
echo $target_path;
move_uploaded_file($_FILES["csvFile"]["tmp_name"],$target_path. $file_name);
?>
To use offline Java API Documentation in Eclipse, you need to download it first. The link for Java docs are (last updated on 2013-10-21):
Java 6
Page: http://www.oracle.com/technetwork/java/javase/downloads/jdk-6u25-doc-download-355137.html
Direct: http://download.oracle.com/otn-pub/java/jdk/6u30-b12/jdk-6u30-apidocs.zip
Java 7
Page: http://www.oracle.com/technetwork/java/javase/documentation/java-se-7-doc-download-435117.html
Java 8
Page: http://www.oracle.com/technetwork/java/javase/documentation/jdk8-doc-downloads-2133158.html
Java 9
Page:http://www.oracle.com/technetwork/java/javase/documentation/jdk9-doc-downloads-3850606.html
Window --> Preferences --> Java --> "Installed JREs"
select available JRE (jre6: C:\Program Files (x86)\Java\jre6 for instance) and click Edit.It must work as it works for me. I don't need Internet connection to view Java API Documentation in Eclipse anymore.
Additionally, if you have the NDK installed, you can also find the listing in ${ndk_path}platforms\android-${api}\${architecture}\usr\include\android\keycodes.h
.
I'm only mentioning it because I've found it simpler to navigate and read than the KeyEvent class or docs.
All current solutions are too coupled to the logging configuration by using a handler. My solution has the following architecture and features:
multiprocessing.Queue
logging.Logger
(and already defined instances) are patched to send all records to the queueCode with usage example and output can be found at the following Gist: https://gist.github.com/schlamar/7003737
It's overly-complicated and ugly but in my opinion this is the way to go:
$fp = fopen("php://memory", 'r+');
fputs($fp, $data);
rewind($fp);
while($line = fgets($fp)){
// deal with $line
}
fclose($fp);
#!/usr/bin/perl
$sub = "\\1";
$str = "hi1234";
$res = $str;
$match = "hi(.*)";
$res =~ s/$match/$1/g;
print $res
This got me the '1234'.
In addition to the answers above you can pass in command line parameters to the mysqld process for logging options instead of manually editing your conf file. For example, to enable general logging and specifiy a file:
mysqld --general-log --general-log-file=/var/log/mysql.general.log
Confirming other answers above, mysqld --help --verbose
gives you the values from the conf file (so running with command line options general-log is FALSE); whereas mysql -se "SHOW VARIABLES" | grep -e log_error -e general_log
gives:
general_log ON
general_log_file /var/log/mysql.general.log
Use slightly more compact syntax for the error log:
mysqld --general-log --general-log-file=/var/log/mysql.general.log --log-error=/var/log/mysql.error.log
For me the with NPP V7.6.6 (x64) this worked:
Download the plugin, and unzip to some local folder (e.g. Downloads). Make sure you download the correct plugin for your Notepad++ (64 or 32 bit - e.g. see ? -> About Notepad++ to find if you are 64-bit)
Check each DLL to ensure it is unblocked (right-click, Properties, and check/select Unblock.
Run Notepad++. If you have UAC enabled, use "Run as Administrator" to run Notepad++ (Hold Shift key down, right-click Notepad++ icon, and select "Run as Administrator").
Go to menu Settings -> Import -> Import plugins...
Use dialog displayed to locate you local copy of the plugin DLL.
Once plugin DLL has been selected, Notepad++ should tell you you need to restart. If it doesn't, then Notepad++ has had some problem - though it doesn't tell you what...!
Restart Notepad++.
The above causes a copy of the plugin DLL to be copied under a subfolder of the same name in C:\Program Files\Notepad++\plugins.
Putting plugins directly into one of the following folders (or sub-folders for each plugin), as suggested in other answers, did not work for me:
a) %PROGRAMDATA%\Notepad++\plugins. b) %ALLDATA%\Notepad++\plugins.
f = lambda A, n=3: [A[i:i+n] for i in range(0, len(A), n)]
f(A)
n
- the predefined length of result arrays
public static void main(String[] args)
{
Date d = new Date();
SimpleDateFormat form = new SimpleDateFormat("dd-mm-yyyy hh:mm:ss");
System.out.println(form.format(d));
String str = form.format(d); // or if you want to save it in String str
System.out.println(str); // and print after that
}
Just create your own action.
namespace WpfUtil
{
using System.Reflection;
using System.Windows;
using System.Windows.Interactivity;
/// <summary>
/// Sets the designated property to the supplied value. TargetObject
/// optionally designates the object on which to set the property. If
/// TargetObject is not supplied then the property is set on the object
/// to which the trigger is attached.
/// </summary>
public class SetPropertyAction : TriggerAction<FrameworkElement>
{
// PropertyName DependencyProperty.
/// <summary>
/// The property to be executed in response to the trigger.
/// </summary>
public string PropertyName
{
get { return (string)GetValue(PropertyNameProperty); }
set { SetValue(PropertyNameProperty, value); }
}
public static readonly DependencyProperty PropertyNameProperty
= DependencyProperty.Register("PropertyName", typeof(string),
typeof(SetPropertyAction));
// PropertyValue DependencyProperty.
/// <summary>
/// The value to set the property to.
/// </summary>
public object PropertyValue
{
get { return GetValue(PropertyValueProperty); }
set { SetValue(PropertyValueProperty, value); }
}
public static readonly DependencyProperty PropertyValueProperty
= DependencyProperty.Register("PropertyValue", typeof(object),
typeof(SetPropertyAction));
// TargetObject DependencyProperty.
/// <summary>
/// Specifies the object upon which to set the property.
/// </summary>
public object TargetObject
{
get { return GetValue(TargetObjectProperty); }
set { SetValue(TargetObjectProperty, value); }
}
public static readonly DependencyProperty TargetObjectProperty
= DependencyProperty.Register("TargetObject", typeof(object),
typeof(SetPropertyAction));
// Private Implementation.
protected override void Invoke(object parameter)
{
object target = TargetObject ?? AssociatedObject;
PropertyInfo propertyInfo = target.GetType().GetProperty(
PropertyName,
BindingFlags.Instance|BindingFlags.Public
|BindingFlags.NonPublic|BindingFlags.InvokeMethod);
propertyInfo.SetValue(target, PropertyValue);
}
}
}
In this case I'm binding to a property called DialogResult on my viewmodel.
<Grid>
<Button>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<wpf:SetPropertyAction PropertyName="DialogResult" TargetObject="{Binding}"
PropertyValue="{x:Static mvvm:DialogResult.Cancel}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
Cancel
</Button>
</Grid>
This worked for me:
<a onClick={this.openPopupbox} style={{cursor: 'pointer'}}>
going along with @binz-nakama, here's an update on his jsfiddle with a very small amount of javascript. also incoporates this very good article on css navigation
Array.from(document.querySelectorAll("a"))
.map(x => x.addEventListener("click",
function(e){
Array.from(document.querySelectorAll("a"))
.map(x => x.classList.remove("active"));
e.target.classList.add("active");
}
));
EDIT:
The gcc guys really improved the diagnosis experience in gcc (ah competition). They created a wiki page to showcase it here. gcc 4.8 now has quite good diagnostics as well (gcc 4.9x added color support). Clang is still in the lead, but the gap is closing.
Original:
For students, I would unconditionally recommend Clang.
The performance in terms of generated code between gcc and Clang is now unclear (though I think that gcc 4.7 still has the lead, I haven't seen conclusive benchmarks yet), but for students to learn it does not really matter anyway.
On the other hand, Clang's extremely clear diagnostics are definitely easier for beginners to interpret.
Consider this simple snippet:
#include <string>
#include <iostream>
struct Student {
std::string surname;
std::string givenname;
}
std::ostream& operator<<(std::ostream& out, Student const& s) {
return out << "{" << s.surname << ", " << s.givenname << "}";
}
int main() {
Student me = { "Doe", "John" };
std::cout << me << "\n";
}
You'll notice right away that the semi-colon is missing after the definition of the Student
class, right :) ?
Well, gcc notices it too, after a fashion:
prog.cpp:9: error: expected initializer before ‘&’ token
prog.cpp: In function ‘int main()’:
prog.cpp:15: error: no match for ‘operator<<’ in ‘std::cout << me’
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:112: note: candidates are: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ostream<_CharT, _Traits>& (*)(std::basic_ostream<_CharT, _Traits>&)) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:121: note: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ios<_CharT, _Traits>& (*)(std::basic_ios<_CharT, _Traits>&)) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:131: note: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::ios_base& (*)(std::ios_base&)) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:169: note: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:173: note: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long unsigned int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:177: note: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(bool) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/ostream.tcc:97: note: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(short int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:184: note: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(short unsigned int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/ostream.tcc:111: note: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:195: note: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(unsigned int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:204: note: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long long int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:208: note: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long long unsigned int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:213: note: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(double) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:217: note: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(float) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:225: note: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long double) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:229: note: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(const void*) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/ostream.tcc:125: note: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_streambuf<_CharT, _Traits>*) [with _CharT = char, _Traits = std::char_traits<char>]
And Clang is not exactly starring here either, but still:
/tmp/webcompile/_25327_1.cc:9:6: error: redefinition of 'ostream' as different kind of symbol
std::ostream& operator<<(std::ostream& out, Student const& s) {
^
In file included from /tmp/webcompile/_25327_1.cc:1:
In file included from /usr/include/c++/4.3/string:49:
In file included from /usr/include/c++/4.3/bits/localefwd.h:47:
/usr/include/c++/4.3/iosfwd:134:33: note: previous definition is here
typedef basic_ostream<char> ostream; ///< @isiosfwd
^
/tmp/webcompile/_25327_1.cc:9:13: error: expected ';' after top level declarator
std::ostream& operator<<(std::ostream& out, Student const& s) {
^
;
2 errors generated.
I purposefully choose an example which triggers an unclear error message (coming from an ambiguity in the grammar) rather than the typical "Oh my god Clang read my mind" examples. Still, we notice that Clang avoids the flood of errors. No need to scare students away.
A = zeros(20, 10, 3); %# Creates a 20x10x3 matrix
B = zeros(4,4);
C = zeros(size(B,1), size(B,2), 4); %# New matrix with B's size, and 3rd dimension of size 4
C(:,:,1) = B; %# Copy the content of B into C's first set of values
zeros is just one way of making a new matrix. Another could be A(1:20,1:10,1:3) = 0
for a 3D matrix. To confirm the size of your matrices you can run: size(A)
which gives 20 10 3
.
There is no explicit bound on the number of dimensions a matrix may have.
If you need a free and simple API for converting one currency to another, try free.currencyconverterapi.com.
Disclaimer, I'm the author of the website and I use it for one of my other websites.
The service is free to use even for commercial applications but offers no warranty. For performance reasons, the values are only updated every hour.
A sample conversion URL is: http://free.currencyconverterapi.com/api/v6/convert?q=EUR_PHP&compact=ultra&apiKey=sample-api-key which will return a json-formatted value, e.g. {"EUR_PHP":60.849184}
Another way is download and unzip chromedriver and put 'chromedriver.exe' in C:\Python27\Scripts and then you need not to provide the path of driver, just
driver= webdriver.Chrome()
will work
Do you mean altering the table after it has been created? If so you need to use alter table, in particular:
ALTER TABLE tablename MODIFY COLUMN new-column-definition
e.g.
ALTER TABLE test MODIFY COLUMN locationExpect VARCHAR(120);
Outsource it to the battle tested requests library.
This is how I will do it:
from requests.models import PreparedRequest
url = 'http://example.com/search?q=question'
params = {'lang':'en','tag':'python'}
req = PreparedRequest()
req.prepare_url(url, params)
print(req.url)
You may use a local variable, like:
float[] values = new float[3];
float[] v = {0.1f, 0.2f, 0.3f};
float[] values = v;
In case you just need to remove the duplicates using only ArrayList, no other Collection classes, then:-
//list is the original arraylist containing the duplicates as well
List<String> uniqueList = new ArrayList<String>();
for(int i=0;i<list.size();i++) {
if(!uniqueList.contains(list.get(i)))
uniqueList.add(list.get(i));
}
Hope this helps!
I don't know if it's possible to run it just like that.
I usually first copy it with scp and then log in to run it.
scp foo.sh user@host:~
ssh user@host
./foo.sh
I generally use Date if possible. Although it is mutable, the mutators are actually deprecated. In the end it basically wraps a long that would represent the date/time. Conversely, I would use Calendars if I have to manipulate the values.
You can think of it this way: you only use StringBuffer only when you need to have Strings that you can easily manipulate and then convert them into Strings using toString() method. In the same way, I only use Calendar if I need to manipulate temporal data.
For best practice, I tend to use immutable objects as much as possible outside of the domain model. It significantly reduces the chances of any side effects and it is done for you by the compiler, rather than a JUnit test. You use this technique by creating private final fields in your class.
And coming back to the StringBuffer analogy. Here is some code that shows you how to convert between Calendar and Date
String s = "someString"; // immutable string
StringBuffer buf = new StringBuffer(s); // mutable "string" via StringBuffer
buf.append("x");
assertEquals("someStringx", buf.toString()); // convert to immutable String
// immutable date with hard coded format. If you are hard
// coding the format, best practice is to hard code the locale
// of the format string, otherwise people in some parts of Europe
// are going to be mad at you.
Date date = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse("2001-01-02");
// Convert Date to a Calendar
Calendar cal = Calendar.getInstance();
cal.setTime(date);
// mutate the value
cal.add(Calendar.YEAR, 1);
// convert back to Date
Date newDate = cal.getTime();
//
assertEquals(new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse("2002-01-02"), newDate);
Character only takes one value dude! like: char y = 'h'; and maybe you typed like char y = 'hello'; or smthg. good luck. for the question asked above the answer is pretty simple u have to use DOUBLE QUOTES to give a string value. easy enough;)
I wouldn't want any public site that I developed to depend on any external site, and thus, I'd host jQuery myself.
Are you willing to have an outage on your site when the other (Google, jquery.com, etc.) goes down? Less dependencies is the key.
You can even use FileOutputStream
to get what you need. This is how it can be done,
File file = new File(Environment.getExternalStorageDirectory(), "abc.txt");
FileOutputStream fOut = new FileOutputStream(file, true);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write("whatever you need to write");
osw.flush();
osw.close();
Came across a scenario with remote sorting of data store in EXTJS 4.X where the string is sent to the server as a JSON array (of only 1 object).
Similar approach to what is presented previously for a simple string, just need conversion to JsonArray first prior to JsonObject.
String from client: [{"property":"COLUMN_NAME","direction":"ASC"}]
String jsonIn = "[{\"property\":\"COLUMN_NAME\",\"direction\":\"ASC\"}]";
JsonArray o = (JsonArray)new JsonParser().parse(jsonIn);
String sortColumn = o.get(0).getAsJsonObject().get("property").getAsString());
String sortDirection = o.get(0).getAsJsonObject().get("direction").getAsString());
Two possible situations :
Your company uses a proxy to connect to the public Maven repository. Then ask someone in your company what the IP address of the proxy is then put it in your settings.xml file
Your company has its/their own Maven repository/ies (Nexus repository for example). Then ask someone in your company what the Nexus repository is then put it in your pom.xml or in your settings.xml. See Adding maven nexus repo to my pom.xml and https://maven.apache.org/guides/mini/guide-multiple-repositories.html
In sublime text, you simply write the two word you are interested in keeping for example in your case it is
"This is" and "sentence"
and you write .* in between
i.e. This is .* sentence
and this should do you well
SELECT id,
Group_concat(column
)
FROM (SELECT id,
Concat(name
, ':', Group_concat(value
)) AS column
FROM mytbl
GROUP BY id,
name) tbl
GROUP BY id;
In Addition you also need to be sure that you have
<context:annotation-config/>
in your SPring configuration xml.
I also would recommend you to read this blog post. It helped me alot. Spring blog - Ajax Simplifications in Spring 3.0
Update:
just checked my working code where I have @RequestBody
working correctly.
I also have this bean in my config:
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter"/>
</list>
</property>
</bean>
May be it would be nice to see what Log4j
is saying. it usually gives more information and from my experience the @RequestBody
will fail if your request's content type is not Application/JSON
. You can run Fiddler 2 to test it, or even Mozilla Live HTTP headers plugin can help.
When moving the thumb with an EditText, the Vertical Seekbar setProgress may not work. The following code can help:
@Override
public synchronized void setProgress(int progress) {
super.setProgress(progress);
updateThumb();
}
private void updateThumb() {
onSizeChanged(getWidth(), getHeight(), 0, 0);
}
This snippet code found here: https://stackoverflow.com/a/33064140/2447726
Map
is an interface; HashMap
is a particular implementation of that interface.
HashMap uses a collection of hashed key values to do its lookup. TreeMap will use a red-black tree as its underlying data store.
Just use the Date
property:
var today = DateTime.Today;
var q = db.Games.Where(t => t.StartDate.Date >= today)
.OrderBy(t => t.StartDate);
Note that I've explicitly evaluated DateTime.Today
once so that the query is consistent - otherwise each time the query is executed, and even within the execution, Today
could change, so you'd get inconsistent results. For example, suppose you had data of:
Entry 1: March 8th, 8am
Entry 2: March 10th, 10pm
Entry 3: March 8th, 5am
Entry 4: March 9th, 8pm
Surely either both entries 1 and 3 should be in the results, or neither of them should... but if you evaluate DateTime.Today
and it changes to March 9th after it's performed the first two checks, you could end up with entries 1, 2, 4.
Of course, using DateTime.Today
assumes you're interested in the date in the local time zone. That may not be appropriate, and you should make absolutely sure you know what you mean. You may want to use DateTime.UtcNow.Date
instead, for example. Unfortunately, DateTime
is a slippery beast...
EDIT: You may also want to get rid of the calls to DateTime
static properties altogether - they make the code hard to unit test. In Noda Time we have an interface specifically for this purpose (IClock
) which we'd expect to be injected appropriately. There's a "system time" implementation for production and a "stub" implementation for testing, or you can implement it yourself.
You can use the same idea without using Noda Time, of course. To unit test this particular piece of code you may want to pass the date in, but you'll be getting it from somewhere - and injecting a clock means you can test all the code.
you can remove last comma:
var sentence = "I got,. commas, here,";
sentence = sentence.replace(/(.+),$/, '$1');
console.log(sentence);
Using your code with some random data, this would work:
fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)
axs = axs.ravel()
for i in range(10):
axs[i].contourf(np.random.rand(10,10),5,cmap=plt.cm.Oranges)
axs[i].set_title(str(250+i))
The layout is off course a bit messy, but that's because of your current settings (the figsize, wspace etc).
select any row in the file (in the example below, it's the 2nd row) and count the number of columns, where the delimiter is a space:
sed -n 2p text_file.dat | tr ' ' '\n' | wc -l
you can also use pgrep
, in prgep
you can also give pattern for match
import subprocess
child = subprocess.Popen(['pgrep','program_name'], stdout=subprocess.PIPE, shell=True)
result = child.communicate()[0]
you can also use awk
with ps like this
ps aux | awk '/name/{print $2}'
This question is old, but I'm surprised why no one mentioned boost::format
:
cout << (boost::format("%x") % 1234).str(); // output is: 4d2
After years of using XAMPP finally I've given up, and started looking for alternatives. XAMPP has not received any updates for quite a while and it kept breaking down once every two weeks.
The one I've just found and I could absolutely recommend is The Uniform Server
It's really frequently updated, has much more emphasis on security and looks like a much more mature project compared to XAMPP.
They have a wiki where they list all the latest versions of packages. As the time of writing, their newest release is only 4 days old!
Versions in Uniform Server as of today:
Versions in XAMPP as of today:
Additionally a simpler example:
return (T)Activator.CreateInstance(typeof(T), new object[] { weight });
Note that using the new() constraint on T is only to make the compiler check for a public parameterless constructor at compile time, the actual code used to create the type is the Activator class.
You will need to ensure yourself regarding the specific constructor existing, and this kind of requirement may be a code smell (or rather something you should just try to avoid in the current version on c#).
use DateTime object obj.Add to add what ever you want day hour and etc. Hope this works:)
use sep='\s*,\s*'
so that you will take care of spaces in column-names:
transactions = pd.read_csv('transactions.csv', sep=r'\s*,\s*',
header=0, encoding='ascii', engine='python')
alternatively you can make sure that you don't have unquoted spaces in your CSV file and use your command (unchanged)
prove:
print(transactions.columns.tolist())
Output:
['product_id', 'customer_id', 'store_id', 'promotion_id', 'month_of_year', 'quarter', 'the_year', 'store_sales', 'store_cost', 'unit_sales', 'fact_count']
$(':checkbox').change(function(){
$('#delete').removeAttr('hidden');
});
Note, thanks to tip by A.Wolff
, you should use removeAttr
instead of setting to false. When set to false, the element will still be hidden. Therefore, removing is more effective.
To create a read-only user, you have to setup a different user than the one owning the tables you want to access.
If you just create the user and grant SELECT permission to the read-only user, you'll need to prepend the schema name to each table name. To avoid this, you have basically two options:
ALTER SESSION SET CURRENT_SCHEMA=XYZ
CREATE SYNONYM READER_USER.TABLE1 FOR XYZ.TABLE1
So if you haven't been told the name of the owner schema, you basically have three options. The last one should always work:
SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL
SELECT * FROM ALL_SYNONYMS WHERE OWNER = USER
SELECT * FROM ALL_TABLES WHERE OWNER NOT IN ('SYS', 'SYSTEM', 'CTXSYS', 'MDSYS');
Im working with ionicframework and solution provided by @Mumthezir is almost perfect. In case if somebody would have same problem as me(after change, input is still focused and when scrolling, value simply dissapears) So I added onchange to make input.blur()
<input placeholder="Date" class="textbox-n" type="text" onfocus=" (this.type='date')" onchange="this.blur();" id="date">
Here's an example:
public class Main {
public static void main(String[] args) {
double val1 = 100;
double val2 = 10;
char operation = 'd';
double result = 0;
switch (operation) {
case 'a':
result = val1 + val2; break;
case 's':
result = val1 - val2; break;
case 'd':
if (val2 != 0)
result = val1 / val2; break;
case 'm':
result = val1 * val2; break;
default: System.out.println("Not a defined operation");
}
System.out.println(result);
}
}
You can get it with .outerHeight()
.
Sometimes, it will return 0
. For the best results, you can call it in your div
's ready event.
To be safe, you should not set the height of the div
to x
. You can keep its height auto
to get content populated properly with the correct height.
$('#x').ready( function(){
// alerts the height in pixels
alert($('#x').outerHeight());
})
You can find a detailed post here.
hey i know it is so late for this answer but add sort_keys and assign false to it as follows :
json.dumps({'****': ***},sort_keys=False)
this worked for me
Another reason why you should avoid converting the column to varchar(max) is because you cannot create an index on a varchar(max) column.
This is the Scala solution if anyone needs it
def anUnsafeOkHttpClient(): OkHttpClient = {
val manager: TrustManager =
new X509TrustManager() {
override def checkClientTrusted(x509Certificates: Array[X509Certificate], s: String) = {}
override def checkServerTrusted(x509Certificates: Array[X509Certificate], s: String) = {}
override def getAcceptedIssuers = Seq.empty[X509Certificate].toArray
}
val trustAllCertificates = Seq(manager).toArray
val sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, trustAllCertificates, new java.security.SecureRandom())
val sslSocketFactory = sslContext.getSocketFactory()
val okBuilder = new OkHttpClient.Builder()
okBuilder.sslSocketFactory(sslSocketFactory, trustAllCertificates(0).asInstanceOf[X509TrustManager])
okBuilder.hostnameVerifier(new NoopHostnameVerifier)
okBuilder.build()
}
From your post I gather that you want to compare dates, not arrays. If this is the case, then use the appropriate object: a datetime
object.
Please check the documentation for the datetime module. Dates are a tough cookie. Use reliable algorithms.
A good solution is avaliable at
http://blogs.digitss.com/javascript/calculate-datetime-difference-simple-javascript-code-snippet/
gives the output in your desired differnece format of
days : hours : minutes : seconds .
A slightly modified version of that code is shown below
var vdaysdiff; // difference of the dates
var vhourDiff;
var vmindiff;
var vsecdiff;
vdaysdiff = Math.floor(diff/1000/60/60/24); // in days
diff -= vdaysdiff*1000*60*60*24;
vhourDiff = Math.floor(diff/1000/60/60); // in hours
diff -= vhourDiff*1000*60*60;
vmindiff = Math.floor(diff/1000/60); // in minutes
diff -= vmindiff*1000*60;
vsecdiff= Math.floor(diff/1000); // in seconds
//Text formatting
var hourtext = '00';
if (hourDiff > 0){ hourtext = String(hourDiff);}
if (hourtext.length == 1){hourtext = '0' + hourtext};
var mintext = '00';
if (mindiff > 0){ mintext = String(mindiff);}
if (mintext.length == 1){mintext = '0' + mintext};
//shows output as HH:MM ( i needed shorter duration)
duration.value= hourtext + ':' + mintext;
Sort the file randomly and pick first 100
lines:
$ sort -R input | head -n 100 >output
Try this. It works for me:
mkdir <repos>/tags/Release1.0
svn commit <repos>/tags/Release1.0
svn copy <repos>/trunk/* <repos>/tag/Release1.0
svn commit <repos/tags/Release1.0 -m "Tagging Release1.0"
Replace this
<button type="button" value=" Send" class="btn btn-success" type="submit" id="submit">
with
<button value=" Send" class="btn btn-success" type="submit" id="submit">
Make sure to invoke done();
on callbacks or it simply won't pass the test.
beforeAll((done /* Call it or remove it */ ) => {
done(); // Calling it
});
It applies to all other functions that have a done() callback.
The documentation currently shows that as of 3.0, $.post will accept the settings object, meaning that you can use the $.ajax options. 3.0 is not released yet and on the commit they're talking about hiding the reference to it in the docs, but look for it in the future!
You can do it with ssh public/private keys only. Or use putty in which you can set the password. scp doesn't support giving password in command line.
You can find the instructions for public/private keys here: http://www.softpanorama.org/Net/Application_layer/SSH/scp.shtml
That part is written to stderr, use 2>
to redirect it. For example:
foo > stdout.txt 2> stderr.txt
or if you want in same file:
foo > allout.txt 2>&1
Note: this works in (ba)sh, check your shell for proper syntax
Make your first pivot table.
Select the first top left cell.
Create a range name using offset:
OFFSET(Sheet1!$A$3,0,0,COUNTA(Sheet1!$A:$A)-1,COUNTA(Sheet1!$3:$3))
Make your second pivot with your range name as source of data using F3.
If you change number of rows or columns from your first pivot, your second pivot will be update after refreshing pivot
GFGDT
Just an other java example:
long dayLength = 1000 * 60 * 60 * 24;
long dayMs = System.currentTimeMillis() % dayLength;
double percentOfDay = (double) dayMs / dayLength;
int hour = (int) (percentOfDay * 24);
int minute = (int) (percentOfDay * 24 * 60) % 60;
int second = (int) (percentOfDay * 24 * 60 * 60) % 60;
an advantage is that you can simulate shorter days, if you adjust dayLength
use this too :
if(e.preventDefault)
e.preventDefault();
else
e.returnValue = false;
Becoz e.preventDefault() is not supported in IE( some versions ). In IE it is e.returnValue = false
This should work in modern browsers:
input[value]:not([value=""])
It selects all inputs with value attribute and then select inputs with non empty value among them.
You can do this by setting the display to 'table-cell' and applying a vertical-align: middle;
:
{
display: table-cell;
vertical-align: middle;
}
This is however not supported by all versions of Internet Explorer according to this excerpt I copied from http://www.w3schools.com/cssref/pr_class_display.asp without permission.
Note: The values "inline-table", "table", "table-caption", "table-cell", "table-column", "table-column-group", "table-row", "table-row-group", and "inherit" are not supported by Internet Explorer 7 and earlier. Internet Explorer 8 requires a !DOCTYPE. Internet Explorer 9 supports the values.
The following table shows the allowed display values also from http://www.w3schools.com/cssref/pr_class_display.asp.
For anyone else out there wondering how to do this, I have the following solution for SQL Server 2008 R2 and later:
USE master
go
DENY VIEW ANY DATABASE TO [user]
go
This will address exactly the requirement outlined above..
First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.
For example,
> z <- factor(letters[c(3, 2, 3, 4)])
# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d
# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"
here, z
has 4 elements.
The index is 2, 1, 2, 3
in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.
Then, as.numeric
converts simply the index part of factor into numeric.
as.character
handles the index and levels, and generates character vector expressed by its level.
?as.numeric
says that Factors are handled by the default method.
Try using setAttribute
instead:
document.getElementById('img')
.setAttribute(
'src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
);
Real answer: (And make sure you remove the line-breaks in the base64.)
There are many ways. Here are at least five:
/*
* An example of converting std::string to (const)char* using five
* different methods. Error checking is emitted for simplicity.
*
* Compile and run example (using gcc on Unix-like systems):
*
* $ g++ -Wall -pedantic -o test ./test.cpp
* $ ./test
* Original string (0x7fe3294039f8): hello
* s1 (0x7fe3294039f8): hello
* s2 (0x7fff5dce3a10): hello
* s3 (0x7fe3294000e0): hello
* s4 (0x7fe329403a00): hello
* s5 (0x7fe329403a10): hello
*/
#include <alloca.h>
#include <string>
#include <cstring>
int main()
{
std::string s0;
const char *s1;
char *s2;
char *s3;
char *s4;
char *s5;
// This is the initial C++ string.
s0 = "hello";
// Method #1: Just use "c_str()" method to obtain a pointer to a
// null-terminated C string stored in std::string object.
// Be careful though because when `s0` goes out of scope, s1 points
// to a non-valid memory.
s1 = s0.c_str();
// Method #2: Allocate memory on stack and copy the contents of the
// original string. Keep in mind that once a current function returns,
// the memory is invalidated.
s2 = (char *)alloca(s0.size() + 1);
memcpy(s2, s0.c_str(), s0.size() + 1);
// Method #3: Allocate memory dynamically and copy the content of the
// original string. The memory will be valid until you explicitly
// release it using "free". Forgetting to release it results in memory
// leak.
s3 = (char *)malloc(s0.size() + 1);
memcpy(s3, s0.c_str(), s0.size() + 1);
// Method #4: Same as method #3, but using C++ new/delete operators.
s4 = new char[s0.size() + 1];
memcpy(s4, s0.c_str(), s0.size() + 1);
// Method #5: Same as 3 but a bit less efficient..
s5 = strdup(s0.c_str());
// Print those strings.
printf("Original string (%p): %s\n", s0.c_str(), s0.c_str());
printf("s1 (%p): %s\n", s1, s1);
printf("s2 (%p): %s\n", s2, s2);
printf("s3 (%p): %s\n", s3, s3);
printf("s4 (%p): %s\n", s4, s4);
printf("s5 (%p): %s\n", s5, s5);
// Release memory...
free(s3);
delete [] s4;
free(s5);
}
Firstly, you need to change this line:
element.setAttribute("onclick", alert("blabla"));
To something like this:
element.setAttribute("onclick", function() { alert("blabla"); });
Secondly, you may have browser compatibility issues when attaching events that way. You might need to use .attachEvent / .addEvent, depending on which browser. I haven't tried manually setting event handlers for a while, but I remember firefox and IE treating them differently.
I have seen reports of people having and additional, self terminating node in the machine.config file. Removing it resolved their issue. machine.config is found in \Windows\Microsoft.net\Framework\vXXXX\Config
. You could have a multitude of config files based on how many versions of the framework are installed, including 32 and 64 bit variants.
<system.data>
<DbProviderFactories>
<add name="Odbc Data Provider" invariant="System.Data.Odbc" ... />
<add name="OleDb Data Provider" invariant="System.Data.OleDb" ... />
<add name="OracleClient Data Provider" invariant="System.Data ... />
<add name="SqlClient Data Provider" invariant="System.Data ... />
<add name="IBM DB2 for i .NET Provider" invariant="IBM.Data ... />
<add name="Microsoft SQL Server Compact Data Provider" ... />
</DbProviderFactories>
<DbProviderFactories/> //remove this one!
</system.data>
Pro-tip Note: for some reason, CSS syntax needs the :active
snippet after the :hover
for the same element in order to be effective
You must need to specify columns name which you want to insert if there is an Identity column. So the command will be like this below:
SET IDENTITY_INSERT DuplicateTable ON
INSERT Into DuplicateTable ([IdentityColumn], [Column2], [Column3], [Column4] )
SELECT [IdentityColumn], [Column2], [Column3], [Column4] FROM MainTable
SET IDENTITY_INSERT DuplicateTable OFF
If your table has many columns then get those columns name by using this command.
SELECT column_name + ','
FROM information_schema.columns
WHERE table_name = 'TableName'
for xml path('')
(after removing the last comma(',')) Just copy past columns name.
If just want to user pure Linq, you can use groupby:
List<obj> distinct =
objs.GroupBy(car => car.typeID).Select(g => g.First()).ToList();
If you want a method to be used all across the app, similar to what MoreLinq does:
public static IEnumerable<TSource> DistinctBy<TSource, TKey>
(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source)
{
if (!seenKeys.Contains(keySelector(element)))
{
seenKeys.Add(keySelector(element));
yield return element;
}
}
}
Using this method to find the distinct values using just the Id property, you could use:
var query = objs.DistinctBy(p => p.TypeId);
you can use multiple properties:
var query = objs.DistinctBy(p => new { p.TypeId, p.Name });
1.You can make overload functions.
SomeF(strin s){}
SomeF(string s, string s2){}
SomeF(string s1, string s2, string s3){}
More info: http://csharpindepth.com/Articles/General/Overloading.aspx
2.or you may create one function with params
SomeF( params string[] paramArray){}
SomeF("aa","bb", "cc", "dd", "ff"); // pass as many as you like
More info: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/params
3.or you can use simple array
Main(string[] args){}
I have found that %CD%
gives the path the script was called from and not the path of the script, however, %~dp0
will give the path of the script itself.
When you return cell's contentView you will have a 2 problems:
viewForHeaderInSection
call, you creating new cell)Solution:
Wrapper class for table header\footer.
It is just container, inherited from UITableViewHeaderFooterView
, which holds cell inside
https://github.com/Magnat12/MGTableViewHeaderWrapperView.git
Register class in your UITableView (for example, in viewDidLoad)
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView registerClass:[MGTableViewHeaderWrapperView class] forHeaderFooterViewReuseIdentifier:@"ProfileEditSectionHeader"];
}
In your UITableViewDelegate:
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
MGTableViewHeaderWrapperView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"ProfileEditSectionHeader"];
// init your custom cell
ProfileEditSectionTitleTableCell *cell = (ProfileEditSectionTitleTableCell * ) view.cell;
if (!cell) {
cell = [tableView dequeueReusableCellWithIdentifier:@"ProfileEditSectionTitleTableCell"];
view.cell = cell;
}
// Do something with your cell
return view;
}
var x = '301.474.4062';_x000D_
_x000D_
x = x.replace(/\D+/g, '')_x000D_
.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');_x000D_
_x000D_
alert(x);
_x000D_
You can use the path
module to join the path of the directory in which helper1.js
lives to the relative path of foobar.json
. This will give you the absolute path to foobar.json
.
var fs = require('fs');
var path = require('path');
var jsonPath = path.join(__dirname, '..', 'config', 'dev', 'foobar.json');
var jsonString = fs.readFileSync(jsonPath, 'utf8');
This should work on Linux, OSX, and Windows assuming a UTF8 encoding.
to_char(tran_date, 'yyyy-mm-dd') = to_char(sysdate-1, 'yyyy-mm-dd')
In my case, the issue was new sites had an implicit deny of all IP addresses unless an explicit allow was created. To fix: Under the site in Features View: Under the IIS Section > IP Address and Domain Restrictions > Edit Feature Settings > Set 'Access for unspecified clients:' to 'Allow'
(in the following code, you should substitute 'UTC'
for zone and now()
for timestamp)
timestamp AT TIME ZONE zone
- SQL-standard-conformingtimezone(zone, timestamp)
- arguably more readableThe function timezone(zone, timestamp) is equivalent to the SQL-conforming construct timestamp AT TIME ZONE zone.
'UTC'
) or as an interval (e.g., INTERVAL '-08:00'
) - here is a list of all available time zonesnow()
returns a value of type timestamp (just what we need) with your database's default time zone attached (e.g. 2018-11-11T12:07:22.3+05:00
).timezone('UTC', now())
turns our current time (of type timestamp with time zone) into the timezonless equivalent in UTC
.SELECT timestamp with time zone '2020-03-16 15:00:00-05' AT TIME ZONE 'UTC'
will return 2020-03-16T20:00:00Z
.Docs: timezone()
Example for your reference, as below:
The folder structure might be as:
Where there are two Makefiles, each as below;
sample/Makefile
test/Makefile
Now, let us see the content of the Makefiles.
sample/Makefile
export ROOT_DIR=${PWD}
all:
echo ${ROOT_DIR}
$(MAKE) -C test
test/Makefile
all:
echo ${ROOT_DIR}
echo "make test ends here !"
Now, execute the sample/Makefile, as;
cd sample
make
OUTPUT:
echo /home/symphony/sample
/home/symphony/sample
make -C test
make[1]: Entering directory `/home/symphony/sample/test'
echo /home/symphony/sample
/home/symphony/sample
echo "make test ends here !"
make test ends here !
make[1]: Leaving directory `/home/symphony/sample/test'
Explanation, would be that the parent/home directory can be stored in the environment-flag, and can be exported, so that it can be used in all the sub-directory makefiles.
Go doesn't really have a character type as such. byte is often used for ASCII characters, and rune is used for Unicode characters, but they are both just aliases for integer types (uint8 and int32). So if you want to force them to be printed as characters instead of numbers, you need to use Printf("%c", x)
. The %c
format specification works for any integer type.
Check that (for jUnit - 4.12 and Eclipse surefire plugin)
SELECT *
FROM courses
WHERE DATE_ADD(NOW(), INTERVAL 2 HOUR) > start_time
See Date and Time Functions for other date/time manipulation.
You can also use "or" operator,
for( int i = 0 ; i < 100 || someOtherCondition() ; i++ ) {
...
}
There are only two ways to be 100% certain that the COUNT(*)
and the actual query will give consistent results:
COUNT(*)
with the query, as in your Approach 2. I recommend the form you show in your example, not the correlated subquery form shown in the comment from kogus.SNAPSHOT
or SERIALIZABLE
isolation level. Using one of those isolation levels is important because any other isolation level allows new rows created by other clients to become visible in your current transaction. Read the MSDN documentation on SET TRANSACTION ISOLATION
for more details.
I'd go with @sandeep's display: table-cell
answer if you don't care about IE7.
Otherwise, here's an alternative, with one downside: the "right" div
has to come first in the HTML.
See: http://jsfiddle.net/thirtydot/qLTMf/
and exactly the same, but with the "right div" removed: http://jsfiddle.net/thirtydot/qLTMf/1/
#parent {
overflow: hidden;
border: 1px solid red
}
.right {
float: right;
width: 100px;
height: 100px;
background: #888;
}
.left {
overflow: hidden;
height: 100px;
background: #ccc
}
<div id="parent">
<div class="right">right</div>
<div class="left">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam semper porta sem, at ultrices ante interdum at. Donec condimentum euismod consequat. Ut viverra lorem pretium nisi malesuada a vehicula urna aliquet. Proin at ante nec neque commodo bibendum. Cras bibendum egestas lacus, nec ullamcorper augue varius eget.</div>
</div>
In addition to Trevor Burnham's answer if you want to deal with disabled javascript and defer css loading
HTML5
<html class="no-js">
<head>...</head>
<body>
<header>...</header>
<main>...</main>
<footer>...</footer>
</body>
</html>
CSS
//at the beginning of the page
.js main, .js footer{
opacity:0;
}
JAVASCRIPT
//at the beginning of the page before loading jquery
var h = document.querySelector("html");
h.className += ' ' + 'js';
h.className = h.className.replace(
new RegExp('( |^)' + 'no-js' + '( |$)', 'g'), ' ').trim();
JQUERY
//somewhere at the end of the page after loading jquery
$(window).load(function() {
$('main').css('opacity',1);
$('footer').css('opacity',1);
});
RESOURCES
I have always thought the different between RDL and RDLC is that RDL are used for SQL Server Reporting Services and RDLC are used in Visual Studio for client side reporting. The implemenation and editor are almost identical. RDL stands for Report Defintion Language
and RDLC Report Definition Language Client-side
.
I hope that helps.
one things to remember push work only with array[] not object{}.
if you want to add Like object o inside inside n
_x000D_
_x000D_
a={ b:"c",
D:"e",
F: {g:"h",
I:"j",
k:{ l:"m"
}}
}
a.F.k.n = { o: "p" };
a.F.k.n = { o: "p" };
console.log(a);
_x000D_
_x000D_
_x000D_
Once you have put the values into the JSONObject then put the JSONObject into the JSONArray staright after.
Something like this maybe:
jsonObj.put("value1", 1);
jsonObj.put("value2", 900);
jsonObj.put("value3", 1368349);
jsonArray.put(jsonObj);
Then create new JSONObject, put the other values into it and add it to the JSONArray:
jsonObj.put("value1", 2);
jsonObj.put("value2", 1900);
jsonObj.put("value3", 136856);
jsonArray.put(jsonObj);
Another option is to use the Apache Maven Shade Plugin: This plugin provides the capability to package the artifact in an uber-jar, including its dependencies and to shade - i.e. rename - the packages of some of the dependencies.
add this to your build plugins section
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
</plugin>
If you have Excel 2010 you can copy your data into another column, than select it and choose Data -> Remove Duplicates. You can then write =COUNTIF($A$1:$A$100,B1)
next to it and copy the formula down. This assumes you have your values in range A1:A100
and the de-duplicated values are in column B.