If you're just looking for extremely precise measurements of elapsed time, use System.nanoTime()
. System.currentTimeMillis()
will give you the most accurate possible elapsed time in milliseconds since the epoch, but System.nanoTime()
gives you a nanosecond-precise time, relative to some arbitrary point.
From the Java Documentation:
public static long nanoTime()
Returns the current value of the most precise available system timer, in nanoseconds.
This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary origin time (perhaps in the future, so values may be negative). This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change. Differences in successive calls that span greater than approximately 292 years (263 nanoseconds) will not accurately compute elapsed time due to numerical overflow.
For example, to measure how long some code takes to execute:
long startTime = System.nanoTime();
// ... the code being measured ...
long estimatedTime = System.nanoTime() - startTime;
See also: JavaDoc System.nanoTime() and JavaDoc System.currentTimeMillis() for more info.
Using Stopwatch class we can achieve it from System.Diagnostics
.
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
stopwatch.Stop();
Debug.WriteLine(stopwatch.ElapsedMilliseconds);
when you need in a timestamp in seconds, you can use the following:
var timestamp = (int)(DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1)).TotalSeconds;
timespec_get
from C11
Returns up to nanoseconds, rounded to the resolution of the implementation.
Looks like an ANSI ripoff from POSIX' clock_gettime
.
Example: a printf
is done every 100ms on Ubuntu 15.10:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
static long get_nanos(void) {
struct timespec ts;
timespec_get(&ts, TIME_UTC);
return (long)ts.tv_sec * 1000000000L + ts.tv_nsec;
}
int main(void) {
long nanos;
long last_nanos;
long start;
nanos = get_nanos();
last_nanos = nanos;
start = nanos;
while (1) {
nanos = get_nanos();
if (nanos - last_nanos > 100000000L) {
printf("current nanos: %ld\n", nanos - start);
last_nanos = nanos;
}
}
return EXIT_SUCCESS;
}
The C11 N1570 standard draft 7.27.2.5 "The timespec_get function says":
If base is TIME_UTC, the tv_sec member is set to the number of seconds since an implementation defined epoch, truncated to a whole value and the tv_nsec member is set to the integral number of nanoseconds, rounded to the resolution of the system clock. (321)
321) Although a struct timespec object describes times with nanosecond resolution, the available resolution is system dependent and may even be greater than 1 second.
C++11 also got std::chrono::high_resolution_clock
: C++ Cross-Platform High-Resolution Timer
glibc 2.21 implementation
Can be found under sysdeps/posix/timespec_get.c
as:
int
timespec_get (struct timespec *ts, int base)
{
switch (base)
{
case TIME_UTC:
if (__clock_gettime (CLOCK_REALTIME, ts) < 0)
return 0;
break;
default:
return 0;
}
return base;
}
so clearly:
only TIME_UTC
is currently supported
it forwards to __clock_gettime (CLOCK_REALTIME, ts)
, which is a POSIX API: http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_getres.html
Linux x86-64 has a clock_gettime
system call.
Note that this is not a fail-proof micro-benchmarking method because:
man clock_gettime
says that this measure may have discontinuities if you change some system time setting while your program runs. This should be a rare event of course, and you might be able to ignore it.
this measures wall time, so if the scheduler decides to forget about your task, it will appear to run for longer.
For those reasons getrusage()
might be a better better POSIX benchmarking tool, despite it's lower microsecond maximum precision.
More information at: Measure time in Linux - time vs clock vs getrusage vs clock_gettime vs gettimeofday vs timespec_get?
We can take ZOOM approach. We can assume that max 30% (or more upto 100%) can be the zooming effect if aspect image height OR width is less than the desired height OR width. We can hide the rest not needed area with overflow: hidden.
.image-container {
width: 200px;
height: 150px;
overflow: hidden;
}
.stage-image-gallery a img {
max-height: 130%;
max-width: 130%;
position: relative;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}
This will adjust images with different width OR height.
It happened to me as well. On a newly provisioned Red Hat Linux 7 server.
When I run a PHP page, i.e. info.php, I could see plain text PHP scripts instead of executing them.
I just installed PHP:
[root@localhost ~]# yum install php
And then restarted Apache HTTP Server:
[root@localhost ~]# systemctl restart httpd
The blog article is mostly right, but not complete. To have a full understanding of what an odex file does, you have to understand a little about how application files (APK) work.
Applications are basically glorified ZIP archives. The java code is stored in a file called classes.dex and this file is parsed by the Dalvik JVM and a cache of the processed classes.dex file is stored in the phone's Dalvik cache.
An odex is basically a pre-processed version of an application's classes.dex that is execution-ready for Dalvik. When an application is odexed, the classes.dex is removed from the APK archive and it does not write anything to the Dalvik cache. An application that is not odexed ends up with 2 copies of the classes.dex file--the packaged one in the APK, and the processed one in the Dalvik cache. It also takes a little longer to launch the first time since Dalvik has to extract and process the classes.dex file.
If you are building a custom ROM, it's a really good idea to odex both your framework JAR files and the stock apps in order to maximize the internal storage space for user-installed apps. If you want to theme, then simply deodex -> apply your theme -> reodex -> release.
To actually deodex, use small and baksmali:
Since this is a top hit on Google, I'd like to give an updated answer.
Using ES6 classes makes inheritance and method overriding a lot easier:
'use strict';
class A {
speak() {
console.log("I'm A");
}
}
class B extends A {
speak() {
super.speak();
console.log("I'm B");
}
}
var a = new A();
a.speak();
// Output:
// I'm A
var b = new B();
b.speak();
// Output:
// I'm A
// I'm B
The super
keyword refers to the parent class when used in the inheriting class. Also, all methods on the parent class are bound to the instance of the child, so you don't have to write super.method.apply(this);
.
As for compatibility: the ES6 compatibility table shows only the most recent versions of the major players support classes (mostly). V8 browsers have had them since January of this year (Chrome and Opera), and Firefox, using the SpiderMonkey JS engine, will see classes next month with their official Firefox 45 release. On the mobile side, Android still does not support this feature, while iOS 9, release five months ago, has partial support.
Fortunately, there is Babel, a JS library for re-compiling Harmony code into ES5 code. Classes, and a lot of other cool features in ES6 can make your Javascript code a lot more readable and maintainable.
If your having a Wordpress theme problem it could be because although you have renamed the theme in your wp_options table you havn't renamed the stylesheet. I struggled with this.
When executable path has whitespace in system, call
#include<iostream>
using namespace std;
int main()
{
system("explorer C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe ");
system("pause");
return 0;
}
A curried function is a function of several arguments rewritten such that it accepts the first argument and returns a function that accepts the second argument and so on. This allows functions of several arguments to have some of their initial arguments partially applied.
You can use the styleSheets object:
document.styleSheets[0].cssRules[0].style.removeProperty("zoom");
Caveat #1: You have to know the index of your stylesheet and the index of your rule.
Caveat #2: This object is implemented inconsistently by the browsers; what works in one may not work in the others.
The easiest way would be to use a GUI:
For Gnome use gnome-schedule (universe)
sudo apt-get install gnome-schedule
For KDE use kde-config-cron
It should be pre installed on Kubuntu
But if you use a headless linux or don´t want GUI´s you may use:
crontab -e
If you type it into Terminal you´ll get a table.
You have to insert your cronjobs now.
Format a job like this:
* * * * * YOURCOMMAND
- - - - -
| | | | |
| | | | +----- Day in Week (0 to 7) (Sunday is 0 and 7)
| | | +------- Month (1 to 12)
| | +--------- Day in Month (1 to 31)
| +----------- Hour (0 to 23)
+------------- Minute (0 to 59)
There are some shorts, too (if you don´t want the *):
@reboot --> only once at startup
@daily ---> once a day
@midnight --> once a day at midnight
@hourly --> once a hour
@weekly --> once a week
@monthly --> once a month
@annually --> once a year
@yearly --> once a year
If you want to use the shorts as cron (because they don´t work or so):
@daily --> 0 0 * * *
@midnight --> 0 0 * * *
@hourly --> 0 * * * *
@weekly --> 0 0 * * 0
@monthly --> 0 0 1 * *
@annually --> 0 0 1 1 *
@yearly --> 0 0 1 1 *
heres a step by step procedure (assuming you've already installed python):
open terminal (Run as Administrator) and type in the command line:
C:/> @powershell -NoProfile -ExecutionPolicy Bypass -Command "iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1'))" && SET PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin
it will take some time to get chocolatey installed on your machine. sit back n relax...
now install pip. type in terminal cinst easy.install pip
now type in terminal: pip install flask
YOU'RE DONE !!! Tested on Win 8.1 with Python 2.7
here is a jsfiddle with an example of showing/hiding div's via a select.
HTML:
<div id="option1" class="group">asdf</div>
<div id="option2" class="group">kljh</div>
<div id="option3" class="group">zxcv</div>
<div id="option4" class="group">qwerty</div>
<select id="selectMe">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
</select>
jQuery:
$(document).ready(function () {
$('.group').hide();
$('#option1').show();
$('#selectMe').change(function () {
$('.group').hide();
$('#'+$(this).val()).show();
})
});
It looks like a common gaps-and-islands problem. The difference between two sequences of row numbers rn1
and rn2
give the "group" number.
Run this query CTE-by-CTE and examine intermediate results to see how it works.
Sample data
I expanded sample data from the question a little.
DECLARE @Source TABLE
(
EmployeeID int,
DateStarted date,
DepartmentID int
)
INSERT INTO @Source
VALUES
(10001,'2013-01-01',001),
(10001,'2013-09-09',001),
(10001,'2013-12-01',002),
(10001,'2014-05-01',002),
(10001,'2014-10-01',001),
(10001,'2014-12-01',001),
(10005,'2013-05-01',001),
(10005,'2013-11-09',001),
(10005,'2013-12-01',002),
(10005,'2014-10-01',001),
(10005,'2016-12-01',001);
Query for SQL Server 2008
There is no LEAD
function in SQL Server 2008, so I had to use self-join via OUTER APPLY
to get the value of the "next" row for the DateEnd
.
WITH
CTE
AS
(
SELECT
EmployeeID
,DateStarted
,DepartmentID
,ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS rn1
,ROW_NUMBER() OVER (PARTITION BY EmployeeID, DepartmentID ORDER BY DateStarted) AS rn2
FROM @Source
)
,CTE_Groups
AS
(
SELECT
EmployeeID
,MIN(DateStarted) AS DateStart
,DepartmentID
FROM CTE
GROUP BY
EmployeeID
,DepartmentID
,rn1 - rn2
)
SELECT
CTE_Groups.EmployeeID
,CTE_Groups.DepartmentID
,CTE_Groups.DateStart
,A.DateEnd
FROM
CTE_Groups
OUTER APPLY
(
SELECT TOP(1) G2.DateStart AS DateEnd
FROM CTE_Groups AS G2
WHERE
G2.EmployeeID = CTE_Groups.EmployeeID
AND G2.DateStart > CTE_Groups.DateStart
ORDER BY G2.DateStart
) AS A
ORDER BY
EmployeeID
,DateStart
;
Query for SQL Server 2012+
Starting with SQL Server 2012 there is a LEAD
function that makes this task more efficient.
WITH
CTE
AS
(
SELECT
EmployeeID
,DateStarted
,DepartmentID
,ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS rn1
,ROW_NUMBER() OVER (PARTITION BY EmployeeID, DepartmentID ORDER BY DateStarted) AS rn2
FROM @Source
)
,CTE_Groups
AS
(
SELECT
EmployeeID
,MIN(DateStarted) AS DateStart
,DepartmentID
FROM CTE
GROUP BY
EmployeeID
,DepartmentID
,rn1 - rn2
)
SELECT
CTE_Groups.EmployeeID
,CTE_Groups.DepartmentID
,CTE_Groups.DateStart
,LEAD(CTE_Groups.DateStart) OVER (PARTITION BY CTE_Groups.EmployeeID ORDER BY CTE_Groups.DateStart) AS DateEnd
FROM
CTE_Groups
ORDER BY
EmployeeID
,DateStart
;
Result
+------------+--------------+------------+------------+
| EmployeeID | DepartmentID | DateStart | DateEnd |
+------------+--------------+------------+------------+
| 10001 | 1 | 2013-01-01 | 2013-12-01 |
| 10001 | 2 | 2013-12-01 | 2014-10-01 |
| 10001 | 1 | 2014-10-01 | NULL |
| 10005 | 1 | 2013-05-01 | 2013-12-01 |
| 10005 | 2 | 2013-12-01 | 2014-10-01 |
| 10005 | 1 | 2014-10-01 | NULL |
+------------+--------------+------------+------------+
Use JSON Simple,
http://code.google.com/p/json-simple/
Which has a small foot-print, no dependencies so it's perfect for Android.
You can do something like this,
Object obj=JSONValue.parse(buffer.tString());
JSONArray finalResult=(JSONArray)obj;
I ran into the same issue today when trying to use a pod written in Objective-C in my Swift project, none of the above solutions seemed to work.
In the podfile I had use_frameworks!
written. Commenting this line and then running pod install
again solved this issue for me and the error went away.
If you want it to check explicit for it to not be false (boolean value) you have to use
if(borrar() !== false)
But in JavaScript we usually use falsy and truthy and you could use
if(!borrar())
but then values 0, '', null, undefined, null and NaN would not generate the alert.
The following values are always falsy:
false,
,0 (zero)
,'' or "" (empty string)
,null
,undefined
,NaN
Everything else is truthy. That includes:
'0' (a string containing a single zero)
,'false' (a string containing the text “false”)
,[] (an empty array)
,{} (an empty object)
,function(){} (an “empty” function)
Source: https://www.sitepoint.com/javascript-truthy-falsy/
As an extra perk to convert any value to true or false (boolean type), use double exclamation mark:
!![] === true
!!'false' === true
!!false === false
!!undefined === false
You have to initialise the object (create the object itself) in order to be able to call its methods otherwise you would get a NullPointerException
.
WordList words = new WordList();
Thanks to @Jousby's solution, I managed to get mine working as well, but found I had to improve his solution's Bootstrap modal markup a bit to make it render correctly as demonstrated in the official examples.
So, here's my modified version of the generic confirm
function that worked fine:
/* Generic Confirm func */
function confirm(heading, question, cancelButtonTxt, okButtonTxt, callback) {
var confirmModal =
$('<div class="modal fade">' +
'<div class="modal-dialog">' +
'<div class="modal-content">' +
'<div class="modal-header">' +
'<a class="close" data-dismiss="modal" >×</a>' +
'<h3>' + heading +'</h3>' +
'</div>' +
'<div class="modal-body">' +
'<p>' + question + '</p>' +
'</div>' +
'<div class="modal-footer">' +
'<a href="#!" class="btn" data-dismiss="modal">' +
cancelButtonTxt +
'</a>' +
'<a href="#!" id="okButton" class="btn btn-primary">' +
okButtonTxt +
'</a>' +
'</div>' +
'</div>' +
'</div>' +
'</div>');
confirmModal.find('#okButton').click(function(event) {
callback();
confirmModal.modal('hide');
});
confirmModal.modal('show');
};
/* END Generic Confirm func */
C# adaptation of approach often used in C - set value of outer loop's variable outside of loop conditions (i.e. for loop using int variable INT_MAX -1
is often good choice):
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 100; j++)
{
if (exit_condition)
{
// cause the outer loop to break:
// use i = INT_MAX - 1; otherwise i++ == INT_MIN < 100 and loop will continue
i = int.MaxValue - 1;
Console.WriteLine("Hi");
// break the inner loop
break;
}
}
// if you have code in outer loop it will execute after break from inner loop
}
As note in code says break
will not magically jump to next iteration of the outer loop - so if you have code outside of inner loop this approach requires more checks. Consider other solutions in such case.
This approach works with for
and while
loops but does not work for foreach
. In case of foreach
you won't have code access to the hidden enumerator so you can't change it (and even if you could IEnumerator
doesn't have some "MoveToEnd" method).
Acknowledgments to inlined comments' authors:
i = INT_MAX - 1
suggestion by Meta
for
/foreach
comment by ygoe.
Proper IntMax
by jmbpiano
remark about code after inner loop by blizpasta
To build on the solutions from Ffisegydd and amaliammr, here's an example where we make CSV representation for a custom colormap:
#! /usr/bin/env python3
import matplotlib
import numpy as np
vmin = 0.1
vmax = 1000
norm = matplotlib.colors.Normalize(np.log10(vmin), np.log10(vmax))
lognum = norm(np.log10([.5, 2., 10, 40, 150,1000]))
cdict = {
'red':
(
(0., 0, 0),
(lognum[0], 0, 0),
(lognum[1], 0, 0),
(lognum[2], 1, 1),
(lognum[3], 0.8, 0.8),
(lognum[4], .7, .7),
(lognum[5], .7, .7)
),
'green':
(
(0., .6, .6),
(lognum[0], 0.8, 0.8),
(lognum[1], 1, 1),
(lognum[2], 1, 1),
(lognum[3], 0, 0),
(lognum[4], 0, 0),
(lognum[5], 0, 0)
),
'blue':
(
(0., 0, 0),
(lognum[0], 0, 0),
(lognum[1], 0, 0),
(lognum[2], 0, 0),
(lognum[3], 0, 0),
(lognum[4], 0, 0),
(lognum[5], 1, 1)
)
}
mycmap = matplotlib.colors.LinearSegmentedColormap('my_colormap', cdict, 256)
norm = matplotlib.colors.LogNorm(vmin, vmax)
colors = {}
count = 0
step_size = 0.001
for value in np.arange(vmin, vmax+step_size, step_size):
count += 1
print("%d/%d %f%%" % (count, vmax*(1./step_size), 100.*count/(vmax*(1./step_size))))
rgba = mycmap(norm(value), bytes=True)
color = (rgba[0], rgba[1], rgba[2])
if color not in colors.values():
colors[value] = color
print ("value, red, green, blue")
for value in sorted(colors.keys()):
rgb = colors[value]
print("%s, %s, %s, %s" % (value, rgb[0], rgb[1], rgb[2]))
Use this function to convert Object to xml string (should be called as convertToXml(sourceObject, Object.class); )-->
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.namespace.QName;
public static <T> String convertToXml(T source, Class<T> clazz) throws JAXBException {
String result;
StringWriter sw = new StringWriter();
JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
QName qName = new QName(StringUtils.uncapitalize(clazz.getSimpleName()));
JAXBElement<T> root = new JAXBElement<T>(qName, clazz, source);
jaxbMarshaller.marshal(root, sw);
result = sw.toString();
return result;
}
Use this function to convert xml string to Object back -->
(should be called as createObjectFromXmlString(xmlString, Object.class)
)
public static <T> T createObjectFromXmlString(String xml, Class<T> clazz) throws JAXBException, IOException{
T value = null;
StringReader reader = new StringReader(xml);
JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
JAXBElement<T> rootElement=jaxbUnmarshaller.unmarshal(new StreamSource(reader),clazz);
value = rootElement.getValue();
return value;
}
try converting the date first.
$date = "2012-08-06";
mysql_query("INSERT INTO data_table (title, date_of_event)
VALUES('" . $_POST['post_title'] . "',
'" . $date . "')")
or die(mysql_error());
My variation that I find to be more flexible.
str_Key = ""
str_FullKey = ""
str_CharacterPool = "01234ABCDEFfghij~-)"
for int_I in range(64):
str_Key = random.choice(str_CharacterPool)
str_FullKey = str_FullKey + str_Key
Try this combination.
const s3 = new AWS.S3({
endpoint: 's3-ap-south-1.amazonaws.com', // Bucket region
accessKeyId: 'A-----------------U',
secretAccessKey: 'k------ja----------------soGp',
Bucket: 'bucket_name',
useAccelerateEndpoint: true,
signatureVersion: 'v4',
region: 'ap-south-1' // Bucket region
});
If
width = img.width;
height = img.height;
var ctx = canvas.getContext('2d');
Then you can use these transformations to turn the image to orientation 1
From orientation:
ctx.transform(1, 0, 0, 1, 0, 0);
ctx.transform(-1, 0, 0, 1, width, 0);
ctx.transform(-1, 0, 0, -1, width, height);
ctx.transform(1, 0, 0, -1, 0, height);
ctx.transform(0, 1, 1, 0, 0, 0);
ctx.transform(0, 1, -1, 0, height, 0);
ctx.transform(0, -1, -1, 0, height, width);
ctx.transform(0, -1, 1, 0, 0, width);
Before drawing the image on ctx
The original form is nearly perfect, you just have to omit prereq after CASE:
SELECT
CASE
WHEN prereq IS NULL THEN ' '
ELSE prereq
END AS prereq
FROM test;
Test for year > 2079. I found that a user typo'ed 2106 instead of 2016 in the year (10/12/2106) and boom; so on 10/12/2016 I tested and found SQL Server accepted up to 2078, started throwing that error if the year is 2079 or higher. I have not done any further research as to what kind of date sliding SQL Server does.
This answer fails in a couple of edge cases (see comments). The accepted solution above will handle these. str.splitlines()
is the way to go. I will leave this answer nevertheless as reference.
Old (incorrect) answer:
s = \
"""line1
line2
line3
"""
lines = s.split('\n')
print(lines)
for line in lines:
print(line)
This warning is about unsafe use of strcpy. Try IOBname[ii]='\0';
instead.
I just the had same problem. I figured out that Intellisense stopped working after I took some databases offline and doing an Intellisense refresh (Ctrl-Shift-R). I brought the offline databases back online, did a refresh (Ctl-Shft-R) again and VOILA! Intellisense is working again.
What a crappy design. Maybe the population of Intellisense's lists chokes when a database exists but is offline. Thanks Microsoft.
The answer to your question is that you need to have permissions. Type the following code in your manifest.xml file:
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_OWNER_DATA"></uses-permission>
<uses-permission android:name="android.permission.READ_OWNER_DATA"></uses-permission>`
It worked for me...
JEP 354: Switch Expressions (Preview) in JDK-13 and JEP 361: Switch Expressions (Standard) in JDK-14 will extend the switch statement so it can be used as an expression.
Now you can:
case L ->
):
The code to the right of a "case L ->" switch label is restricted to be an expression, a block, or (for convenience) a throw statement.
To yield a value from a switch expression, the
break
with value statement is dropped in favor of ayield
statement.
So the demo from one of the answers might look like this:
public class SwitchExpression {
public static void main(String[] args) {
int month = 9;
int year = 2018;
int numDays = switch (month) {
case 1, 3, 5, 7, 8, 10, 12 -> 31;
case 4, 6, 9, 11 -> 30;
case 2 -> {
if (java.time.Year.of(year).isLeap()) {
System.out.println("Wow! It's leap year!");
yield 29;
} else {
yield 28;
}
}
default -> {
System.out.println("Invalid month.");
yield 0;
}
};
System.out.println("Number of Days = " + numDays);
}
}
PHP array_walk() function is specifically for altering array.
Try this:
array_walk ( $data, function (&$key) {
$key["transaction_date"] = date('d/m/Y',$key["transaction_date"]);
});
In my case, my problem was environmental. Meaning, I did something wrong in my bash session. After attempting nearly everything in this thread, I opened a new bash session and everything was back to normal.
I had a similar problem with a physical device. The problem was related with the fact that the google app ( the search bar for google on top ) was disabled. After the first reboot launcher3 began failing. No matter how many cache/data cleaning I did, it kept failing. I reenabled it and launched it, so it appeared again on the screen and from that moment on, launcher3 was back to life.
I guess there mmust be some kind of dependency with this app.
All the above works, and here is another way if you just want to number of days/time back rather a entering date
select * from *table_name* where *datetime_column* BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY) AND NOW()
You can also modify your theme using theme Editor by clicking :
Tools -> Android -> Theme Editor
Then, you don't even need to put some extra content in your .xml or .class files.
I recommend using subprocess
if writing a beautiful and readable code is your cup of tea:
import subprocess
subprocess.Popen("rm -r my_dir", shell=True)
And if you are not a software engineer, then maybe consider using Jupyter; you can simply type bash commands:
!rm -r my_dir
Traditionally, you use shutil
:
import shutil
shutil.rmtree(my_dir)
This really isn't too hard to implement with ModelForms. So lets say you have Forms A, B, and C. You print out each of the forms and the page and now you need to handle the POST.
if request.POST():
a_valid = formA.is_valid()
b_valid = formB.is_valid()
c_valid = formC.is_valid()
# we do this since 'and' short circuits and we want to check to whole page for form errors
if a_valid and b_valid and c_valid:
a = formA.save()
b = formB.save(commit=False)
c = formC.save(commit=False)
b.foreignkeytoA = a
b.save()
c.foreignkeytoB = b
c.save()
Here are the docs for custom validation.
You can use SimpleDateFormat
to do it. You just have to know 2 things.
.getTime()
returns the number of milliseconds since 1970-01-01 00:00:00 UTC.package se.wederbrand.milliseconds;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String inputString = "00:01:30.500";
Date date = sdf.parse("1970-01-01 " + inputString);
System.out.println("in milliseconds: " + date.getTime());
}
}
Maybe you could have a look at this if your printer is an epson. There is a javascript driver
EDIT:
Previous link seems to be broken
All details about how to use epos of epson are on epson website:
https://reference.epson-biz.com/modules/ref_epos_device_js_en/index.php?content_id=139
Since my related question was removed by a righteous hand after I had killed the whole day searching how to beat the "macro not found or disabled" error, posting here the only syntax that worked for me (application.run didn't, no matter what I tried)
Set objExcel = CreateObject("Excel.Application")
' Didn't run this way from the Modules
'objExcel.Application.Run "c:\app\Book1.xlsm!Sub1"
' Didn't run this way either from the Sheet
'objExcel.Application.Run "c:\app\Book1.xlsm!Sheet1.Sub1"
' Nor did it run from a named Sheet
'objExcel.Application.Run "c:\app\Book1.xlsm!Named_Sheet.Sub1"
' Only ran like this (from the Module1)
Set objWorkbook = objExcel.Workbooks.Open("c:\app\Book1.xlsm")
objExcel.Run "Sub1"
Excel 2010, Win 7
Tie::File
is what you need:
Synopsis
# This file documents Tie::File version 0.98 use Tie::File; tie @array, 'Tie::File', 'filename' or die ...; $array[13] = 'blah'; # line 13 of the file is now 'blah' print $array[42]; # display line 42 of the file $n_recs = @array; # how many records are in the file? $#array -= 2; # chop two records off the end for (@array) { s/PERL/Perl/g; # Replace PERL with Perl everywhere in the file } # These are just like regular push, pop, unshift, shift, and splice # Except that they modify the file in the way you would expect push @array, new recs...; my $r1 = pop @array; unshift @array, new recs...; my $r2 = shift @array; @old_recs = splice @array, 3, 7, new recs...; untie @array; # all finished
You can achieve this by setting the android:theme
attribute to @android:style/Theme.NoTitleBar
on your <activity>
element in your AndroidManifest.xml like this:
<activity android:name=".Activity"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Add this at your TODO point:
aRange.Columns.AutoFit();
I don't think you can achieve that with mysql date. You have to use timestamp or try this approach..
CREATE TRIGGER table_OnInsert BEFORE INSERT ON `DB`.`table`
FOR EACH ROW SET NEW.dateColumn = IFNULL(NEW.dateColumn, NOW());
Try this. I set the blue box to float right, gave left and right a fixed height, and added a white border on the right of the left div. Also added rounded corners to more match your example (These won't work in ie 8 or less). I also took out the position: relative. You don't need it. Block level elements are set to position relative by default.
See it here: http://jsfiddle.net/ZSgLJ/
#left {
float: left;
width: 44%;
margin: 0;
padding: 0;
border-right: 1px solid white;
height:400px;
}
#right {
position: relative;
float: right;
width: 49%;
margin: 0;
padding: 0;
height:400px;
}
#blue_box {
background-color:blue;
border-radius: 10px;
-moz-border-radius:10px;
-webkit-border-radius: 10px;
width: 45%;
min-width: 400px;
max-width: 600px;
padding: 2%;
float: right;
}
In static class, if you are getting information from xml or reg, class tries to initialize all properties. therefore, you should control if the config variable is there otherwise properties will not initialize so the class.
Check xml referance variable is there, Check reg referance variable is is there, Make sure you handle if they are not there.
If you're posting a json body, dont use the form
parameter. Using form
will make the arrays into field[0].attribute
, field[1].attribute
etc. Instead use body
like so.
var jsonDataObj = {'mes': 'hey dude', 'yo': ['im here', 'and here']};
request.post({
url: 'https://api.site.com',
body: jsonDataObj,
json: true
}, function(error, response, body){
console.log(body);
});
For all Spring users out there, this is how I usually do my integration tests nowadays, where async behaviour is involved:
Fire an application event in production code, when an async task (such as an I/O call) has finished. Most of the time this event is necessary anyway to handle the response of the async operation in production.
With this event in place, you can then use the following strategy in your test case:
To break this down, you'll first need some kind of domain event to fire. I'm using a UUID here to identify the task that has completed, but you're of course free to use something else as long as it's unique.
(Note, that the following code snippets also use Lombok annotations to get rid of boiler plate code)
@RequiredArgsConstructor
class TaskCompletedEvent() {
private final UUID taskId;
// add more fields containing the result of the task if required
}
The production code itself then typically looks like this:
@Component
@RequiredArgsConstructor
class Production {
private final ApplicationEventPublisher eventPublisher;
void doSomeTask(UUID taskId) {
// do something like calling a REST endpoint asynchronously
eventPublisher.publishEvent(new TaskCompletedEvent(taskId));
}
}
I can then use a Spring @EventListener
to catch the published event in test code. The event listener is a little bit more involved, because it has to handle two cases in a thread safe manner:
A CountDownLatch
is used for the second case as mentioned in other answers here. Also note, that the @Order
annotation on the event handler method makes sure, that this event handler method gets called after any other event listeners used in production.
@Component
class TaskCompletionEventListener {
private Map<UUID, CountDownLatch> waitLatches = new ConcurrentHashMap<>();
private List<UUID> eventsReceived = new ArrayList<>();
void waitForCompletion(UUID taskId) {
synchronized (this) {
if (eventAlreadyReceived(taskId)) {
return;
}
checkNobodyIsWaiting(taskId);
createLatch(taskId);
}
waitForEvent(taskId);
}
private void checkNobodyIsWaiting(UUID taskId) {
if (waitLatches.containsKey(taskId)) {
throw new IllegalArgumentException("Only one waiting test per task ID supported, but another test is already waiting for " + taskId + " to complete.");
}
}
private boolean eventAlreadyReceived(UUID taskId) {
return eventsReceived.remove(taskId);
}
private void createLatch(UUID taskId) {
waitLatches.put(taskId, new CountDownLatch(1));
}
@SneakyThrows
private void waitForEvent(UUID taskId) {
var latch = waitLatches.get(taskId);
latch.await();
}
@EventListener
@Order
void eventReceived(TaskCompletedEvent event) {
var taskId = event.getTaskId();
synchronized (this) {
if (isSomebodyWaiting(taskId)) {
notifyWaitingTest(taskId);
} else {
eventsReceived.add(taskId);
}
}
}
private boolean isSomebodyWaiting(UUID taskId) {
return waitLatches.containsKey(taskId);
}
private void notifyWaitingTest(UUID taskId) {
var latch = waitLatches.remove(taskId);
latch.countDown();
}
}
Last step is to execute the system under test in a test case. I'm using a SpringBoot test with JUnit 5 here, but this should work the same for all tests using a Spring context.
@SpringBootTest
class ProductionIntegrationTest {
@Autowired
private Production sut;
@Autowired
private TaskCompletionEventListener listener;
@Test
void thatTaskCompletesSuccessfully() {
var taskId = UUID.randomUUID();
sut.doSomeTask(taskId);
listener.waitForCompletion(taskId);
// do some assertions like looking into the DB if value was stored successfully
}
}
Note, that in contrast to other answers here, this solution will also work if you execute your tests in parallel and multiple threads exercise the async code at the same time.
Gwerder's solution wont work because hash = hmac.read();
happens before the stream is done being finalized. Thus AngraX's issues. Also the hmac.write
statement is un-necessary in this example.
Instead do this:
var crypto = require('crypto');
var hmac;
var algorithm = 'sha1';
var key = 'abcdeg';
var text = 'I love cupcakes';
var hash;
hmac = crypto.createHmac(algorithm, key);
// readout format:
hmac.setEncoding('hex');
//or also commonly: hmac.setEncoding('base64');
// callback is attached as listener to stream's finish event:
hmac.end(text, function () {
hash = hmac.read();
//...do something with the hash...
});
More formally, if you wish, the line
hmac.end(text, function () {
could be written
hmac.end(text, 'utf8', function () {
because in this example text is a utf string
using system ping command to ping a list of hosts:
import re
from subprocess import Popen, PIPE
from threading import Thread
class Pinger(object):
def __init__(self, hosts):
for host in hosts:
pa = PingAgent(host)
pa.start()
class PingAgent(Thread):
def __init__(self, host):
Thread.__init__(self)
self.host = host
def run(self):
p = Popen('ping -n 1 ' + self.host, stdout=PIPE)
m = re.search('Average = (.*)ms', p.stdout.read())
if m: print 'Round Trip Time: %s ms -' % m.group(1), self.host
else: print 'Error: Invalid Response -', self.host
if __name__ == '__main__':
hosts = [
'www.pylot.org',
'www.goldb.org',
'www.google.com',
'www.yahoo.com',
'www.techcrunch.com',
'www.this_one_wont_work.com'
]
Pinger(hosts)
The documentation for Environment.UserName seems to be a bit conflicting:
On the same page it says:
Gets the user name of the person who is currently logged on to the Windows operating system.
AND
displays the user name of the person who started the current thread
If you test Environment.UserName using RunAs, it will give you the RunAs user account name, not the user originally logged on to Windows.
First of all, I'd recommend using the ISO-8601 standard format for date/time - it works regardless of the language and regional settings on your SQL Server. ISO-8601 is the YYYYMMDD
format - no spaces, no dashes - just the data:
select * from tblErrorLog
where errorDate = '20081220'
Second of all, you need to be aware that SQL Server 2005 DATETIME
always includes a time. If you check for exact match with just the date part, you'll get only rows that match with a time of 0:00:00 - nothing else.
You can either use any of the recommend range queries mentioned, or in SQL Server 2008, you could use the DATE
only date time - or you could do a check something like:
select * from tblErrorLog
where DAY(errorDate) = 20 AND MONTH(errorDate) = 12 AND YEAR(errorDate) = 2008
Whichever works best for you.
If you need to do this query often, you could either try to normalize the DATETIME
to include only the date, or you could add computed columns for DAY, MONTH and YEAR:
ALTER TABLE tblErrorLog
ADD ErrorDay AS DAY(ErrorDate) PERSISTED
ALTER TABLE tblErrorLog
ADD ErrorMonth AS MONTH(ErrorDate) PERSISTED
ALTER TABLE tblErrorLog
ADD ErrorYear AS YEAR(ErrorDate) PERSISTED
and then you could query more easily:
select * from tblErrorLog
where ErrorMonth = 5 AND ErrorYear = 2009
and so forth. Since those fields are computed and PERSISTED, they're always up to date and always current, and since they're peristed, you can even index them if needed.
You could define a macro containing the following code:
Sub DeleteA5X50()
Range("A5:X50").Select
Selection.ClearContents
end sub
Running the macro would select the range A5:x50 on the active worksheet and clear all the contents of the cells within that range.
To leave your formulas intact use the following instead:
Sub DeleteA5X50()
Range("A5:X50").Select
Selection.SpecialCells(xlCellTypeConstants, 23).Select
Selection.ClearContents
end sub
This will first select the overall range of cells you are interested in clearing the contents from and will then further limit the selection to only include cells which contain what excel considers to be 'Constants.'
You can do this manually in excel by selecting the range of cells, hitting 'f5' to bring up the 'Go To' dialog box and then clicking on the 'Special' button and choosing the 'Constants' option and clicking 'Ok'.
git branch --set-upstream-to=origin/main
This is a more common error now as many projects are moving their master
branch to another name like main
, primary
, default
, root
, reference
, latest
, etc, as discussed at Github plans to replace racially insensitive terms like ‘master’ and ‘whitelist’.
To fix it, first find out what the project is now using, which you can find via their github, gitlab or other git server.
Then do this to capture the current configuration:
$ git branch -vv
...
* master 968695b [origin/master] Track which contest a ballot was sampled for (#629)
...
Find the line describing the master
branch, and note whether the remote repo is called origin
, upstream
or whatever.
Then using that information, change the branch name to the new one, e.g. if it says you're currently tracking origin/master
, substitute main
:
git branch master --set-upstream-to origin/main
You can also rename your own branch to avoid future confusion:
git branch -m main
My apt-get
was old and busted, so I had to install from source. Here is what worked for me:
# Get the latest version from nodejs.org. At the time of this writing, it was 0.10.24
curl -o ~/node.tar.gz http://nodejs.org/dist/v0.10.24/node-v0.10.24.tar.gz
cd
tar -zxvf node.tar.gz
cd node-v0.6.18
./configure && make && sudo make install
These steps were mostly taken from joyent's installation wiki.
You can run the following command to determine if postgress is running:
$ pg_ctl status
You'll also want to set the PGDATA
environment variable.
Here's what I have in my ~/.bashrc
file for postgres:
export PGDATA='/usr/local/var/postgres'
export PGHOST=localhost
alias start-pg='pg_ctl -l $PGDATA/server.log start'
alias stop-pg='pg_ctl stop -m fast'
alias show-pg-status='pg_ctl status'
alias restart-pg='pg_ctl reload'
To get them to take effect, remember to source it like so:
$ . ~/.bashrc
Now, try it and you should get something like this:
$ show-pg-status
pg_ctl: server is running (PID: 11030)
/usr/local/Cellar/postgresql/9.2.4/bin/postgres
There are two solutions posted on that page. The one with lower votes I would recommend if possible.
If you are using HTML5 then it is perfectly valid to put a div
inside of a
. As long as the div doesn't also contain some other specific elements like other link tags.
<a href="Music.html">
<div id="music" class="nav">
Music I Like
</div>
</a>
The solution you are confused about actually makes the link as big as its container div. To make it work in your example you just need to add position: relative
to your div. You also have a small syntax error which is that you have given the span a class instead of an id. You also need to put your span inside the link because that is what the user is clicking on. I don't think you need the z-index
at all from that example.
div { position: relative; }
.hyperspan {
position:absolute;
width:100%;
height:100%;
left:0;
top:0;
}
<div id="music" class="nav">Music I Like
<a href="http://www.google.com">
<span class="hyperspan"></span>
</a>
</div>
When you give absolute
positioning to an element it bases its location and size after the first parent it finds that is relatively positioned. If none, then it uses the document. By adding relative
to the parent div you tell the span to only be as big as that.
I solved this on 12.10 by installing libssl-dev.
sudo apt-get install libssl-dev
I had this issue and changing the Compilation Mode setting for the project from Incremental to Whole Module fixed it for me.
days = (endDate - beginDate)/(60*60*24)
I don't think you'll get a better way than your function.
It is clean, easy to follow and understand, and returns the result of the condition (no return (...) ? true : false
mess).
Regarding 4., you still need to ensure that your "dummy script stub" is actually the target URL after all the rewriting is done, or you won't see anything!
A similar/related trick (see this question) is to insert a temporary rule such as:
RewriteRule (.*) /show.php?url=$1 [END]
Where show.php
is some very simple script that just displays its $_GET
parameters (you can display environment variables too, if you want).
This will stop the rewriting at the point you insert it into the ruleset, rather like a breakpoint in a debugger.
If you're using Apache <2.3.9, you'll need to use [L]
rather than [END]
, and you may then need to add:
RewriteRule ^show.php$ - [L]
At the very top of your ruleset, if the URL /show.php
is itself being rewritten.
Try changing the ADB connection timeout. I think it defaults that to 5000ms and I changed mine to 10000ms to get rid of that problem.
If you are in Eclipse, you can do this by going through
Window -> Preferences -> Android -> DDMS -> ADB Connection Timeout (ms)
Here is two examples, one print the logs (stdout) the other write the logs to a file:
import logging
import sys
logger = logging.getLogger()
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s')
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setLevel(logging.DEBUG)
stdout_handler.setFormatter(formatter)
file_handler = logging.FileHandler('logs.log')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.addHandler(stdout_handler)
With this example, all logs will be printed and also be written to a file named logs.log
Use example:
logger.info('This is a log message!')
logger.error('This is an error message.')
To summarize what was mentioned by Breno above
Say you have a variable with a path to a file
path = '/home/User/Desktop/myfile.py'
os.path.basename(path)
returns the string 'myfile.py'
and
os.path.dirname(path)
returns the string '/home/User/Desktop'
(without a trailing slash '/')
These functions are used when you have to get the filename/directory name given a full path name.
In case the file path is just the file name (e.g. instead of path = '/home/User/Desktop/myfile.py'
you just have myfile.py
), os.path.dirname(path)
returns an empty string.
awk '{$1=$2="";$0=$0;$1=$1}1'
Input
a b c d
Output
c d
echo $bool_val ? 'true' : 'false';
Or if you only want output when it's false:
echo !$bool_val ? 'false' : '';
Pure Python2 w/o dep:
def relpath(cwd, path):
"""Create a relative path for path from cwd, if possible"""
if sys.platform == "win32":
cwd = cwd.lower()
path = path.lower()
_cwd = os.path.abspath(cwd).split(os.path.sep)
_path = os.path.abspath(path).split(os.path.sep)
eq_until_pos = None
for i in xrange(min(len(_cwd), len(_path))):
if _cwd[i] == _path[i]:
eq_until_pos = i
else:
break
if eq_until_pos is None:
return path
newpath = [".." for i in xrange(len(_cwd[eq_until_pos+1:]))]
newpath.extend(_path[eq_until_pos+1:])
return os.path.join(*newpath) if newpath else "."
If your request contains an object like this:
{
"year": 1900,
"month": 1,
"day": 20
}
Then you can use:
data class DateObject(
val day: Int,
val month: Int,
val year: Int
)
class LocalDateConverter : StdConverter<DateObject, LocalDate>() {
override fun convert(value: DateObject): LocalDate {
return value.run { LocalDate.of(year, month, day) }
}
}
Above the field:
@JsonDeserialize(converter = LocalDateConverter::class)
val dateOfBirth: LocalDate
The code is in Kotlin but this would work for Java too of course.
The good way to get all the members from a group is to, make the DN of the group as the searchDN and pass the "member" as attribute to get in the search function. All of the members of the group can now be found by going through the attribute values returned by the search. The filter can be made generic like (objectclass=*).
If you can use LINQ you can use:
var e = enumerable.First();
This will throw an exception though if enumerable is empty: in which case you can use:
var e = enumerable.FirstOrDefault();
FirstOrDefault()
will return default(T)
if the enumerable is empty, which will be null
for reference types or the default 'zero-value' for value types.
If you can't use LINQ, then your approach is technically correct and no different than creating an enumerator using the GetEnumerator
and MoveNext
methods to retrieve the first result (this example assumes enumerable is an IEnumerable<Elem>
):
Elem e = myDefault;
using (IEnumerator<Elem> enumer = enumerable.GetEnumerator()) {
if (enumer.MoveNext()) e = enumer.Current;
}
Joel Coehoorn mentioned .Single()
in the comments; this will also work, if you are expecting your enumerable to contain exactly one element - however it will throw an exception if it is either empty or larger than one element. There is a corresponding SingleOrDefault()
method that covers this scenario in a similar fashion to FirstOrDefault()
. However, David B explains that SingleOrDefault()
may still throw an exception in the case where the enumerable contains more than one item.
Edit: Thanks Marc Gravell for pointing out that I need to dispose of my IEnumerator
object after using it - I've edited the non-LINQ example to display the using
keyword to implement this pattern.
No, C++ does not have a construct for this, given that the keyword "break" is already reserved for exiting the switch block. Alternatively a do..while() with an exit flag could suffice.
do {
switch(option){
case 1: ..; break;
...
case n: .. ;break;
default: flag = false; break;
}
} while(flag);
They are functionally equivalent, but INNER JOIN
can be a bit clearer to read, especially if the query has other join types (i.e. LEFT
or RIGHT
or CROSS
) included in it.
I believe i have found the answer, This code converts the integer to a hex string an removes the alpha.
Integer intColor = -16895234;
String hexColor = "#" + Integer.toHexString(intColor).substring(2);
Note only use this code if you are sure that removing the alpha would not affect anything.
You can install miniconda (https://conda.io/miniconda.html). That's a bit more than just python 3.7 but the installation is very straightforward and simple.
curl https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O
sudo yum install bzip2
bash Miniconda3-latest-Linux-x86_64.sh
You'll have to accept the license agreement and choose some options in interactive mode (accept the defaults). I believe it can be also installed silently somehow.
Calendar access is being added in iPhone OS 4.0:
Calendar Access
Apps can now create and edit events directly in the Calendar app with Event Kit.
Create recurring events, set up start and end times and assign them to any calendar on the device.
You can make a back-tracker character, ex, you could append any special character say "%" to the end of your string and then check the occurrence of that character.
But this is a very risky way as that character can be in other places also in the char*
char* stringVar = new char[4] ;
stringVar[0] = 'H' ;
stringVar[1] = 'E' ;
stringVar[2] = '$' ; // back-tracker character.
int i = 0 ;
while(1)
{
if (stringVar[i] == '$')
break ;
i++ ;
}
// i is the length of the string.
// you need to make sure, that there is no other $ in the char*
Otherwise define a custom structure to keep track of length and allocate memory.
Just to add to the other answers, the documentation gives this explanation:
KEY
is normally a synonym forINDEX
. The key attributePRIMARY KEY
can also be specified as justKEY
when given in a column definition. This was implemented for compatibility with other database systems.A
UNIQUE
index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. For all engines, aUNIQUE
index permits multipleNULL
values for columns that can containNULL
.A
PRIMARY KEY
is a unique index where all key columns must be defined asNOT NULL
. If they are not explicitly declared asNOT NULL
, MySQL declares them so implicitly (and silently). A table can have only onePRIMARY KEY
. The name of aPRIMARY KEY
is alwaysPRIMARY
, which thus cannot be used as the name for any other kind of index.
Just adding so you don't have to click-through:
curl --user name:password http://www.example.com
or if you're trying to do send authentication for OAuth 2:
curl -H "Authorization: OAuth <ACCESS_TOKEN>" http://www.example.com
Suppose cellspcing
/ cellpadding
/ border-spacing
property did not worked, you can use the code as follow.
<div class="form-group">
<table width="100%" cellspacing="2px" style="border-spacing: 10px;">
<tr>
<td width="47%">
<input type="submit" class="form-control btn btn-info" id="submit" name="Submit" />
</td>
<td width="5%"></td>
<td width="47%">
<input type="reset" class="form-control btn btn-info" id="reset" name="Reset" />
</td>
</tr>
</table>
</div>
I've tried and got succeed while seperate the button by using table-width and make an empty td as 2 or 1% it doesn't return more different.
yield is similar to return. The difference is:
yield makes a function iterable (in the following example primes(n = 1)
function becomes iterable).
What it essentially means is the next time the function is called, it will continue from where it left (which is after the line of yield expression
).
def isprime(n):
if n == 1:
return False
for x in range(2, n):
if n % x == 0:
return False
else:
return True
def primes(n = 1):
while(True):
if isprime(n): yield n
n += 1
for n in primes():
if n > 100: break
print(n)
In the above example if isprime(n)
is true it will return the prime number. In the next iteration it will continue from the next line
n += 1
The best is to install default Java until a specific Java version is not required. Before this, execute java -version to check if Java is not already installed.
sudo apt-get update
sudo apt-get install default-jre
sudo apt-get install default-jdk
That is everything that is needed to install Java.
System environment variables are globally accessed by all users.
User environment variables are specific only to the currently logged-in user.
Try what van said:
Right click your project
→ android tools
→ android support library
.
Hope this helps :)
Lots of reasonable answers already. I'll chip in with an analogy that may help some readers. ::
works a lot like the filesystem directory separator '/
', when searching your path for a program you'd like to run. Consider:
/path/to/executable
This is very explicit - only an executable at that exact location in the filesystem tree can match this specification, irrespective of the PATH in effect. Similarly...
::std::cout
...is equally explicit in the C++ namespace "tree".
Contrasting with such absolute paths, you can configure good UNIX shells (e.g. zsh) to resolve relative paths under your current directory or any element in your PATH
environment variable, so if PATH=/usr/bin:/usr/local/bin
, and you were "in" /tmp
, then...
X11/xterm
...would happily run /tmp/X11/xterm
if found, else /usr/bin/X11/xterm
, else /usr/local/bin/X11/xterm
. Similarly, say you were in a namespace called X
, and had a "using namespace Y
" in effect, then...
std::cout
...could be found in any of ::X::std::cout
, ::std::cout
, ::Y::std::cout
, and possibly other places due to argument-dependent lookup (ADL, aka Koenig lookup). So, only ::std::cout
is really explicit about exactly which object you mean, but luckily nobody in their right mind would ever create their own class/struct or namespace called "std
", nor anything called "cout
", so in practice using only std::cout
is fine.
Noteworthy differences:
1) shells tend to use the first match using the ordering in PATH
, whereas C++ gives a compiler error when you've been ambiguous.
2) In C++, names without any leading scope can be matched in the current namespace, while most UNIX shells only do that if you put .
in the PATH
.
3) C++ always searches the global namespace (like having /
implicitly your PATH
).
Using absolute ::abc::def::...
"paths" can sometimes be useful to isolate you from any other namespaces you're using, part of but don't really have control over the content of, or even other libraries that your library's client code also uses. On the other hand, it also couples you more tightly to the existing "absolute" location of the symbol, and you miss the advantages of implicit matching in namespaces: less coupling, easier mobility of code between namespaces, and more concise, readable source code.
As with many things, it's a balancing act. The C++ Standard puts lots of identifiers under std::
that are less "unique" than cout
, that programmers might use for something completely different in their code (e.g. merge
, includes
, fill
, generate
, exchange
, queue
, toupper
, max
). Two unrelated non-Standard libraries have a far higher chance of using the same identifiers as the authors are generally un- or less-aware of each other. And libraries - including the C++ Standard library - change their symbols over time. All this potentially creates ambiguity when recompiling old code, particularly when there's been heavy use of using namespace
s: the worst thing you can do in this space is allow using namespace
s in headers to escape the headers' scopes, such that an arbitrarily large amount of direct and indirect client code is unable to make their own decisions about which namespaces to use and how to manage ambiguities.
So, a leading ::
is one tool in the C++ programmer's toolbox to actively disambiguate a known clash, and/or eliminate the possibility of future ambiguity....
While the accepted solution works, it is not complete. By far.
If you want to get all the keys, you need to take into consideration 2 more things:
x86 & x64 applications do not have access to the same registry. Basically x86 cannot normally access x64 registry. And some applications only register to the x64 registry.
and
some applications actually install into the CurrentUser registry instead of the LocalMachine
With that in mind, I managed to get ALL installed applications using the following code, WITHOUT using WMI
Here is the code:
List<string> installs = new List<string>();
List<string> keys = new List<string>() {
@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",
@"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
};
// The RegistryView.Registry64 forces the application to open the registry as x64 even if the application is compiled as x86
FindInstalls(RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64), keys, installs);
FindInstalls(RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64), keys, installs);
installs = installs.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList();
installs.Sort(); // The list of ALL installed applications
private void FindInstalls(RegistryKey regKey, List<string> keys, List<string> installed)
{
foreach (string key in keys)
{
using (RegistryKey rk = regKey.OpenSubKey(key))
{
if (rk == null)
{
continue;
}
foreach (string skName in rk.GetSubKeyNames())
{
using (RegistryKey sk = rk.OpenSubKey(skName))
{
try
{
installed.Add(Convert.ToString(sk.GetValue("DisplayName")));
}
catch (Exception ex)
{ }
}
}
}
}
}
public static List<string> DevideByStringLength(string text, int chunkSize)
{
double a = (double)text.Length / chunkSize;
var numberOfChunks = Math.Ceiling(a);
Console.WriteLine($"{text.Length} | {numberOfChunks}");
List<string> chunkList = new List<string>();
for (int i = 0; i < numberOfChunks; i++)
{
string subString = string.Empty;
if (i == (numberOfChunks - 1))
{
subString = text.Substring(chunkSize * i, text.Length - chunkSize * i);
chunkList.Add(subString);
continue;
}
subString = text.Substring(chunkSize * i, chunkSize);
chunkList.Add(subString);
}
return chunkList;
}
Use:
IF Var IS NULL THEN
var := 5;
END IF;
Oracle 9i+:
var = COALESCE(Var, 5)
Other alternatives:
var = NVL(var, 5)
Reference:
I have the same issue and solved it by reading this post, while solving it, I hitted a problem: auth failed
.
And I finally solved it by using a ssh key
way to authorize myself. I found the EGit offical guide very useful and I configured the ssh
way successfully by refer to the Eclipse SSH Configuration
section in the link provided.
Hope it helps.
I will add to @Aaron's answer with an approach that gives you the opportunity to style the dialog box in a better way. Here is an adjusted example:
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Title");
// I'm using fragment here so I'm using getView() to provide ViewGroup
// but you can provide here any other instance of ViewGroup from your Fragment / Activity
View viewInflated = LayoutInflater.from(getContext()).inflate(R.layout.text_inpu_password, (ViewGroup) getView(), false);
// Set up the input
final EditText input = (EditText) viewInflated.findViewById(R.id.input);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
builder.setView(viewInflated);
// Set up the buttons
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
m_Text = input.getText().toString();
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
Here is the example layout used to create the EditText dialog:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="@dimen/content_padding_normal">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<AutoCompleteTextView
android:id="@+id/input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_password"
android:imeOptions="actionDone"
android:inputType="textPassword" />
</android.support.design.widget.TextInputLayout>
</FrameLayout>
The final result:
I had similar problem (in bash terminal command was working correctly but zsh showed command not found error)
just paste whatever you were earlier pasting in ~/.bashrc to:
~/.zshrc
Execute this command in the command prompt and you will be good to go
npm install -g @angular/cli@version_name
Use another text editor
env EDITOR=nano crontab -e
or
env EDITOR=code crontab -e
I use bootstrap 4.0.0
since we want to simulate .show
to hover event, it simply easy. just add all styles in .dropdown.show .dropdown-menu
to the :hover
. like this:
.dropdown:hover>.dropdown-menu {
opacity: 1;
visibility: visible;
transform: translate3d(0px, 0px, 0px);
}
Well this should change your format to text.
Worksheets("Sheetname").Activate
Worksheets("SheetName").Columns(1).Select 'or Worksheets("SheetName").Range("A:A").Select
Selection.NumberFormat = "@"
There is a jQuery plugin that can deal with this very well
http://www.jqui.net/jquery-projects/jquery-mutate-official/
here is a demo of it with different scenarios as to when the height change, if you resize the red bordered div.
Presumably the method does something, and doesn't simply return?
Assuming this is the case, then:
If youy let us know what the method does, I could be more specific.
pip install -r requirements.txt
for python 2.x
pip3 install -r requirements.txt
for python 3.x
(in case multiple versions are installed)
The solution is described here: How to remove whitespace from right end of NSString?
Add the following categories to NSString:
- (NSString *)stringByTrimmingTrailingCharactersInSet:(NSCharacterSet *)characterSet {
NSRange rangeOfLastWantedCharacter = [self rangeOfCharacterFromSet:[characterSet invertedSet]
options:NSBackwardsSearch];
if (rangeOfLastWantedCharacter.location == NSNotFound) {
return @"";
}
return [self substringToIndex:rangeOfLastWantedCharacter.location+1]; // non-inclusive
}
- (NSString *)stringByTrimmingTrailingWhitespaceAndNewlineCharacters {
return [self stringByTrimmingTrailingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
And you use it as such:
[yourNSString stringByTrimmingTrailingWhitespaceAndNewlineCharacters]
(Assuming C, C++, Java, JavaScript)
|
and &
are bitwise operators while ||
and &&
are logical operators. Usually you'd want to use ||
and &&
for if statements and loops and such (i.e. for your examples above). The bitwise operators are for setting and checking bits within bitmasks.
I like using a function decorator. I added a class, which also times the function time. Assume gLog is a standard python logger:
class EnterExitLog():
def __init__(self, funcName):
self.funcName = funcName
def __enter__(self):
gLog.debug('Started: %s' % self.funcName)
self.init_time = datetime.datetime.now()
return self
def __exit__(self, type, value, tb):
gLog.debug('Finished: %s in: %s seconds' % (self.funcName, datetime.datetime.now() - self.init_time))
def func_timer_decorator(func):
def func_wrapper(*args, **kwargs):
with EnterExitLog(func.__name__):
return func(*args, **kwargs)
return func_wrapper
so now all you have to do with your function is decorate it and voila
@func_timer_decorator
def my_func():
I got the same problem and it is not the solution that you told. So I changed the "from datetime import datetime" to "import datetime". After that with the help of "datetime.datetime" I can get the whole modules correctly. I guess this is the correct answer to that question.
That's not possible. but you can use an Object Mapper like AutoMapper
Example:
class A
{
public int IntProp { get; set; }
}
class B
{
public int IntProp { get; set; }
public string StrProp { get; set; }
}
In global.asax or application startup:
AutoMapper.Mapper.CreateMap<A, B>();
Usage:
var b = AutoMapper.Mapper.Map<B>(a);
It's easily configurable via a fluent API.
Microsoft just added an official prelease version of exactly what you're looking for (called a MultiDictionary) available through NuGet here: https://www.nuget.org/packages/Microsoft.Experimental.Collections/
Info on usage and more details can be found through the official MSDN blog post here: http://blogs.msdn.com/b/dotnet/archive/2014/06/20/would-you-like-a-multidictionary.aspx
I'm the developer for this package, so let me know either here or on MSDN if you have any questions about performance or anything.
Hope that helps.
Update
The MultiValueDictionary
is now on the corefxlab repo, and you can get the NuGet package from this MyGet feed.
Since it appears you are using jQuery, here is a jQuery solution.
$(function() {
$('#Eframe').on("mousewheel", function() {
alert($(document).scrollTop());
});
});
Not much to explain here. If you want, here is the jQuery documentation.
Try using TempData
:
public ActionResult Create(FormCollection collection) {
...
TempData["notice"] = "Successfully registered";
return RedirectToAction("Index");
...
}
Then, in your Index view, or master page, etc., you can do this:
<% if (TempData["notice"] != null) { %>
<p><%= Html.Encode(TempData["notice"]) %></p>
<% } %>
Or, in a Razor view:
@if (TempData["notice"] != null) {
<p>@TempData["notice"]</p>
}
Quote from MSDN (page no longer exists as of 2014, archived copy here):
An action method can store data in the controller's TempDataDictionary object before it calls the controller's RedirectToAction method to invoke the next action. The TempData property value is stored in session state. Any action method that is called after the TempDataDictionary value is set can get values from the object and then process or display them. The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request.
increase heap size of tomcat for window add this file in apache-tomcat-7.0.42\bin
heap size can be changed based on Requirements.
set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256m
.communicate()
writes input (there is no input in this case so it just closes subprocess' stdin to indicate to the subprocess that there is no more input), reads all output, and waits for the subprocess to exit.
The exception EOFError is raised in the child process by raw_input()
(it expected data but got EOF (no data)).
p.stdout.read()
hangs forever because it tries to read all output from the child at the same time as the child waits for input (raw_input()
) that causes a deadlock.
To avoid the deadlock you need to read/write asynchronously (e.g., by using threads or select) or to know exactly when and how much to read/write, for example:
from subprocess import PIPE, Popen
p = Popen(["python", "-u", "1st.py"], stdin=PIPE, stdout=PIPE, bufsize=1)
print p.stdout.readline(), # read the first line
for i in range(10): # repeat several times to show that it works
print >>p.stdin, i # write input
p.stdin.flush() # not necessary in this case
print p.stdout.readline(), # read output
print p.communicate("n\n")[0], # signal the child to exit,
# read the rest of the output,
# wait for the child to exit
Note: it is a very fragile code if read/write are not in sync; it deadlocks.
Beware of block-buffering issue (here it is solved by using "-u" flag that turns off buffering for stdin, stdout in the child).
for column in df:
print(df[column])
This answer seems good.
however, it lead me towards an error as it resulted with
Configuration 'xyz' could not be found in project ...
error in build.
It is requierd not only to updated build configurations, but also serve
ones.
So just to leave no confusions:
--env
is not supported in angular 6
--env
got changed into --configuration
|| -c
(and is now more powerful)angular.json
file:
{ ... "build": "configurations": ...
propertyfileReplacements
part, (but more options are available){ ... "serve": "configurations": ...
propertybrowserTarget="your-project-name:build:staging"
select min(DEPARTMENT.DeptName) as deptname
from DEPARTMENT
inner join employee on
DEPARTMENT.DeptId = employee.DeptId
where Salary > 1000
group by (EmpId) having count(EmpId) > =2
Jenkins stores the console log on master. If you want programmatic access to the log, and you are running on master, you can access the log that Jenkins already has, without copying it to the artifacts or having to GET the http job URL.
From http://javadoc.jenkins.io/archive/jenkins-1.651/hudson/model/Run.html#getLogFile(), this returns the File object for the console output (in the jenkins file system, this is the "log" file in the build output directory).
In my case, we use a chained (child) job to do parsing and analysis on a parent job's build.
When using a groovy script run in Jenkins, you get an object named "build" for the run. We use this to get the http://javadoc.jenkins.io/archive/jenkins-1.651/hudson/model/Build.html for the upstream job, then call this job's .getLogFile().
Added bonus; since it's just a File object, we call .getParent() to get the folder where Jenkins stores build collateral (like test xmls, environment variables, and other things that may not be explicitly exposed through the artifacts) which we can also parse.
Double added bonus; we also use matrix jobs. This sometimes makes inferring the file path on the system a pain. .getLogFile().getParent() takes away all the pain.
This may be what you want:
This code places a default text string Enter your name here
inside the <input>
textbox, and colorizes the text to light grey.
As soon as the box is clicked, the default text is cleared and text color set to black.
If text is erased, the default text string is replaced and light grey color reset.
HTML:
<input id="fname" type="text" />
jQuery/javascript:
$(document).ready(function() {
var curval;
var fn = $('#fname');
fn.val('Enter your name here').css({"color":"lightgrey"});
fn.focus(function() {
//Upon ENTERING the field
curval = $(this).val();
if (curval == 'Enter your name here' || curval == '') {
$(this).val('');
$(this).css({"color":"black"});
}
}); //END focus()
fn.blur(function() {
//Upon LEAVING the field
curval = $(this).val();
if (curval != 'Enter your name here' && curval != '') {
$(this).css({"color":"black"});
}else{
fn.val('Enter your name here').css({"color":"lightgrey"});
}
}); //END blur()
}); //END document.ready
An alternative method:
for idx, car in enumerate(cars):
# Skip first line.
if not idx:
continue
# Skip last line.
if idx + 1 == len(cars):
continue
# Real code here.
print car
as said above simple line of code will fix your problems
border: 1px solid #000;
There is another option to add border to your image and that with photoshop you can see how it's done with this tutorial below: http://bannercheapdesign.com/articles-and-tutorials/learn-how-to-add-border-to-your-banner-design-using-photoshop/
To fix up the second method in Jeff Hillman's post, you could either do a:
$app = Get-WmiObject
-Query "SELECT * FROM Win32_Product WHERE Name = 'Software Name'"
Or
$app = Get-WmiObject -Class Win32_Product `
-Filter "Name = 'Software Name'"
I had this problem when trying to run 'npm install' in a Terminal window which had been opened before installing Node.js.
Opening a new Terminal window (i.e. bash session) worked. (Presumably this provided the correct environment variables for npm to run correctly.)
The line-continuation will fail if you have whitespace (spaces or tab characters[1]) after the backslash and before the newline. With no such whitespace, your example works fine for me:
$ cat test.sh
if ! fab --fabfile=.deploy/fabfile.py \
--forward-agent \
--disable-known-hosts deploy:$target; then
echo failed
else
echo succeeded
fi
$ alias fab=true; . ./test.sh
succeeded
$ alias fab=false; . ./test.sh
failed
Some detail promoted from the comments: the line-continuation backslash in the shell is not really a special case; it is simply an instance of the general rule that a backslash "quotes" the immediately-following character, preventing any special treatment it would normally be subject to. In this case, the next character is a newline, and the special treatment being prevented is terminating the command. Normally, a quoted character winds up included literally in the command; a backslashed newline is instead deleted entirely. But otherwise, the mechanism is the same. Most importantly, the backslash only quotes the immediately-following character; if that character is a space or tab, you just get a literal space or tab, and any subsequent newline remains unquoted.
[1] or carriage returns, for that matter, as Czechnology points out. Bash does not get along with Windows-formatted text files, not even in WSL. Or Cygwin, but at least their Bash port has added a set -o igncr
option that you can set to make it carriage-return-tolerant.
use <strong>
or <b>
tag
also, you can try with css <span style="font-weight:bold">text</span>
A quick hack that may suit your needs..
Take off the frame of the box and manually position the two legends next to each other. Something like this..
ax1.legend(loc = (.75,.1), frameon = False)
ax2.legend( loc = (.75, .05), frameon = False)
Where the loc tuple is left-to-right and bottom-to-top percentages that represent the location in the chart.
Use data type 'MultilineText':
[DataType(DataType.MultilineText)]
public string Text { get; set; }
Create file myButton.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/colorButton"/>
<corners android:radius="10dp"/>
</shape>
add to your button
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/myButton"/>
I did not realize that the first nested element is actually an array. The correct way access to the post code key is as follows:
r = requests.get('http://api.zippopotam.us/us/ma/belmont')
j = r.json()
print j['state']
print j['places'][1]['post code']
By combining the multicol package and enumitem package packages it is easy to define environments that are multi-column analogues of the enumerate and itemize environments:
\documentclass{article}
\usepackage{enumitem}
\usepackage{multicol}
\newlist{multienum}{enumerate}{1}
\setlist[multienum]{
label=\alph*),
before=\begin{multicols}{2},
after=\end{multicols}
}
\newlist{multiitem}{itemize}{1}
\setlist[multiitem]{
label=\textbullet,
before=\begin{multicols}{2},
after=\end{multicols}
}
\begin{document}
\textsf{Two column enumerate}
\begin{multienum}
\item item 1
\item item 2
\item item 3
\item item 4
\item item 5
\item item 6
\end{multienum}
\textsf{Two column itemize}
\begin{multiitem}
\item item 1
\item item 2
\item item 3
\item item 4
\item item 5
\item item 6
\end{multiitem}
\end{document}
The output is what you would hope for:
Since you are using an INNER JOIN you can just put the conditions in the WHERE clause, like this:
SELECT
p1.kArtikel,
p1.cName,
p1.cKurzBeschreibung,
p1.dLetzteAktualisierung,
p1.dErstellt,
p1.cSeo,
p2.kartikelpict,
p2.nNr,
p2.cPfad
FROM
tartikel AS p1 INNER JOIN tartikelpict AS p2
ON p1.kArtikel = p2.kArtikel
WHERE
DATE(dErstellt) > (NOW() - INTERVAL 7 DAY)
AND p2.nNr = 1
ORDER BY
p1.kArtikel DESC
LIMIT
100;
One thing to note is that the two are actually very related. Linear SVMs are equivalent to single-layer NN's (i.e., perceptrons), and multi-layer NNs can be expressed in terms of SVMs. See here for some details.
There is another way, take this as example
Dim sr As String
sr = "6:10"
Rows(sr).Select
All you need to do is to convert your variables iStartRow
, iEndRow
to a string.
if you use Windows 10, this is the directory:
C:\Users<UserName>\AppData\Local\
+
<ProjectName.exe_Url_somedata>\1.0.0.0<filename.config>
If you are using Spring Framework with application.yml
and having trouble to make the test find the SQL file on the INIT
property, you can use the classpath:
notation.
For example, if you have a init.sql
SQL file on the src/test/resources
, just use:
url=jdbc:h2:~/test;INIT=RUNSCRIPT FROM 'classpath:init.sql';DB_CLOSE_DELAY=-1;
Lets see two efficient ways that deal with escaped quotes. These patterns are not designed to be concise nor aesthetic, but to be efficient.
These ways use the first character discrimination to quickly find quotes in the string without the cost of an alternation. (The idea is to discard quickly characters that are not quotes without to test the two branches of the alternation.)
Content between quotes is described with an unrolled loop (instead of a repeated alternation) to be more efficient too: [^"\\]*(?:\\.[^"\\]*)*
Obviously to deal with strings that haven't balanced quotes, you can use possessive quantifiers instead: [^"\\]*+(?:\\.[^"\\]*)*+
or a workaround to emulate them, to prevent too much backtracking. You can choose too that a quoted part can be an opening quote until the next (non-escaped) quote or the end of the string. In this case there is no need to use possessive quantifiers, you only need to make the last quote optional.
Notice: sometimes quotes are not escaped with a backslash but by repeating the quote. In this case the content subpattern looks like this: [^"]*(?:""[^"]*)*
The patterns avoid the use of a capture group and a backreference (I mean something like (["']).....\1
) and use a simple alternation but with ["']
at the beginning, in factor.
Perl like:
["'](?:(?<=")[^"\\]*(?s:\\.[^"\\]*)*"|(?<=')[^'\\]*(?s:\\.[^'\\]*)*')
(note that (?s:...)
is a syntactic sugar to switch on the dotall/singleline mode inside the non-capturing group. If this syntax is not supported you can easily switch this mode on for all the pattern or replace the dot with [\s\S]
)
(The way this pattern is written is totally "hand-driven" and doesn't take account of eventual engine internal optimizations)
ECMA script:
(?=["'])(?:"[^"\\]*(?:\\[\s\S][^"\\]*)*"|'[^'\\]*(?:\\[\s\S][^'\\]*)*')
POSIX extended:
"[^"\\]*(\\(.|\n)[^"\\]*)*"|'[^'\\]*(\\(.|\n)[^'\\]*)*'
or simply:
"([^"\\]|\\.|\\\n)*"|'([^'\\]|\\.|\\\n)*'
Alternatively to calling plt.show()
at the end of the script, you can also control each figure separately doing:
f = plt.figure(1)
plt.hist........
............
f.show()
g = plt.figure(2)
plt.hist(........
................
g.show()
raw_input()
In this case you must call raw_input
to keep the figures alive.
This way you can select dynamically which figures you want to show
Note: raw_input()
was renamed to input()
in Python 3
You can avoid the 100% width issue by specifying a maximum width. The maxWidth
option does not seem to work; so set the CSS max-width
property on the dialog widget instead.
In case you also want to constrain the maximum height, use the maxHeight
option. It will correctly show a scrollbar when necessary.
$(function() {_x000D_
var $dialog = $("#dialog");_x000D_
$dialog.dialog({_x000D_
autoOpen: false,_x000D_
modal: true,_x000D_
width: "auto"_x000D_
});_x000D_
/*_x000D_
* max-width should be set on dialog widget because maxWidth option has known issues_x000D_
* max-height should be set using maxHeight option_x000D_
*/_x000D_
$dialog.dialog("widget").css("max-width", $(window).width() - 100);_x000D_
$dialog.dialog("option", "maxHeight", $(window).height() - 100);_x000D_
$(".test-link").on("click", function(e) {_x000D_
e.preventDefault();_x000D_
$dialog.html($(this.hash).html());_x000D_
// if you change the content of dialog after it is created then reset the left_x000D_
// coordinate otherwise content only grows up to the right edge of screen_x000D_
$dialog.dialog("widget").css({ left: 0 });_x000D_
$dialog.dialog("open");_x000D_
});_x000D_
});
_x000D_
@import url("https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.min.css");
_x000D_
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>_x000D_
_x000D_
<div id="dialog"></div>_x000D_
_x000D_
<!-- test links -->_x000D_
_x000D_
<p>_x000D_
<a href="#content-1" class="test-link">Image (Landscape)</a>_x000D_
<a href="#content-2" class="test-link">Image (Portrait)</a>_x000D_
<a href="#content-3" class="test-link">Text Content (Small)</a>_x000D_
<a href="#content-4" class="test-link">Text Content (Large)</a>_x000D_
</p>_x000D_
<p>If you are viewing in Stack Snippets > Full page then reload the snippet so that window height is recalculated (Right click > Reload frame).</p>_x000D_
_x000D_
<!-- sample content -->_x000D_
_x000D_
<div id="content-1" style="display: none;">_x000D_
<img src="https://i.stack.imgur.com/5leq2.jpg" width="450" height="300">_x000D_
</div>_x000D_
_x000D_
<div id="content-2" style="display: none;">_x000D_
<img src="https://i.stack.imgur.com/9pVkn.jpg" width="300" height="400">_x000D_
</div>_x000D_
_x000D_
<div id="content-3" style="display: none;">_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sodales eu urna sit amet fermentum. Morbi ornare, leo ut ornare volutpat, nibh diam mattis elit, eget porta sapien quam eu mi. Nullam sollicitudin, nibh non suscipit commodo, nisi metus bibendum urna, vitae congue nisl risus eu tellus. Praesent diam ligula, hendrerit eget bibendum quis, convallis eu erat. Aliquam scelerisque turpis augue, sit amet dictum urna hendrerit id. Vestibulum luctus dolor quis ex sodales, nec aliquet lacus elementum. Mauris sollicitudin dictum augue eget posuere. Suspendisse diam elit, scelerisque eu quam vel, tempus sodales metus. Morbi et vehicula elit. In sit amet bibendum mi.</p>_x000D_
</div>_x000D_
_x000D_
<div id="content-4" style="display: none;">_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sodales eu urna sit amet fermentum. Morbi ornare, leo ut ornare volutpat, nibh diam mattis elit, eget porta sapien quam eu mi. Nullam sollicitudin, nibh non suscipit commodo, nisi metus bibendum urna, vitae congue nisl risus eu tellus. Praesent diam ligula, hendrerit eget bibendum quis, convallis eu erat. Aliquam scelerisque turpis augue, sit amet dictum urna hendrerit id. Vestibulum luctus dolor quis ex sodales, nec aliquet lacus elementum. Mauris sollicitudin dictum augue eget posuere. Suspendisse diam elit, scelerisque eu quam vel, tempus sodales metus. Morbi et vehicula elit. In sit amet bibendum mi.</p>_x000D_
<p>Aenean eu magna tempor, pellentesque arcu eget, mattis enim. Cras at volutpat mi. Aenean id placerat felis, quis imperdiet nunc. Aenean a iaculis est, quis lacinia nisl. Sed aliquet sem eget justo convallis congue. Quisque rhoncus nulla sit amet cursus maximus. Phasellus nec auctor urna. Nam mattis felis et diam finibus consectetur. Etiam finibus dignissim vestibulum. In eu urna mattis dui pharetra iaculis. Nam eleifend odio et massa imperdiet, et hendrerit mauris tempor. Quisque sapien lorem, dapibus ut ultricies ut, hendrerit in nulla. Nunc lobortis mi libero, nec tincidunt lacus pretium at. Aliquam erat volutpat.</p>_x000D_
<p>Fusce eleifend enim nec massa porttitor tempor a eget neque. Quisque vel augue ac urna posuere iaculis. Morbi pharetra augue ac interdum pulvinar. Duis vel posuere risus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Ut vitae lectus non nisl iaculis volutpat nec vitae ante. Maecenas quis condimentum elit. Sed nisl urna, convallis ut pellentesque sit amet, pellentesque eget quam. Pellentesque ornare sapien ac scelerisque pretium. Pellentesque metus tortor, accumsan in vehicula iaculis, efficitur eget nisi. Donec tincidunt, felis vel viverra convallis, lectus lectus elementum magna, faucibus viverra risus nulla in dolor.</p>_x000D_
<p>Duis tristique sapien ut commodo laoreet. In vel sapien dui. Vestibulum non bibendum erat. Etiam iaculis vehicula accumsan. Phasellus finibus, elit et molestie luctus, massa arcu tempor nulla, id hendrerit metus mauris non mi. Morbi a ultricies magna. Proin condimentum suscipit urna eu maximus. Mauris condimentum massa ac egestas fermentum. Praesent faucibus a neque a molestie. Integer sed diam at eros accumsan convallis.</p>_x000D_
</div>
_x000D_
Add .*
to s
in your first line.
Try:
DELETE s.* FROM spawnlist s
INNER JOIN npc n ON s.npc_templateid = n.idTemplate
WHERE (n.type = "monster");
Save below in a test.bat
and It'll work for you:
@echo off
net use Z: \\server\SharedFolderName password /user:domain\Username /persistent:yes
/persistent:yes
flag will tell the computer to automatically reconnect this share on logon. Otherwise, you need to run the script again during each boot to map the drive.
For Example:
net use Z: \\WindowsServer123\g$ P@ssw0rd /user:Mynetdomain\Sysadmin /persistent:yes
As a previous answer mentioned, passing the -F
option to less
causes it to quit if the content is less than one screen. However, after doing so, the screen is reset, and you end up not seeing the content.
The -X
option does away with that behaviour. So, I use the following to enable conditional paging based on the amount of content:
git config --global --replace-all core.pager "less -F -X"
if you want to rotate inline elements, you should set the inline element to inline-block
first.
i {
display: inline-block;
}
i:hover {
animation: rotate-btn .5s linear 3;
-webkit-animation: rotate-btn .5s linear 3;
}
@keyframes rotate-btn {
0% {
transform: rotate(0);
}
100% {
transform: rotate(-360deg);
}
}
I just deleted the existing DB that i wanted to override with the backup and restored it from backup and it worked without the error.
Since Python is open source you can read the source code.
To find out what file a particular module or function is implemented in you can usually print the __file__
attribute. Alternatively, you may use the inspect
module, see the section Retrieving Source Code in the documentation of inspect
.
For built-in classes and methods this is not so straightforward since inspect.getfile
and inspect.getsource
will return a type error stating that the object is built-in. However, many of the built-in types can be found in the Objects
sub-directory of the Python source trunk. For example, see here for the implementation of the enumerate class or here for the implementation of the list
type.
In my case, I was missing import UIKit
on top of my NSManagedObject
subclass.
After importing it, I could remove that error as UIApplication
is the part of UIKit
Hope it helps others !!!
The single most important difference between the two is that you should start using JupyterLab straight away, and that you should not worry about Jupyter Notebook at all. Because:
JupyterLab will eventually replace the classic Jupyter Notebook. Throughout this transition, the same notebook document format will be supported by both the classic Notebook and JupyterLab
Other posts have suggested that Jupyter Notebook (JN) could potentially be easier to use than JupyterLab (JL) for beginners. But I would have to disagree.
A great advantage with JL, and arguably one of the most important differences between JL and JN, is that you can more easily run a single line and even highlighted text. I prefer using a keyboard shortcut for this, and assigning shortcuts is pretty straight-forward.
And the fact that you can execute code in a Python console makes JL much more fun to work with. Other answers have already mentioned this, but JL can in some ways be considered a tool to run Notebooks and more. So the way I use JupyterLab is by having it set up with an .ipynb file, a file browser and a python console like this:
And now you have these tools at your disposal:
Ctrl+Enter
Shift+Enter
Anywhere between your <body>
and </body>
tags, put in a button using the below code:
<button>
<a href="file.doc" download>Click to Download!</a>
</button>
This is sure to work!
Go to the "Database" option you mentioned.
Copied from here.
The problem is that variables declared in one case
are still visible in the subsequent case
s unless an explicit { }
block is used, but they will not be initialized because the initialization code belongs to another case
.
In the following code, if foo
equals 1, everything is ok, but if it equals 2, we'll accidentally use the i
variable which does exist but probably contains garbage.
switch(foo) {
case 1:
int i = 42; // i exists all the way to the end of the switch
dostuff(i);
break;
case 2:
dostuff(i*2); // i is *also* in scope here, but is not initialized!
}
Wrapping the case in an explicit block solves the problem:
switch(foo) {
case 1:
{
int i = 42; // i only exists within the { }
dostuff(i);
break;
}
case 2:
dostuff(123); // Now you cannot use i accidentally
}
To further elaborate, switch
statements are just a particularly fancy kind of a goto
. Here's an analoguous piece of code exhibiting the same issue but using a goto
instead of a switch
:
int main() {
if(rand() % 2) // Toss a coin
goto end;
int i = 42;
end:
// We either skipped the declaration of i or not,
// but either way the variable i exists here, because
// variable scopes are resolved at compile time.
// Whether the *initialization* code was run, though,
// depends on whether rand returned 0 or 1.
std::cout << i;
}
I agree with Ed B. You should use EXISTS method but a more efficient way to do this is:
IF EXISTS(SELECT 1 FROM service s WHERE s.service_id = ?)
BEGIN
--DO STUFF HERE
END
HTH
Ideally we should do it from either controller or directive as per applicable.
Use $anchorScroll
, $location
as dependency injection.
Then call this two method as
$location.hash('scrollToDivID');
$anchorScroll();
Here scrollToDivID
is the id where you want to scroll.
Assumed you want to navigate to a error message div as
<div id='scrollToDivID'>Your Error Message</div>
For more information please see this documentation
Use ThisWorkbook
which will refer to the original workbook which holds the code.
Alternatively at code start
Dim Wb As Workbook
Set Wb = ActiveWorkbook
sample code that activates all open books before returning to ThisWorkbook
Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
Wb2.Activate
Next
Wb.Activate
End Sub
function DecimalNumberValidation() {
var amounttext = ;
if (!(/^[-+]?\d*\.?\d*$/.test(document.getElementById('txtRemittanceNumber').value))){
alert('Please enter only numbers into amount textbox.')
}
else
{
alert('Right Number');
}
}
function will validate any decimal number weather number has decimal places or not, it will say "Right Number" other wise "Please enter only numbers into amount textbox." alert message will come up.
Thanks... :)
For setting select value with triggering selected:
$('select.opts').val('SEL1').change();
For setting option from a scope:
$('.selDiv option[value="SEL1"]')
.attr('selected', 'selected')
.change();
This code use selector to find out the select object with condition, then change the selected attribute by attr()
.
Futher, I recommend to add change()
event after setting attribute to selected
, by doing this the code will close to changing select by user.
With the latest update to the extension all you need to do is just specify the "python.pythonPath"
as follows.
The values for "python.autoComplete.extraPaths"
will be determined during runtime, but you are still free to specify custom paths in there.
Please, remember to restart Visual Studio Code once the necessary changes have been made.
{
"editor.rulers": [80,100],
"python.pythonPath":"~/dev/venvs/proj/bin/python"
}
You can use many ports together for each project,
php artisan serve --port=8000
php artisan serve --port=8001
php artisan serve --port=8002
php artisan serve --port=8003
You need to put the worksheet identifier in your range statements as shown below ...
Option Explicit
Dim ws As Worksheet, a As Range
Sub forEachWs()
For Each ws In ActiveWorkbook.Worksheets
Call resizingColumns
Next
End Sub
Sub resizingColumns()
ws.Range("A:A").ColumnWidth = 20.14
ws.Range("B:B").ColumnWidth = 9.71
ws.Range("C:C").ColumnWidth = 35.86
ws.Range("D:D").ColumnWidth = 30.57
ws.Range("E:E").ColumnWidth = 23.57
ws.Range("F:F").ColumnWidth = 21.43
ws.Range("G:G").ColumnWidth = 18.43
ws.Range("H:H").ColumnWidth = 23.86
ws.Range("i:I").ColumnWidth = 27.43
ws.Range("J:J").ColumnWidth = 36.71
ws.Range("K:K").ColumnWidth = 30.29
ws.Range("L:L").ColumnWidth = 31.14
ws.Range("M:M").ColumnWidth = 31
ws.Range("N:N").ColumnWidth = 41.14
ws.Range("O:O").ColumnWidth = 33.86
End Sub
spark-submit \
--class org.apache.spark.examples.SparkPi \
--master yarn \
--deploy-mode cluster \ # can be client for client mode
--executor-memory 2G \
--num-executors 5 \
/path/to/examples.jar \
1000
Apparently things are changing.... getDerivedStateFromProps() is now the preferred function.
class Component extends React.Component {_x000D_
static getDerivedStateFromProps(props, current_state) {_x000D_
if (current_state.value !== props.value) {_x000D_
return {_x000D_
value: props.value,_x000D_
computed_prop: heavy_computation(props.value)_x000D_
}_x000D_
}_x000D_
return null_x000D_
}_x000D_
}
_x000D_
A war file is just a zip file with a specific directory structure. So you can use unzip or the jar tool for unzipping.
But you probably don't want to do that. If you add the war file into the webapps directory of Tomcat the Tomcat will take care of extracting/installing the war file.
If you want to read large files, you should read them bit by bit instead of reading them at once.
It’s simple math: If you read a 1 MB large file at once, than at least 1 MB of memory is needed at the same time to hold the data.
So you should read them bit by bit using fopen
& fread
.
df.iloc[i]
returns the ith
row of df
. i
does not refer to the index label, i
is a 0-based index.
In contrast, the attribute index
returns actual index labels, not numeric row-indices:
df.index[df['BoolCol'] == True].tolist()
or equivalently,
df.index[df['BoolCol']].tolist()
You can see the difference quite clearly by playing with a DataFrame with a non-default index that does not equal to the row's numerical position:
df = pd.DataFrame({'BoolCol': [True, False, False, True, True]},
index=[10,20,30,40,50])
In [53]: df
Out[53]:
BoolCol
10 True
20 False
30 False
40 True
50 True
[5 rows x 1 columns]
In [54]: df.index[df['BoolCol']].tolist()
Out[54]: [10, 40, 50]
If you want to use the index,
In [56]: idx = df.index[df['BoolCol']]
In [57]: idx
Out[57]: Int64Index([10, 40, 50], dtype='int64')
then you can select the rows using loc
instead of iloc
:
In [58]: df.loc[idx]
Out[58]:
BoolCol
10 True
40 True
50 True
[3 rows x 1 columns]
Note that loc
can also accept boolean arrays:
In [55]: df.loc[df['BoolCol']]
Out[55]:
BoolCol
10 True
40 True
50 True
[3 rows x 1 columns]
If you have a boolean array, mask
, and need ordinal index values, you can compute them using np.flatnonzero
:
In [110]: np.flatnonzero(df['BoolCol'])
Out[112]: array([0, 3, 4])
Use df.iloc
to select rows by ordinal index:
In [113]: df.iloc[np.flatnonzero(df['BoolCol'])]
Out[113]:
BoolCol
10 True
40 True
50 True
If none of them are working then check this.. say if you have x and y arrays of data along respective axis. Then check in which cell(jupyter) you have initialized x and y to empty. This is because , maybe you are appending data to x and y without re-initializing them. So plot has old data too. So check that..
Checkout the ByteSize library. It's the System.TimeSpan
for bytes!
It handles the conversion and formatting for you.
var maxFileSize = ByteSize.FromKiloBytes(10);
maxFileSize.Bytes;
maxFileSize.MegaBytes;
maxFileSize.GigaBytes;
It also does string representation and parsing.
// ToString
ByteSize.FromKiloBytes(1024).ToString(); // 1 MB
ByteSize.FromGigabytes(.5).ToString(); // 512 MB
ByteSize.FromGigabytes(1024).ToString(); // 1 TB
// Parsing
ByteSize.Parse("5b");
ByteSize.Parse("1.55B");
SSL properties are set at the JVM level via system properties. Meaning you can either set them when you run the program (java -D....) Or you can set them in code by doing System.setProperty.
The specific keys you have to set are below:
javax.net.ssl.keyStore- Location of the Java keystore file containing an application process's own certificate and private key. On Windows, the specified pathname must use forward slashes, /, in place of backslashes.
javax.net.ssl.keyStorePassword - Password to access the private key from the keystore file specified by javax.net.ssl.keyStore. This password is used twice: To unlock the keystore file (store password), and To decrypt the private key stored in the keystore (key password).
javax.net.ssl.trustStore - Location of the Java keystore file containing the collection of CA certificates trusted by this application process (trust store). On Windows, the specified pathname must use forward slashes,
/
, in place of backslashes,\
.If a trust store location is not specified using this property, the SunJSSE implementation searches for and uses a keystore file in the following locations (in order):
$JAVA_HOME/lib/security/jssecacerts
$JAVA_HOME/lib/security/cacerts
javax.net.ssl.trustStorePassword - Password to unlock the keystore file (store password) specified by
javax.net.ssl.trustStore
.javax.net.ssl.trustStoreType - (Optional) For Java keystore file format, this property has the value jks (or JKS). You do not normally specify this property, because its default value is already jks.
javax.net.debug - To switch on logging for the SSL/TLS layer, set this property to ssl.
open your browser,check whether Tomcat homepage is visible by below command.
http://ipaddress:portnumber
also check this
In Android Studio 3.1.2 this error occurs due to Wrong validation of the cache memory.,
Go to Project folder and delete all the contents in .idea folder
This will delete the cache memory and reloading the project will create new cache memory folder and makes it good to go.,
use spawn
import os
os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
To convert a time in one timezone to another timezone in Python, you could use datetime.astimezone():
so, below code is to convert the local time to other time zone.
# Time conversion from local time
import datetime
import pytz
dt_today = datetime.datetime.today() # Local time
dt_India = dt_today.astimezone(pytz.timezone('Asia/Kolkata'))
dt_London = dt_today.astimezone(pytz.timezone('Europe/London'))
India = (dt_India.strftime('%m/%d/%Y %H:%M'))
London = (dt_London.strftime('%m/%d/%Y %H:%M'))
print("Indian standard time: "+India+" IST")
print("British Summer Time: "+London+" BST")
import pytz
for tz in pytz.all_timezones:
print(tz)
Its very simple in Windows OS.
You do not have to do any uninstallation of the old node or npm or anything else.
Just go to nodejs.org
And then look for Downloads for Windows option and below that click on Current... Latest Feature Tab and follow automated instructions
It will download the latest node & npm for you & discarding the old one.
Check your connection string like I forget to add services.AddDbContext<dbsContext>(options => options.UseSqlServer("Default"));
It causes the error and here when I add Configuration.GetConnectionString
, then it solves the issue
like now the connection is:
services.AddDbContext<dbsContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));
works fine (This problem is solved for .net core)
The problem is that echo works only under an execution block. i.e. anything after "xx:"
So anything above the first execution block is just initialization so no execution command can used.
So create a execution blocl
This worked for me with Laravel 5.6.
In the file web.php
, just replace:
Auth::routes();
By:
//Auth::routes();
// Authentication Routes...
Route::get('admin/login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('admin/login', 'Auth\LoginController@login');
Route::post('admin/logout', 'Auth\LoginController@logout')->name('logout');
// Password Reset Routes...
Route::get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController@reset');
And remove the Register link in the two files below:
welcome.blade.php
layouts/app.blade.php
driver.findElement(By.id("invoice_supplier_id")).setAttribute("value", "your value");
Mehrdad Afshari's answer would do the trick, but I found it a bit too verbose for this simple task. Look-up tables can sometimes do wonders:
#include <iostream>
#include <ctime>
#include <unistd.h>
using namespace std;
string gen_random(const int len) {
string tmp_s;
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
srand( (unsigned) time(NULL) * getpid());
tmp_s.reserve(len);
for (int i = 0; i < len; ++i)
tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)];
return tmp_s;
}
int main(int argc, char *argv[]) {
cout << gen_random(12) << endl;
return 0;
}
Just run into the same problem and was the database returning the values as strings.
I use this as a workaround:
$a = array(
'id' => $row['id'] * 1,
'another' => ...,
'ananother' => ...,
);
$json = json_encode($a);
That is multiplying the value by 1 to cast it into a number
Hope that helps someone
use this one:
DecimalFormat form = new DecimalFormat("0.00");
etToll.setText(form.format(tvTotalAmount) );
Note: Data must be in decimal format (tvTotalAmount)
Not sure if this is still relevant, but I use this way
Public bEnableEvents As Boolean
Public bclickok As Boolean
Public booRestoreErrorChecking As Boolean 'put this at the top of the module
Private Declare Function apiGetComputerName Lib "kernel32" Alias _
"GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Private Declare Function apiGetUserName Lib "advapi32.dll" Alias _
"GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
Function GetUserID() As String
' Returns the network login name
On Error Resume Next
Dim lngLen As Long, lngX As Long
Dim strUserName As String
strUserName = String$(254, 0)
lngLen = 255
lngX = apiGetUserName(strUserName, lngLen)
If lngX <> 0 Then
GetUserID = Left$(strUserName, lngLen - 1)
Else
GetUserID = ""
End If
Exit Function
End Function
This next bit I save file as PDF, but can change to suit
Public Sub SaveToDesktop()
Dim LoginName As String
LoginName = UCase(GetUserID)
ChDir "C:\Users\" & LoginName & "\Desktop\"
Debug.Print LoginName
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\Users\" & LoginName & "\Desktop\MyFileName.pdf", Quality:=xlQualityStandard, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
True
End Sub
Paths specified with a .
are relative to the current working directory, not relative to the script file. So the file might be found if you run node app.js
but not if you run node folder/app.js
. The only exception to this is require('./file')
and that is only possible because require
exists per-module and thus knows what module it is being called from.
To make a path relative to the script, you must use the __dirname
variable.
var path = require('path');
path.join(__dirname, 'path/to/file')
or potentially
path.join(__dirname, 'path', 'to', 'file')
It seems impossible to prevent spinners from appearing in Opera. As a temporary workaround, you can make room for the spinners. As far as I can tell, the following CSS adds just enough padding, only in Opera:
noindex:-o-prefocus,
input[type=number] {
padding-right: 1.2em;
}
i forgot to add below line to my HTML code after i add problem has resolved.
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js"></script>
In case you are targeting Win32 platforms or NT kernel mode, you should have a look at cfix.
First Install Dynamic Tools --> NuGet Package Manager --> Package Manager Console
install-package System.Linq.Dynamic
Add Namespace using System.Linq.Dynamic;
Now you can use OrderBy("Name, Age DESC")
So I spent a fair amount of time trying to do this with py2exe The problem was to get the base folder of the script whether it was being run as a python script or as a py2exe executable. Also to have it work whether it was being run from the current folder, another folder or (this was the hardest) from the system's path.
Eventually I used this approach, using sys.frozen as an indicator of running in py2exe:
import os,sys
if hasattr(sys,'frozen'): # only when running in py2exe this exists
base = sys.prefix
else: # otherwise this is a regular python script
base = os.path.dirname(os.path.realpath(__file__))
I also had to come up with an alternate solution, as none of the options listed here worked in my case. I was using an IEnumerable and the underlying data was a IEnumerable and the properties couldn't be enumerated. This did the trick:
// remove "this" if not on C# 3.0 / .NET 3.5
public static DataTable ConvertToDataTable<T>(this IEnumerable<T> data)
{
List<IDataRecord> list = data.Cast<IDataRecord>().ToList();
PropertyDescriptorCollection props = null;
DataTable table = new DataTable();
if (list != null && list.Count > 0)
{
props = TypeDescriptor.GetProperties(list[0]);
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
}
if (props != null)
{
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item) ?? DBNull.Value;
}
table.Rows.Add(values);
}
}
return table;
}
It is simple: if recv()
returns 0 bytes; you will not receive any more data on this connection. Ever. You still might be able to send.
It means that your non-blocking socket have to raise an exception (it might be system-dependent) if no data is available but the connection is still alive (the other end may send).
You can convert it to datetime
, and then use DATEADD(DAY, -30, date)
.
See here.
edit
I suspect many people are finding this question because they want to substract from current date (as is the title of the question, but not what OP intended). The comment of munyul below answers that question more specifically. Since comments are considered ethereal (may be deleted at any given point), I'll repeat it here:
DATEADD(DAY, -30, GETDATE())
Java SE (formerly J2SE) is the basic Java environment. In Java SE, you make all the "standards" programs with Java, using the API described here. You only need a JVM to use Java SE.
Java EE (formerly J2EE) is the enterprise edition of Java. With it, you make websites, Java Beans, and more powerful server applications. Besides the JVM, you need an application server Java EE-compatible, like Glassfish, JBoss, and others.
When connecting to SQL Server with Windows Authentication (as opposed to a local SQL Server account), attempting to use a linked server may result in the error message:
Cannot create an instance of OLE DB provider "(OLEDB provider name)"...
The most direct answer to this problem is provided by Microsoft KB 2647989, because "Security settings for the MSDAINITIALIZE DCOM class are incorrect."
The solution is to fix the security settings for MSDAINITIALIZE. In Windows Vista and later, the class is owned by TrustedInstaller, so the ownership of MSDAINITIALIZE must be changed before the security can be adjusted. The KB above has detailed instructions for doing so.
This MSDN blog post describes the reason:
MSDAINITIALIZE is a COM class that is provided by OLE DB. This class can parse OLE DB connection strings and load/initialize the provider based on property values in the connection string. MSDAINITILIAZE is initiated by users connected to SQL Server. If Windows Authentication is used to connect to SQL Server, then the provider is initialized under the logged in user account. If the logged in user is a SQL login, then provider is initialized under SQL Server service account. Based on the type of login used, permissions on MSDAINITIALIZE have to be provided accordingly.
The issue dates back at least to SQL Server 2000; KB 280106 from Microsoft describes the error (see "Message 3") and has the suggested fix of setting the In Process flag for the OLEDB provider.
While setting In Process can solve the immediate problem, it may not be what you want. According to Microsoft,
Instantiating the provider outside the SQL Server process protects the SQL Server process from errors in the provider. When the provider is instantiated outside the SQL Server process, updates or inserts referencing long columns (text, ntext, or image) are not allowed. -- Linked Server Properties doc for SQL Server 2008 R2.
The better answer is to go with the Microsoft guidance and adjust the MSDAINITIALIZE security.
A sort of an "older style" of error handling is available to us in VBScript, that does make use of On Error Resume Next
. First we enable that (often at the top of a file; but you may use it in place of the first Err.Clear
below for their combined effect), then before running our possibly-error-generating code, clear any errors that have already occurred, run the possibly-error-generating code, and then explicitly check for errors:
On Error Resume Next
' ...
' Other Code Here (that may have raised an Error)
' ...
Err.Clear ' Clear any possible Error that previous code raised
Set myObj = CreateObject("SomeKindOfClassThatDoesNotExist")
If Err.Number <> 0 Then
WScript.Echo "Error: " & Err.Number
WScript.Echo "Error (Hex): " & Hex(Err.Number)
WScript.Echo "Source: " & Err.Source
WScript.Echo "Description: " & Err.Description
Err.Clear ' Clear the Error
End If
On Error Goto 0 ' Don't resume on Error
WScript.Echo "This text will always print."
Above, we're just printing out the error if it occurred. If the error was fatal to the script, you could replace the second Err.clear
with WScript.Quit(Err.Number)
.
Also note the On Error Goto 0
which turns off resuming execution at the next statement when an error occurs.
If you want to test behavior for when the Set
succeeds, go ahead and comment that line out, or create an object that will succeed, such as vbscript.regexp
.
The On Error
directive only affects the current running scope (current Sub
or Function
) and does not affect calling or called scopes.
If you want to check some sort of state and then raise an error to be handled by code that calls your function, you would use Err.Raise
. Err.Raise
takes up to five arguments, Number
, Source
, Description
, HelpFile
, and HelpContext
. Using help files and contexts is beyond the scope of this text. Number
is an error number you choose, Source
is the name of your application/class/object/property that is raising the error, and Description
is a short description of the error that occurred.
If MyValue <> 42 Then
Err.Raise(42, "HitchhikerMatrix", "There is no spoon!")
End If
You could then handle the raised error as discussed above.
Change Log
Err.Clear
before the possibly error causing line to clear any previous errors that may have been ignored.
On Error Resume Next
and Err.Clear
. Fixed some grammar to be less awkward. Added info on Err.Raise
. Formatting.
$filename = "fille.txt";
$fp = fopen($filename, "r");
$content = fread($fp, filesize($filename));
$lines = explode("\n", $content);
fclose($fp);
print_r($lines);
In this code full content of the file is copied to the variable $content
and then split it into an array with each newline character in the file.
... using org.apache.http api. ...
You need to include SOAPAction
as a header in the request. As you have httpPost
and requestWrapper
handles, there are three ways adding the header.
1. httpPost.addHeader( "SOAPAction", strReferenceToSoapActionValue );
2. httpPost.setHeader( "SOAPAction", strReferenceToSoapActionValue );
3. requestWrapper.setHeader( "SOAPAction", strReferenceToSoapActionValue );
Only difference is that addHeader
allows multiple values with same header name and setHeader
allows unique header names only. setHeader(...
over writes first header with the same name.
You can go with any of these on your requirement.
<script>
var jq=jQuery.noConflict();
(function ($)
{
function nameoffunction()
{
// Set your code here!!
}
$(document).ready(readyFn);
})(jQuery);
now use jq in place of jQuery
Install ncftpput and ncftpget. They're usually part of the same package.
x = [i for i in x if len(i)==2]
In Css file:
p.Title
{
font-family: Arial;
font-size: 16px;
}
p.SubTitle p.Title
{
font-size: 12px;
}
Follow below 5 steps to add framework in your project.
Here is the official Apple Link
position: absolute
will position the element by coordinates, relative to the closest positioned ancestor, i.e. the closest parent which isn't position: static
.
Have your four divs nested inside the target div, give the target div position: relative
, and use position: absolute
on the others.
Structure your HTML similar to this:
<div id="container">
<div class="top left"></div>
<div class="top right"></div>
<div class="bottom left"></div>
<div class="bottom right"></div>
</div>
And this CSS should work:
#container {
position: relative;
}
#container > * {
position: absolute;
}
.left {
left: 0;
}
.right {
right: 0;
}
.top {
top: 0;
}
.bottom {
bottom: 0;
}
...
To catch Guzzle errors you can do something like this:
try {
$response = $client->get('/not_found.xml')->send();
} catch (Guzzle\Http\Exception\BadResponseException $e) {
echo 'Uh oh! ' . $e->getMessage();
}
... but, to be able to "log" or "resend" your request try something like this:
// Add custom error handling to any request created by this client
$client->getEventDispatcher()->addListener(
'request.error',
function(Event $event) {
//write log here ...
if ($event['response']->getStatusCode() == 401) {
// create new token and resend your request...
$newRequest = $event['request']->clone();
$newRequest->setHeader('X-Auth-Header', MyApplication::getNewAuthToken());
$newResponse = $newRequest->send();
// Set the response object of the request without firing more events
$event['response'] = $newResponse;
// You can also change the response and fire the normal chain of
// events by calling $event['request']->setResponse($newResponse);
// Stop other events from firing when you override 401 responses
$event->stopPropagation();
}
});
... or if you want to "stop event propagation" you can overridde event listener (with a higher priority than -255) and simply stop event propagation.
$client->getEventDispatcher()->addListener('request.error', function(Event $event) {
if ($event['response']->getStatusCode() != 200) {
// Stop other events from firing when you get stytus-code != 200
$event->stopPropagation();
}
});
thats a good idea to prevent guzzle errors like:
request.CRITICAL: Uncaught PHP Exception Guzzle\Http\Exception\ClientErrorResponseException: "Client error response
in your application.
If its in a landscape then you will be needing more width and less height! That's just what all websites have.
Lets go with a basic first then the rest!
The basic CSS:
By CSS you can do this,
#body {
width: 100%;
height: 100%;
}
Here you are using a div with id
body, as:
<body>
<div id="body>
all the text would go here!
</div>
</body>
Then you can have a web page with 100%
height and width.
What if he tries to resize the window?
The issues pops up, what if he tries to resize the window? Then all the elements inside #body
would try to mess up the UI. For that you can write this:
#body {
height: 100%;
width: 100%;
}
And just add min-height
max-height
min-width
and max-width
.
This way, the page element would stay at the place they were at the page load.
Using JavaScript:
Using JavaScript, you can control the UI, use jQuery as:
$('#body').css('min-height', '100%');
And all other remaining CSS properties, and JS will take care of the User Interface when the user is trying to resize the window.
How to not add scroll to the web page:
If you are not trying to add a scroll, then you can use this JS
$('#body').css('min-height', screen.height); // or anyother like window.height
This way, the document will get a new height whenever the user would load the page.
Second option is better, because when users would have different screen resolutions they would want a CSS or Style sheet created for their own screen. Not for others!
Tip: So try using JS to find current Screen size and edit the page! :)
This post is Old I know but I just had to fix the same issue because simply writing a normal link tag with the display set to block does not make the whole div clickable in IE. so to fix this issue far simpler than having to use JQuery.
Firstly let us understand why this happens: IE wont make an empty div clickable it only make the text/image within that div/a tag clickable.
Solution: Fill the div with a bakground image and hide it from the viewer.
How? You ask good questions, now listen up. add this backround style to the a tag
> "background:url('some_small_image_path')
> -2000px -2000px no-repeat;"
And there you have it the whole div is now clickable. This was the best way for me cause Im using it for my Photo Gallery to let the user clik on one half of the image to move left/right and then place a small image as well just for visual effects. so for me I used the left and right images as background images anyway!
Using fancybox version: 2.1.5 and tried all of the different options suggest here and none of them worked still showing the scrollbar.
$('.foo').click(function(e){
$.fancybox({
href: $(this).data('href'),
type: 'iframe',
scrolling: 'no',
iframe : {
scrolling : 'no'
}
});
e.preventDefault();
});
So did some debugging in the code until I found this, so its overwriting all options I set and no way to overwrite this using the many options.
if (type === 'iframe' && isTouch) {
coming.scrolling = 'scroll';
}
In the end the solutions was to use CSS !important hack.
.fancybox-inner {
overflow: hidden !important;
}
The line of code responsible is:
current.inner.css('overflow', scrolling === 'yes' ? 'scroll' : (scrolling === 'no' ? 'hidden' : scrolling));
Fancybox used to be a reliable working solution now I am finding nothing but inconsistencies. Actually debating about downgrading now even after purchasing a developers license. More info here if you didn't realize you needed one for commercial project: https://stackoverflow.com/a/8837258/560287
777
!If you use nginx (like me), just change the ownership of the folders under /var/lib/php/
from apache
to nginx
:
[root@centos ~]# cd /var/lib/php/
[root@centos php]# ll
total 12
drwxrwx---. 2 root apache 4096 Jan 30 16:23 opcache
drwxrwx---. 2 root apache 4096 Feb 5 20:56 session
drwxrwx---. 2 root apache 4096 Jan 30 16:23 wsdlcache
[root@centos php]# chown -R :nginx opcache/
[root@centos php]# chown -R :nginx session/
[root@centos php]# chown -R :nginx wsdlcache/
[root@centos php]# ll
total 12
drwxrwx---. 2 root nginx 4096 Jan 30 16:23 opcache
drwxrwx---. 2 root nginx 4096 Feb 5 20:56 session
drwxrwx---. 2 root nginx 4096 Jan 30 16:23 wsdlcache
And also for the folders under /var/lib/phpMyAdmin/
:
[root@centos php]# cd /var/lib/phpMyAdmin
[root@centos phpMyAdmin]# ll
total 12
drwxr-x---. 2 apache apache 4096 Dec 23 20:29 config
drwxr-x---. 2 apache apache 4096 Dec 23 20:29 save
drwxr-x---. 2 apache apache 4096 Dec 23 20:29 upload
[root@centos phpMyAdmin]# chown -R nginx:nginx config/
[root@centos phpMyAdmin]# chown -R nginx:nginx save/
[root@centos phpMyAdmin]# chown -R nginx:nginx upload/
[root@centos phpMyAdmin]# ll
total 12
drwxr-x---. 2 nginx nginx 4096 Dec 23 20:29 config
drwxr-x---. 2 nginx nginx 4096 Dec 23 20:29 save
drwxr-x---. 2 nginx nginx 4096 Dec 23 20:29 upload
You cannot push anything that hasn't been committed yet. The order of operations is:
git add
- this stages your changes for committinggit commit
- this commits your staged changes locallygit push
- this pushes your committed changes to a remoteIf you push without committing, nothing gets pushed. If you commit without adding, nothing gets committed. If you add without committing, nothing at all happens, git merely remembers that the changes you added should be considered for the following commit.
The message you're seeing (your branch is ahead by 1 commit) means that your local repository has one commit that hasn't been pushed yet.
In other words: add
and commit
are local operations, push
, pull
and fetch
are operations that interact with a remote.
Since there seems to be an official source control workflow in place where you work, you should ask internally how this should be handled.