As the other poster mention, py2exe
, will generate an executable + some libraries to load. You can also have some data to add to your program.
Next step is to use an installer, to package all this into one easy-to-use installable/unistallable program.
I have used InnoSetup with delight for several years and for commercial programs, so I heartily recommend it.
next
- it's like return
, but for blocks! (So you can use this in any proc
/lambda
too.)
That means you can also say next n
to "return" n
from the block. For instance:
puts [1, 2, 3].map do |e|
next 42 if e == 2
e
end.inject(&:+)
This will yield 46
.
Note that return
always returns from the closest def
, and never a block; if there's no surrounding def
, return
ing is an error.
Using return
from within a block intentionally can be confusing. For instance:
def my_fun
[1, 2, 3].map do |e|
return "Hello." if e == 2
e
end
end
my_fun
will result in "Hello."
, not [1, "Hello.", 2]
, because the return
keyword pertains to the outer def
, not the inner block.
Use the FileSystemObject
object, namely, its CreateFolder
and CopyFile
methods. Basically, this is what your script will look like:
Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")
' Create a new folder
oFSO.CreateFolder "C:\MyFolder"
' Copy a file into the new folder
' Note that the destination folder path must end with a path separator (\)
oFSO.CopyFile "\\server\folder\file.ext", "C:\MyFolder\"
You may also want to add additional logic, like checking whether the folder you want to create already exists (because CreateFolder
raises an error in this case) or specifying whether or not to overwrite the file being copied. So, you can end up with this:
Const strFolder = "C:\MyFolder\", strFile = "\\server\folder\file.ext"
Const Overwrite = True
Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")
If Not oFSO.FolderExists(strFolder) Then
oFSO.CreateFolder strFolder
End If
oFSO.CopyFile strFile, strFolder, Overwrite
You can't, you either need to keep the index separately:
int index = 0;
for(Element song : question) {
System.out.println("Current index is: " + (index++));
}
or use a normal for loop:
for(int i = 0; i < question.length; i++) {
System.out.println("Current index is: " + i);
}
The reason is you can use the condensed for syntax to loop over any Iterable, and it's not guaranteed that the values actually have an "index"
Best way would be
#include <iostream>
using namespace std;
int main() {
float celsius;
float fahrenheit;
cout << "Enter Celsius temperature: ";
cin >> celsius;
fahrenheit = (celsius * 1.8) + 32;// removing division for the confusion
cout << "Fahrenheit = " << fahrenheit << endl;
return 0;
}
:)
No, Not if your website is on a remote server, i.e not on localhost.
I used the following approach for determining the frame of the keyboard in iOS 7.1.
In the init method of my view controller, I registered for the UIKeyboardDidShowNotification
:
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(keyboardOnScreen:) name:UIKeyboardDidShowNotification object:nil];
Then, I used the following code in keyboardOnScreen:
to gain access to the frame of the keyboard. This code gets the userInfo
dictionary from the notification and then accesses the NSValue
associated with UIKeyboardFrameEndUserInfoKey
. You can then access the CGRect and convert it to the coordinates of the view of your view controller. From there, you can perform any calculations you need based on that frame.
-(void)keyboardOnScreen:(NSNotification *)notification
{
NSDictionary *info = notification.userInfo;
NSValue *value = info[UIKeyboardFrameEndUserInfoKey];
CGRect rawFrame = [value CGRectValue];
CGRect keyboardFrame = [self.view convertRect:rawFrame fromView:nil];
NSLog(@"keyboardFrame: %@", NSStringFromCGRect(keyboardFrame));
}
Swift
And the equivalent implementation with Swift:
NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidShow), name: UIResponder.keyboardDidShowNotification, object: nil)
@objc
func keyboardDidShow(notification: Notification) {
guard let info = notification.userInfo else { return }
guard let frameInfo = info[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
let keyboardFrame = frameInfo.cgRectValue
print("keyboardFrame: \(keyboardFrame)")
}
There is not only 1 %SystemRoot%\System32
on Windows x64. There are 2 such directories.
The real %SystemRoot%\System32
directory is for 64-bit applications. This directory contains a 64-bit cmd.exe
.
But there is also %SystemRoot%\SysWOW64
for 32-bit applications. This directory is used if a 32-bit application accesses %SystemRoot%\System32
. It contains a 32-bit cmd.exe
.
32-bit applications can access %SystemRoot%\System32
for 64-bit applications by using the alias %SystemRoot%\Sysnative
in path.
For more details see the Microsoft documentation about File System Redirector.
So the subdirectory run
was created either in %SystemRoot%\System32
for 64-bit applications and 32-bit cmd
is run for which this directory does not exist because there is no subdirectory run
in %SystemRoot%\SysWOW64
which is %SystemRoot%\System32
for 32-bit cmd.exe
or the subdirectory run
was created in %SystemRoot%\System32
for 32-bit applications and 64-bit cmd
is run for which this directory does not exist because there is no subdirectory run
in %SystemRoot%\System32
as this subdirectory exists only in %SystemRoot%\SysWOW64
.
The following code could be used at top of the batch file in case of subdirectory run
is in %SystemRoot%\System32
for 64-bit applications:
@echo off
set "SystemPath=%SystemRoot%\System32"
if not "%ProgramFiles(x86)%" == "" if exist %SystemRoot%\Sysnative\* set "SystemPath=%SystemRoot%\Sysnative"
Every console application in System32\run
directory must be executed with %SystemPath%
in the batch file, for example %SystemPath%\run\YourApp.exe
.
How it works?
There is no environment variable ProgramFiles(x86) on Windows x86 and therefore there is really only one %SystemRoot%\System32
as defined at top.
But there is defined the environment variable ProgramFiles(x86) with a value on Windows x64. So it is additionally checked on Windows x64 if there are files in %SystemRoot%\Sysnative
. In this case the batch file is processed currently by 32-bit cmd.exe
and only in this case %SystemRoot%\Sysnative
needs to be used at all. Otherwise %SystemRoot%\System32
can be used also on Windows x64 as when the batch file is processed by 64-bit cmd.exe
, this is the directory containing the 64-bit console applications (and the subdirectory run
).
Note: %SystemRoot%\Sysnative
is not a directory! It is not possible to cd
to %SystemRoot%\Sysnative
or use if exist %SystemRoot%\Sysnative
or if exist %SystemRoot%\Sysnative\
. It is a special alias existing only for 32-bit executables and therefore it is necessary to check if one or more files exist on using this path by using if exist %SystemRoot%\Sysnative\cmd.exe
or more general if exist %SystemRoot%\Sysnative\*
.
Please install at ubuntu openjdk-7-jdk
sudo apt-get install openjdk-7-jdk
on Windows try find find openjdk
DBSIZE
returns the number of keys and it's easier to parse.
Downside: if a key has expired it may still count.
WebApplicationInitializer is an interface you can implement in one of your classes. At startup Spring is scanning for this classes, as long as you are using servlet spec 3 and have a metadata-complete="false" attribute in your web.xml. But that doesn't seem to be the problem. The only error I can figure out is the missing slf4j-log4j12.jar.
Maybe, you need to specify more exactly what didn't work and in what environment you are.
As to the claim that the dot is special in a charackter class, this is not true in every programming environment. For example the following perl script
use warnings;
use strict;
my $str = '!!!.###';
$str =~ s/[A-Za-z_.]/X/g;
print "$str\n";
produces
!!!X###
In the spectrum of kernel designs the two extreme points are monolithic kernels and microkernels.
The (classical) Linux kernel for instance is a monolithic kernel (and so is every commercial OS to date as well - though they might claim otherwise);
In that its code is a
single C file giving rise to a single process that implements all of the above
services.
To exemplify the encapsulation of the Linux kernel we remark that
the Linux kernel does not even have access to any of the standard C libraries.
Indeed the Linux kernel cannot use rudimentary C library functions such as
printf. Instead it implements its own printing function (called prints).
This seclusion of the Linux kernel and self-containment provide Linux kernel
with its main advantage: the kernel resides in a single address space1
enabling
all features to communicate in the fastest way possible without resorting to
any type of message passing.
In particular, a monolithic kernel implements all of the device drivers
of the system.
This however is the main drawback of a monolithic kernel:
introduction of any new unsupported hardware requires a rewrite of the
kernel (in the relevant parts), recompilation of it, and re-installing the entire
OS.
More importantly, if any device driver crashes the entire kernel suffers
as a result.
This un-modular approach to hardware additions and hardware crashes
is the main argument for supporting the other extreme design approach
for kernels. A microkernel is in a sense a minimalistic kernel that houses
only the very basic of OS services (like process management and file system
management). In a microkernel the device drivers lie outside of the kernel
allowing for addition and removal of device drivers while the OS is running
and require no alternations of the kernel.
-pattern_type glob
This great option makes it easier to select the images in many cases.
Slideshow video with one image per second
ffmpeg -framerate 1 -pattern_type glob -i '*.png' \
-c:v libx264 -r 30 -pix_fmt yuv420p out.mp4
Add some music to it, cutoff when the presumably longer audio when the images end:
ffmpeg -framerate 1 -pattern_type glob -i '*.png' -i audio.ogg \
-c:a copy -shortest -c:v libx264 -r 30 -pix_fmt yuv420p out.mp4
Here are two demos on YouTube:
Be a hippie and use the Theora patent-unencumbered video format:
ffmpeg -framerate 1 -pattern_type glob -i '*.png' -i audio.ogg \
-c:a copy -shortest -c:v libtheora -r 30 -pix_fmt yuv420p out.ogg
Your images should of course be sorted alphabetically, typically as:
0001-first-thing.jpg
0002-second-thing.jpg
0003-and-third.jpg
and so on.
I would also first ensure that all images to be used have the same aspect ratio, possibly by cropping them with imagemagick
or nomacs beforehand, so that ffmpeg will not have to make hard decisions. In particular, the width has to be divisible by 2, otherwise conversion fails with: "width not divisible by 2".
Normal speed video with one image per frame at 30 FPS
ffmpeg -framerate 30 -pattern_type glob -i '*.png' \
-c:v libx264 -pix_fmt yuv420p out.mp4
Here's what it looks like:
GIF generated with: https://askubuntu.com/questions/648603/how-to-create-an-animated-gif-from-mp4-video-via-command-line/837574#837574
Add some audio to it:
ffmpeg -framerate 30 -pattern_type glob -i '*.png' \
-i audio.ogg -c:a copy -shortest -c:v libx264 -pix_fmt yuv420p out.mp4
Result: https://www.youtube.com/watch?v=HG7c7lldhM4
These are the test media I've used:a
wget -O opengl-rotating-triangle.zip https://github.com/cirosantilli/media/blob/master/opengl-rotating-triangle.zip?raw=true
unzip opengl-rotating-triangle.zip
cd opengl-rotating-triangle
wget -O audio.ogg https://upload.wikimedia.org/wikipedia/commons/7/74/Alnitaque_%26_Moon_Shot_-_EURO_%28Extended_Mix%29.ogg
Images generated with: How to use GLUT/OpenGL to render to a file?
It is cool to observe how much the video compresses the image sequence way better than ZIP as it is able to compress across frames with specialized algorithms:
opengl-rotating-triangle.mp4
: 340K opengl-rotating-triangle.zip
: 7.3M Convert one music file to a video with a fixed image for YouTube upload
Answered at: https://superuser.com/questions/700419/how-to-convert-mp3-to-youtube-allowed-video-format/1472572#1472572
Full realistic slideshow case study setup step by step
There's a bit more to creating slideshows than running a single ffmpeg command, so here goes a more interesting detailed example inspired by this timeline.
Get the input media:
mkdir -p orig
cd orig
wget -O 1.png https://upload.wikimedia.org/wikipedia/commons/2/22/Australopithecus_afarensis.png
wget -O 2.jpg https://upload.wikimedia.org/wikipedia/commons/6/61/Homo_habilis-2.JPG
wget -O 3.jpg https://upload.wikimedia.org/wikipedia/commons/c/cb/Homo_erectus_new.JPG
wget -O 4.png https://upload.wikimedia.org/wikipedia/commons/1/1f/Homo_heidelbergensis_-_forensic_facial_reconstruction-crop.png
wget -O 5.jpg https://upload.wikimedia.org/wikipedia/commons/thumb/5/5a/Sabaa_Nissan_Militiaman.jpg/450px-Sabaa_Nissan_Militiaman.jpg
wget -O audio.ogg https://upload.wikimedia.org/wikipedia/commons/7/74/Alnitaque_%26_Moon_Shot_-_EURO_%28Extended_Mix%29.ogg
cd ..
# Convert all to PNG for consistency.
# https://unix.stackexchange.com/questions/29869/converting-multiple-image-files-from-jpeg-to-pdf-format
# Hardlink the ones that are already PNG.
mkdir -p png
mogrify -format png -path png orig/*.jpg
ln -P orig/*.png png
Now we have a quick look at all image sizes to decide on the final aspect ratio:
identify png/*
which outputs:
png/1.png PNG 557x495 557x495+0+0 8-bit sRGB 653KB 0.000u 0:00.000
png/2.png PNG 664x800 664x800+0+0 8-bit sRGB 853KB 0.000u 0:00.000
png/3.png PNG 544x680 544x680+0+0 8-bit sRGB 442KB 0.000u 0:00.000
png/4.png PNG 207x238 207x238+0+0 8-bit sRGB 76.8KB 0.000u 0:00.000
png/5.png PNG 450x600 450x600+0+0 8-bit sRGB 627KB 0.000u 0:00.000
so the classic 480p (640x480 == 4/3) aspect ratio seems appropriate.
Do one conversion with minimal resizing to make widths even (TODO
automate for any width, here I just manually looked at identify
output and reduced width and height by one):
mkdir -p raw
convert png/1.png -resize 556x494 raw/1.png
ln -P png/2.png png/3.png png/4.png png/5.png raw
ffmpeg -framerate 1 -pattern_type glob -i 'raw/*.png' -i orig/audio.ogg -c:v libx264 -c:a copy -shortest -r 30 -pix_fmt yuv420p raw.mp4
This produces terrible output, because as seen from:
ffprobe raw.mp4
ffmpeg just takes the size of the first image, 556x494, and then converts all others to that exact size, breaking their aspect ratio.
Now let's convert the images to the target 480p aspect ratio automatically by cropping as per ImageMagick: how to minimally crop an image to a certain aspect ratio?
mkdir -p auto
mogrify -path auto -geometry 640x480^ -gravity center -crop 640x480+0+0 png/*.png
ffmpeg -framerate 1 -pattern_type glob -i 'auto/*.png' -i orig/audio.ogg -c:v libx264 -c:a copy -shortest -r 30 -pix_fmt yuv420p auto.mp4
So now, the aspect ratio is good, but inevitably some cropping had to be done, which kind of cut up interesting parts of the images.
The other option is to pad with black background to have the same aspect ratio as shown at: Resize to fit in a box and set background to black on "empty" part
mkdir -p black
ffmpeg -framerate 1 -pattern_type glob -i 'black/*.png' -i orig/audio.ogg -c:v libx264 -c:a copy -shortest -r 30 -pix_fmt yuv420p black.mp4
Generally speaking though, you will ideally be able to select images with the same or similar aspect ratios to avoid those problems in the first place.
About the CLI options
Note however that despite the name, -glob
this is not as general as shell Glob patters, e.g.: -i '*'
fails: https://trac.ffmpeg.org/ticket/3620 (apparently because filetype is deduced from extension).
-r 30
makes the -framerate 1
video 30 FPS to overcome bugs in players like VLC for low framerates: VLC freezes for low 1 FPS video created from images with ffmpeg Therefore it repeats each frame 30 times to keep the desired 1 image per second effect.
Next steps
You will also want to:
cut up the part of the audio that you want before joining it: Cutting the videos based on start and end time using ffmpeg
ffmpeg -i in.mp3 -ss 03:10 -to 03:30 -c copy out.mp3
TODO: learn to cut and concatenate multiple audio files into the video without intermediate files, I'm pretty sure it's possible:
Tested on
ffmpeg 3.4.4, vlc 3.0.3, Ubuntu 18.04.
Bibliography
If you need to pass UUID for a primary key for your model or unique field then below code returns the UUID object -
import uuid
uuid.uuid4()
If you need to pass UUID as a parameter for URL you can do like below code -
import uuid
str(uuid.uuid4())
If you want the hex value for a UUID you can do the below one -
import uuid
uuid.uuid4().hex
It could also mean that the current Java type system version isn't good enough for your case. There were several JSR propositions / hacks to fix this: Type tokens, Super Type Tokens, Class.cast().
If you really need this supression, narrow it down as much as possible (e.g. don't put it onto the class itself or onto a long method). An example:
public List<String> getALegacyListReversed() {
@SuppressWarnings("unchecked") List<String> list =
(List<String>)legacyLibrary.getStringList();
Collections.reverse(list);
return list;
}
If you are trying to generate thumbnails, you must first resize the image using imagecopyresampled();
. You must resize the image so that the size of the smaller side of the image is equal to the corresponding side of the thumb.
For example, if your source image is 1280x800px and your thumb is 200x150px, you must resize your image to 240x150px and then crop it to 200x150px. This is so that the aspect ratio of the image won't change.
Here's a general formula for creating thumbnails:
$image = imagecreatefromjpeg($_GET['src']);
$filename = 'images/cropped_whatever.jpg';
$thumb_width = 200;
$thumb_height = 150;
$width = imagesx($image);
$height = imagesy($image);
$original_aspect = $width / $height;
$thumb_aspect = $thumb_width / $thumb_height;
if ( $original_aspect >= $thumb_aspect )
{
// If image is wider than thumbnail (in aspect ratio sense)
$new_height = $thumb_height;
$new_width = $width / ($height / $thumb_height);
}
else
{
// If the thumbnail is wider than the image
$new_width = $thumb_width;
$new_height = $height / ($width / $thumb_width);
}
$thumb = imagecreatetruecolor( $thumb_width, $thumb_height );
// Resize and crop
imagecopyresampled($thumb,
$image,
0 - ($new_width - $thumb_width) / 2, // Center the image horizontally
0 - ($new_height - $thumb_height) / 2, // Center the image vertically
0, 0,
$new_width, $new_height,
$width, $height);
imagejpeg($thumb, $filename, 80);
Haven't tested this but it should work.
EDIT
Now tested and working.
function isValidDate(year, month, day) {
var d = new Date(year, month - 1, day, 0, 0, 0, 0);
return (!isNaN(d) && (d.getDate() == day && d.getMonth() + 1 == month && d.getYear() == year));
}
There will be an option in configure under Build Triggers
Check the GitHub Branches
A hook will be created and then you can build any branch you like from Jenkins when you select github Branches
Hope it helps :)
Since complexity doesn’t matter, I present to you...BogoSort:
from random import shuffle
def is_sorted(ls):
for idx in range(len(ls)-1):
if x[idx] > x[idx + 1]:
return False
return True
def sort(ls):
while not is_sorted(ls):
shuffle(ls)
return ls
ls = list(range(5))
shuffle(ls)
print(
"Original: ",
ls
)
print(
"Sorted: ",
sorted(ls)
)
Using an enhanced for would be even nicer:
int sum = 0;
for (int d : data) sum += d;
Another thing that will probably give you a big surprise is the wrong result that you will obtain from
double average = sum / data.length;
Reason: on the right-hand side you have integer division and Java will not automatically promote it to floating-point division. It will calculate the integer quotient of sum/data.length
and only then promote that integer to a double
. A solution would be
double average = 1.0d * sum / data.length;
This will force the dividend into a double
, which will automatically propagate to the divisor.
So, the concept of a "wildcard" in Regular Expressions works a bit differently. In order to match "any character" you would use "." The "*" modifier means, match any number of times.
Check sysobjects and syscolumns tables.
Here is a diagram of Sybase system tables.
List of all user tables:
SELECT * FROM sysobjects WHERE type = 'U'
You can change 'U' to other objects:
List of columns in a table:
SELECT sc.*
FROM syscolumns sc
INNER JOIN sysobjects so ON sc.id = so.id
WHERE so.name = 'my_table_name'
$data = json_decode($json, true);
echo $data[0]["c_name"]; // "John"
$data = json_decode($json);
echo $data[0]->c_name; // "John"
I created this npm package to change date of old commits.
https://github.com/bitriddler/git-change-date
Sample Usage:
npm install -g git-change-date
cd [your-directory]
git-change-date
You will be prompted to choose the commit you want to modify then to enter the new date.
If you want to change a commit by specific hash run this git-change-date --hash=[hash]
You can get everything through ExternalContext
. In JSF 1.x, you can get the raw HttpServletResponse
object by ExternalContext#getResponse()
. In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream()
without the need to grab the HttpServletResponse
from under the JSF hoods.
On the response, you should set the Content-Type
header so that the client knows which application to associate with the provided file. And, you should set the Content-Length
header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition
header to attachment
if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.
Most important part is to call FacesContext#responseComplete()
to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException
with a message like getoutputstream() has already been called for this response
when the JSF implementation calls getWriter()
to render HTML.
You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink>
and <h:commandButton>
. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.
In case you're using e.g. PrimeFaces <p:commandXxx>
, then you need to make sure that you explicitly turn off ajax via ajax="false"
attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" />
in the command component.
public void download() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
OutputStream output = ec.getResponseOutputStream();
// Now you can write the InputStream of the file to the above OutputStream the usual way.
// ...
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}
public void download() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
OutputStream output = response.getOutputStream();
// Now you can write the InputStream of the file to the above OutputStream the usual way.
// ...
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}
In case you need to stream a static file from the local disk file system, substitute the code as below:
File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();
// ...
Files.copy(file.toPath(), output);
In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output
there where the API being used expects an OutputStream
.
E.g. iText PDF:
String fileName = "dynamic.pdf";
String contentType = "application/pdf";
// ...
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();
E.g. Apache POI HSSF:
String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";
// ...
HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();
Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.
If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile()
methods taking either a File
, or an InputStream
, or a byte[]
, and specifying whether the file should be downloaded as an attachment (true
) or inline (false
).
public void download() throws IOException {
Faces.sendFile(file, true);
}
Yes, this code is complete as-is. You don't need to invoke responseComplete()
and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.
Don't forget about switch statements:
default
.instanceof
can match on superclass.constructor
will match on the exact class.function handleError() {_x000D_
try {_x000D_
throw new RangeError();_x000D_
}_x000D_
catch (e) {_x000D_
switch (e.constructor) {_x000D_
case Error: return console.log('generic');_x000D_
case RangeError: return console.log('range');_x000D_
default: return console.log('unknown');_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
handleError();
_x000D_
From the python command prompt:
import scipy
print scipy.__version__
In python 3 you'll need to change it to:
print (scipy.__version__)
Socket.IO uses WebSocket and when WebSocket is not available uses fallback algo to make real time connections.
Try smallR for writing quick R scripts in the command line:
http://code.google.com/p/simple-r/
(r
command in the directory)
Plotting from the command line using smallR would look like this:
r -p file.txt
Run in a subshell to remove notifications and close STDOUT and STDERR:
(&>/dev/null script.sh &)
>> strs = "{u'key':u'val'}"
>> strs = strs.replace("'",'"')
>> json.loads(strs.replace('u"','"'))
jQuery's .bind() fires in the order it was bound:
When an event reaches an element, all handlers bound to that event type for the element are fired. If there are multiple handlers registered, they will always execute in the order in which they were bound. After all handlers have executed, the event continues along the normal event propagation path.
Source: http://api.jquery.com/bind/
Because jQuery's other functions (ex. .click()
) are shortcuts for .bind('click', handler)
, I would guess that they are also triggered in the order they are bound.
That probably means that your id
is an AUTO_INCREMENT
integer and you're trying to send a string. You should specify a column list and omit it from your INSERT
.
INSERT INTO workorders (column1, column2) VALUES ($column1, $column2)
Drawing my conclusion from posts of awesome SO evangelists above, I conclude that both are software that resides on actual metal servers(physical servers). Both work hand in hand to get service to the end-user. Then, depending on the setup, we can choose what to call it, which means how to describe it depends on the actual setup in use. If they both reside on the same bare metal(physical server), we call it web and application server...simple! If on separate machines, obviously, we have two distinct bare metals(physical servers) at our hands. Then we can label these servers according to their function: one web server and the other application server.
Note that if you have committed a bunch of changes in various submodules, you can (or will be soon able to) push everything in one go (ie one push from the parent repo), with:
git push --recurse-submodules=on-demand
git1.7.11 ([ANNOUNCE] Git 1.7.11.rc1) mentions:
"
git push --recurse-submodules
" learned to optionally look into the histories of submodules bound to the superproject and push them out.
Probably done after this patch and the --on-demand
option:
--recurse-submodules=<check|on-demand|no>::
Make sure all submodule commits used by the revisions to be pushed are available on a remote tracking branch.
- If
check
is used, it will be checked that all submodule commits that changed in the revisions to be pushed are available on a remote.
Otherwise the push will be aborted and exit with non-zero status.- If
on-demand
is used, all submodules that changed in the revisions to be pushed will be pushed.
If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status.
This option only works for one level of nesting. Changes to the submodule inside of another submodule will not be pushed.
In terms of it in regards to using the popular Twitter Bootstrap I feel like this type of bootstrapping is the action of integrating a modular component into a Web application without the Web application having to even acknowledge the modular component exists until it needs it or references it.
The developer can seamlessly integrate a default copy of the CSS Twitter Bootstrap theme by simply loading (referencing) it into the Web application. Vuola! Then you may need to override some of these changes, but you can do so in such a way that the resource/component is untouched and completely reusable.
This same concept is how Web Devs implement jQuery APIs and so on, but it's not really expressed by Devs as bootstrapping per se. What it does is it improves flexibility and reusability while allowing the isolation of different components/resources of an app to reside freely either on the same server/s or possibly on a CDN.
NOTE: In computing bootstrapping deals with the MBR and in UNIX it requires a special bootloader or manager which is a small program in ROM that loads the OS into RAM. If you think about it the same concept takes places in the action of the bootstrap loader checking the MBR and loading the OS based on this table which occurs without the OS having any idea that this takes place.
$_GET['start_date']
is not numeric is my bet, but an date format not supported by strtotime
. You will need to re-format the date to a workable format for strtotime or use combination of explode/mktime.
I could add you an example if you'd be kind enough to post the format you currently receive.
Edit: Generally try to avoid doing the below except as a last ditch effort to avoid deadlocks. Read the first comment from Stephen Cleary.
Quick fix from here. Instead of writing:
Task tsk = AsyncOperation();
tsk.Wait();
Try:
Task.Run(() => AsyncOperation()).Wait();
Or if you need a result:
var result = Task.Run(() => AsyncOperation()).Result;
From the source (edited to match the above example):
AsyncOperation will now be invoked on the ThreadPool, where there won’t be a SynchronizationContext, and the continuations used inside of AsyncOperation won’t be forced back to the invoking thread.
For me this looks like a useable option since I do not have the option of making it async all the way (which I would prefer).
From the source:
Ensure that the await in the FooAsync method doesn’t find a context to marshal back to. The simplest way to do that is to invoke the asynchronous work from the ThreadPool, such as by wrapping the invocation in a Task.Run, e.g.
int Sync() { return Task.Run(() => Library.FooAsync()).Result; }
FooAsync will now be invoked on the ThreadPool, where there won’t be a SynchronizationContext, and the continuations used inside of FooAsync won’t be forced back to the thread that’s invoking Sync().
private void Form1_Load(object sender, EventArgs e)
{
//Write a file
string text = "The text inside the file.";
System.IO.File.WriteAllText("file_name.txt", text);
//Read a file
string read = System.IO.File.ReadAllText("file_name.txt");
MessageBox.Show(read); //Display text in the file
}
Not sure exactly what your after, but I think I get it.
A header - stays at the top of the screen? A footer - stays at the bottom of the screen? Content area -> fits the space between the footer and the header?
You can do this by absolute positioning or with fixed positioning.
Here is an example with absolute positioning: http://jsfiddle.net/FMYXY/1/
Markup:
<div class="header">Header</div>
<div class="mainbody">Main Body</div>
<div class="footer">Footer</div>
CSS:
.header {outline:1px solid red; height: 40px; position:absolute; top:0px; width:100%;}
.mainbody {outline:1px solid green; min-height:200px; position:absolute; top:40px; width:100%; height:90%;}
.footer {outline:1px solid blue; height:20px; position:absolute; height:25px;bottom:0; width:100%; }
To make it work best, I'd suggest using % instead of pixels, as you will run into problems with different screen/device sizes.
Since IntelliJ 2016, the location is File | Settings | Build, Execution, Deployment | Compiler | Build process heap size.
Useful tip - if you use __FILE__
and __LINE__
then format your debug as:
"file(line): Your output here"
then when you click on that line in the output window Visual Studio will jump directly to that line of code. An example:
#include <Windows.h>
#include <iostream>
#include <sstream>
void DBOut(const char *file, const int line, const WCHAR *s)
{
std::wostringstream os_;
os_ << file << "(" << line << "): ";
os_ << s;
OutputDebugStringW(os_.str().c_str());
}
#define DBOUT(s) DBOut(__FILE__, __LINE__, s)
I wrote a blog post about this so I always knew where I could look it up: https://windowscecleaner.blogspot.co.nz/2013/04/debug-output-tricks-for-visual-studio.html
You can call sortable
on a <tbody>
instead of on the individual rows.
<table>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
</tr>
</tbody>
</table>?
<script>
$('tbody').sortable();
</script>
$(function() {_x000D_
$( "tbody" ).sortable();_x000D_
});
_x000D_
_x000D_
table {_x000D_
border-spacing: collapse;_x000D_
border-spacing: 0;_x000D_
}_x000D_
td {_x000D_
width: 50px;_x000D_
height: 25px;_x000D_
border: 1px solid black;_x000D_
}
_x000D_
_x000D_
_x000D_
<link href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet">_x000D_
<script src="//code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>_x000D_
_x000D_
<table>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>1</td>_x000D_
<td>2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>3</td>_x000D_
<td>4</td>_x000D_
</tr>_x000D_
<tr> _x000D_
<td>5</td>_x000D_
<td>6</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>7</td>_x000D_
<td>8</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>9</td> _x000D_
<td>10</td>_x000D_
</tr> _x000D_
</tbody> _x000D_
</table>
_x000D_
Random ra = new Random();
int r, g, b;
r=ra.nextInt(255);
g=ra.nextInt(255);
b=ra.nextInt(255);
Color color = new Color(r,g,b);
String hex = Integer.toHexString(color.getRGB() & 0xffffff);
if (hex.length() < 6) {
hex = "0" + hex;
}
hex = "#" + hex;
Besides all of the other responses here, I really don't think that using backgroundColor in this way is the proper way to do things. Personally, I would create a UIImageView and insert it into your view hierarchy. You can either insert it into your top view and push it all the way to the back with sendSubviewToBack: or you can make the UIImageView the parent view.
I wouldn't worry about things like how efficient each implementation is at this point because unless you actually see an issue, it really doesn't matter. Your first priority for now should be writing code that you can understand and can easily be changed. Creating a UIColor to use as your background image isn't the clearest method of doing this.
https://www.w3schools.com/bootstrap/bootstrap_ref_js_modal.asp
Note: For <a>
elements, omit data-target, and use href="#modalID"
instead.
From this answer:
[HttpPost]
public void Confirmation(HttpRequestMessage request)
{
var content = request.Content;
string jsonContent = content.ReadAsStringAsync().Result;
}
Note: As seen in the comments, this code could cause a deadlock and should not be used. See this blog post for more detail.
Dynamic resources can only be used when property being set is on object which is derived from dependency object or freezable where as static resources can be used anywhere. You can abstract away entire control using static resources.
Static resources are used under following circumstances:
Dynamic resources:
Add rich comparison operators to the object class, then use sort() method of the list.
See rich comparison in python.
Update: Although this method would work, I think solution from Triptych is better suited to your case because way simpler.
Two things. First I don't think you are adding the data that you want to pass to the fragment correctly. What you need to pass to the fragment is a bundle, not an intent. For example if I wanted send an int
value to a fragment I would create a bundle, put the int
into that bundle, and then set that bundle as an argument to be used when the fragment was created.
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);
Second to retrieve that information you need to get the arguments sent to the fragment. You then extract the value based on the key you identified it with. For example in your fragment:
Bundle bundle = this.getArguments();
if (bundle != null) {
int i = bundle.getInt(key, defaulValue);
}
What you are getting changes depending on what you put. Also the default value is usually null
but does not need to be. It depends on if you set a default value for that argument.
Lastly I do not think you can do this in onCreateView
. I think you must retrieve this data within your fragment's onActivityCreated
method. My reasoning is as follows. onActivityCreated
runs after the underlying activity has finished its own onCreate
method. If you are placing the information you wish to retrieve within the bundle durring your activity's onCreate
method, it will not exist during your fragment's onCreateView
. Try using this in onActivityCreated
and just update your ListView
contents later.
The following should work:
from matplotlib import pyplot as plt
plt.imshow(data, interpolation='nearest')
plt.show()
If you are using Jupyter notebook/lab, use this inline command before importing matplotlib:
%matplotlib inline
You can concat many kind of expression by sorrounding your simple/complex expression between ||
characters:
<p th:text="|${bean.field} ! ${bean.field}|">Static content</p>
This option was introduced in order to remove the need to deploy very large PIAs (Primary Interop Assemblies) for interop.
It simply embeds the managed bridging code used that allows you to talk to unmanaged assemblies, but instead of embedding it all it only creates the stuff you actually use in code.
Read more in Scott Hanselman's blog post about it and other VS improvements here.
As for whether it is advised or not, I'm not sure as I don't need to use this feature. A quick web search yields a few leads:
The only risk of turning them all to false is more deployment concerns with PIA files and a larger deployment if some of those files are large.
A simple solution for a simple question:
split -n l/5 your_file.txt
no need for scripting here.
From the man file, CHUNKS may be:
l/N split into N files without splitting lines
Update
Not all unix dist include this flag. For example, it will not work in OSX. To use it, you can consider replacing the Mac OS X utilities with GNU core utilities.
I wanted to do exactly this, and I thought of a solution involving both the keyup and the keypress events.
(I haven't tested it in all browsers, but I used the information compiled at http://unixpapa.com/js/key.html)
Edit: rewrote it as a jQuery plugin.
(function($) {
$.fn.normalkeypress = function(onNormal, onSpecial) {
this.bind('keydown keypress keyup', (function() {
var keyDown = {}, // keep track of which buttons have been pressed
lastKeyDown;
return function(event) {
if (event.type == 'keydown') {
keyDown[lastKeyDown = event.keyCode] = false;
return;
}
if (event.type == 'keypress') {
keyDown[lastKeyDown] = event; // this keydown also triggered a keypress
return;
}
// 'keyup' event
var keyPress = keyDown[event.keyCode];
if ( keyPress &&
( ( ( keyPress.which >= 32 // not a control character
//|| keyPress.which == 8 || // \b
//|| keyPress.which == 9 || // \t
//|| keyPress.which == 10 || // \n
//|| keyPress.which == 13 // \r
) &&
!( keyPress.which >= 63232 && keyPress.which <= 63247 ) && // not special character in WebKit < 525
!( keyPress.which == 63273 ) && //
!( keyPress.which >= 63275 && keyPress.which <= 63277 ) && //
!( keyPress.which === event.keyCode && // not End / Home / Insert / Delete (i.e. in Opera < 10.50)
( keyPress.which == 35 || // End
keyPress.which == 36 || // Home
keyPress.which == 45 || // Insert
keyPress.which == 46 || // Delete
keyPress.which == 144 // Num Lock
)
)
) ||
keyPress.which === undefined // normal character in IE < 9.0
) &&
keyPress.charCode !== 0 // not special character in Konqueror 4.3
) {
// Normal character
if (onNormal) onNormal.call(this, keyPress, event);
} else {
// Special character
if (onSpecial) onSpecial.call(this, event);
}
delete keyDown[event.keyCode];
};
})());
};
})(jQuery);
Swift 2
Using Trailing Closures this becomes:
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
Trailing Closures is Swift syntactic sugar that enables defining the closure outside of the function parameter scope. For more information see Trailing Closures in Swift 2.2 Programming Language Guide.
In dispatch_async case the API is func dispatch_async(queue: dispatch_queue_t, _ block: dispatch_block_t)
since dispatch_block_t
is type alias for () -> Void
- A closure that receives 0 parameters and does not have a return value, and block being the last parameter of the function we can define the closure in the outer scope of dispatch_async
.
Use this.
$('#mydiv').load(document.URL + ' #mydiv');
Note, include a space before the hastag.
First reset
locally:
git reset 23b6772
To see if you're on the right position, verify with:
git status
You will see something like:
On branch master Your branch is behind 'origin/master' by 17 commits, and can be fast-forwarded.
Then rewrite history on your remote tracking branch to reflect the change:
git push --force-with-lease // a useful command @oktober mentions in comments
Using --force-with-lease
instead of --force
will raise an error if others have meanwhile committed to the remote branch, in which case you should fetch first. More info in this article.
In case you are like me, and cannot work out how to use "regular expression with capturing groups" for extract
, the following code replicates the extract(...)
line in Hadleys' answer:
df %>%
gather(question_number, value, starts_with("Q3.")) %>%
mutate(loop_number = str_sub(question_number,-2,-2), question_number = str_sub(question_number,1,4)) %>%
select(id, time, loop_number, question_number, value) %>%
spread(key = question_number, value = value)
The problem here is that the initial gather forms a key column that is actually a combination of two keys. I chose to use mutate
in my original solution in the comments to split this column into two columns with equivalent info, a loop_number
column and a question_number
column. spread
can then be used to transform the long form data, which are key value pairs (question_number, value)
to wide form data.
There are many correct answers here. Here's another!
find . -type f | sort | uniq -w 10 -c
where .
is the folder to look in and 10
is the number of characters by which to group the directory.
If you are a user of the free Visual Studio Express edition the right key is in
HKEY_CURRENT_USER\Software\Microsoft\VCExpress\9.0\Text Editor
{note the VCExpress instead of VisualStudio) but it works! :)
// assuming positive numbers
$highest_key;
$highest_value = 0;
foreach ($array as $key => $value) {
if ($value > $highest_value) {
$highest_key = $key;
}
}
// $highest_key holds the highest value
I had the same issue, but my setup required a different solution.
I'm using the create-react-app-rewired
package with a config-overrides.js
file. Previously, I was using the addBabelPresets
import (in the override()
method) from customize-cra
and decided to abstract those presets to a separate file. Coincidentally, this solved my problem.
I added useBabelRc()
to the override()
method in config-overrides.js
and created a babel.config.js
file with the following:
module.exports = {
presets: [
'@babel/preset-react',
'@babel/preset-env'
],
}
While it isn't optimal for all operations, if you are making map tiles or working with large numbers of markers (dots) with only one projection (e.g. Mercator, like Google Maps and many other slippy maps frameworks expect), I have found what I call "Vast Coordinate System" to be really, really handy. Basically, you store x and y pixel coordinates at some way-zoomed-in -- I use zoom level 23. This has several benefits:
I talked about all this in a recent blog post: http://blog.webfoot.com/2013/03/12/optimizing-map-tile-generation/
The "Lines" property of a TextBox is an array of strings. By definition, you cannot add elements to an existing string[]
, like you can to a List<string>
. There is simply no method available for the purpose. You must instead create a new string[]
based on the current Lines reference, and assign it to Lines.
Using a little Linq (.NET 3.5 or later):
textBox1.Lines = textBox.Lines.Concat(new[]{"Some Text"}).ToArray();
This code is fine for adding one new line at a time based on user interaction, but for initializing a textbox with a few dozen new lines, it will perform very poorly. If you're setting the initial value of a TextBox, I would either set the Text property directly using a StringBuilder (as other answers have mentioned), or if you're set on manipulating the Lines property, use a List to compile the collection of values and then convert it to an array to assign to Lines:
var myLines = new List<string>();
myLines.Add("brown");
myLines.Add("brwn");
myLines.Add("brn");
myLines.Add("brow");
myLines.Add("br");
myLines.Add("brw");
...
textBox1.Lines = myLines.ToArray();
Even then, because the Lines array is a calculated property, this involves a lot of unnecessary conversion behind the scenes.
How to do it without using cURL with straight-up PHP: http://netevil.org/blog/2006/nov/http-post-from-php-without-curl
To send a file from windows to linux system
scp path-to-file user@ipaddress:/path-to-destination
Example:
scp C:/Users/adarsh/Desktop/Document.txt [email protected]:/tmp
keep in mind that there need to use forward slash(/) inplace of backward slash(\) in for the file in windows path else it will show an error
C:UsersadarshDesktopDocument.txt: No such file or directory
. After executing scp command you will ask for password of root user in linux machine. There you GO...
To send a file from linux to windows system
scp -r user@ipaddress:/path-to-file path-to-destination
Example:
scp -r [email protected]:/tmp/Document.txt C:/Users/adarsh/Desktop/
and provide your linux password. only one you have to add in this command is -r. Thanks.
I presume you've got validate_required() function from this page: http://www.w3schools.com/js/js_form_validation.asp?
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{
alert(alerttxt);return false;
}
else
{
return true;
}
}
}
In this case your last condition will not work as you expect it.
You can replace it with this:
if (password.value != cpassword.value) {
alert("Your password and confirmation password do not match.");
cpassword.focus();
return false;
}
I use this to solve it, go to cmd line
devenv.exe /setup /resetuserdata /resetsettings
What you need is the function strftime:
Time.now.strftime("%Y-%d-%m %H:%M:%S %Z")
Yes, it is possible to specify your own credentials without modifying the current code. It requires a small piece of code from your part though.
Create an assembly called SomeAssembly.dll with this class :
namespace SomeNameSpace
{
public class MyProxy : IWebProxy
{
public ICredentials Credentials
{
get { return new NetworkCredential("user", "password"); }
//or get { return new NetworkCredential("user", "password","domain"); }
set { }
}
public Uri GetProxy(Uri destination)
{
return new Uri("http://my.proxy:8080");
}
public bool IsBypassed(Uri host)
{
return false;
}
}
}
Add this to your config file :
<defaultProxy enabled="true" useDefaultCredentials="false">
<module type = "SomeNameSpace.MyProxy, SomeAssembly" />
</defaultProxy>
This "injects" a new proxy in the list, and because there are no default credentials, the WebRequest class will call your code first and request your own credentials. You will need to place the assemble SomeAssembly in the bin directory of your CMS application.
This is a somehow static code, and to get all strings like the user, password and URL, you might either need to implement your own ConfigurationSection, or add some information in the AppSettings, which is far more easier.
PS C:\> $MyVar = "C:\MyTxt.txt"
PS C:\> ($MyVar -ne $null) -and (Get-Content $MyVar)
True
($MyVar -ne $null)
returned true and (Get-Content $MyVar)
also returned true.
PS C:\> $MyVar = $null
PS C:\> ($MyVar -ne $null) -and (Get-Content $MyVar)
False
($MyVar -ne $null)
returned false and so far I must assume the (Get-Content $MyVar)
also returned false.
PS C:\> ($MyVar -ne $null) -and (Get-Content "C:\MyTxt.txt")
False
($MyVar -ne $null)
returned false and proved the second condition (Get-Content "C:\MyTxt.txt")
never ran, by returning false on the whole command.
This one is similar to @Wilhelm's solution. The loop automates based on a range created by evaluating the populated date column. This was slapped together based strictly on the conversation here and screenshots.
Please note: This assumes that the headers will always be on the same row (row 8). Changing the first row of data (moving the header up/down) will cause the range automation to break unless you edit the range block to take in the header row dynamically. Other assumptions include that VOL and CAPACITY formula column headers are named "Vol" and "Cap" respectively.
Sub Loop3()
Dim dtCnt As Long
Dim rng As Range
Dim frmlas() As String
Application.ScreenUpdating = False
'The following code block sets up the formula output range
dtCnt = Sheets("Loop").Range("A1048576").End(xlUp).Row 'lowest date column populated
endHead = Sheets("Loop").Range("XFD8").End(xlToLeft).Column 'right most header populated
Set rng = Sheets("Loop").Range(Cells(9, 2), Cells(dtCnt, endHead)) 'assigns range for automation
ReDim frmlas(1) 'array assigned to formula strings
'VOL column formula
frmlas(0) = "VOL FORMULA"
'CAPACITY column formula
frmlas(1) = "CAP FORMULA"
For i = 1 To rng.Columns.count
If rng(0, i).Value = "Vol" Then 'checks for volume formula column
For j = 1 To rng.Rows.count
rng(j, i).Formula= frmlas(0) 'inserts volume formula
Next j
ElseIf rng(0, i).Value = "Cap" Then 'checks for capacity formula column
For j = 1 To rng.Rows.count
rng(j, i).Formula = frmlas(1) 'inserts capacity formula
Next j
End If
Next i
Application.ScreenUpdating = True
End Sub
I have created, yet another one, function for this purpose:
function dateDiff(date) {
date = date.split('-');
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth() + 1;
var day = today.getDate();
var yy = parseInt(date[0]);
var mm = parseInt(date[1]);
var dd = parseInt(date[2]);
var years, months, days;
// months
months = month - mm;
if (day < dd) {
months = months - 1;
}
// years
years = year - yy;
if (month * 100 + day < mm * 100 + dd) {
years = years - 1;
months = months + 12;
}
// days
days = Math.floor((today.getTime() - (new Date(yy + years, mm + months - 1, dd)).getTime()) / (24 * 60 * 60 * 1000));
//
return {years: years, months: months, days: days};
}
Doesn't require any 3rd party libraries. Takes one argument -- date in YYYY-MM-DD format.
https://gist.github.com/lemmon/d27c2d4a783b1cf72d1d1cc243458d56
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())
Looks file you use the .mkdirs()
method on a File
object: http://www.roseindia.net/java/beginners/java-create-directory.shtml
// Create a directory; all non-existent ancestor directories are
// automatically created
success = (new File("../potentially/long/pathname/without/all/dirs")).mkdirs();
if (!success) {
// Directory creation failed
}
I did not find the -q1
option on my netcat. Instead I used the -w1
option. Below is the bash script I did to send an udp packet to any host and port:
#!/bin/bash
def_host=localhost
def_port=43211
HOST=${2:-$def_host}
PORT=${3:-$def_port}
echo -n "$1" | nc -4u -w1 $HOST $PORT
Perhaps you want something like:
<style name="CustomActivityTheme" parent="@android:style/Theme.Holo">
<item name="android:checkboxStyle">@style/customCheckBoxStyle</item>
</style>
<style name="customCheckBoxStyle" parent="@android:style/Widget.CompoundButton.CheckBox">
<item name="android:textColor">@android:color/black</item>
</style>
Note, the textColor item.
Take a look at this:
<input type="number" step="0.01" />
Is your link to another web page? If so, perhaps you could put the variable in the query string and set the session variable when the page being linked to is loaded.
So the link looks like this:
<a href="home.php?variable=value" name="home">home</a>
And the homge page would parse the query string and set the session variable.
If all that you are concerned about is that the field contains an integer (i.e., not concerned with a range), then add a CompareValidator
with it's Operator
property set to DataTypeCheck
:
<asp:CompareValidator runat="server" Operator="DataTypeCheck" Type="Integer"
ControlToValidate="ValueTextBox" ErrorMessage="Value must be a whole number" />
If there is a specific range of values that are valid (there probably are), then you can use a RangeValidator
, like so:
<asp:RangeValidator runat="server" Type="Integer"
MinimumValue="0" MaximumValue="400" ControlToValidate="ValueTextBox"
ErrorMessage="Value must be a whole number between 0 and 400" />
These will only validate if there is text in the TextBox, so you will need to keep the RequiredFieldValidator
there, too.
As @Mahin said, make sure you check the Page.IsValid
property on the server side, otherwise the validator only works for users with JavaScript enabled.
You will need to skip first row (where column names are defined) and you will need to check which "character" is separating cells (usually is ,
, but in my case was ;
)
Bellow is the picture of my import:
A possibility is that the git server you are pushing to is down/crashed, and the solution lies in restarting the git server.
Try this:
$('select option:selected').prop('label');
This will pull out the displayed text for both styles of <option>
elements:
<option label="foo"><option>
-> "foo"
<option>bar<option>
-> "bar"
If it has both a label
attribute and text inside the element, it'll use the label
attribute, which is the same behavior as the browser.
For posterity, this was tested under jQuery 3.1.1
I tried one after other and found a best answer at the time:
https://stackoverflow.com/a/3187524/985399
I skip old browsers so I made the code shorter to work on modern browsers (IE9+)
document.addEventListener("mouseout", function(e) {_x000D_
let t = e.relatedTarget || e.toElement;_x000D_
if (!t || t.nodeName == "HTML") {_x000D_
console.log("left window");_x000D_
}_x000D_
});_x000D_
_x000D_
document.write("<br><br>PROBLEM<br><br><div>Mouseout trigg on HTML elements</div>")
_x000D_
Here you see the browser support
That was pretty short I thought
But a problem still remained because "mouseout" trigg on all elements in the document.
To prevent it from happen, use mouseleave (IE5.5+). See the good explanation in the link.
The following code works without triggering on elements inside the element to be inside or outside of. Try also drag-release outside the document.
var x = 0_x000D_
_x000D_
document.addEventListener("mouseleave", function(e) { console.log(x++) _x000D_
})_x000D_
_x000D_
document.write("<br><br>SOLUTION<br><br><div>Mouseleave do not trigg on HTML elements</div>")
_x000D_
You can set the event on any HTML element. Do not have the event on document.body
though, because the windows scrollbar may shrink the body and fire when mouse pointer is abowe the scroll bar when you want to scroll but not want to trigg a mouseLeave event over it. Set it on document
instead, as in the example.
My solution to this issue was to create the function shown below. My requirements included that the number had to be a standard integer, not a BIGINT, and I needed to allow negative numbers and positive numbers. I have not found a circumstance where this fails.
CREATE FUNCTION [dbo].[udfIsInteger]
(
-- Add the parameters for the function here
@Value nvarchar(max)
)
RETURNS int
AS
BEGIN
-- Declare the return variable here
DECLARE @Result int = 0
-- Add the T-SQL statements to compute the return value here
DECLARE @MinValue nvarchar(11) = '-2147483648'
DECLARE @MaxValue nvarchar(10) = '2147483647'
SET @Value = ISNULL(@Value,'')
IF LEN(@Value)=0 OR
ISNUMERIC(@Value)<>1 OR
(LEFT(@Value,1)='-' AND LEN(@Value)>11) OR
(LEFT(@Value,1)='-' AND LEN(@Value)=11 AND @Value>@MinValue) OR
(LEFT(@Value,1)<>'-' AND LEN(@Value)>10) OR
(LEFT(@Value,1)<>'-' AND LEN(@Value)=10 AND @Value>@MaxValue)
GOTO FINISHED
DECLARE @cnt int = 0
WHILE @cnt<LEN(@Value)
BEGIN
SET @cnt=@cnt+1
IF SUBSTRING(@Value,@cnt,1) NOT IN ('-','0','1','2','3','4','5','6','7','8','9') GOTO FINISHED
END
SET @Result=1
FINISHED:
-- Return the result of the function
RETURN @Result
END
Old thread, but just only to say: to use the classic Left()
, Right()
, Mid()
right now you don't need to write the full path (Microsoft.VisualBasic.Strings
). You can use fast and easily like this:
Strings.Right(yourString, 5)
Setting android:noHistory="true"
on the activity in your manifest will remove an activity from the stack whenever it is navigated away from. see here
Now that flexbox is supported in all modern browsers, something like this seems like an easier approach to me.
<style>
label {
display: flex;
align-items: center;
}
input[type=radio], input[type=checkbox]{
flex: none;
}
</style>
<form>
<div>
<label><input type="checkbox" /> Label text</label>
</div>
</form>
Here's the complete prefixed version demo:
label {_x000D_
display: -webkit-box;_x000D_
display: -webkit-flex;_x000D_
display: -ms-flexbox;_x000D_
display: flex;_x000D_
-webkit-box-align: center;_x000D_
-webkit-align-items: center;_x000D_
-ms-flex-align: center;_x000D_
align-items: center;_x000D_
}_x000D_
input[type=radio], _x000D_
input[type=checkbox] {_x000D_
-webkit-box-flex: 0;_x000D_
-webkit-flex: none;_x000D_
-ms-flex: none;_x000D_
flex: none;_x000D_
margin-right: 10px; _x000D_
}_x000D_
/* demo only (to show alignment) */_x000D_
form {_x000D_
max-width: 200px_x000D_
}
_x000D_
<form>_x000D_
<label>_x000D_
<input type="radio" checked>_x000D_
I am an aligned radio and label_x000D_
</label>_x000D_
<label>_x000D_
<input type="checkbox" checked>_x000D_
I am an aligned checkbox and label_x000D_
</label>_x000D_
</form>
_x000D_
To list files based on size in asending order.
find ./ -size +1000M -exec ls -tlrh {} \; |awk -F" " '{print $5,$9}' | sort -n\
As said by Sparky in comments on many answers to this question, there is NOT any textarea
value for the type
attribute of the input
tag.
On other terms, the following markup is not valid :
<input type="textarea" />
And the browser replaces it by the default :
<input type="text" />
To define a multi-lines text input, use :
<textarea></textarea>
See the textarea element documentation for more details.
trim() is your choice, but if you want to use replace
method -- which might be more flexiable, you can try the following:
String stripppedString = myString.replaceAll("(^ )|( $)", "");
The canonical T-SQL (SqlServer) answer is to use a DELETE
with JOIN
as such
DELETE o
FROM Orders o
INNER JOIN Customers c
ON o.CustomerId = c.CustomerId
WHERE c.FirstName = 'sklivvz'
This will delete all orders which have a customer with first name Sklivvz.
I kinda disagree with the accepted answer. Sometimes an application architecture doesn't want you to mess with the array id, or makes it inconvenient. For instance, I use CakePHP quite a lot, and a database query returns the primary key as a value in each record, very similar to the above.
Assuming the array is not stupidly large, I would use array_filter. This will create a copy of the array, minus the records you want to remove, which you can assign back to the original array variable.
Although this may seem inefficient it's actually very much in vogue these days to have variables be immutable, and the fact that most php array functions return a new array rather than futzing with the original implies that PHP kinda wants you to do this too. And the more you work with arrays, and realize how difficult and annoying the unset() function is, this approach makes a lot of sense.
Anyway:
$my_array = array_filter($my_array,
function($el) {
return $el["value"]!="Completed" && $el!["value"]!="Marked as Spam";
});
You can use whatever inclusion logic (eg. your id field) in the embedded function that you want.
If you're on Chrome, Firefox or IE10 + why not extend the console and use
(function() {
console.dump = function(object) {
if (window.JSON && window.JSON.stringify)
console.log(JSON.stringify(object));
else
console.log(object);
};
})();
for a concise, cross-browser solution.
<meta charset="utf-8">
was introduced with/for HTML5.
As mentioned in the documentation, both are valid. However, <meta charset="utf-8">
is only for HTML5 (and easier to type/remember).
In due time, the old style is bound to become deprecated in the near future. I'd stick to the new <meta charset="utf-8">
.
There's only one way, but up. In tech's case, that's phasing out the old (really, REALLY fast)
Documentation: HTML meta charset Attribute—W3Schools
It's useful to remember that state machines are an abstraction, and you don't need particular tools to create one, however tools can be useful.
You can for example realise a state machine with functions:
void Hunt(IList<Gull> gulls)
{
if (gulls.Empty())
return;
var target = gulls.First();
TargetAcquired(target, gulls);
}
void TargetAcquired(Gull target, IList<Gull> gulls)
{
var balloon = new WaterBalloon(weightKg: 20);
this.Cannon.Fire(balloon);
if (balloon.Hit)
{
TargetHit(target, gulls);
}
else
TargetMissed(target, gulls);
}
void TargetHit(Gull target, IList<Gull> gulls)
{
Console.WriteLine("Suck on it {0}!", target.Name);
Hunt(gulls);
}
void TargetMissed(Gull target, IList<Gull> gulls)
{
Console.WriteLine("I'll get ya!");
TargetAcquired(target, gulls);
}
This machine would hunt for gulls and try to hit them with water balloons. If it misses it will try firing one until it hits (could do with some realistic expectations ;)), otherwise it will gloat in the console. It continues to hunt until it's out of gulls to harass.
Each function corresponds to each state; the start and end (or accept) states are not shown. There are probably more states in there than modelled by the functions though. For example after firing the balloon the machine is really in another state than it was before it, but I decided this distinction was impractical to make.
A common way is to use classes to represent states, and then connect them in different ways.
To avoid that exception, if you are using JUnit and Spring try adding this in every test class:
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
I think the best option for you is to enclose both divs by another div. Then you can make it by CSS in the following way:
<html>
<head>
<style>
div.both:hover .image { border: 1px solid blue }
div.both:hover .layer { border: 1px solid blue }
</style>
</head>
<body>
<div class="section">
<div class="both">
<div class="image"><img src="myImage.jpg" /></div>
<div class="layer">Lorem Ipsum</div>
</div>
</div>
</body>
</html>
A common cause for Cannot read property 'fnSetData' of undefined
is the mismatched number of columns, like in this erroneous code:
<thead> <!-- thead required -->
<tr> <!-- tr required -->
<th>Rep</th> <!-- td instead of th will also work -->
<th>Titel</th>
<!-- th missing here -->
</tr>
</thead>
<tbody>
<tr>
<td>Rep</td>
<td>Titel</td>
<td>Missing corresponding th</td>
</tr>
</tbody>
While the following code with one <th>
per <td>
(number of columns must match) works:
<thead>
<tr>
<th>Rep</th> <!-- 1st column -->
<th>Titel</th> <!-- 2nd column -->
<th>Added th</th> <!-- 3rd column; th added here -->
</tr>
</thead>
<tbody>
<tr>
<td>Rep</td> <!-- 1st column -->
<td>Titel</td> <!-- 2nd column -->
<td>th now present</td> <!-- 3rd column -->
</tr>
</tbody>
The error also appears when using a well-formed thead with a colspan but without a second row.
For a table with 7 colums, the following does not work and we see "Cannot read property 'mData' of undefined" in the javascript console:
<thead>
<tr>
<th>Rep</th>
<th>Titel</th>
<th colspan="5">Download</th>
</tr>
</thead>
While this works:
<thead>
<tr>
<th rowspan="2">Rep</th>
<th rowspan="2">Titel</th>
<th colspan="5">Download</th>
</tr>
<tr>
<th>pdf</th>
<th>nwc</th>
<th>nwctxt</th>
<th>mid</th>
<th>xml</th>
</tr>
</thead>
If you are using Netbeans to develop, use jLabel and change it's icon property.
Just one thing to add to this (although I do think you have already had your question answered by others). In the interests of extensibility (since we all know it will happen at some point) you may want to check out the Composite Pattern This is ideal for working with "Tree-Like Structures"..
Like I said, I know you are only expecting one sub-level, but this could really be useful for you if you later need to extend ^_^
This one works better if you don't have the python on path or want to specify the directory :
//for Windows
npm config set python C:\Python27\python.exe
//for Linux
npm config set python /usr/bin/python27
Taking a uniform random variable as the value of RGB may generate a large amount of gray, white, and black, which are often not the colors we want.
The cv::applyColorMap
can easily generate a random RGB palette, and you can choose a favorite color map from the list here
Example for C++11:
#include <algorithm>
#include <numeric>
#include <random>
#include <opencv2/opencv.hpp>
std::random_device rd;
std::default_random_engine re(rd());
// Generating randomized palette
cv::Mat palette(1, 255, CV_8U);
std::iota(palette.data, palette.data + 255, 0);
std::shuffle(palette.data, palette.data + 255, re);
cv::applyColorMap(palette, palette, cv::COLORMAP_JET);
// ...
// Picking random color from palette and drawing
auto randColor = palette.at<cv::Vec3b>(i % palette.cols);
cv::rectangle(img, cv::Rect(0, 0, 100, 100), randColor, -1);
Example for Python3:
import numpy as np, cv2
palette = np.arange(0, 255, dtype=np.uint8).reshape(1, 255, 1)
palette = cv2.applyColorMap(palette, cv2.COLORMAP_JET).squeeze(0)
np.random.shuffle(palette)
# ...
rand_color = tuple(palette[i % palette.shape[0]].tolist())
cv2.rectangle(img, (0, 0), (100, 100), rand_color, -1)
If you don't need so many colors, you can just cut the palette to the desired length.
All a Try-Catch does is allow your program to fail gracefully. In a catch statement, you generally try to log the error, and maybe roll back changes if you need to.
bool finished = false;
while(finished == false)
{
try
{
//your code here
finished = true
}
catch(exception ex)
{
log.error("there was an error, ex");
}
}
There is no single magic function to force a frame to a minimum or fixed size. However, you can certainly force the size of a frame by giving the frame a width and height. You then have to do potentially two more things: when you put this window in a container you need to make sure the geometry manager doesn't shrink or expand the window. Two, if the frame is a container for other widget, turn grid or pack propagation off so that the frame doesn't shrink or expand to fit its own contents.
Note, however, that this won't prevent you from resizing a window to be smaller than an internal frame. In that case the frame will just be clipped.
import Tkinter as tk
root = tk.Tk()
frame1 = tk.Frame(root, width=100, height=100, background="bisque")
frame2 = tk.Frame(root, width=50, height = 50, background="#b22222")
frame1.pack(fill=None, expand=False)
frame2.place(relx=.5, rely=.5, anchor="c")
root.mainloop()
if you want to add the data in the increment order inside your associative array you can do this:
$newdata = array (
'wpseo_title' => 'test',
'wpseo_desc' => 'test',
'wpseo_metakey' => 'test'
);
// for recipe
$md_array["recipe_type"][] = $newdata;
//for cuisine
$md_array["cuisine"][] = $newdata;
this will get added to the recipe or cuisine depending on what was the last index.
Array push is usually used in the array when you have sequential index: $arr[0] , $ar[1].. you cannot use it in associative array directly. But since your sub array is had this kind of index you can still use it like this
array_push($md_array["cuisine"],$newdata);
To set the range of the x-axis, you can use set_xlim(left, right)
, here are the docs
Update:
It looks like you want an identical plot, but only change the 'tick values', you can do that by getting the tick values and then just changing them to whatever you want. So for your need it would be like this:
ticks = your_plot.get_xticks()*10**9
your_plot.set_xticklabels(ticks)
As the question is asked simply use @Min(1) instead of @size on integer fields and it will work.
To save and load an arraylist of public static ArrayList data = new ArrayList ();
I used (to write)...
static void saveDatabase() {
try {
FileOutputStream fos = new FileOutputStream("mydb.fil");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(data);
oos.close();
databaseIsSaved = true;
}
catch (IOException e) {
e.printStackTrace();
}
} // End of saveDatabase
And used (to read) ...
static void loadDatabase() {
try {
FileInputStream fis = new FileInputStream("mydb.fil");
ObjectInputStream ois = new ObjectInputStream(fis);
data = (ArrayList<User>)ois.readObject();
ois.close();
}
catch (IOException e) {
System.out.println("***catch ERROR***");
e.printStackTrace();
}
catch (ClassNotFoundException e) {
System.out.println("***catch ERROR***");
e.printStackTrace();
}
} // End of loadDatabase
Casting to an int implicitly drops any decimal. No need to call Math.floor() (assuming positive numbers)
Simply typecast with (int), e.g.:
System.out.println((int)(99.9999)); // Prints 99
This being said, it does have a different behavior from Math.floor
which rounds towards negative infinity (@Chris Wong)
The ally.js accessibility library provides an unofficial, test-based list here:
https://allyjs.io/data-tables/focusable.html
(NB: Their page doesn't say how often tests were performed.)
Having tried $customer = new WC_Customer();
and global $woocommerce; $customer = $woocommerce->customer;
I was still getting empty address data even when I logged in as a non-admin user.
My solution was as follows:
function mwe_get_formatted_shipping_name_and_address($user_id) {
$address = '';
$address .= get_user_meta( $user_id, 'shipping_first_name', true );
$address .= ' ';
$address .= get_user_meta( $user_id, 'shipping_last_name', true );
$address .= "\n";
$address .= get_user_meta( $user_id, 'shipping_company', true );
$address .= "\n";
$address .= get_user_meta( $user_id, 'shipping_address_1', true );
$address .= "\n";
$address .= get_user_meta( $user_id, 'shipping_address_2', true );
$address .= "\n";
$address .= get_user_meta( $user_id, 'shipping_city', true );
$address .= "\n";
$address .= get_user_meta( $user_id, 'shipping_state', true );
$address .= "\n";
$address .= get_user_meta( $user_id, 'shipping_postcode', true );
$address .= "\n";
$address .= get_user_meta( $user_id, 'shipping_country', true );
return $address;
}
...and this code works regardless of whether you are logged in as admin or not.
iris %>% dplyr::select(where(is.numeric)) #as per most recent updates
Another option with purrr
would be to negate discard
function:
iris %>% purrr::discard(~!is.numeric(.))
If you want the names of the numeric columns, you can add names
or colnames
:
iris %>% purrr::discard(~!is.numeric(.)) %>% names
My similar issue was caused by having special characters (e.g. periods) in the selector.
The fix was to escape the special characters:
$("#dots\\.er\\.bad").val("mmmk");
Unless I have misunderstood:
$("e").prepend("<yourelem>Text</yourelem>");
Or
$("<yourelem>Text</yourelem>").prependTo("e");
Although it sounds like from your description that there is some condition attached, so
if (SomeCondition){
$("e").prepend("<yourelem>Text</yourelem>");
}
else{
$("e").append("<yourelem>Text</yourelem>");
}
Change the function that you get one single Result=[array, listp, freep]. So there is only one result to be displayed
Generally, The DNS Domain of the URL MUST match the Certificate Subject of the certificate.
In former times this could be either by setting the domain as cn of the certificate or by having the domain set as a Subject Alternative Name.
Support for cn was deprecated for a long time (since 2000 in RFC 2818) and Chrome browser will not even look at the cn anymore so today you need to have the DNS Domain of the URL as a Subject Alternative Name.
RFC 6125 which forbids checking the cn if SAN for DNS Domain is present, but not if SAN for IP Address is present. RFC 6125 also repeats that cn is deprecated which was already said in RFC 2818. And the Certification Authority Browser Forum to be present which in combination with RFC 6125 essentially means that cn will never be checked for DNS Domain name.
SELECT * FROM table SAMPLE(10) WHERE ROWNUM <= 20;
This is more efficient as it doesn't need to sort the Table.
You can have many java versions in your system.
I think you should add the java 8 in yours JREs installed or edit.
Take a look my screen:
If you click in edit (check your java 8 path):
You have several problems.
First, you have the example that you cited.
You also have a similar problem if rows are inserted, but in this case the user get duplicate data (arguably easier to manage than missing data, but still an issue).
If you are not snapshotting the original data set, then this is just a fact of life.
You can have the user make an explicit snapshot:
POST /createquery
filter.firstName=Bob&filter.lastName=Eubanks
Which results:
HTTP/1.1 301 Here's your query
Location: http://www.example.org/query/12345
Then you can page that all day long, since it's now static. This can be reasonably light weight, since you can just capture the actual document keys rather than the entire rows.
If the use case is simply that your users want (and need) all of the data, then you can simply give it to them:
GET /query/12345?all=true
and just send the whole kit.
You may not pass str
to fit this kind of classifier.
For example, if you have a feature column named 'grade' which has 3 different grades:
A,B and C.
you have to transfer those str
"A","B","C" to matrix by encoder like the following:
A = [1,0,0]
B = [0,1,0]
C = [0,0,1]
because the str
does not have numerical meaning for the classifier.
In scikit-learn, OneHotEncoder
and LabelEncoder
are available in inpreprocessing
module.
However OneHotEncoder
does not support to fit_transform()
of string.
"ValueError: could not convert string to float" may happen during transform.
You may use LabelEncoder
to transfer from str
to continuous numerical values. Then you are able to transfer by OneHotEncoder
as you wish.
In the Pandas dataframe, I have to encode all the data which are categorized to dtype:object
. The following code works for me and I hope this will help you.
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
for column_name in train_data.columns:
if train_data[column_name].dtype == object:
train_data[column_name] = le.fit_transform(train_data[column_name])
else:
pass
Java doesn't have direct equivalent of C# language feature called async/await, however there's a different approach to the problem that async/await tries to solve. It's called project Loom, which will provide virtual threads for high-throughput concurrency. It will be available in some future version of OpenJDK.
This approach also solves "colored function problem" that async/await has.
Similar feature can be also found in Golang (goroutines).
Use a CASE statement:
SELECT CASE
WHEN (Obsolete = 'N' OR InStock = 'Y')
THEN 'Y'
ELSE 'N'
END as Available
etc...
There is nothing particularly tricky about the example you posted.
In a ternary operator, the first argument (the conditional) is evaluated and if the result is true
, the second argument is evaluated and returned, otherwise, the third is evaluated and returned. Each of those arguments can be any valid code block, including function calls.
Think of it this way:
var x = (1 < 2) ? true : false;
Could also be written as:
var x = (1 < 2) ? getTrueValue() : getFalseValue();
This is perfectly valid, and those functions can contain any arbitrary code, whether it is related to returning a value or not. Additionally, the results of the ternary operation don't have to be assigned to anything, just as function results do not have to be assigned to anything:
(1 < 2) ? getTrueValue() : getFalseValue();
Now simply replace those with any arbitrary functions, and you are left with something like your example:
(1 < 2) ? removeItem($this) : addItem($this);
Now your last example really doesn't need a ternary at all, as it can be written like this:
x = (1 < 2); // x will be set to "true"
First of all, this what is written in documentation. I think it is one of your class fields, not the main one - and how you want deserialiser to construct it back w/o parameterless construction ?
I think there is a workaround to make constructor private.
step 1. stop redis server using below command /etc/init.d/redis-server stop
step 2.enter command : sudo nano /etc/redis/redis.conf
step 3.find # requirepass foobared word and remove # and change foobared to YOUR PASSWORD
ex. requirepass root
There are multiple ways:
ng --version
The command above will result in the following output:
Angular CLI: 7.0.3
Node: 9.4.0
OS: darwin x64
Angular: 7.0.1
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router
Package Version
@angular-devkit/architect 0.10.3
@angular-devkit/build-angular 0.10.3
@angular-devkit/build-optimizer 0.10.3
@angular-devkit/build-webpack 0.10.3
@angular-devkit/core 7.0.3
@angular-devkit/schematics 7.0.3
@angular/cli 7.0.3
@ngtools/webpack 7.0.3
@schematics/angular 7.0.3
@schematics/update 0.10.3
rxjs 6.3.3
typescript 3.1.4
webpack 4.19.1
So, the version of Angular, Angular CLI, Node and many other packages can be verified from here.
You probably just need to see the ASCII
and EXTENDED ASCII
character sets. As far as I know any of these are allowed in a char
/varchar
field.
If you use nchar
/nvarchar
then it's pretty much any character in any unicode set in the world.
I finished using this function:
onkeypress="if(event.which < 48 || event.which > 57 ) if(event.which != 8) return false;"
This works well in IE and Chrome, I don´t know why it´s not work well in firefox too, this function block the tab key in Firefox.
For the tab key works fine in firefox add this:
onkeypress="if(event.which < 48 || event.which > 57 ) if(event.which != 8) if(event.keyCode != 9) return false;"
Yes. Recent versions of IE (IE8 or above) let you adjust that. Here's how:
That should open the Developer Tools window. That window has two menu items that are of interest:
More at http://blogs.msdn.com/b/ie/archive/2010/06/16/ie-s-compatibility-features-for-site-developers.aspx
I was able to get this to work by adding it to the body tag. Was nicer for me because I don't have anything on the html element.
body {
overflow-y: scroll;
}
Your syntax is invalid.
string[] arr = new string[5];
That will create arr
, a referenced array of strings, where all elements of this array are null
. (Since strings are reference types)
This array contains the elements from arr[0]
to arr[4]
. The new
operator is used to create the array and initialize the array elements to their default values. In this example, all the array elements are initialized to null
.
See this fiddle for a preview and check the documentation for jquerys toggle and animate methods.
$('#toggle').toggle(function(){
$('#A').animate({width:0});
$('#B').animate({left:0});
},function(){
$('#A').animate({width:200});
$('#B').animate({left:200});
});
Basically you animate on the properties that sets the layout.
A more advanced version:
$('#toggle').toggle(function(){
$('#A').stop(true).animate({width:0});
$('#B').stop(true).animate({left:0});
},function(){
$('#A').stop(true).animate({width:200});
$('#B').stop(true).animate({left:200});
})
This stops the previous animation, clears animation queue and begins the new animation.
The only time I've seen this happen it was when the host filesystem was basically out of space. Do you have much free space on the filesystem where the VM's filesystem is stored?
If the content of the iframe is not completely under your control or you want to access the content from different pages with different styles you could try manipulating it using JavaScript.
var frm = frames['frame'].document;
var otherhead = frm.getElementsByTagName("head")[0];
var link = frm.createElement("link");
link.setAttribute("rel", "stylesheet");
link.setAttribute("type", "text/css");
link.setAttribute("href", "style.css");
otherhead.appendChild(link);
Note that depending on what browser you use this might only work on pages served from the same domain.
The maximum length of a string variable is only 2GiB - (2^(32-1) bits). Variables can be addressed on a character (8 bits/1 byte) basis and the addressing is done by signed integers which is why the limit is what it is. Arrays can contain multiple variables that each follow the previous restriction but can have a total cumulative size up to memory_limit of which a string variable is also subject to.
this is for objective c add your segmented control name in place of mysegmentedcontrol
UIFont *font = [UIFont systemFontOfSize:11.0f];
NSDictionary *attributes = [NSDictionary dictionaryWithObject:font
forKey:UITextAttributeFont];
[mySegmentedcontrol setTitleTextAttributes:attributes forState:UIControlStateNormal];
hope it helps
Target= "_blank"
This does it in html, give it a try in C#
@papigee should work on Windows 10 just fine. I'm using the integrated VSCode terminal with git bash and this always works for me.
winpty docker exec -it <container-id> //bin//sh
Two things:
I'm Daniel Stenberg.
I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.
I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.
Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.
Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.
Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.
At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.
Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.
Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?
Yes. So insanely much.
But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.
We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.
Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.
Yeah. For real.
Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.
But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.
curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.
For a css-only solution, try setting pointer-events: none
on the input.
one way...
$needle = "blah";
$content = file_get_contents('file.txt');
preg_match('~^(.*'.$needle.'.*)$~',$content,$line);
echo $line[1];
though it would probably be better to read it line by line with fopen() and fread() and use strpos()
Suppose I have committed changes to master branch.I will get the commit id(xyz) of the commit now i have to go to branch for which i need to push my commits.
Single commit id xyx
git checkout branch-name
git cherry-pick xyz
git push origin branch-name
Multiple commit id's xyz abc qwe
git checkout branch-name
git cherry-pick xyz abc qwe
git push origin branch-name
It depends what you want to do with each line. awk is a useful utility for this type of processing. Example:
ls -l | awk '{print $9, $5}'
.. on my system prints the name and size of each item in the directory.
Python 3.0 doesn't have sys.maxint any more since Python 3's ints are of arbitrary length. Instead of sys.maxint it has sys.maxsize; the maximum size of a positive sized size_t aka Py_ssize_t.
Bit late for reply but this should do the trick
Type myType = Type.GetType("AssemblyQualifiedName");
your assembly qualified name should be like this
"Boom.Bam.Class, Boom.Bam, Version=1.0.0.262, Culture=neutral, PublicKeyToken=e16dba1a3c4385bd"
Better yet, consider sp_getapplock
which is designed for this. Or use SET LOCK_TIMEOUT
Otherwise, you'd have to do something with sys.dm_tran_locks
which I'd use only for DBA stuff: not for user defined concurrency.
This worked for me:
using System.ComponentModel.DataAnnotations;
[Key]
public int ID { get; set; }
You can use a Regex for this. This is as concise as it gets
System.out.println(yourArrayList.toString().replaceAll("\\[|\\]|[,][ ]","\t"));
Don't forget to use var/let while declaring any variable.See below examples for JS compiler behaviour.
function func(){
return true;
}
isBool = func();
console.log(typeof (isBool)); // output - string
let isBool = func();
console.log(typeof (isBool)); // output - boolean
I got
No 'Access-Control-Allow-Origin' header is present
and the problem was with the URL I was providing. I was providing the URL without a route, e.g., https://misty-valley-1234.herokuapp.com/
.
When I added a path it worked, e.g.,
https://misty-valley-1234.herokuapp.com/messages
. With GET requests it worked either way but with POST responses it only worked with the added path.
SELECT * FROM
(SELECT [UserID] FROM [User]) a
LEFT JOIN (SELECT [TailUser], [Weight] FROM [Edge] WHERE [HeadUser] = 5043) b
ON a.UserId = b.TailUser
I created a JsFiddle here based on the answer given by Zachary. It provides a more accessible user interface and also escapes double quotes within strings properly.
Thread.interrupt() method sets internal 'interrupt status' flag. Usually that flag is checked by Thread.interrupted() method.
By convention, any method that exists via InterruptedException have to clear interrupt status flag.
Others have answered your question perfectly, but I just thought I would throw out another way. It's always a good idea to separate HTML markup, CSS styling, and javascript code when possible. The cleanest way to hide something, with that in mind, is using a class. It allows the definition of "hide" to be defined in the CSS where it belongs. Using this method, you could later decide you want the ul
to hide by scrolling up or fading away using CSS transition
, all without changing your HTML or code. This is longer, but I feel it's a better overall solution.
Demo: http://jsfiddle.net/ThinkingStiff/RkQCF/
HTML:
<a id="showTags" href="#" title="Show Tags">Show All Tags</a>
<ul id="subforms" class="subforums hide"><li>one</li><li>two</li><li>three</li></ul>
CSS:
#subforms {
overflow-x: visible;
overflow-y: visible;
}
.hide {
display: none;
}
Script:
document.getElementById( 'showTags' ).addEventListener( 'click', function () {
document.getElementById( 'subforms' ).toggleClass( 'hide' );
}, false );
Element.prototype.toggleClass = function ( className ) {
if( this.className.split( ' ' ).indexOf( className ) == -1 ) {
this.className = ( this.className + ' ' + className ).trim();
} else {
this.className = this.className.replace( new RegExp( '(\\s|^)' + className + '(\\s|$)' ), ' ' ).trim();
};
};
You should use DateTime.TryParseExcact
if you know the format, or if not and want to use the system settings DateTime.TryParse
. And to print the date,DateTime.ToString
with the right format in the argument. To get the year, month or day you have DateTime.Year
, DateTime.Month
or DateTime.Day
.
See DateTime Structures in MSDN for additional references.
You could use the PECL extension
runkit_function_redefine
— Replace a function definition with a new implementation but that is bad practise in my opinion. You are using functions, but check out the Decorator design pattern. Can borrow the basic idea from it.
First Create Bitmap Image
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.image);
now set bitmap in Notification Builder Icon....
Notification.Builder.setLargeIcon(bmp);
I have a one-liner answer (this example gives you 999 lines of data and one header row per file)
cat bigFile.csv | parallel --header : --pipe -N999 'cat >file_{#}.csv'
I already said that I was new to exec()
function. After doing some more digging, I came upon 2>&1
which needs to be added at the end of command in exec()
.
Thanks @mattosmat
for pointing it out in the comments too. I did not try this at once because you said it is a Linux command, I am on Windows.
So, what I have discovered, the command is actually executing in the back-end. That is why I could not see it actually running, which I was expecting to happen.
For all of you, who had similar problem, my advise is to use that command. It will point out all the errors and also tell you info/details about execution.
exec('some_command 2>&1', $output);
print_r($output); // to see the response to your command
Thanks for all the help guys, I appreciate it ;)
I tried to find solution to this problem.I tried most of the solutions mentioned in this thread. However, I am not very sure why this was occurring. Probably a bug in Android Studio. Anyhow, this is what solved the problem:
In Application level build.gradle, removed:
classpath 'com.android.tools.build:gradle:2.2.0-beta1'
replaced with:
classpath 'com.android.tools.build:gradle:2.0.0'
Strings can have for loops to:
for a in string:
print a
Here you go: ES5
var test = 'Hello World';
if( test.indexOf('World') >= 0){
// Found world
}
With ES6 best way would be to use includes
function to test if the string contains the looking work.
const test = 'Hello World';
if (test.includes('World')) {
// Found world
}
For MySQL or PostgreSQL 9.3+, a better way is to use the LEAST
and GREATEST
functions.
SELECT GREATEST(A.date0, B.date0) AS date0,
LEAST(A.date1, B.date1, B.date2) AS date1
FROM A, B
WHERE B.x = A.x
With:
GREATEST(value [, ...])
: Returns the largest (maximum-valued) argument from values providedLEAST(value [, ...])
Returns the smallest (minimum-valued) argument from values providedDocumentation links :
There are a few ways of doing that... the simplest is to have the async method also do the follow-on operation. Another popular approach is to pass in a callback, i.e.
void RunFooAsync(..., Action<bool> callback) {
// do some stuff
bool result = ...
if(callback != null) callback(result);
}
Another approach would be to raise an event (with the result in the event-args data) when the async operation is complete.
Also, if you are using the TPL, you can use ContinueWith
:
Task<bool> outerTask = ...;
outerTask.ContinueWith(task =>
{
bool result = task.Result;
// do something with that
});
In AngularJS (version 1.x), there is a build-in directive ngRequired
<input type='email'
name='email'
ng-model='user.email'
placeholder='[email protected]'
ng-required='!user.phone' />
<input type='text'
ng-model='user.phone'
placeholder='(xxx) xxx-xxxx'
ng-required='!user.email' />
In Angular2 or above
<input type='email'
name='email'
[(ngModel)]='user.email'
placeholder='[email protected]'
[required]='!user.phone' />
<input type='text'
[(ngModel)]='user.phone'
placeholder='(xxx) xxx-xxxx'
[required]='!user.email' />
For a custom class to work properly in collections you'll have to implement/override the equals()
methods of the class. For sorting also override compareTo()
.
See this article or google about how to implement those methods properly.
@(new HtmlString(myString))
You can use the CSS3 Linear Gradient property along with your background-image like this:
#landing-wrapper {
display:table;
width:100%;
background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('landingpagepic.jpg');
background-position:center top;
height:350px;
}
Here's a demo:
#landing-wrapper {_x000D_
display: table;_x000D_
width: 100%;_x000D_
background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('http://placehold.it/350x150');_x000D_
background-position: center top;_x000D_
height: 350px;_x000D_
color: white;_x000D_
}
_x000D_
<div id="landing-wrapper">Lorem ipsum dolor ismet.</div>
_x000D_
The Best way is to create a user for your application and assign the permissions that are suitable for that user. Dont use 'NT AUTHORITY\NETWORK SERVICE' as your user it has its own vulnerability and it is a user that has permissions to so many things on the OS level. Stay away from this built in user.
I'd like to add one thing to chazomaticus' excellent answer:
Don't forget the META tag either (like this, or the HTML4 or XHTML version of it):
<meta charset="utf-8">
That seems trivial, but IE7 has given me problems with that before.
I was doing everything right; the database, database connection and Content-Type HTTP header were all set to UTF-8, and it worked fine in all other browsers, but Internet Explorer still insisted on using the "Western European" encoding.
It turned out the page was missing the META tag. Adding that solved the problem.
Edit:
The W3C actually has a rather large section dedicated to I18N. They have a number of articles related to this issue – describing the HTTP, (X)HTML and CSS side of things:
They recommend using both the HTTP header and HTML meta tag (or XML declaration in case of XHTML served as XML).
@param
will not affect testNumber.It is a Javadoc
comment - i.e used for generating documentation .
You can put a Javadoc
comment immediately before a class, field, method, constructor, or interface such as @param
, @return
.
Generally begins with '@' and must be the first thing on the line.
The Advantage of using @param
is :-
By creating simple Java classes that contain attributes and some custom Javadoc tags, you allow those classes to serve as a simple metadata description for code generation.
/*
*@param testNumber
*@return integer
*/
public int main testNumberIsValid(int testNumber){
if (testNumber < 6) {
//Something
}
}
Whenever in your code if you reuse testNumberIsValid method, IDE will show you the parameters the method accepts and return type of the method.
I am sure my code will be easier and works faster.
$logon_sessions = get-process -includeusername | Select-Object -Unique -Property UserName, si | ? { $_ -match "server" -and $_ -notmatch "admin" }
foreach ($id in $logon_sessions.si) {
logoff $id
}
Set these on php.ini
:
;display_startup_errors = On
display_startup_errors=off
display_errors =on
html_errors= on
From your PHP page, use a suitable filter for error reporting.
error_reporting(E_ALL);
Filers can be made according to requirements.
E_ALL
E_ALL | E_STRICT
use
head -n 1 filename | od -c
to figure WHAT is the offending character. then use
tr -d '\n' <filename
for LF
tr -d '\r\n' <filename
for CRLF
At my previous job, we had a technical test which all candidates were asked to sit. 10ish questions, took about an hour. In all honesty though, 90% of failures could be screened out because they couldn't write an INNER JOIN statement. Not even an outer.
I'd consider that a prerequisite for any job description involving SQL and would leave well alone until that was mastered. From there though, talk to them - any further info on what they're actually looking for will, worst case scenario, be a useful list of things to learn as part of your professional development.
for(int i=0;i<ytFiles.size();i++){
int key = ytFiles.keyAt(i);
Log.e("key", String.valueOf(key));
String format = ytFiles.get(key).getFormat().toString();
String url = ytFiles.get(key).getUrl();
Log.e("url",url);
}
you can get key by method keyat and you have to pass the index then it will return key at that particular index. this loop will get all the key
Node.js uses the environmental variable NODE_PATH
to allow for specifying additional directories to include in the module search path. You can use npm
itself to tell you where global modules are stored with the npm root -g
command. So putting those two together, you can make sure global modules are included in your search path with the following command (on Linux-ish)
export NODE_PATH=$(npm root --quiet -g)
HTML already has a built-in horizontal divider called <hr/>
(short for "horizontal rule"). Bootstrap styles it like this:
hr {
margin-top: 1rem;
margin-bottom: 1rem;
border: 0;
border-top: 1px solid rgba(0, 0, 0, 0.1);
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />_x000D_
<p>_x000D_
Some text_x000D_
<hr/>_x000D_
More text_x000D_
</p>
_x000D_
private static T[] prepareArray<T>(T[] arrayToCopy, T value)
{
Array.Copy(arrayToCopy, 1, arrayToCopy, 0, arrayToCopy.Length - 1);
arrayToCopy[arrayToCopy.Length - 1] = value;
return (T[])arrayToCopy;
}
I was performing this throughout my code and wanted a way to put it into a method. I wanted to share this here because I didn't have to use the Convert.ChangeType for my return value. This may not be a best practice but it worked for me. This method takes in an array of generic type and a value to add to the end of the array. The array is then copied with the first value stripped and the value taken into the method is added to the end of the array. The last thing is that I return the generic array.
Under Apache, the limit is a configurable value, LimitRequestLine
. Change this value to something larger than its default of 8190 if you want to support a longer request URI. The value is in /etc/apache2/apache2.conf. If not, add a new line (LimitRequestLine 10000
) under AccessFileName .htaccess
.
However, note that if you're actually running into this limit, you are probably abusing GET
to begin with. You should use POST
to transmit this sort of data -- especially since you even concede that you're using it to update values. If you check the link above, you'll notice that Apache even says "Under normal conditions, the value should not be changed from the default."
I have got a much simpler answer to your question, run the following two commands
sudo docker run -t -d ubuntu --name mycontainername /bin/bash
sudo docker ps -a
the above ps -a command returns a list of all containers. Take the name of the container which references the image name - 'ubuntu' . docker auto generates names for the containers for example - 'lightlyxuyzx'
, that's if you don't use the --name option.
The -t and -d options are important, the created container is detached and can be reattached as given below with the -t option.
With --name option, you can name your container in my case 'mycontainername'.
sudo docker exec -ti mycontainername bash
and this above command helps you login to the container with bash shell. From this point on any changes you make in the container is automatically saved by docker.
For example - apt-get install curl
inside the container
You can exit the container without any issues, docker auto saves the changes.
On the next usage, All you have to do is, run these two commands every time you want to work with this container.
This Below command will start the stopped container:
sudo docker start mycontainername
sudo docker exec -ti mycontainername bash
Another example with ports and a shared space given below:
docker run -t -d --name mycontainername -p 5000:5000 -v ~/PROJECTS/SPACE:/PROJECTSPACE 7efe2989e877 /bin/bash
In my case: 7efe2989e877 - is the imageid of a previous container running which I obtained using
docker ps -a
Composition is where something is made up of distinct parts and it has a strong relationship with those parts. If the main part dies so do the others, they cannot have a life of their own. A rough example is the human body. Take out the heart and all the other parts die away.
Inheritance is where you just take something that already exists and use it. There is no strong relationship. A person could inherit his fathers estate but he can do without it.
I don't know Java so I cannot provide an example but I can provide an explanation of the concepts.
You can go from String (hex)
to byte array
to String as UTF-8(?)
. Make sure your hex string does not have leading spaces and stuff.
public static byte[] hexStringToByteArray(String hex) {
int l = hex.length();
byte[] data = new byte[l / 2];
for (int i = 0; i < l; i += 2) {
data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
+ Character.digit(hex.charAt(i + 1), 16));
}
return data;
}
Usage:
String b = "0xfd00000aa8660b5b010006acdc0100000101000100010000";
byte[] bytes = hexStringToByteArray(b);
String st = new String(bytes, StandardCharsets.UTF_8);
System.out.println(st);
You can get this error in the context of, e.g. a Travis build that, by default, checks code out with git clone --depth=50 --branch=master
. To the best of my knowledge, you can control --depth
via .travis.yml
but not the --branch
. Since that results in only a single branch being tracked by the remote, you need to independently update the remote to track the desired remote's refs.
Before:
$ git branch -a
* master
remotes/origin/HEAD -> origin/master
remotes/origin/master
The fix:
$ git remote set-branches --add origin branch-1
$ git remote set-branches --add origin branch-2
$ git fetch
After:
$ git branch -a
* master
remotes/origin/HEAD -> origin/master
remotes/origin/branch-1
remotes/origin/branch-2
remotes/origin/master
Many people have answered this correctly but here is another way which actually not only covers 1-99 but it actually goes above any data range but it does not cover decimals.
Note: this was tested using python 3.7
def convert(num):
units = ("", "one ", "two ", "three ", "four ","five ", "six ", "seven ","eight ", "nine ", "ten ", "eleven ", "twelve ", "thirteen ", "fourteen ", "fifteen ","sixteen ", "seventeen ", "eighteen ", "nineteen ")
tens =("", "", "twenty ", "thirty ", "forty ", "fifty ","sixty ","seventy ","eighty ","ninety ")
if num < 0:
return "minus "+convert(-num)
if num<20:
return units[num]
if num<100:
return tens[num // 10] +units[int(num % 10)]
if num<1000:
return units[num // 100] +"hundred " +convert(int(num % 100))
if num<1000000:
return convert(num // 1000) + "thousand " + convert(int(num % 1000))
if num < 1000000000:
return convert(num // 1000000) + "million " + convert(int(num % 1000000))
return convert(num // 1000000000)+ "billion "+ convert(int(num % 1000000000))
print(convert(100001333))
Here are a couple dplyr
options:
library(dplyr)
# all columns:
df %>%
mutate_all(~na_if(., ''))
# specific column types:
df %>%
mutate_if(is.factor, ~na_if(., ''))
# specific columns:
df %>%
mutate_at(vars(A, B), ~na_if(., ''))
# or:
df %>%
mutate(A = replace(A, A == '', NA))
# replace can be used if you want something other than NA:
df %>%
mutate(A = as.character(A)) %>%
mutate(A = replace(A, A == '', 'used to be empty'))
For me it was a windows firewall issue. Allow incoming connections. Opening port didn't work but allow programs did.
try this:
//a[contains(@prop,'foo')]
that should work for any "a" tags in the document
To prepare the configration for WCF is hard, and sometimes a service type definition go unnoticed.
I wrote only the namespace in the service tag, so I got the same error.
<service name="ServiceNameSpace">
Do not forget, the service tag needs a fully-qualified service class name.
<service name="ServiceNameSpace.ServiceClass">
For the other folks who are like me.
Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.
You can use git add -i
to get an interactive version of git add
, although that's not exactly what you're after. The simplest thing to do is, after having git add
ed, use git status
to see what is staged or not.
Using git add .
isn't really recommended unless it's your first commit. It's usually better to explicitly list the files you want staged, so that you don't start tracking unwanted files accidentally (temp files and such).
This error is basically saying that maven couldn't read a certain dependency from local repository. It might happend because a jar file didn't get downloaded correctly. So, go to your maven local repository and make sure there isn't any .lastUpdated extension file.