I used a gradient based method in the program below. Added the resulting images. Please note that I'm using a scaled down version of the image for processing.
c++ version
The MIT License (MIT)
Copyright (c) 2014 Dhanushka Dangampola
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
#include "stdafx.h"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
using namespace cv;
using namespace std;
#define INPUT_FILE "1.jpg"
#define OUTPUT_FOLDER_PATH string("")
int _tmain(int argc, _TCHAR* argv[])
{
Mat large = imread(INPUT_FILE);
Mat rgb;
// downsample and use it for processing
pyrDown(large, rgb);
Mat small;
cvtColor(rgb, small, CV_BGR2GRAY);
// morphological gradient
Mat grad;
Mat morphKernel = getStructuringElement(MORPH_ELLIPSE, Size(3, 3));
morphologyEx(small, grad, MORPH_GRADIENT, morphKernel);
// binarize
Mat bw;
threshold(grad, bw, 0.0, 255.0, THRESH_BINARY | THRESH_OTSU);
// connect horizontally oriented regions
Mat connected;
morphKernel = getStructuringElement(MORPH_RECT, Size(9, 1));
morphologyEx(bw, connected, MORPH_CLOSE, morphKernel);
// find contours
Mat mask = Mat::zeros(bw.size(), CV_8UC1);
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
findContours(connected, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
// filter contours
for(int idx = 0; idx >= 0; idx = hierarchy[idx][0])
{
Rect rect = boundingRect(contours[idx]);
Mat maskROI(mask, rect);
maskROI = Scalar(0, 0, 0);
// fill the contour
drawContours(mask, contours, idx, Scalar(255, 255, 255), CV_FILLED);
// ratio of non-zero pixels in the filled region
double r = (double)countNonZero(maskROI)/(rect.width*rect.height);
if (r > .45 /* assume at least 45% of the area is filled if it contains text */
&&
(rect.height > 8 && rect.width > 8) /* constraints on region size */
/* these two conditions alone are not very robust. better to use something
like the number of significant peaks in a horizontal projection as a third condition */
)
{
rectangle(rgb, rect, Scalar(0, 255, 0), 2);
}
}
imwrite(OUTPUT_FOLDER_PATH + string("rgb.jpg"), rgb);
return 0;
}
python version
The MIT License (MIT)
Copyright (c) 2017 Dhanushka Dangampola
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
import cv2
import numpy as np
large = cv2.imread('1.jpg')
rgb = cv2.pyrDown(large)
small = cv2.cvtColor(rgb, cv2.COLOR_BGR2GRAY)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
grad = cv2.morphologyEx(small, cv2.MORPH_GRADIENT, kernel)
_, bw = cv2.threshold(grad, 0.0, 255.0, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 1))
connected = cv2.morphologyEx(bw, cv2.MORPH_CLOSE, kernel)
# using RETR_EXTERNAL instead of RETR_CCOMP
contours, hierarchy = cv2.findContours(connected.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
#For opencv 3+ comment the previous line and uncomment the following line
#_, contours, hierarchy = cv2.findContours(connected.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
mask = np.zeros(bw.shape, dtype=np.uint8)
for idx in range(len(contours)):
x, y, w, h = cv2.boundingRect(contours[idx])
mask[y:y+h, x:x+w] = 0
cv2.drawContours(mask, contours, idx, (255, 255, 255), -1)
r = float(cv2.countNonZero(mask[y:y+h, x:x+w])) / (w * h)
if r > 0.45 and w > 8 and h > 8:
cv2.rectangle(rgb, (x, y), (x+w-1, y+h-1), (0, 255, 0), 2)
cv2.imshow('rects', rgb)
Alternatively, cv2.merge()
can be used to turn a single channel binary mask layer into a three channel color image by merging the same layer together as the blue, green, and red layers of the new image. We pass in a list of the three color channel layers - all the same in this case - and the function returns a single image with those color channels. This effectively transforms a grayscale image of shape (height, width, 1)
into (height, width, 3)
To address your problem
I did some thresholding on an image and want to label the contours in green, but they aren't showing up in green because my image is in black and white.
This is because you're trying to display three channels on a single channel image. To fix this, you can simply merge the three single channels
image = cv2.imread('image.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray_three = cv2.merge([gray,gray,gray])
Example
We create a color image with dimensions (200,200,3)
image = (np.random.standard_normal([200,200,3]) * 255).astype(np.uint8)
Next we convert it to grayscale and create another image using cv2.merge()
with three gray channels
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray_three = cv2.merge([gray,gray,gray])
We now draw a filled contour onto the single channel grayscale image (left) with shape (200,200,1)
and the three channel grayscale image with shape (200,200,3)
(right). The left image showcases the problem you're experiencing since you're trying to display three channels on a single channel image. After merging the grayscale image into three channels, we can now apply color onto the image
contour = np.array([[10,10], [190, 10], [190, 80], [10, 80]])
cv2.fillPoly(gray, [contour], [36,255,12])
cv2.fillPoly(gray_three, [contour], [36,255,12])
Full code
import cv2
import numpy as np
# Create random color image
image = (np.random.standard_normal([200,200,3]) * 255).astype(np.uint8)
# Convert to grayscale (1 channel)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Merge channels to create color image (3 channels)
gray_three = cv2.merge([gray,gray,gray])
# Fill a contour on both the single channel and three channel image
contour = np.array([[10,10], [190, 10], [190, 80], [10, 80]])
cv2.fillPoly(gray, [contour], [36,255,12])
cv2.fillPoly(gray_three, [contour], [36,255,12])
cv2.imshow('image', image)
cv2.imshow('gray', gray)
cv2.imshow('gray_three', gray_three)
cv2.waitKey()
Using your code with some random data, this would work:
fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)
axs = axs.ravel()
for i in range(10):
axs[i].contourf(np.random.rand(10,10),5,cmap=plt.cm.Oranges)
axs[i].set_title(str(250+i))
The layout is off course a bit messy, but that's because of your current settings (the figsize, wspace etc).
If you have only these regular shapes, there is a simple procedure as follows :
approxPolyDP
function.Below is my example in Python:
import numpy as np
import cv2
img = cv2.imread('shapes.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(gray,127,255,1)
contours,h = cv2.findContours(thresh,1,2)
for cnt in contours:
approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
print len(approx)
if len(approx)==5:
print "pentagon"
cv2.drawContours(img,[cnt],0,255,-1)
elif len(approx)==3:
print "triangle"
cv2.drawContours(img,[cnt],0,(0,255,0),-1)
elif len(approx)==4:
print "square"
cv2.drawContours(img,[cnt],0,(0,0,255),-1)
elif len(approx) == 9:
print "half-circle"
cv2.drawContours(img,[cnt],0,(255,255,0),-1)
elif len(approx) > 15:
print "circle"
cv2.drawContours(img,[cnt],0,(0,255,255),-1)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
Below is the output:
Remember, it works only for regular shapes.
Alternatively to find circles, you can use houghcircles
. You can find a tutorial here.
Regarding iOS, OpenCV devs are developing some iOS samples this summer, So visit their site : www.code.opencv.org and contact them.
You can find slides of their tutorial here : http://code.opencv.org/svn/gsoc2012/ios/trunk/doc/CVPR2012_OpenCV4IOS_Tutorial.pdf
I'm not aware of OpenCV but looking at the problem logically I think you could differentiate between bottle and can by changing the image which you are looking for i.e. Coca Cola. You should incorporate till top portion of can as in case of can there is silver lining at top of coca cola and in case of bottle there will be no such silver lining.
But obviously this algorithm will fail in cases where top of can is hidden, but in such case even human will not be able to differentiate between the two (if only coca cola portion of bottle/can is visible)
Once you have detected the bounding box of the document, you can perform a four-point perspective transform to obtain a top-down birds eye view of the image. This will fix the skew and isolate only the desired object.
Input image:
Detected text object
Top-down view of text document
Code
from imutils.perspective import four_point_transform
import cv2
import numpy
# Load image, grayscale, Gaussian blur, Otsu's threshold
image = cv2.imread("1.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (7,7), 0)
thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
# Find contours and sort for largest contour
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
displayCnt = None
for c in cnts:
# Perform contour approximation
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
if len(approx) == 4:
displayCnt = approx
break
# Obtain birds' eye view of image
warped = four_point_transform(image, displayCnt.reshape(4, 2))
cv2.imshow("thresh", thresh)
cv2.imshow("warped", warped)
cv2.imshow("image", image)
cv2.waitKey()
I think the following code is close to what you want
x <- c(0.1, 0.2, 0.3, 0.4, 0.5)
y <- c(1, 2, 3, 4, 5)
zfun <- function(a,b) {a*b * ( 0.9 + 0.2*runif(a*b) )}
z <- outer(x, y, FUN="zfun")
It gives data like this (note that x
and y
are both increasing)
> x
[1] 0.1 0.2 0.3 0.4 0.5
> y
[1] 1 2 3 4 5
> z
[,1] [,2] [,3] [,4] [,5]
[1,] 0.1037159 0.2123455 0.3244514 0.4106079 0.4777380
[2,] 0.2144338 0.4109414 0.5586709 0.7623481 0.9683732
[3,] 0.3138063 0.6015035 0.8308649 1.2713930 1.5498939
[4,] 0.4023375 0.8500672 1.3052275 1.4541517 1.9398106
[5,] 0.5146506 1.0295172 1.5257186 2.1753611 2.5046223
and a graph like
persp(x, y, z)
Maybe is late now but following Spacedman, did you try duplicate="strip" or any other option?
x=runif(1000)
y=runif(1000)
z=rnorm(1000)
s=interp(x,y,z,duplicate="strip")
surface3d(s$x,s$y,s$z,color="blue")
points3d(s)
Try this:
import matplotlib.pyplot as plt
import seaborn as sns
from mpl_toolkits.mplot3d import axes3d
fig=plt.figure(figsize=(16,12.5))
ax=fig.add_subplot(2,2,1,projection="3d")
a=ax.scatter(Dataframe['bedrooms'],Dataframe['bathrooms'],Dataframe['floors'])
plt.plot(a)
To answer your main question, you want to use the subplot command. I think changing plt.figure(i)
to plt.subplot(4,4,i+1)
should work.
Get yesterday date in javascript
You have to run code and check it output
var today = new Date();_x000D_
var yesterday = new Date(today);_x000D_
_x000D_
yesterday.setDate(today.getDate() - 1);_x000D_
console.log("Original Date : ",yesterday);_x000D_
_x000D_
const monthNames = [_x000D_
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"_x000D_
];_x000D_
var month = today.getMonth() + 1_x000D_
yesterday = yesterday.getDate() + ' ' + monthNames[month] + ' ' + yesterday.getFullYear()_x000D_
_x000D_
console.log("Modify Date : ",yesterday);
_x000D_
Adding the correct doctype declaration and avoiding the XML prolog should be enough to avoid quirks mode.
Php has a super sexy function for this, just pass the array to it:
$json = json_encode($var);
$.ajax({
url:"Example.php",
type:"POST",
dataType : "json",
success:function(msg){
console.info(msg);
}
});
simples :)
I personally use if/else statement in children with this kind of block statement. It only supports on Dart version 2.3.0 above.
if / else
Column(
children: [
if (_selectedIndex == 0) ...[
DayScreen(),
] else ...[
StatsScreen(),
],
],
),
if / else if
Column(
children: [
if (_selectedIndex == 0) ...[
DayScreen(),
] else if(_selectedIndex == 1)...[
StatsScreen(),
],
],
),
If I use exit()
in a code and run it in the shell, it shows a message asking whether I want to kill the program or not. It's really disturbing.
See here
But sys.exit()
is better in this case. It closes the program and doesn't create any dialogue box.
I was facing this error in VS code because I was using VS code git extension. It saves my git credentials on Linux key-ring. While I wanted to git pull from another account which has access to the repository. The most simple solution is to open the Linux shell (not the one integrated in VS code) and then run:
git pull origin master
This time, it will ask you the username and password of Github.
sp_change_users_login
is deprecated.
Much easier is:
ALTER USER usr1 WITH LOGIN = login1;
Even though that this question was already answered I feel that there are missing examples in the answer that was answered.
Therefore I'll bring here what I wrote in a blog post "Android Log Levels"
Verbose
Is the lowest level of logging. If you want to go nuts with logging then you go with this level. I never understood when to use Verbose and when to use Debug. The difference sounded to me very arbitrary. I finally understood it once I was pointed to the source code of Android¹ “Verbose should never be compiled into an application except during development.” Now it is clear to me, whenever you are developing and want to add deletable logs that help you during the development it is useful to have the verbose level this will help you delete all these logs before you go into production.
Debug
Is for debugging purposes. This is the lowest level that should be in production. Information that is here is to help during development. Most times you’ll disable this log in production so that less information will be sent and only enable this log if you have a problem. I like to log in debug all the information that the app sends/receives from the server (take care not to log passwords!!!). This is very helpful to understand if the bug lies in the server or the app. I also make logs of entering and exiting of important functions.
Info
For informational messages that highlight the progress of the application. For example, when initialising of the app is finished. Add info when the user moves between activities and fragments. Log each API call but just little information like the URL , status and the response time.
Warning
When there is a potentially harmful situation.
This log is in my experience a tricky level. When do you have a potential harmful situation? In general or that it is OK or that it is an error. I personally don’t use this level much. Examples of when I use it are usually when stuff happens several times. For example, a user has a wrong password more than 3 times. This could be because he entered the password wrongly 3 times, it could also be because there is a problem with a character that isn’t being accepted in our system. Same goes with network connection problems.
Error
Error events. The application can still continue to run after the error. This can be for example when I get a null pointer where I’m not supposed to get one. There was an error parsing the response of the server. Got an error from the server.
WTF (What a Terrible Failure)
Fatal is for severe error events that will lead the application to exit. In Android the fatal is in reality the Error level, the difference is that it also adds the fullstack.
If copy-dependencies, unpack, pack, etc., are important for your project you shouldn't ignore it. You have to enclose your <plugins>
in <pluginManagement>
tested with Eclipse Indigo SR1, maven 2.2.1
Delete you AVD and create another. Maybe isn't the perfect thing to do, but it's the fastest.
This is vary useful please try it and change as required.
#!/bin/bash
for load in $(seq 1 100); do
echo -ne "$load % downloded ...\r"
sleep 1
done
echo "100"
echo "Loaded ..."
This if for Django 1.10:
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
We can try by using latest jQuery library. I got the same issue. I used jQuery-1.4.2.min before and getting the error. After that I used version 1.9.1 and it works. Thanks
It's undesirable to have to know how to instantiate a widget when you just want to override its placeholder.
q = forms.CharField(label='search')
...
q.widget.attrs['placeholder'] = "Search"
Also check SELINUX (/etc/selinux):
# getenforce
turn it off:
# setenforce 0
Yes, sort of.
You can explicitly size a container using units relative to font-size:
In addition you can use a few CSS properties such as overflow:hidden;
white-space:nowrap;
text-overflow:ellipsis;
to help limit the number as well.
There is no direct equivalent to C-style macros in C#, but inline
d static methods - with or without #if
/#elseif
/#else
pragmas - is the closest you can get:
/// <summary>
/// Prints a message when in debug mode
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void Log(object message) {
#if DEBUG
Console.WriteLine(message);
#endif
}
/// <summary>
/// Prints a formatted message when in debug mode
/// </summary>
/// <param name="format">A composite format string</param>
/// <param name="args">An array of objects to write using format</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void Log(string format, params object[] args) {
#if DEBUG
Console.WriteLine(format, args);
#endif
}
/// <summary>
/// Computes the square of a number
/// </summary>
/// <param name="x">The value</param>
/// <returns>x * x</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static double Square(double x) {
return x * x;
}
/// <summary>
/// Wipes a region of memory
/// </summary>
/// <param name="buffer">The buffer</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void ClearBuffer(ref byte[] buffer) {
ClearBuffer(ref buffer, 0, buffer.Length);
}
/// <summary>
/// Wipes a region of memory
/// </summary>
/// <param name="buffer">The buffer</param>
/// <param name="offset">Start index</param>
/// <param name="length">Number of bytes to clear</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe void ClearBuffer(ref byte[] buffer, int offset, int length) {
fixed(byte* ptrBuffer = &buffer[offset]) {
for(int i = 0; i < length; ++i) {
*(ptrBuffer + i) = 0;
}
}
}
This works perfectly as a macro, but comes with a little drawback: Methods marked as inline
d will be copied to the reflection part of your assembly like any other "normal" method.
Try installing tensorflow in the user site - This installation only works for you.
pip install tensorflow --user
Almost everything is mentioned here. I would like to share one question which I was asked by a senior manager on database. I found the question pretty interesting and if you think about it deeply, it sort of has lot of meaning in it.
Question was - How would you describe database to your 5 year old kid ?
I've worked with Marmalade
and I found it satisfying. Although it's not free and the developer community is also not large enough, but still you can handle most of the task using it's tutorials. (I'll write my tutorials once I got some times too).
IwGame
is a good engine, developed by one of the Marmalade user. It's good for a basic game, but if you are looking for some serious advanced gaming stuff, you can also use Cocos2D-x
with Marmalade. I've never used Cocos2D-x, but there's an Extension on Marmalade's Github
.
Another good thing about Marmalade is it's EDK (Extension Development Kit)
, which lets you make an extension for whatever functionality you need which is available in native code, but not in Marmalade. I've used it to develop my own Customized Admob extension and a Facebook extension too.
Edit:
Marmalade now has it's own RAD(Rapid Application Development) tool just for 2D development, named as Marmalade Quick
. Although the coding will be in Lua not in C++, but since it's built on top of C++ Marmalade, you can easily include a C++ library, and all other EDK extensions. Also the Cocos-2Dx
and Box2D
extensions are preincluded in the Quick. They recently launched it's Release version (It was in beta for 3-4 months). I think we you're really looking for only 2D development, you should give it a try.
Update:
Unity3D recently launched support for 2D games, which seems better than any other 2D game engine, due to it's GUI and Editor. Physics, sprite etc support is inbuilt. You can have a look on it.
Update 2
Marmalade is going to discontinue their SDK in favor of their in-house game production soon. So it won't be a wise decision to rely on that.
Adding onto the comment by ehogue, you should make the size of the keys on both tables match. Rather than
customer_id INT( 4 ) NOT NULL ,
make it
customer_id INT( 10 ) NOT NULL ,
and make sure your int column in the customers table is int(10) also.
It would be better to add a background item into the style of the app actionbar to consistent with the background color of the customized actionbar:
<item name="android:background">@color/actionbar_bgcolor</item>
After android 6.0, the actionbar even has a margin-right space and cannot be set. Add a right margin adjusting in the activity like this: (the view is the customized actionbar or a right button in it)
int rightMargin = Build.VERSION.SDK_INT>=Build.VERSION_CODES.M ? 0 : 8; // may the same with actionbar leftMargin in px
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
p.setMargins(p.leftMargin, p.topMargin, rightMargin, p.bottomMargin);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1){
p.setMarginEnd(rightMargin);
}
view.setLayoutParams(p);
The actionbar machenism is just supported after Android 3.0+ app. If we use a toolbar (of support lib v7) instead, we should layout it in each xml of each activity, and take care of the issue of overlapping with system status bar in the Android 5.0 or later device.
Download and include this plugin
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/md5.js"></script>
and use like
if(CryptoJS.MD5($("#txtOldPassword").val())) != oldPassword) {
}
//Following lines shows md5 value
//var hash = CryptoJS.MD5("Message");
//alert(hash);
This is Atharva's answer from: https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView. Just wanted to add if your document is in an iframe, you can choose an element in the parent frame to scroll into view:
$('#element-in-parent-frame', window.parent.document).get(0).scrollIntoView();
Append this string to your command: >&- 2>&- <&- &. >&- means close stdout. 2>&- means close stderr. <&- means close stdin. & means run in the background. This works to programmatically start a job via ssh, too:
$ ssh myhost 'sleep 30 >&- 2>&- <&- &'
# ssh returns right away, and your sleep job is running remotely
$
Tried to install lxml, grab and other extensions, which requires VS 10.0+ and get the same issue. I find own way to solve this problem(Windows 10 x64, Python 3.4+):
Install Visual C++ 2010 Express (download). (Do not install Microsoft Visual Studio 2010 Service Pack 1 )
Remove all the Microsoft Visual C++ 2010 Redistributable packages from Control Panel\Programs and Features. If you don't do those then the install is going to fail with an obscure "Fatal error during installation" error.
Install offline version of Windows SDK for Visual Studio 2010 (v7.1) (download). This is required for 64bit extensions. Windows has builtin mounting for ISOs. Just mount the ISO and run Setup\SDKSetup.exe instead of setup.exe.
Create a vcvars64.bat file in C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64 that contains:
CALL "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.cmd" /x64
Find extension on this site, then put them into the python folder, and install .whl extension with pip:
python -m pip install extensionname.whl
Enjoy
File file = new File("src/test/resources/validation.txt");
DiskFileItem fileItem = new DiskFileItem("file", "text/plain", false, file.getName(), (int) file.length() , file.getParentFile());
fileItem.getOutputStream();
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
You need the
fileItem.getOutputStream();
because it will throw NPE otherwise.
Just make a new class like this:
public class SortedList<T> extends ArrayList<T> {
private final Comparator<? super T> comparator;
public SortedList() {
super();
this.comparator = null;
}
public SortedList(Comparator<T> comparator) {
super();
this.comparator = comparator;
}
@Override
public boolean add(T item) {
int index = comparator == null ? Collections.binarySearch((List<? extends Comparable<? super T>>)this, item) :
Collections.binarySearch(this, item, comparator);
if (index < 0) {
index = index * -1 - 2;
}
super.add(index+1, item);
return true;
}
@Override
public void add(int index, T item) {
throw new UnsupportedOperationException("'add' with an index is not supported in SortedArrayList");
}
@Override
public boolean addAll(Collection<? extends T> items) {
boolean allAdded = true;
for (T item : items) {
allAdded = allAdded && add(item);
}
return allAdded;
}
@Override
public boolean addAll(int index, Collection<? extends T> items) {
throw new UnsupportedOperationException("'addAll' with an index is not supported in SortedArrayList");
}
}
You can test it like this:
List<Integer> list = new SortedArrayList<>((Integer i1, Integer i2) -> i1.compareTo(i2));
for (Integer i : Arrays.asList(4, 7, 3, 8, 9, 25, 20, 23, 52, 3)) {
list.add(i);
}
System.out.println(list);
In their book The Practice of Programming (which is well worth reading), Kernighan and Pike discuss this problem, and they solve it by using snprintf()
to create the string with the correct buffer size for passing to the scanf()
family of functions. In effect:
int scanner(const char *data, char *buffer, size_t buflen)
{
char format[32];
if (buflen == 0)
return 0;
snprintf(format, sizeof(format), "%%%ds", (int)(buflen-1));
return sscanf(data, format, buffer);
}
Note, this still limits the input to the size provided as 'buffer'. If you need more space, then you have to do memory allocation, or use a non-standard library function that does the memory allocation for you.
Note that the POSIX 2008 (2013) version of the scanf()
family of functions supports a format modifier m
(an assignment-allocation character) for string inputs (%s
, %c
, %[
). Instead of taking a char *
argument, it takes a char **
argument, and it allocates the necessary space for the value it reads:
char *buffer = 0;
if (sscanf(data, "%ms", &buffer) == 1)
{
printf("String is: <<%s>>\n", buffer);
free(buffer);
}
If the sscanf()
function fails to satisfy all the conversion specifications, then all the memory it allocated for %ms
-like conversions is freed before the function returns.
It looks like you are calling a non static member (a property or method, specifically setTextboxText
) from a static method (specifically SumData
). You will need to either:
Make the called member static also:
static void setTextboxText(int result)
{
// Write static logic for setTextboxText.
// This may require a static singleton instance of Form1.
}
Create an instance of Form1
within the calling method:
private static void SumData(object state)
{
int result = 0;
//int[] icount = (int[])state;
int icount = (int)state;
for (int i = icount; i > 0; i--)
{
result += i;
System.Threading.Thread.Sleep(1000);
}
Form1 frm1 = new Form1();
frm1.setTextboxText(result);
}
Passing in an instance of Form1
would be an option also.
Make the calling method a non-static instance method (of Form1
):
private void SumData(object state)
{
int result = 0;
//int[] icount = (int[])state;
int icount = (int)state;
for (int i = icount; i > 0; i--)
{
result += i;
System.Threading.Thread.Sleep(1000);
}
setTextboxText(result);
}
More info about this error can be found on MSDN.
If you are using python3.6 or later you can use f-string to do the conversion:
Binary to decimal:
>>> print(f'{0b1011010:#0}')
90
>>> bin_2_decimal = int(f'{0b1011010:#0}')
>>> bin_2_decimal
90
binary to octal hexa and etc.
>>> f'{0b1011010:#o}'
'0o132' # octal
>>> f'{0b1011010:#x}'
'0x5a' # hexadecimal
>>> f'{0b1011010:#0}'
'90' # decimal
Pay attention to 2 piece of information separated by colon.
In this way, you can convert between {binary, octal, hexadecimal, decimal} to {binary, octal, hexadecimal, decimal} by changing right side of colon[:]
:#b -> converts to binary
:#o -> converts to octal
:#x -> converts to hexadecimal
:#0 -> converts to decimal as above example
Try changing left side of colon to have octal/hexadecimal/decimal.
I got this error because I was using a wrong CSS selector with the Selenium WebDriver Node.js function By.css()
.
You can check if your selector is correct by using it in the web console of your web browser (Ctrl+Shift+K shortcut), with the JavaScript function document.querySelectorAll()
.
I'm using source tree.... You can do revert all uncommitted changes with 2 easy steps:
1) just need to reset the workspace file status
2) select all unstage files (command +a), right click and select remove
It's that simple :D
Unfortunately, it is not possible to "get" the height of an element via CSS because CSS is not a language that returns any sort of data other than rules for the browser to adjust its styling.
Your resolution can be achieved with jQuery, or alternatively, you can fake it with CSS3's transform:translateY();
rule.
If we assume that your target div in this instance is 200px high - this would mean that you want the div to have a margin of 190px?
This can be achieved by using the following CSS:
.dynamic-height {
-webkit-transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
margin-top: -10px;
}
In this instance, it is important to remember that translateY(100%)
will move the element in question downwards by a total of it's own length.
The problem with this route is that it will not push element below it out of the way, where a margin would.
If faking it isn't going to work for you, then your next best bet would be to implement a jQuery script to add the correct CSS for you.
jQuery(document).ready(function($){ //wait for the document to load
$('.dynamic-height').each(function(){ //loop through each element with the .dynamic-height class
$(this).css({
'margin-top' : $(this).outerHeight() - 10 + 'px' //adjust the css rule for margin-top to equal the element height - 10px and add the measurement unit "px" for valid CSS
});
});
});
@JeffersonBe's answer is close, but returns true
if the string is "something containing [email protected] a valid email" which is not what we want. The following is an extension on String that works well (and allows testing for valid phoneNumber and other data detectors to boot.
/// Helper for various data detector matches.
/// Returns `true` iff the `String` matches the data detector type for the complete string.
func matchesDataDetector(type: NSTextCheckingResult.CheckingType, scheme: String? = nil) -> Bool {
let dataDetector = try? NSDataDetector(types: type.rawValue)
guard let firstMatch = dataDetector?.firstMatch(in: self, options: NSRegularExpression.MatchingOptions.reportCompletion, range: NSRange(location: 0, length: length)) else {
return false
}
return firstMatch.range.location != NSNotFound
// make sure the entire string is an email, not just contains an email
&& firstMatch.range.location == 0
&& firstMatch.range.length == length
// make sure the link type matches if link scheme
&& (type != .link || scheme == nil || firstMatch.url?.scheme == scheme)
}
/// `true` iff the `String` is an email address in the proper form.
var isEmail: Bool {
return matchesDataDetector(type: .link, scheme: "mailto")
}
/// `true` iff the `String` is a phone number in the proper form.
var isPhoneNumber: Bool {
return matchesDataDetector(type: .phoneNumber)
}
/// number of characters in the `String` (required for above).
var length: Int {
return self.characters.count
}
Multiple clients can connect to the same port (say 80) on the server because on the server side, after creating a socket and binding (setting local IP and port) listen is called on the socket which tells the OS to accept incoming connections.
When a client tries to connect to server on port 80, the accept call is invoked on the server socket. This creates a new socket for the client trying to connect and similarly new sockets will be created for subsequent clients using same port 80.
Words in italics are system calls.
Ref
try using -U
(aka --update-snapshots
) when you run maven
And make sure the dependency definition is correct
Yes, the first function has no relationship with an object instance of that constructor function, you can consider it like a 'static method'.
In JavaScript functions are first-class objects, that means you can treat them just like any object, in this case, you are only adding a property to the function object.
The second function, as you are extending the constructor function prototype, it will be available to all the object instances created with the new
keyword, and the context within that function (the this
keyword) will refer to the actual object instance where you call it.
Consider this example:
// constructor function
function MyClass () {
var privateVariable; // private member only available within the constructor fn
this.privilegedMethod = function () { // it can access private members
//..
};
}
// A 'static method', it's just like a normal function
// it has no relation with any 'MyClass' object instance
MyClass.staticMethod = function () {};
MyClass.prototype.publicMethod = function () {
// the 'this' keyword refers to the object instance
// you can access only 'privileged' and 'public' members
};
var myObj = new MyClass(); // new object instance
myObj.publicMethod();
MyClass.staticMethod();
Have you considered using the CCR since you are writing to separate files you can do everything in parallel (read and write) and the CCR makes it very easy to do this.
static void Main(string[] args)
{
Dispatcher dp = new Dispatcher();
DispatcherQueue dq = new DispatcherQueue("DQ", dp);
Port<long> offsetPort = new Port<long>();
Arbiter.Activate(dq, Arbiter.Receive<long>(true, offsetPort,
new Handler<long>(Split)));
FileStream fs = File.Open(file_path, FileMode.Open);
long size = fs.Length;
fs.Dispose();
for (long i = 0; i < size; i += split_size)
{
offsetPort.Post(i);
}
}
private static void Split(long offset)
{
FileStream reader = new FileStream(file_path, FileMode.Open,
FileAccess.Read);
reader.Seek(offset, SeekOrigin.Begin);
long toRead = 0;
if (offset + split_size <= reader.Length)
toRead = split_size;
else
toRead = reader.Length - offset;
byte[] buff = new byte[toRead];
reader.Read(buff, 0, (int)toRead);
reader.Dispose();
File.WriteAllBytes("c:\\out" + offset + ".txt", buff);
}
This code posts offsets to a CCR port which causes a Thread to be created to execute the code in the Split method. This causes you to open the file multiple times but gets rid of the need for synchronization. You can make it more memory efficient but you'll have to sacrifice speed.
Try this:
<table width="200" style="margin-left:auto;margin-right:auto">
on Fedora it is currently impossible to set a new jdk-HOME to some sdk. They designed it such that it will always break. Try --jdkhome [whatever] but in all likelihood it will break and show some cryptic nonsensical error message as usual.
If you need to update the value in a particular table:
UPDATE TABLE-NAME SET COLUMN-NAME = REPLACE(TABLE-NAME.COLUMN-NAME, 'STRING-TO-REPLACE', 'REPLACEMENT-STRING');
where
TABLE-NAME - The name of the table being updated
COLUMN-NAME - The name of the column being updated
STRING-TO-REPLACE - The value to replace
REPLACEMENT-STRING - The replacement
When render_template() function is used it tries to search for template in the folder called templates and it throws error jinja2.exceptions.TemplateNotFound when :
To solve the problem :
Remapped to in my .vimrc.local file, quick and dirty but very functional:
" Clear last search highlighting
map <Space> :noh<cr>
The following script works for me for multiple values of $COLUMNS
. I wonder if you are not setting COLUMNS
prior to this call?
#!/bin/bash
COLUMNS=30
svn diff $@ --diff-cmd /usr/bin/diff -x "-y -w -p -W $COLUMNS"
Can you echo $COLUMNS
inside your script to see if it set correctly?
Depending on the version you are running. It is basically the same just go to
File -> Invalidate caches, then restart Intellij
or
File -> Invalidate caches / Restart
The main difference is that in older versions you had to manually restart as cache files are not removed until you restart. The newer versions will ask if you also want to restart.
As seen here on this official Jetbrains help page
You can also try delete caches manually in the system
folder for your installed version. The location of this folder depends on your OS and version installed.
Windows Vista, 7, 8, 10
<SYSTEM DRIVE>\Users\<USER ACCOUNT NAME>\.<PRODUCT><VERSION>
Linux/Unix
~/.<PRODUCT><VERSION>
Mac OS
~/Library/Caches/<PRODUCT><VERSION>
Read this for more details on cache locations.
You can wrap the whole connection in a context manager, like the following:
from contextlib import contextmanager
import pyodbc
import sys
@contextmanager
def open_db_connection(connection_string, commit=False):
connection = pyodbc.connect(connection_string)
cursor = connection.cursor()
try:
yield cursor
except pyodbc.DatabaseError as err:
error, = err.args
sys.stderr.write(error.message)
cursor.execute("ROLLBACK")
raise err
else:
if commit:
cursor.execute("COMMIT")
else:
cursor.execute("ROLLBACK")
finally:
connection.close()
Then do something like this where ever you need a database connection:
with open_db_connection("...") as cursor:
# Your code here
The connection will close when you leave the with block. This will also rollback the transaction if an exception occurs or if you didn't open the block using with open_db_connection("...", commit=True)
.
Use the str.isspace()
method:
Return
True
if there are only whitespace characters in the string and there is at least one character,False
otherwise.A character is whitespace if in the Unicode character database (see unicodedata), either its general category is Zs (“Separator, space”), or its bidirectional class is one of WS, B, or S.
Combine that with a special case for handling the empty string.
Alternatively, you could use str.strip()
and check if the result is empty.
Using the standard mysql.createPool(), connections are lazily created by the pool. If you configure the pool to allow up to 100 connections, but only ever use 5 simultaneously, only 5 connections will be made. However if you configure it for 500 connections and use all 500 they will remain open for the durations of the process, even if they are idle!
This means if your MySQL Server max_connections is 510 your system will only have 10 mySQL connections available until your MySQL Server closes them (depends on what you have set your wait_timeout to) or your application closes! The only way to free them up is to manually close the connections via the pool instance or close the pool.
mysql-connection-pool-manager module was created to fix this issue and automatically scale the number of connections dependant on the load. Inactive connections are closed and idle connection pools are eventually closed if there has not been any activity.
// Load modules
const PoolManager = require('mysql-connection-pool-manager');
// Options
const options = {
...example settings
}
// Initialising the instance
const mySQL = PoolManager(options);
// Accessing mySQL directly
var connection = mySQL.raw.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
// Initialising connection
connection.connect();
// Performing query
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
// Ending connection
connection.end();
Ref: https://www.npmjs.com/package/mysql-connection-pool-manager
This assumes that the column of potential date values is in column A. You could do something like this in an adjacent column:
Make a nested formula that converts the "date" to its numeric value if it's valid, or an error value to zero if it's not.
Then it converts the valid numeric values to 1's and leaves the zeroes as they are.
Then sum the new column to get the total number of valid dates.
=IF(IFERROR(DATEVALUE(A1),0)>0,1,0)
window.load = function(){}
Its fully supported by all browsers, and it will fire an event when all images are fully loaded.
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload
For me echo XYZ_20200824.zip | grep -Eo '[[:digit:]]{4}[[:digit:]]{2}[[:digit:]]{2}'
was working fine but unable to store output of command into variable.
I had same issue I tried eval
but didn't got output.
Here is answer for my problem:
cmd=$(echo XYZ_20200824.zip | grep -Eo '[[:digit:]]{4}[[:digit:]]{2}[[:digit:]]{2}')
echo $cmd
My output is now 20200824
Nevermind.
I had to look at the Lucene documentation. Seems I can use wildcards! :-)
curl http://localhost:9200/my_idx/my_type/_search?q=*Doe*
does the trick!
Short story: links. Make use of something like:
a[href='red'] {
color: red;
pointer-events: none;
cursor: default;
text-decoration: none;
}
_x000D_
<a href="red">Look, ma! Red!</a>
_x000D_
(HTML above for demonstration purposes)
And in your md source:
[Look, ma! Red!](red)
UPDATE:
compile 'com.android.volley:volley:1.0.0'
OLD ANSWER: You need the next in your build.gradle of your app module:
dependencies {
compile 'com.mcxiaoke.volley:library:1.0.19'
(Rest of your dependencies)
}
This is not the official repo but is a highly trusted one.
Yep, that's definitely possible. The v$sql views contain that info. Something like this piece of code should point you in the right direction. I haven't tried that specific piece of code myself - nowhere near an Oracle DB right now.
[Edit] Damn two other answers already. Must type faster next time ;-)
When you declare:
new Vue({
el: '#app',
data () {
return {}
}
)}
That is typically your root Vue instance that the rest of the application descends from. This hangs off the root element declared in an html document, for example:
<html>
...
<body>
<div id="app"></div>
</body>
</html>
The other syntax is declaring a component which can be registered and reused later. For example, if you create a single file component like:
// my-component.js
export default {
name: 'my-component',
data () {
return {}
}
}
You can later import this and use it like:
// another-component.js
<template>
<my-component></my-component>
</template>
<script>
import myComponent from 'my-component'
export default {
components: {
myComponent
}
data () {
return {}
}
...
}
</script>
Also, be sure to declare your data
properties as functions, otherwise they are not going to be reactive.
Here is a more complete example of an XML filter (the example above by itself will not work since it just shows a snippet and is missing the <FindBugsFilter>
begin and end tags):
<FindBugsFilter>
<Match>
<Class name="com.mycompany.foo" />
<Method name="bar" />
<Bug pattern="NP_BOOLEAN_RETURN_NULL" />
</Match>
</FindBugsFilter>
If you are using the Android Studio FindBugs plugin, browse to your XML filter file using File->Other Settings->Default Settings->Other Settings->FindBugs-IDEA->Filter->Exclude filter files->Add.
The new default toArray
method in Collection
interface allows the elements of the collection to be transferred to a newly created array of the desired runtime type. It takes IntFunction<T[]> generator
as argument and can be used as:
String[] array = set.toArray(String[]::new);
There is already a similar method Collection.toArray(T[])
and this addition means we no longer be able to pass null
as argument because in that case reference to the method would be ambiguous. But it is still okay since both methods throw a NPE anyways.
In Java 8 we can use streams API:
String[] array = set.stream().toArray(String[]::new);
We can also make use of the overloaded version of toArray() which takes IntFunction<A[]> generator
as:
String[] array = set.stream().toArray(n -> new String[n]);
The purpose of the generator function here is to take an integer (size of desired array) and produce an array of desired size. I personally prefer the former approach using method reference than the later one using lambda expression.
Check out this Unicode code converter. For example, enter 0x2009
, where 2009 is the Unicode number for thin space, in the "0x... notation" field, and click Convert. The hexadecimal number E2 80 89
(3 bytes) appears in the "UTF-8 code units" field.
You can use
long startTime = date.getTime() * 1000000;;
long estimatedTime = System.nanoTime() - startTime;
To get time in nano.
Either remove one } from end of responseText;}}
or from the end of the line
What has worked for me (may be a newer feature of Maven) is merely doing wildcards in the exclusion element.
I have a multi-module project that contains an "app" module that is referenced in two WAR-packaged modules. One of those WAR-packaged modules really only needs the domain classes (and I haven't separated them out of the app module yet). I found this to work:
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>app</artifactId>
<version>${project.version}</version>
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
The wildcard on both groupId and artifactId exclude all dependencies that normally would propagate through to the module using this dependency.
At least for me, there was an easy answer (after much digging around) to changing a tab title at runtime:
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.getTabAt(MyTabPos).setText("My New Text");
You can make a function to do it:
drop function if exists getIdade;
delimiter |
create function getIdade( data_nascimento datetime )
returns int
begin
declare idade int;
declare ano_atual int;
declare mes_atual int;
declare dia_atual int;
declare ano int;
declare mes int;
declare dia int;
set ano_atual = year(curdate());
set mes_atual = month( curdate());
set dia_atual = day( curdate());
set ano = year( data_nascimento );
set mes = month( data_nascimento );
set dia = day( data_nascimento );
set idade = ano_atual - ano;
if( mes > mes_atual ) then
set idade = idade - 1;
end if;
if( mes = mes_atual and dia > dia_atual ) then
set idade = idade - 1;
end if;
return idade;
end|
delimiter ;
Now, you can get the age from a date:
select getIdade('1983-09-16');
If you date is in format Y-m-d H:i:s, you can do this:
select getIdade(substring_index('1983-09-16 23:43:01', ' ', 1));
You can reuse this function anywhere ;)
I am assuming that you are wanting to add items to a ComboBox on an Windows form. Although Klaus is on the right track I believe that the ListItem class is a member of the System.Web.UI.WebControls namespace. So you shouldn't be using it in a Windows forms solution. You can, however, create your own class that you can use in its place. Create a simple class called MyListItem (or whatever name you choose) like this:
Public Class MyListItem
Private mText As String
Private mValue As String
Public Sub New(ByVal pText As String, ByVal pValue As String)
mText = pText
mValue = pValue
End Sub
Public ReadOnly Property Text() As String
Get
Return mText
End Get
End Property
Public ReadOnly Property Value() As String
Get
Return mValue
End Get
End Property
Public Overrides Function ToString() As String
Return mText
End Function
End Class
Now when you want to add the items to your ComboBox you can do it like this:
myComboBox.Items.Add(New MyListItem("Text to be displayed", "value of the item"))
Now when you want to retrieve the value of the selected item from your ComboBox you can do it like this:
Dim oItem As MyListItem = CType(myComboBox.SelectedItem, MyListItem)
MessageBox.Show("The Value of the Item selected is: " & oItem.Value)
One of the keys here is overriding the ToString method in the class. This is where the ComboBox gets the text that is displayed.
Matt made an excellent point, in his comment below, about using Generics to make this even more flexible. So I wondered what that would look like.
Here's the new and improved GenericListItem
class:
Public Class GenericListItem(Of T)
Private mText As String
Private mValue As T
Public Sub New(ByVal pText As String, ByVal pValue As T)
mText = pText
mValue = pValue
End Sub
Public ReadOnly Property Text() As String
Get
Return mText
End Get
End Property
Public ReadOnly Property Value() As T
Get
Return mValue
End Get
End Property
Public Overrides Function ToString() As String
Return mText
End Function
End Class
And here is how you would now add Generic items to your ComboBox. In this case an Integer:
Me.myComboBox.Items.Add(New GenericListItem(Of Integer)("Text to be displayed", 1))
And now the retrieval of the item:
Dim oItem As GenericListItem(Of Integer) = CType(Me.myComboBox.SelectedItem, GenericListItem(Of Integer))
MessageBox.Show("The value of the Item selected is: " & oItem.Value.ToString())
Keep in mind that the type Integer
can be any type of object or value type. If you want it to be an object from one of your own custom classes that's fine. Basically anything goes with this approach.
Months in Java Calendar are 0-indexed. Calendar.JANUARY
isn't a field so you shouldn't be passing it in to the get
method.
Compact solution (provided you don't need other environment variables):
call('sqsub -np {} /homedir/anotherdir/executable'.format(var1).split(),
env=dict(LD_LIBRARY_PATH=my_path))
Using the env command line tool:
call('env LD_LIBRARY_PATH=my_path sqsub -np {} /homedir/anotherdir/executable'.format(var1).split())
Instead of initializing the variables with arbitrary values (for example int smallest = 9999, largest = 0
) it is safer to initialize the variables with the largest and smallest values representable by that number type (that is int smallest = Integer.MAX_VALUE, largest = Integer.MIN_VALUE
).
Since your integer array cannot contain a value larger than Integer.MAX_VALUE
and smaller than Integer.MIN_VALUE
your code works across all edge cases.
File.ReadLines()
returns an object of type System.Collections.Generic.IEnumerable<String>
File.ReadAllLines()
returns an array of strings.
If you want to use an array of strings you need to call the correct function.
You could use Jim solution, just use ReadAllLines()
or you could change your return type.
This would also work:
System.Collections.Generic.IEnumerable<String> lines = File.ReadLines("c:\\file.txt");
You can use any generic collection which implements IEnumerable. IList for an example.
Copies a whole directory to a new location preserving the file dates. This method copies the specified directory and all its child directories and files to the specified destination. The destination is the new location and name of the directory.
The destination directory is created if it does not exist. If the destination directory did exist, then this method merges the source with the destination, with the source taking precedence.
To do so, here's the example code
String source = "C:/your/source";
File srcDir = new File(source);
String destination = "C:/your/destination";
File destDir = new File(destination);
try {
FileUtils.copyDirectory(srcDir, destDir);
} catch (IOException e) {
e.printStackTrace();
}
I found a solution of my own. I know that Andras answer is probably the most consistent with MSTEST, but I didn't feel like refactoring my code.
[TestMethod]
public void OneIsOne()
{
using (ConsoleRedirector cr = new ConsoleRedirector())
{
Assert.IsFalse(cr.ToString().Contains("New text"));
/* call some method that writes "New text" to stdout */
Assert.IsTrue(cr.ToString().Contains("New text"));
}
}
The disposable ConsoleRedirector
is defined as:
internal class ConsoleRedirector : IDisposable
{
private StringWriter _consoleOutput = new StringWriter();
private TextWriter _originalConsoleOutput;
public ConsoleRedirector()
{
this._originalConsoleOutput = Console.Out;
Console.SetOut(_consoleOutput);
}
public void Dispose()
{
Console.SetOut(_originalConsoleOutput);
Console.Write(this.ToString());
this._consoleOutput.Dispose();
}
public override string ToString()
{
return this._consoleOutput.ToString();
}
}
Normally constructors involve initializing the members of an object being created. In concept of inheritance, typically each class constructor in the inheritance hierarchy, is responsible for instantiating its own member variables. This makes sense because instantiation has to be done where the variables are defined.
Since an abstract class is not completely abstract (unlike interfaces), it is mix of both abstract and concrete members, and the members which are not abstract are needed to be initialized, which is done in abstract class's constructors, it is necessary to have constructors in the abstract class. Off course the abstract class's constructors can only be called from the constructors of derived class.
.nav a {
transition: color .2s, text-shadow .2s;
}
There could be another way to achieve what you want. Basically,
Then tar with the -T option which allows it to take a list of file locations (the one you just created with find!)
find . -name "*.whatever" > yourListOfFiles
tar -cvf yourfile.tar -T yourListOfFiles
“Gists are actually Git repositories, which means that you can fork or clone any gist, even if you aren't the original author. You can also view a gist's full commit history, including diffs.”
? check out the official github documentation
So the key difference is, that they are single files.
Oh, and: gists can be “secret” (as in: private url) also without being a paying github customer, if I understand correctly...
It sounds like you may want to use something like SimpleDateFormat. http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html
You declare your date format and then call the parse method with your string.
private static final DateFormat DF = new SimpleDateFormat(...);
Date myDate = DF.parse("1234");
And as Guillaume says, set the timezone!
Your applets will run.
If they are still not running then you have to add that website name in exception site list of Security tab of Java in Control panel.
Right Click on the server tab, go for NEW-> Server. then choose recent version of tomcat server. Click on next, and then give path for your tomcat server.(You can download tomcat server from this link https://tomcat.apache.org/download-80.cgi#8.5.32). Click on finish.
You can start your server now..!!
td {
overflow: hidden;
max-width: 400px;
word-wrap: break-word;
}
jQuery implements this quite elegantly. If you look at the source for jQuery's offset
, you'll find this is basically how it's implemented:
var rect = elem.getBoundingClientRect();
var win = elem.ownerDocument.defaultView;
return {
top: rect.top + win.pageYOffset,
left: rect.left + win.pageXOffset
};
Best practice of getting length is use length
filter returns the number of items of a sequence or mapping, or the length of a string. For example: {{ notcount | length }}
But you can calculate count of elements in for
loop. For example:
{% set count = 0 %}
{% for nc in notcount %}
{% set count = count + 1 %}
{% endfor %}
{{ count }}
This solution helps if you want to calculate count of elements by condition, for example you have a property name
inside object and you want to calculate count of objects with not empty names:
{% set countNotEmpty = 0 %}
{% for nc in notcount if nc.name %}
{% set countNotEmpty = countNotEmpty + 1 %}
{% endfor %}
{{ countNotEmpty }}
Useful links:
This are the steps :
I haven't tried for eclipse but it might work for that also.
You did not do anything wrong here, it will any other thing that is overriding the image size.
You can check this working fiddle.
And in this fiddle I have alter the image size using %
, and it is working.
Also try using this code:
<img src="image.jpg" style="width: 50%; height: 50%"/>?
Here is the example fiddle.
I understand that you want the Widget2 sharing the bottom border with the contents div. Try adding
style="position: relative; bottom: 0px"
to your Widget2 tag. Also try:
style="position: absolute; bottom: 0px"
if you want to snap your widget to the bottom of the screen.
I am a little rusty with CSS, perhaps the correct style is "margin-bottom: 0px" instead "bottom: 0px", give it a try. Also the pull-right class seems to add a "float=right" style to the element, and I am not sure how this behaves with "position: relative" and "position: absolute", I would remove it.
The simplest that helped me:
rm -rf _dir_in_question_
svn up
If you have changes in the problematic dir, then this is not a good solution for you.
Hibernate Optional findTopByClientIdAndStatusOrderByCreateTimeDesc(Integer clientId, Integer status);
"findTop"!! The only one result!
May be this can help, it's not exactly a background, but you get the simple idea
<style>
div {
float: left;
position: relative;
}
div img {
position: relative;
}
div div {
position: absolute;
top:0;
left:0;
}
</style>
<div>
<img src="http://www.planwallpaper.com/static/images/recycled_texture_background_by_sandeep_m-d6aeau9_PZ9chud.jpg" />
<div>Hello</div>
</div>
Updated based on Muhammad's answer...
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log(headers()['Content-Range']);
})
.error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Simply put, the equals-method in Object check for reference equality, where as two instances of your class could still be semantically equal when the properties are equal. This is for instance important when putting your objects into a container that utilizes equals and hashcode, like HashMap and Set. Let's say we have a class like:
public class Foo {
String id;
String whatevs;
Foo(String id, String whatevs) {
this.id = id;
this.whatevs = whatevs;
}
}
We create two instances with the same id:
Foo a = new Foo("id", "something");
Foo b = new Foo("id", "something else");
Without overriding equals we are getting:
Correct? Well maybe, if this is what you want. But let's say we want objects with the same id to be the same object, regardless if it's two different instances. We override the equals (and hashcode):
public class Foo {
String id;
String whatevs;
Foo(String id, String whatevs) {
this.id = id;
this.whatevs = whatevs;
}
@Override
public boolean equals(Object other) {
if (other instanceof Foo) {
return ((Foo)other).id.equals(this.id);
}
}
@Override
public int hashCode() {
return this.id.hashCode();
}
}
As for implementing equals and hashcode I can recommend using Guava's helper methods
I think you might be able to use the ExpandProperty
parameter of Select-Object
.
For example, to get the list of the current directory and just have the Name property displayed, one would do the following:
ls | select -Property Name
This is still returning DirectoryInfo or FileInfo objects. You can always inspect the type coming through the pipeline by piping to Get-Member (alias gm
).
ls | select -Property Name | gm
So, to expand the object to be that of the type of property you're looking at, you can do the following:
ls | select -ExpandProperty Name
In your case, you can just do the following to have a variable be an array of strings, where the strings are the Name property:
$objects = ls | select -ExpandProperty Name
For Xcode 4.1 you can simply add /Developer/usr/bin to the PATH environment variable. This is easily done:
$ export PATH=$PATH:/Developer/usr/bin
Also be certain to update your ~/.bashrc (or ~/.profile or ~/.bash_login) file.
It would appear as though this event has some clipboardData
property attached to it (it may be nested within the originalEvent
property). The clipboardData
contains an array of items and each one of those items has a getAsString()
function that you can call. This returns the string representation of what is in the item.
Those items also have a getAsFile()
function, as well as some others which are browser specific (e.g. in webkit browsers, there is a webkitGetAsEntry()
function).
For my purposes, I needed the string value of what is being pasted. So, I did something similar to this:
$(element).bind("paste", function (e) {
e.originalEvent.clipboardData.items[0].getAsString(function (pStringRepresentation) {
debugger;
// pStringRepresentation now contains the string representation of what was pasted.
// This does not include HTML or any markup. Essentially jQuery's $(element).text()
// function result.
});
});
You'll want to perform an iteration through the items, keeping a string concatenation result.
The fact that there is an array of items makes me think more work will need to be done, analyzing each item. You'll also want to do some null/value checks.
A foreign key with a cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted. This is called a cascade delete.
You are saying in a opposite way, this is not that when you delete from child table then records will be deleted from parent table.
UPDATE 1:
ON DELETE CASCADE option is to specify whether you want rows deleted in a child table when corresponding rows are deleted in the parent table. If you do not specify cascading deletes, the default behaviour of the database server prevents you from deleting data in a table if other tables reference it.
If you specify this option, later when you delete a row in the parent table, the database server also deletes any rows associated with that row (foreign keys) in a child table. The principal advantage to the cascading-deletes feature is that it allows you to reduce the quantity of SQL statements you need to perform delete actions.
So it's all about what will happen when you delete rows from Parent table not from child table.
So in your case when user removes entries from CATs table then rows will be deleted from books table. :)
Hope this helps you :)
->
calls/sets object variables. Ex:
$obj = new StdClass;
$obj->foo = 'bar';
var_dump($obj);
=> Sets key/value pairs for arrays. Ex:
$array = array(
'foo' => 'bar'
);
var_dump($array);
Just add these to libraries to your project:
<link href="https://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.min.css" rel="stylesheet"></link>
<script src="https://code.jquery.com/ui/1.10.2/jquery-ui.min.js"></script>
Save and reload. You're good to go.
Yes, you can run commands on the Ansible host. You can specify that all tasks in a play run on the Ansible host, or you can mark individual tasks to run on the Ansible host.
If you want to run an entire play on the Ansible host, then specify hosts: 127.0.0.1
and connection:local
in the play, for example:
- name: a play that runs entirely on the ansible host
hosts: 127.0.0.1
connection: local
tasks:
- name: check out a git repository
git: repo=git://foosball.example.org/path/to/repo.git dest=/local/path
See Local Playbooks in the Ansible documentation for more details.
If you just want to run a single task on your Ansible host, you can use local_action
to specify that a task should be run locally. For example:
- name: an example playbook
hosts: webservers
tasks:
- ...
- name: check out a git repository
local_action: git repo=git://foosball.example.org/path/to/repo.git dest=/local/path
See Delegation in the Ansible documentation for more details.
Edit: You can avoid having to type connection: local
in your play by adding this to your inventory:
localhost ansible_connection=local
(Here you'd use "localhost" instead of "127.0.0.1" to refer to the play).
Edit: In newer versions of ansible, you no longer need to add the above line to your inventory, ansible assumes it's already there.
Use System.Diagnostics.Process.Start()
method.
Check out this article on how to use it.
Process.Start("notepad", "readme.txt");
string winpath = Environment.GetEnvironmentVariable("windir");
string path = System.IO.Path.GetDirectoryName(
System.Windows.Forms.Application.ExecutablePath);
Process.Start(winpath + @"\Microsoft.NET\Framework\v1.0.3705\Installutil.exe",
path + "\\MyService.exe");
Try below piece of code.
this.dataGridView1.RefreshEdit();
I guess this can help :
selection styles
It's possible to define color and background for text the user selects.
Try it below. If you select something and it looks like this, your browser supports selection styles.
This is the paragraph with
normal ::selection
.This is the paragraph with
::-moz-selection
.This is the paragraph with
::-webkit-selection
.Testsheet:
p.normal::selection { background:#cc0000; color:#fff; } p.moz::-moz-selection { background:#cc0000; color:#fff; } p.webkit::-webkit-selection { background:#cc0000; color:#fff; }
Quoted from Quirksmode
First remove the rows which contain NaN. Then do Integer conversion on remaining rows. At Last insert the removed rows again. Hope it will work
Care must be taken that i
is an integer type of variable. In javaScript we don't specify the datatype during declaration of variables, but our initialisation can guarantee that our variable is of a specific datatype.
It is a good practice to initialize variables of declaration:
var num = 0;
var str = "";
Even if your i
variable is integer, +
operator can perform concatenation instead of addition.
In your problem's case, you have supposed that i = 1
, in order to get 2
in addition with 1
try using (i-1+2)
. Use of ()
-parenthesis will not be necessary.
-
(minus operator) cannot be misunderstood and you will not get unexpected result/s.
some guys who still might have the problem like me (FOR IRANIAN and all the coutries who have sanctions) , this is error can be fixed with proxy
i used this free proxy for android studio 3.2
https://github.com/freedomofdevelopers/fod
just to to Settings (Ctrl + Alt + S)
and search HTTP proxy
then check Manual proxy configuration
then add fodev.org
for host name
and 8118
for Port number
You can use Simple JSON for PHP. It sends the headers help you to forge the JSON.
It looks like :
<?php
// Include the json class
include('includes/json.php');
// Then create the PHP-Json Object to suits your needs
// Set a variable ; var name = {}
$Json = new json('var', 'name');
// Fire a callback ; callback({});
$Json = new json('callback', 'name');
// Just send a raw JSON ; {}
$Json = new json();
// Build data
$object = new stdClass();
$object->test = 'OK';
$arraytest = array('1','2','3');
$jsonOnly = '{"Hello" : "darling"}';
// Add some content
$Json->add('width', '565px');
$Json->add('You are logged IN');
$Json->add('An_Object', $object);
$Json->add("An_Array",$arraytest);
$Json->add("A_Json",$jsonOnly);
// Finally, send the JSON.
$Json->send();
?>
http://joda-time.sourceforge.net/quickstart.html
Each datetime class provides a variety of constructors. These include the Object constructor. This allows you to construct, for example, DateTime from the following objects:
* Date - a JDK instant
* Calendar - a JDK calendar
* String - in ISO8601 format
* Long - in milliseconds
* any Joda-Time datetime class
As of version 2.4 of the Maven Dependency Plugin, you can also define a target destination for the artifact by using the -Ddest flag. It should point to a filename (not a directory) for the destination artifact. See the parameter page for additional parameters that can be used
mvn org.apache.maven.plugins:maven-dependency-plugin:2.4:get \
-DremoteRepositories=http://download.java.net/maven/2 \
-Dartifact=robo-guice:robo-guice:0.4-SNAPSHOT \
-Ddest=c:\temp\robo-guice.jar
The easiest way is to use to_datetime
:
df['col'] = pd.to_datetime(df['col'])
It also offers a dayfirst
argument for European times (but beware this isn't strict).
Here it is in action:
In [11]: pd.to_datetime(pd.Series(['05/23/2005']))
Out[11]:
0 2005-05-23 00:00:00
dtype: datetime64[ns]
You can pass a specific format:
In [12]: pd.to_datetime(pd.Series(['05/23/2005']), format="%m/%d/%Y")
Out[12]:
0 2005-05-23
dtype: datetime64[ns]
We can use $set
operator to update the nested array inside object filed update the value
db.getCollection('geolocations').update(
{
"_id" : ObjectId("5bd3013ac714ea4959f80115"),
"geolocation.country" : "United States of America"
},
{ $set:
{
"geolocation.$.country" : "USA"
}
},
false,
true
);
Also, StringBuffer
is thread-safe, which StringBuilder
is not.
So in a real-time situation when different threads are accessing it, StringBuilder
could have an undeterministic result.
You can use
call script.bat
or just
script.bat
I tried all of the above solutions and it still wouldn't work, until I found that the web.config compilation element was referencing version 2.0.0.0 of WebMatrix.Data and WebMatrix.WebData. Changing the version of those entries in the web.config to 3.0.0.0 helped me.
the above solutions wont work on ipad-2
recently I had an safari browser crash issue while plotting the markers even if there are less number of markers. Initially I was using marker with label (markerwithlabel.js) library for plotting the marker , when i use google native marker it was working fine even with large number of markers but i want customized markers , so i refer the above solution given by jonathan but still the crashing issue is not resolved after doing lot of research i came to know about http://nickjohnson.com/b/google-maps-v3-how-to-quickly-add-many-markers this blog and now my map search is working smoothly on ipad-2 :)
Right now with using Spring-Boot 2.0.4 - { } won't work.
@RequestMapping
still has String[] as a value parameter, so declaration looks like this:
@RequestMapping(value=["/","/index","/login","/home"], method = RequestMethod.GET)
** Update - Works With Spring-Boot 2.2**
@RequestMapping(value={"/","/index","/login","/home"}, method = RequestMethod.GET)
Assuming you're using WinForms, as it was the first thing I did when I was starting C# you need to create an event to close this form.
Lets say you've got a button called myNewButton. If you double click it on WinForms designer you will create an event. After that you just have to use this.Close
private void myNewButton_Click(object sender, EventArgs e) {
this.Close();
}
And that should be it.
The only reason for this not working is that your Event is detached from button. But it should create new event if old one is no longer attached when you double click on the button in WinForms designer.
This seems to work for me.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DropDownList1.DataBind(); // get the data into the list you can set it
DropDownList1.Items.FindByValue("SOMECREDITPROBLEMS").Selected = true;
}
}
I have 2.0 and found the above to help; however, the selecting of a static did not highlight the cell for some reason. I followed these steps:
Now your column headers should repeat on each page.
Hi it is also possible for Strings with XML-Table
SELECT trim(COLUMN_VALUE) str FROM xmltable(('"'||REPLACE('a1, b2, a2, c1', ',', '","')||'"'));
Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application.....
with filename = GetFileName(Range("A1"))
Function GetFileName(rngNamedCell As Range) As String
Dim strSaveDirectory As String: strSaveDirectory = ""
Dim strFileName As String: strFileName = ""
Dim strTestPath As String: strTestPath = ""
Dim strFileBaseName As String: strFileBaseName = ""
Dim strFilePath As String: strFilePath = ""
Dim intFileCounterIndex As Integer: intFileCounterIndex = 1
' Get the users desktop directory.
strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
Debug.Print "Saving to: " & strSaveDirectory
' Base file name
strFileBaseName = Trim(rngNamedCell.Value)
Debug.Print "File Name will contain: " & strFileBaseName
' Loop until we find a free file number
Do
If intFileCounterIndex > 1 Then
' Build test path base on current counter exists.
strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
Else
' Build test path base just on base name to see if it exists.
strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
End If
If (Dir(strTestPath) = "") Then
' This file path does not currently exist. Use that.
strFileName = strTestPath
Else
' Increase the counter as we have not found a free file yet.
intFileCounterIndex = intFileCounterIndex + 1
End If
Loop Until strFileName <> ""
' Found useable filename
Debug.Print "Free file name: " & strFileName
GetFileName = strFileName
End Function
The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.
In Action
My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.
Sub Testing()
Dim filename As String: filename = GetFileName(Range("o1"))
ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
filename:=filename, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub
Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.
The top answer is actually wrong.
The suggested equation:
a - (b * (a \ b))
Will solve to: a - a
Which is of course 0 in all cases.
The correct equation is:
a - (b * INT(a \ b))
Or, if the number (a) can be negative, use this:
a - (b * FIX(a \ b))
If the app minSdkVersion
which you are working is level 9, you can use:
android:foreground="?selectableItemBackground"
android:clickable="true"
Instead, starting from level 11, you use:
android:foreground="?android:attr/selectableItemBackground"
android:clickable="true"
From documentation:
clickable - Defines whether this view reacts to click events. Must be a boolean value, either "true" or "false".
foreground - Defines the drawable to draw over the content. This can be used as an overlay. The foreground drawable participates in the padding of the content if the gravity is set to fill.
<Button Content="Click" Width="200" Height="50">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="LightBlue" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="Border" Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="LightGreen" TargetName="Border" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Button.Style>
Here is what made the error disappear for me:
Close eclipse, open up a terminal window and run:
$ mvn clean eclipse:clean eclipse:eclipse
Are you using Maven? If so,
To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.
And then clean
Edit 1:
If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.
Edit 2:
You can also try going into the folder where you have all your projects and delete the .metadata
for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.
Go to Gradle
file (module app), add below code block
android {
...
lintOptions {
disable 'ContentDescription'
}
...
}
No more warning! happy coding
Nothing is secure when you put it on end-users hand but some common practice may make this harder for attacker to steal data.
webview
protect resource + code on serverMultiple approaches; this is obvious you have to sacrifice among performance and security
Short answer: classmaps are static while PSR autoloading is dynamic.
If you don't want to use classmaps, use PSR autoloading instead.
if your using snap package dotnet-sdk on linux this can resolve by updating your ~.bashrc / etc. as follows:
#!/bin/bash
export DOTNET_ROOT=/snap/dotnet-sdk/current
export MSBuildSDKsPath=$DOTNET_ROOT/sdk/$(${DOTNET_ROOT}/dotnet --version)/Sdks
export PATH="${PATH}:${DOTNET_ROOT}"
export PATH="$PATH:$HOME/.dotnet/tools"
You can also set DirectoryIndex in apache's httpd.conf file.
CentOS keeps this file in /etc/httpd/conf/httpd.conf
Debian: /etc/apache2/apache2.conf
Open the file in your text editor and find the line starting with DirectoryIndex
To load landing.html as a default (but index.html if that's not found) change this line to read:
DirectoryIndex landing.html index.html
When is it ok to use READ UNCOMMITTED
?
Good: Big aggregate reports showing constantly changing totals.
Risky: Nearly everything else.
The good news is that the majority of read-only reports fall in that Good category.
Ok to use it:
That covers probably the majority of what an Business Intelligence department would do in, say, SSRS. The exception of course, is anything with $ signs in front of it. Many people account for money with much more zeal than applied to the related core metrics required to service the customer and generate that money. (I blame accountants).
When risky
Any report that goes down to the detail level. If that detail is required it usually implies that every row will be relevant to a decision. In fact, if you can't pull a small subset without blocking it might be for the good reason that it's being currently edited.
Historical data. It rarely makes a practical difference but whereas users understand constantly changing data can't be perfect, they don't feel the same about static data. Dirty reads won't hurt here but double reads can occasionally be. Seeing as you shouldn't have blocks on static data anyway, why risk it?
Nearly anything that feeds an application which also has write capabilities.
When even the OK scenario is not OK.
NOLOCK
on those tables for anything.If you updated Internet Explorer and began having technical problems, you can use the Compatibility View feature to emulate a previous version of Internet Explorer.
For instructions, see the section below that corresponds with your version. To find your version number, click Help > About Internet Explorer. Internet Explorer 11
To edit the Compatibility View list:
Open the desktop, and then tap or click the Internet Explorer icon on the taskbar.
Tap or click the Tools button (Image), and then tap or click Compatibility View settings.
To remove a website:
Click the website(s) where you would like to turn off Compatibility View, clicking Remove after each one.
To add a website:
Under Add this website, enter the website(s) where you would like to turn on Compatibility View, clicking Add after each one.
i had the same problem and this fixed it. Hope it helps you.
listView.setFocusable(false);
When a module is loaded from a file in Python, __file__
is set to its path. You can then use that with other functions to find the directory that the file is located in.
Taking your examples one at a time:
A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.
B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where the program resides.
C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where the program resides.
You can see the various values returned from these here:
import os
print(__file__)
print(os.path.join(os.path.dirname(__file__), '..'))
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.dirname(__file__)))
and make sure you run it from different locations (such as ./text.py
, ~/python/text.py
and so forth) to see what difference that makes.
I just want to address some confusion first. __file__
is not a wildcard it is an attribute. Double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.
http://docs.python.org/reference/datamodel.html shows many of the special methods and attributes, if not all of them.
In this case __file__
is an attribute of a module (a module object). In Python a .py
file is a module. So import amodule
will have an attribute of __file__
which means different things under difference circumstances.
Taken from the docs:
__file__
is the pathname of the file from which the module was loaded, if it was loaded from a file. The__file__
attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.
In your case the module is accessing it's own __file__
attribute in the global namespace.
To see this in action try:
# file: test.py
print globals()
print __file__
And run:
python test.py
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__':
'test_print__file__.py', '__doc__': None, '__package__': None}
test_print__file__.py
Connects to both Office 365 and Exchange Online in one easy to use script.
REMINDER: You must have the following installed in order to manage Office 365 via PowerShell.
Microsoft Online Services Sign-in Assistant: http://go.microsoft.com/fwlink/?LinkId=286152
Azure AD Module for Windows PowerShell 32 bit - http://go.microsoft.com/fwlink/p/?linkid=236298 64 bit - http://go.microsoft.com/fwlink/p/?linkid=236297
MORE INFORMATION FOUND HERE: http://technet.microsoft.com/en-us/library/hh974317.aspx
(1) SQLite has a built in rowid
pseudo-column so this works:
sqldf("select min(rowid) rowid, id, string
from test
group by id")
giving:
rowid id string
1 1 1 A
2 3 2 B
3 5 3 C
4 7 4 D
5 9 5 E
(2) Also sqldf
itself has a row.names=
argument:
sqldf("select min(cast(row_names as real)) row_names, id, string
from test
group by id", row.names = TRUE)
giving:
id string
1 1 A
3 2 B
5 3 C
7 4 D
9 5 E
(3) A third alternative which mixes the elements of the above two might be even better:
sqldf("select min(rowid) row_names, id, string
from test
group by id", row.names = TRUE)
giving:
id string
1 1 A
3 2 B
5 3 C
7 4 D
9 5 E
Note that all three of these rely on a SQLite extension to SQL where the use of min
or max
is guaranteed to result in the other columns being chosen from the same row. (In other SQL-based databases that may not be guaranteed.)
If you look at the code of %in%
function (x, table) match(x, table, nomatch = 0L) > 0L
then you should be able to write your version of opposite. I use
`%not in%` <- function (x, table) is.na(match(x, table, nomatch=NA_integer_))
Another way is:
function (x, table) match(x, table, nomatch = 0L) == 0L
If you use
ssh [email protected] "~/tools/run_pvt.pl $BUILD_NUMBER"
instead of
ssh [email protected] '~/tools/run_pvt.pl $BUILD_NUMBER'
your shell will interpolate the $BUILD_NUMBER
before sending the command string to the remote host.
In Eclipse, Goto Window-> Show View -> Other -> Android-> Logcat.
Logcat is nothing but a console of your Emulator or Device.
System.out.println
does not work in Android. So you have to handle every thing in Logcat. More Info Look out this Documentation.
Edit 1: System.out.println is working on Logcat. If you use that the Tag will be like System.out and Message will be your message.
There is a free tool from theRightAPI that lets you test any HTTP based API. It also lets you save and share your test scenarios.
No, you can use a StringWriter
to get rid of the intermediate MemoryStream
. However, to force it into XML you need to use a StringWriter
which overrides the Encoding
property:
public class Utf8StringWriter : StringWriter
{
public override Encoding Encoding => Encoding.UTF8;
}
Or if you're not using C# 6 yet:
public class Utf8StringWriter : StringWriter
{
public override Encoding Encoding { get { return Encoding.UTF8; } }
}
Then:
var serializer = new XmlSerializer(typeof(SomeSerializableObject));
string utf8;
using (StringWriter writer = new Utf8StringWriter())
{
serializer.Serialize(writer, entry);
utf8 = writer.ToString();
}
Obviously you can make Utf8StringWriter
into a more general class which accepts any encoding in its constructor - but in my experience UTF-8 is by far the most commonly required "custom" encoding for a StringWriter
:)
Now as Jon Hanna says, this will still be UTF-16 internally, but presumably you're going to pass it to something else at some point, to convert it into binary data... at that point you can use the above string, convert it into UTF-8 bytes, and all will be well - because the XML declaration will specify "utf-8" as the encoding.
EDIT: A short but complete example to show this working:
using System;
using System.Text;
using System.IO;
using System.Xml.Serialization;
public class Test
{
public int X { get; set; }
static void Main()
{
Test t = new Test();
var serializer = new XmlSerializer(typeof(Test));
string utf8;
using (StringWriter writer = new Utf8StringWriter())
{
serializer.Serialize(writer, t);
utf8 = writer.ToString();
}
Console.WriteLine(utf8);
}
public class Utf8StringWriter : StringWriter
{
public override Encoding Encoding => Encoding.UTF8;
}
}
Result:
<?xml version="1.0" encoding="utf-8"?>
<Test xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<X>0</X>
</Test>
Note the declared encoding of "utf-8" which is what we wanted, I believe.
Let say you have 2 columns named first_name and last_name in your users table and you want to retrieve full name. you can achieve with the following code :
class User extends Eloquent {
public function getFullNameAttribute()
{
return $this->first_name.' '.$this->last_name;
}
}
now you can get full name as:
$user = User::find(1);
$user->full_name;
For a single string String.ToCharArray should be used
string str = "One";
var charArray = str.ToCharArray();
For an array of strings
string[] arrayStrings = { "One", "Two", "Three" };
var charArrayList = arrayStrings.Select(str => str.ToCharArray()).ToList();
For a single character from a single string:
string str = "One";
var ch = str[0]; // means 'O'
The tail
program can do this:
ls -lart | tail -n +2
The -n +2
means “start passing through on the second line of output”.
May I suggest Node ORM?
https://github.com/dresende/node-orm2
There's documentation on the Readme, supports MySQL, PostgreSQL and SQLite.
MongoDB is available since version 2.1.x (released in July 2013)
UPDATE: This package is no longer maintained, per the project's README. It instead recommends bookshelf and sequelize
Don't we all sometimes wish there was a
<T>void java.util.Arrays.deepFill(T[]…multiDimensional)
. Problems start with
Object threeByThree[][] = new Object[3][3];
threeByThree[1] = null;
and
threeByThree[2][1] = new int[]{42};
being perfectly legal.
(If only Object twoDim[]final[]
was legal and well defined…)
(Using one of the public methods from below keeps loops from the calling source code.
If you insist on using no loops at all, substitute the loops and the call to Arrays.fill()
(!) using recursion.)
/** Fills matrix {@code m} with {@code value}.
* @return {@code m}'s dimensionality.
* @throws java.lang.ArrayStoreException if the component type
* of a subarray of non-zero length at the bottom level
* doesn't agree with {@code value}'s type. */
public static <T>int deepFill(Object[] m, T value) {
Class<?> components;
if (null == m ||
null == (components = m.getClass().getComponentType()))
return 0;
int dim = 0;
do
dim++;
while (null != (components = components.getComponentType()));
filler((Object[][])m, value, dim);
return dim;
}
/** Fills matrix {@code m} with {@code value}.
* @throws java.lang.ArrayStoreException if the component type
* of a subarray of non-zero length at level {@code dimensions}
* doesn't agree with {@code value}'s type. */
public static <T>void fill(Object[] m, T value, int dimensions) {
if (null != m)
filler(m, value, dimensions);
}
static <T>void filler(Object[] m, T value, int toGo) {
if (--toGo <= 0)
java.util.Arrays.fill(m, value);
else
for (Object[] subArray : (Object[][])m)
if (null != subArray)
filler(subArray, value, toGo);
}
HTML:
First, we will need to add a class to your text container so that we can access and style it accordingly.
<div class="col-xs-5 textContainer">
<h3 class="text-left">Link up with other gamers all over the world who share the same tastes in games.</h3>
</div>
CSS:
Next, we will apply the following styles to align it vertically, according to the size of the image div next to it.
.textContainer {
height: 345px;
line-height: 340px;
}
.textContainer h3 {
vertical-align: middle;
display: inline-block;
}
All Done! Adjust the line-height and height on the styles above if you believe that it is still slightly out of align.
Never parallelize an infinite stream with a limit. Here is what happens:
public static void main(String[] args) {
// let's count to 1 in parallel
System.out.println(
IntStream.iterate(0, i -> i + 1)
.parallel()
.skip(1)
.findFirst()
.getAsInt());
}
Result
Exception in thread "main" java.lang.OutOfMemoryError
at ...
at java.base/java.util.stream.IntPipeline.findFirst(IntPipeline.java:528)
at InfiniteTest.main(InfiniteTest.java:24)
Caused by: java.lang.OutOfMemoryError: Java heap space
at java.base/java.util.stream.SpinedBuffer$OfInt.newArray(SpinedBuffer.java:750)
at ...
Same if you use .limit(...)
Explanation here: Java 8, using .parallel in a stream causes OOM error
Similarly, don't use parallel if the stream is ordered and has much more elements than you want to process, e.g.
public static void main(String[] args) {
// let's count to 1 in parallel
System.out.println(
IntStream.range(1, 1000_000_000)
.parallel()
.skip(100)
.findFirst()
.getAsInt());
}
This may run much longer because the parallel threads may work on plenty of number ranges instead of the crucial one 0-100, causing this to take very long time.
I use this shell script on Linux https://github.com/eloone/mergejs.
Compared to the above scripts it has the advantages of being very simple to use, and a big plus is that you can list the js files you want to merge in an input text file and not in the command line, so your list is reusable and you don't have to type it every time you want to merge your files. It's very handy since you will repeat this step every time you want to push into production. You can also comment files you don't want to merge in the list. The command line you would most likely type is :
$ mergejs js_files_list.txt output.js
And if you want to also compress the resulting merged file :
$ mergejs -c js_files_list.txt output.js
This will create output-min.js
minified by Google's closure compiler. Or :
$ mergejs -c js_files_list.txt output.js output.minified.js
If you want a specific name for your minified file named output.minified.js
I find it really helpful for a simple website.
I am on a Windows (WIN7), running Python 2.7.5 & Matplotlib 1.3.1.
I was able to maximize Figure windows for TkAgg, QT4Agg, and wxAgg using the following lines:
from matplotlib import pyplot as plt
### for 'TkAgg' backend
plt.figure(1)
plt.switch_backend('TkAgg') #TkAgg (instead Qt4Agg)
print '#1 Backend:',plt.get_backend()
plt.plot([1,2,6,4])
mng = plt.get_current_fig_manager()
### works on Ubuntu??? >> did NOT working on windows
# mng.resize(*mng.window.maxsize())
mng.window.state('zoomed') #works fine on Windows!
plt.show() #close the figure to run the next section
### for 'wxAgg' backend
plt.figure(2)
plt.switch_backend('wxAgg')
print '#2 Backend:',plt.get_backend()
plt.plot([1,2,6,4])
mng = plt.get_current_fig_manager()
mng.frame.Maximize(True)
plt.show() #close the figure to run the next section
### for 'Qt4Agg' backend
plt.figure(3)
plt.switch_backend('QT4Agg') #default on my system
print '#3 Backend:',plt.get_backend()
plt.plot([1,2,6,4])
figManager = plt.get_current_fig_manager()
figManager.window.showMaximized()
plt.show()
if you want to maximize multiple figures you can use
for fig in figs:
mng = fig.canvas.manager
# ...
Hope this summary of the previous answers (and some additions) combined in a working example (at least for windows) helps. Cheers
UPDATE 23/Dec/2015: Since this answer seems to be getting a lot of upvotes, I've updated it to fix silly bugs and to generally improve the code based upon comments and feedback. See the end of the post for a list of specific improvements.
As other people have said, Cryptography is not simple so it's best to avoid "rolling your own" encryption algorithm.
You can, however, "roll your own" wrapper class around something like the built-in RijndaelManaged
cryptography class.
Rijndael is the algorithmic name of the current Advanced Encryption Standard, so you're certainly using an algorithm that could be considered "best practice".
The RijndaelManaged
class does indeed normally require you to "muck about" with byte arrays, salts, keys, initialization vectors etc. but this is precisely the kind of detail that can be somewhat abstracted away within your "wrapper" class.
The following class is one I wrote a while ago to perform exactly the kind of thing you're after, a simple single method call to allow some string-based plaintext to be encrypted with a string-based password, with the resulting encrypted string also being represented as a string. Of course, there's an equivalent method to decrypt the encrypted string with the same password.
Unlike the first version of this code, which used the exact same salt and IV values every time, this newer version will generate random salt and IV values each time. Since salt and IV must be the same between the encryption and decryption of a given string, the salt and IV is prepended to the cipher text upon encryption and extracted from it again in order to perform the decryption. The result of this is that encrypting the exact same plaintext with the exact same password gives and entirely different ciphertext result each time.
The "strength" of using this comes from using the RijndaelManaged
class to perform the encryption for you, along with using the Rfc2898DeriveBytes function of the System.Security.Cryptography
namespace which will generate your encryption key using a standard and secure algorithm (specifically, PBKDF2) based upon the string-based password you supply. (Note this is an improvement of the first version's use of the older PBKDF1 algorithm).
Finally, it's important to note that this is still unauthenticated encryption. Encryption alone provides only privacy (i.e. message is unknown to 3rd parties), whilst authenticated encryption aims to provide both privacy and authenticity (i.e. recipient knows message was sent by the sender).
Without knowing your exact requirements, it's difficult to say whether the code here is sufficiently secure for your needs, however, it has been produced to deliver a good balance between relative simplicity of implementation vs "quality". For example, if your "receiver" of an encrypted string is receiving the string directly from a trusted "sender", then authentication may not even be necessary.
If you require something more complex, and which offers authenticated encryption, check out this post for an implementation.
Here's the code:
using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Linq;
namespace EncryptStringSample
{
public static class StringCipher
{
// This constant is used to determine the keysize of the encryption algorithm in bits.
// We divide this by 8 within the code below to get the equivalent number of bytes.
private const int Keysize = 256;
// This constant determines the number of iterations for the password bytes generation function.
private const int DerivationIterations = 1000;
public static string Encrypt(string plainText, string passPhrase)
{
// Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
// so that the same Salt and IV values can be used when decrypting.
var saltStringBytes = Generate256BitsOfRandomEntropy();
var ivStringBytes = Generate256BitsOfRandomEntropy();
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
{
var keyBytes = password.GetBytes(Keysize / 8);
using (var symmetricKey = new RijndaelManaged())
{
symmetricKey.BlockSize = 256;
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.PKCS7;
using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
{
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
// Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
var cipherTextBytes = saltStringBytes;
cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
memoryStream.Close();
cryptoStream.Close();
return Convert.ToBase64String(cipherTextBytes);
}
}
}
}
}
}
public static string Decrypt(string cipherText, string passPhrase)
{
// Get the complete stream of bytes that represent:
// [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
// Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.
var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
// Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
// Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();
using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
{
var keyBytes = password.GetBytes(Keysize / 8);
using (var symmetricKey = new RijndaelManaged())
{
symmetricKey.BlockSize = 256;
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.Padding = PaddingMode.PKCS7;
using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes))
{
using (var memoryStream = new MemoryStream(cipherTextBytes))
{
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
var plainTextBytes = new byte[cipherTextBytes.Length];
var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
}
}
}
}
}
private static byte[] Generate256BitsOfRandomEntropy()
{
var randomBytes = new byte[32]; // 32 Bytes will give us 256 bits.
using (var rngCsp = new RNGCryptoServiceProvider())
{
// Fill the array with cryptographically secure random bytes.
rngCsp.GetBytes(randomBytes);
}
return randomBytes;
}
}
}
The above class can be used quite simply with code similar to the following:
using System;
namespace EncryptStringSample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter a password to use:");
string password = Console.ReadLine();
Console.WriteLine("Please enter a string to encrypt:");
string plaintext = Console.ReadLine();
Console.WriteLine("");
Console.WriteLine("Your encrypted string is:");
string encryptedstring = StringCipher.Encrypt(plaintext, password);
Console.WriteLine(encryptedstring);
Console.WriteLine("");
Console.WriteLine("Your decrypted string is:");
string decryptedstring = StringCipher.Decrypt(encryptedstring, password);
Console.WriteLine(decryptedstring);
Console.WriteLine("");
Console.WriteLine("Press any key to exit...");
Console.ReadLine();
}
}
}
(You can download a simple VS2013 sample solution (which includes a few unit tests) here).
UPDATE 23/Dec/2015: The list of specific improvements to the code are:
Or - build on @Jamaica Geek's answer, using Express - to avoid saving and reading a file:
res.attachment('file.xls');
var header="Sl No"+"\t"+" Age"+"\t"+"Name"+"\n";
var row1 = [0,21,'BOB'].join('\t')
var row2 = [0,22,'bob'].join('\t');
var c = header + row1 + row2;
return res.send(c);
There is another way to reset the password through command prompt ...
1) Go to the Oracle Database Folder ( In my case Oracle Database 11g Express Edition) in the START MENU.
2) Within that folder click "Run SQL Commandline"
3) Type "connect username/password" (your username and old password without the quotation marks)
4) The message displayed is ...
ERROR: ORA-28001: the password has expired
Changing password for hr
--> New password:
Enter Username, Password image
5) Type the new password
6) Retype the new password
7) Message displayed is ...
Password changed Connected.
SQL>
8) GO TO Sql developer --> type the new password --> connected
Solutions listed did not exactly work for me. The closest was Chief Wiggum - I wanted to add a comment on his answer but lack the reputation to do so. So I post as separate answer:
=MIN(IF(A1:E1>0;A1:E1))
Then instead of pressing ENTER, press CTRL+SHIFT+ENTER and watch Excel add {
and }
to respectively the beginning and the end of the formula (to activate the formula on array).
The comma "," and "If" statement as proposed by Chief Wiggum did not work on Excel Home and Student 2013. Need a semicolon ";" as well as full cap "IF" did the trick. Small syntax difference but took me 1.5 hour to figure out why I was getting an error and #VALUE.
Short & Sweet:
/**
* Get a diff between two dates
*
* @param oldDate the old date
* @param newDate the new date
* @return the diff value, in the days
*/
public static long getDateDiff(SimpleDateFormat format, String oldDate, String newDate) {
try {
return TimeUnit.DAYS.convert(format.parse(newDate).getTime() - format.parse(oldDate).getTime(), TimeUnit.MILLISECONDS);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
Usage:
int dateDifference = (int) getDateDiff(new SimpleDateFormat("dd/MM/yyyy"), "29/05/2017", "31/05/2017");
System.out.println("dateDifference: " + dateDifference);
Output:
dateDifference: 2
Kotlin Version:
@ExperimentalTime
fun getDateDiff(format: SimpleDateFormat, oldDate: String, newDate: String): Long {
return try {
DurationUnit.DAYS.convert(
format.parse(newDate).time - format.parse(oldDate).time,
DurationUnit.MILLISECONDS
)
} catch (e: Exception) {
e.printStackTrace()
0
}
}
maybe this trick will help somebody
SELECT
[id],
[code],
[created_at]
FROM
( SELECT
[id],
[code],
[created_at],
(ROW_NUMBER() OVER (
ORDER BY
created_at DESC)) AS Row
FROM
[Code_tbl]
WHERE
[created_at] BETWEEN '2009-11-17 00:00:01' AND '2010-11-17 23:59:59'
) Rows
WHERE
Row BETWEEN 10 AND 20;
here inner subquery ordered by field created_at (could be any from your table)
Chiming in to recommend the use of the xmltodict library. It handled your xml text pretty well and I've used it for ingesting an xml file with almost a million records.
In your test class if wrote import org.junit.jupiter.api.Test; delete it and write import org.junit.Test; In this case it worked me as well.
What about @Primary
?
Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value. This annotation is semantically equivalent to the
<bean>
element'sprimary
attribute in Spring XML.
@Primary
public class HibernateDeviceDao implements DeviceDao
Or if you want your Jdbc version to be used by default:
<bean id="jdbcDeviceDao" primary="true" class="com.initech.service.dao.jdbc.JdbcDeviceDao">
@Primary
is also great for integration testing when you can easily replace production bean with stubbed version by annotating it.
My immediate solution (since I couldn't find the ASP.NET worker process) was to give write (that is, Modify) permission to IIS_IUSRS. This worked. I seem to recall that in WinXP I had to specifically given the ASP.NET worker process write permission to accomplish this. Maybe my memory is faulty, but anyway...
@DraganRadivojevic wrote that he thought this was dangerous from a security viewpoint. I do not disagree, but since this was my workstation and not a network server, it seemed relatively safe. In any case, his answer is better and is what I finally settled on after chasing down a fail-path due to not specifying the correct domain for the AppPool user.
Bringing a bit for users of Sublime Text 2, there is a plugin that gives the base64 code we load the images in the ST.
Called Image2base64: https://github.com/tm-minty/sublime-text-2-image2base64
PS: Never save this file generated by the plugin because it would overwrite the file and would destroy.
If you want to lookup/associate an object with a unique identifier without modifying the underlying object, you can use a WeakMap
:
// Note that object must be an object or array,
// NOT a primitive value like string, number, etc.
var objIdMap=new WeakMap, objectCount = 0;
function objectId(object){
if (!objIdMap.has(object)) objIdMap.set(object,++objectCount);
return objIdMap.get(object);
}
var o1={}, o2={}, o3={a:1}, o4={a:1};
console.log( objectId(o1) ) // 1
console.log( objectId(o2) ) // 2
console.log( objectId(o1) ) // 1
console.log( objectId(o3) ) // 3
console.log( objectId(o4) ) // 4
console.log( objectId(o3) ) // 3
Using a WeakMap
instead of Map
ensures that the objects can still be garbage-collected.
Instead of override you can add another class to the element and then you have an extra abilities. for example:
HTML
<div class="style1 style2"></div>
CSS
//only style for the first stylesheet
.style1 {
width: 100%;
}
//only style for second stylesheet
.style2 {
width: 50%;
}
//override all
.style1.style2 {
width: 70%;
}
Kibana doesn't have a log file by default. but you can set it up using log_file Kibana server property - https://www.elastic.co/guide/en/kibana/current/kibana-server-properties.html
<iframe>
The iframe element represents a nested browsing context. HTML 5 standard - "The
<iframe>
element"
Primarily used to include resources from other domains or subdomains but can be used to include content from the same domain as well. The <iframe>
's strength is that the embedded code is 'live' and can communicate with the parent document.
<embed>
Standardised in HTML 5, before that it was a non standard tag, which admittedly was implemented by all major browsers. Behaviour prior to HTML 5 can vary ...
The embed element provides an integration point for an external (typically non-HTML) application or interactive content. (HTML 5 standard - "The
<embed>
element")
Used to embed content for browser plugins. Exceptions to this is SVG and HTML that are handled differently according to the standard.
The details of what can and can not be done with the embedded content is up to the browser plugin in question. But for SVG you can access the embedded SVG document from the parent with something like:
svg = document.getElementById("parent_id").getSVGDocument();
From inside an embedded SVG or HTML document you can reach the parent with:
parent = window.parent.document;
For embedded HTML there is no way to get at the embedded document from the parent (that I have found).
<object>
The
<object>
element can represent an external resource, which, depending on the type of the resource, will either be treated as an image, as a nested browsing context, or as an external resource to be processed by a plugin. (HTML 5 standard - "The<object>
element")
Unless you are embedding SVG or something static you are probably best of using <iframe>
. To include SVG use <embed>
(if I remember correctly <object>
won't let you script†). Honestly I don't know why you would use <object>
unless for older browsers or flash (that I don't work with).
† As pointed out in the comments below; scripts in <object>
will run but the parent and child contexts can't communicate directly. With <embed>
you can get the context of the child from the parent and vice versa. This means they you can use scripts in the parent to manipulate the child etc. That part is not possible with <object>
or <iframe>
where you would have to set up some other mechanism instead, such as the JavaScript postMessage API.
You're getting the starting position of 'punishment immediately', but passing that in as the length parameter for your substring.
You would need to substract the starting position of 'the dog' from the charindex of 'punishment immediately', and then add the length of the 'punishment immediately' string to your third parameter. This would then give you the correct text.
Here's some rough, hacky code to illustrate the process:
DECLARE @text VARCHAR(MAX)
SET @text = 'All I knew was that the dog had been very bad and required harsh punishment immediately regardless of what anyone else thought.'
DECLARE @start INT
SELECT @start = CHARINDEX('the dog',@text)
DECLARE @endLen INT
SELECT @endLen = LEN('immediately')
DECLARE @end INT
SELECT @end = CHARINDEX('immediately',@text)
SET @end = @end - @start + @endLen
SELECT @end
SELECT SUBSTRING(@text,@start,@end)
Result: the dog had been very bad and required harsh punishment immediately
Same issue, but I just cleared my settings. I went into Settings > Preferences and Clicked [Restore defaults and reload]. Just remember what your settings were.
d = dict([(x,0) for x in a])
**edit Tim's solution is better because it uses generators see the comment to his answer.
Probaly you can use Iframe
for this. Facebook probably uses this technique. You can read more on this here. Stackoverflow uses similar technique, but with HTML5 local storage, more on this on their blog
I got this fixed by doing the below steps,
The eclipse finds the JAVA executables from 'C:\ProgramData\Oracle\Java\javapath'
2.The folder structure will contain shortcuts to the below executables,
i. java.exe
ii. javaw.exe
iii. javaws.exe
3.For me the executable paths were pointing to my (ProgramFiles(x84)) folder location
I corrected it to Program Files path(64 bit) and the issue got resolved
Please find the screenshot for the same.
Ran into this problem today and I wrote a function for it. In my particular case, I needed to make sure all values were at least 0 (hence the "LT0" name) and were rounded to two decimal places.
Private Function LT0(ByVal Input As Decimal, Optional ByVal Precision As Int16 = 2) As Decimal
' returns 0 for all values less than 0, the decimal rounded to (Precision) decimal places otherwise.
If Input < 0 Then Input = 0
if Precision < 0 then Precision = 0 ' just in case someone does something stupid.
Return Decimal.Round(Input, Precision) ' this is the line everyone's probably looking for.
End Function
You can define like this
define('GENERIC_DOMAIN',json_encode(array(
'gmail.com','gmail.co.in','yahoo.com'
)));
$domains = json_decode(GENERIC_DOMAIN);
var_dump($domains);
The value for your onClick
attribute should be a function, not a function call.
<button type="submit" onClick={function(){removeTaskFunction(todo)}}>Submit</button>
Another possibility is too many threads. We just ran into this error message when running a test harness against an app that uses a thread pool. We used
watch -n 5 -d "ps -eL <java_pid> | wc -l"
to watch the ongoing count of Linux native threads running within the given Java process ID. After this hit about 1,000 (for us--YMMV), we started getting the error message you mention.
sup {
line-height: 0;
/* The following rules (or similar) likely come from browser
* style and are not needed
*/
font-size: 0.83em;
vertical-align: super;
}
The trick is to set the <sup>
's line-height to 0. @Scott said to use normal, but this doesn't always work.
This means you don't have to change the line-height of surrounding text to accommodate the superscript text. I've tested this in IE7+ and the other major browsers.
This is what I've been using. Haven't seen any issues.
destroy: function(){
this.remove();
this.unbind();
}
I'm not sure if I'm answering the question right, but here's a familiar example:
The return type of GetLastError()
in Windows is nonzero if there was an error, or zero otherwise. The reverse is usually true of the return value of the function you called.
At least 8 = {8,}
:
str.match(/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8,})$/)
It depends on your mark-up, but it can certainly be made to work, I used the following:
$(document).ready(
function() {
$('td p').slideUp();
$('td h2').click(
function(){
$(this).siblings('p').slideToggle();
}
);
}
);
<table>
<thead>
<tr>
<th>Actor</th>
<th>Which Doctor</th>
<th>Significant companion</th>
</tr>
</thead>
<tbody>
<tr>
<td><h2>William Hartnell</h2></td>
<td><h2>First</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
<td><h2>Susan Foreman</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
</tr>
<tr>
<td><h2>Patrick Troughton</h2></td>
<td><h2>Second</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
<td><h2>Jamie MacCrimmon</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
</tr>
<tr>
<td><h2>Jon Pertwee</h2></td>
<td><h2>Third</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
<td><h2>Jo Grant</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
</tr>
</tbody>
</table>
The way I approached it is to collapse specific elements within the cells of the row, so that, in my case, the row would slideUp()
as the paragraphs were hidden, and still leave an element, h2
to click on in order to re-show the content. If the row collapsed entirely there'd be no easily obvious way to bring it back.
As @Peter Ajtai noted, in the comments, the above approach focuses on only one cell (though deliberately). To expand all the child p
elements this would work:
$(document).ready(
function() {
$('td p').slideUp();
$('td h2').click(
function(){
$(this).closest('tr').find('p').slideToggle();
}
);
}
);
Position the cursor inside the class, then press ALT + Ins and select Getters and Setters
from the contextual menu.
In case of ugrading to Visual Studio 2010, 2012, 2013 or 2015, there's a Visual Studio extension to show current registered keyboard shortcuts, IntelliCommand.
In a Android app I was building, I had three EditText
s in a LinearLayout
arranged horizontally. I had to prevent the soft keyboard from appearing when the fragment loaded. In addition to setting focusable
and focusableInTouchMode
to true on the LinearLayout
, I had to set descendantFocusability
to blocksDescendants
. In onCreate
, I called requestFocus
on the LinearLayout
. This prevented the keyboard from appearing when the fragment is created.
Layout -
<LinearLayout
android:id="@+id/text_selector_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="3"
android:orientation="horizontal"
android:focusable="true"
android:focusableInTouchMode="true"
android:descendantFocusability="blocksDescendants"
android:background="@color/black">
<!-- EditText widgets -->
</LinearLayout>
In onCreate
- mTextSelectorContainer.requestFocus();
On my PC I had to open the Tomcat6 entry again after the 7th step mentioned above and then change the default option under Server locations
to Use tomcat installation
.
I faced the same issue which was due to going to branch with wrong casing. git let me switch to branch with incorrect casing ie feature/Name
instead of feature/name
. Found an easier solution than listed above just:
git checkout master (or develop)
git checkout feature/name
< with correct casinggit push
Depending on the underlying JPQL or Criteria API query type, DISTINCT
has two meanings in JPA.
For scalar queries, which return a scalar projection, like the following query:
List<Integer> publicationYears = entityManager
.createQuery(
"select distinct year(p.createdOn) " +
"from Post p " +
"order by year(p.createdOn)", Integer.class)
.getResultList();
LOGGER.info("Publication years: {}", publicationYears);
The DISTINCT
keyword should be passed to the underlying SQL statement because we want the DB engine to filter duplicates prior to returning the result set:
SELECT DISTINCT
extract(YEAR FROM p.created_on) AS col_0_0_
FROM
post p
ORDER BY
extract(YEAR FROM p.created_on)
-- Publication years: [2016, 2018]
For entity queries, DISTINCT
has a different meaning.
Without using DISTINCT
, a query like the following one:
List<Post> posts = entityManager
.createQuery(
"select p " +
"from Post p " +
"left join fetch p.comments " +
"where p.title = :title", Post.class)
.setParameter(
"title",
"High-Performance Java Persistence eBook has been released!"
)
.getResultList();
LOGGER.info(
"Fetched the following Post entity identifiers: {}",
posts.stream().map(Post::getId).collect(Collectors.toList())
);
is going to JOIN the post
and the post_comment
tables like this:
SELECT p.id AS id1_0_0_,
pc.id AS id1_1_1_,
p.created_on AS created_2_0_0_,
p.title AS title3_0_0_,
pc.post_id AS post_id3_1_1_,
pc.review AS review2_1_1_,
pc.post_id AS post_id3_1_0__
FROM post p
LEFT OUTER JOIN
post_comment pc ON p.id=pc.post_id
WHERE
p.title='High-Performance Java Persistence eBook has been released!'
-- Fetched the following Post entity identifiers: [1, 1]
But the parent post
records are duplicated in the result set for each associated post_comment
row. For this reason, the List
of Post
entities will contain duplicate Post
entity references.
To eliminate the Post
entity references, we need to use DISTINCT
:
List<Post> posts = entityManager
.createQuery(
"select distinct p " +
"from Post p " +
"left join fetch p.comments " +
"where p.title = :title", Post.class)
.setParameter(
"title",
"High-Performance Java Persistence eBook has been released!"
)
.getResultList();
LOGGER.info(
"Fetched the following Post entity identifiers: {}",
posts.stream().map(Post::getId).collect(Collectors.toList())
);
But then DISTINCT
is also passed to the SQL query, and that's not desirable at all:
SELECT DISTINCT
p.id AS id1_0_0_,
pc.id AS id1_1_1_,
p.created_on AS created_2_0_0_,
p.title AS title3_0_0_,
pc.post_id AS post_id3_1_1_,
pc.review AS review2_1_1_,
pc.post_id AS post_id3_1_0__
FROM post p
LEFT OUTER JOIN
post_comment pc ON p.id=pc.post_id
WHERE
p.title='High-Performance Java Persistence eBook has been released!'
-- Fetched the following Post entity identifiers: [1]
By passing DISTINCT
to the SQL query, the EXECUTION PLAN is going to execute an extra Sort phase which adds overhead without bringing any value since the parent-child combinations always return unique records because of the child PK column:
Unique (cost=23.71..23.72 rows=1 width=1068) (actual time=0.131..0.132 rows=2 loops=1)
-> Sort (cost=23.71..23.71 rows=1 width=1068) (actual time=0.131..0.131 rows=2 loops=1)
Sort Key: p.id, pc.id, p.created_on, pc.post_id, pc.review
Sort Method: quicksort Memory: 25kB
-> Hash Right Join (cost=11.76..23.70 rows=1 width=1068) (actual time=0.054..0.058 rows=2 loops=1)
Hash Cond: (pc.post_id = p.id)
-> Seq Scan on post_comment pc (cost=0.00..11.40 rows=140 width=532) (actual time=0.010..0.010 rows=2 loops=1)
-> Hash (cost=11.75..11.75 rows=1 width=528) (actual time=0.027..0.027 rows=1 loops=1)
Buckets: 1024 Batches: 1 Memory Usage: 9kB
-> Seq Scan on post p (cost=0.00..11.75 rows=1 width=528) (actual time=0.017..0.018 rows=1 loops=1)
Filter: ((title)::text = 'High-Performance Java Persistence eBook has been released!'::text)
Rows Removed by Filter: 3
Planning time: 0.227 ms
Execution time: 0.179 ms
To eliminate the Sort phase from the execution plan, we need to use the HINT_PASS_DISTINCT_THROUGH
JPA query hint:
List<Post> posts = entityManager
.createQuery(
"select distinct p " +
"from Post p " +
"left join fetch p.comments " +
"where p.title = :title", Post.class)
.setParameter(
"title",
"High-Performance Java Persistence eBook has been released!"
)
.setHint(QueryHints.HINT_PASS_DISTINCT_THROUGH, false)
.getResultList();
LOGGER.info(
"Fetched the following Post entity identifiers: {}",
posts.stream().map(Post::getId).collect(Collectors.toList())
);
And now, the SQL query will not contain DISTINCT
but Post
entity reference duplicates are going to be removed:
SELECT
p.id AS id1_0_0_,
pc.id AS id1_1_1_,
p.created_on AS created_2_0_0_,
p.title AS title3_0_0_,
pc.post_id AS post_id3_1_1_,
pc.review AS review2_1_1_,
pc.post_id AS post_id3_1_0__
FROM post p
LEFT OUTER JOIN
post_comment pc ON p.id=pc.post_id
WHERE
p.title='High-Performance Java Persistence eBook has been released!'
-- Fetched the following Post entity identifiers: [1]
And the Execution Plan is going to confirm that we no longer have an extra Sort phase this time:
Hash Right Join (cost=11.76..23.70 rows=1 width=1068) (actual time=0.066..0.069 rows=2 loops=1)
Hash Cond: (pc.post_id = p.id)
-> Seq Scan on post_comment pc (cost=0.00..11.40 rows=140 width=532) (actual time=0.011..0.011 rows=2 loops=1)
-> Hash (cost=11.75..11.75 rows=1 width=528) (actual time=0.041..0.041 rows=1 loops=1)
Buckets: 1024 Batches: 1 Memory Usage: 9kB
-> Seq Scan on post p (cost=0.00..11.75 rows=1 width=528) (actual time=0.036..0.037 rows=1 loops=1)
Filter: ((title)::text = 'High-Performance Java Persistence eBook has been released!'::text)
Rows Removed by Filter: 3
Planning time: 1.184 ms
Execution time: 0.160 ms
Plain old C doesn't actually support exceptions natively.
You can use alternative error handling strategies, such as:
FALSE
and using a last_error
variable or function.See http://en.wikibooks.org/wiki/C_Programming/Error_handling.
Try with this code, you will get the image preview while uploading
<input type='file' id="upload" onChange="readURL(this);"/>
<img id="img" src="#" alt="your image" />
function readURL(input){
var ext = input.files[0]['name'].substring(input.files[0]['name'].lastIndexOf('.') + 1).toLowerCase();
if (input.files && input.files[0] && (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg"))
var reader = new FileReader();
reader.onload = function (e) {
$('#img').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}else{
$('#img').attr('src', '/assets/no_preview.png');
}
}
Here's one solution that extracts all zip files to the working directory and involves the find command and a while loop:
find . -name "*.zip" | while read filename; do unzip -o -d "`basename -s .zip "$filename"`" "$filename"; done;
This may be sufficient in many cases
stream.findAny().isPresent()
The extensions methods also provide a ToDictionary extension. It is fairly simple to use, the general usage is passing a lambda selector for the key and getting the object as the value, but you can pass a lambda selector for both key and value.
class SomeObject
{
public int ID { get; set; }
public string Name { get; set; }
}
SomeObject[] objects = new SomeObject[]
{
new SomeObject { ID = 1, Name = "Hello" },
new SomeObject { ID = 2, Name = "World" }
};
Dictionary<int, string> objectDictionary = objects.ToDictionary(o => o.ID, o => o.Name);
Then objectDictionary[1]
Would contain the value "Hello"
async function main() {
var getQuoteError
var quote = await getQuote().catch(err => { getQuoteError = err }
if (getQuoteError) return console.error(err)
console.log(quote)
}
Alternatively instead of declaring a possible var to hold an error at the top you can do
if (quote instanceof Error) {
// ...
}
Though that won't work if something like a TypeError or Reference error is thrown. You can ensure it is a regular error though with
async function main() {
var quote = await getQuote().catch(err => {
console.error(err)
return new Error('Error getting quote')
})
if (quote instanceOf Error) return quote // get out of here or do whatever
console.log(quote)
}
My preference for this is wrapping everything in a big try-catch block where there's multiple promises being created can make it cumbersome to handle the error specifically to the promise that created it. With the alternative being multiple try-catch blocks which I find equally cumbersome
I guess you're missing the ENCLOSED BY clause
LOAD DATA LOCAL INFILE '/path/to/your/csv/file/model.csv'
INTO TABLE test.dummy FIELDS TERMINATED BY ','
ENCLOSED BY '"' LINES TERMINATED BY '\n';
And specify the csv file full path
As kmcamara discovered, this is exactly the kind of problem that VLOOKUP is intended to solve, and using vlookup is arguably the simplest of the alternative ways to get the job done.
In addition to the three parameters for lookup_value, table_range to be searched, and the column_index for return values, VLOOKUP takes an optional fourth argument that the Excel documentation calls the "range_lookup".
Expanding on deathApril's explanation, if this argument is set to TRUE (or 1) or omitted, the table range must be sorted in ascending order of the values in the first column of the range for the function to return what would typically be understood to be the "correct" value. Under this default behavior, the function will return a value based upon an exact match, if one is found, or an approximate match if an exact match is not found.
If the match is approximate, the value that is returned by the function will be based on the next largest value that is less than the lookup_value. For example, if "12AT8003" were missing from the table in Sheet 1, the lookup formulas for that value in Sheet 2 would return '2', since "12AT8002" is the largest value in the lookup column of the table range that is less than "12AT8003". (VLOOKUP's default behavior makes perfect sense if, for example, the goal is to look up rates in a tax table.)
However, if the fourth argument is set to FALSE (or 0), VLOOKUP returns a looked-up value only if there is an exact match, and an error value of #N/A if there is not. It is now the usual practice to wrap an exact VLOOKUP in an IFERROR function in order to catch the no-match gracefully. Prior to the introduction of IFERROR, no matches were checked with an IF function using the VLOOKUP formula once to check whether there was a match, and once to return the actual match value.
Though initially harder to master, deusxmach1na's proposed solution is a variation on a powerful set of alternatives to VLOOKUP that can be used to return values for a column or list to the left of the lookup column, expanded to handle cases where an exact match on more than one criterion is needed, or modified to incorporate OR as well as AND match conditions among multiple criteria.
Repeating kcamara's chosen solution, the VLOOKUP formula for this problem would be:
=VLOOKUP(A1,Sheet1!A$1:B$600,2,FALSE)
(From http://git.or.cz/gitwiki/GitTips#head-9f87cd21bcdf081a61c29985604ff4be35a5e6c0)
How to change commits deeper in history
Since history in Git is immutable, fixing anything but the most recent commit (commit which is not branch head) requires that the history is rewritten from the changed commit and forward.
You can use StGIT for that, initialize branch if necessary, uncommitting up to the commit you want to change, pop to it if necessary, make a change then refresh patch (with -e option if you want to correct commit message), then push everything and stg commit.
Or you can use rebase to do that. Create new temporary branch, rewind it to the commit you want to change using git reset --hard, change that commit (it would be top of current head), then rebase branch on top of changed commit, using git rebase --onto .
Or you can use git rebase --interactive, which allows various modifications like patch re-ordering, collapsing, ...
I think that should answer your question. However, note that if you have pushed code to a remote repository and people have pulled from it, then this is going to mess up their code histories, as well as the work they've done. So do it carefully.
You can use date(t_stamp)
to get only the date part from a timestamp.
You can check the date() function in the docs
DATE(expr)
Extracts the date part of the date or datetime expression expr.
mysql> SELECT DATE('2003-12-31 01:02:03'); -> '2003-12-31'
In Java 7, you can use Objects.requireNonNull()
.
Add an import of Objects
class from java.util
.
public class FooClass {
//...
public void acceptFoo(Foo obj) {
//If obj is null, NPE is thrown
Objects.requireNonNull(obj).bar(); //or better requireNonNull(obj, "obj is null");
}
//...
}
If PowerShell is open in a directory other than the target file, e.g.:
If someScript.ps1
is located here: C:\SlowLearner\some_missing_path\someScript.ps1
, then C:\SlowLearner>. ./someScript.ps1
wont work.
In that case, navigate to the path: cd some_missing_path
then this would work:
C:\SlowLearner\some_missing_path>. ./someScript.ps1
How about extending a jquery for this?
(function () {
var ev = new $.Event('remove'),
orig = $.fn.remove;
var evap = new $.Event('append'),
origap = $.fn.append;
$.fn.remove = function () {
$(this).trigger(ev);
return orig.apply(this, arguments);
}
$.fn.append = function () {
$(this).trigger(evap);
return origap.apply(this, arguments);
}
})();
$(document).on('append', function (e) { /*write your logic here*/ });
$(document).on('remove', function (e) { /*write your logic here*/ });
Jquery 1.9+ has built support for this(I have heard not tested).
You could give bluefish a try. Has a bunch of nice features for website work. Syntax files for most every language.
http://bluefish.openoffice.nl/
If on windows give Crimson Editor a try http://www.crimsoneditor.com/ It's been a long while since I ran windows, but iirc, 'official' development has stopped on it, but the community has taken up a fork of it and called it emerald or somesuch. Crimson editor is still very capable as is.
Both bluefish and crimson editor have project management abilities. FTP ablilities, macros etc etc
As with most things, "it depends". But to me, your practice is not bad and is not going against the HTTP spec per se. However, let's clear some things up.
First, URI's should be opaque. Even if they're not opaque to people, they are opaque to machines. In other words, the difference between http://mywebsite/api/user/13
, http://mywebsite/restapi/user/13
is the same as the difference between http://mywebsite/api/user/13
and http://mywebsite/api/user/14
i.e. not the same is not the same period. So a 404 would be completely appropriate for http://mywebsite/api/user/14
(if there is no such user) but not necessarily the only appropriate response.
You could also return an empty 200 response or more explicitly a 204 (No Content) response. This would convey something else to the client. It would imply that the resource identified by http://mywebsite/api/user/14
has no content or is essentially nothing. It does mean that there is such a resource. However, it does not necessarily mean that you are claiming there is some user persisted in a data store with id 14. That's your private concern, not the concern of the client making the request. So, if it makes sense to model your resources that way, go ahead.
There are some security implications to giving your clients information that would make it easier for them to guess legitimate URI's. Returning a 200 on misses instead of a 404 may give the client a clue that at least the http://mywebsite/api/user
part is correct. A malicious client could just keep trying different integers. But to me, a malicious client would be able to guess the http://mywebsite/api/user
part anyway. A better remedy would be to use UUID's. i.e. http://mywebsite/api/user/3dd5b770-79ea-11e1-b0c4-0800200c9a66
is better than http://mywebsite/api/user/14
. Doing that, you could use your technique of returning 200's without giving much away.