If you are looking for a simple way, here it is.
Create a utility class like this,
public class ApplicationUtils {
/**
* Sets the boolean preference value
*
* @param context the current context
* @param key the preference key
* @param value the value to be set
*/
public static void setBooleanPreferenceValue(Context context, String key, boolean value) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().putBoolean(key, value).apply();
}
/**
* Get the boolean preference value from the SharedPreference
*
* @param context the current context
* @param key the preference key
* @return the the preference value
*/
public static boolean getBooleanPreferenceValue(Context context, String key) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getBoolean(key, false);
}
}
At your Main Activity, onCreate()
if(!ApplicationUtils.getBooleanPreferenceValue(this,"isFirstTimeExecution")){
Log.d(TAG, "First time Execution");
ApplicationUtils.setBooleanPreferenceValue(this,"isFirstTimeExecution",true);
// do your first time execution stuff here,
}
Quite a painful problem for me too. Just spent about an hour trying to build and re-build - no joy. In the end I had to do this:
I guess it's a bunch of jargon about arm6 , arm7 as it looked like my project was valid for both, at least the settings seemed to say so ) , my guess is this is a cynical way to bamboozle us with the technicalities, which we don't understand, so we just take the easy option and target the latest iOS ( good for Apple with more people being up-to-date ) ....
In case someone stumbled over this in more recent times, I have added a simple variation using Java 8 reduce()
. It also includes some of the already mentioned solutions by others:
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import com.google.common.base.Joiner;
public class Dummy {
public static void main(String[] args) {
List<String> strings = Arrays.asList("abc", "de", "fg");
String commaSeparated = strings
.stream()
.reduce((s1, s2) -> {return s1 + "," + s2; })
.get();
System.out.println(commaSeparated);
System.out.println(Joiner.on(',').join(strings));
System.out.println(StringUtils.join(strings, ","));
}
}
This may be achieved by using AppCompatCheckBox
. You can use app:buttonCompat="@drawable/selector_drawable"
to change the selector.
It's working with PNGs, but I didn't find a way for it to work with Vector Drawables.
Here's the complete procedure to auto-indent a file with Netbeans 8.
First step is to go to Tools -> Options
and click on Editor button and Formatting tab as it is shown on the following image.
When you have set your formatting options, click the Apply button and OK. Note that my example is with C++ language, but this also apply for Java as well.
The second step is to CTRL + A on the file where you want to apply your new formatting setting. Then, ALT + SHIFT + F or click on the menu Source -> Format
.
Hope this will help.
This worked for me and includes using OutputStream:
PdfReader reader = new PdfReader(new RandomAccessFileOrArray(Request.MapPath("Template.pdf")), null);
Rectangle size = reader.GetPageSizeWithRotation(1);
using (Stream outStream = Response.OutputStream)
{
Document document = new Document(size);
PdfWriter writer = PdfWriter.GetInstance(document, outStream);
document.Open();
try
{
PdfContentByte cb = writer.DirectContent;
cb.BeginText();
try
{
cb.SetFontAndSize(BaseFont.CreateFont(), 12);
cb.SetTextMatrix(110, 110);
cb.ShowText("aaa");
}
finally
{
cb.EndText();
}
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
}
finally
{
document.Close();
writer.Close();
reader.Close();
}
}
String String_firstNumber = JOptionPane.showInputDialog("Input Semisecond");
int Int_firstNumber = Integer.parseInt(firstNumber);
Now your Int_firstnumber
contains integer value of String_fristNumber
.
hope it helped
There's no readily available syntax to do this in the original Markdown syntax, but Markdown Extra provides a means to at least assign IDs to headers — which you can then link to easily. Note also that you can use regular HTML in both Markdown and Markdown Extra, and that the name
attribute has been superseded by the id
attribute in more recent versions of HTML.
Despite all answers above, here goes my 5 cents.
It works on any OS and from any-to-any postgres version.
postgresql.conf
-> port
from 5432
to 5433
;cd
to the new version bin
folder;pg_dumpall -p 5433 -U <username> | psql -p 5432 -U <username>
Here's a complete solution for those using Imagick in PHP:
$im = new \Imagick($filePath);
$im->setImageCompression(\Imagick::COMPRESSION_JPEG);
$im->setImageCompressionQuality(85);
$im->stripImage();
$im->setInterlaceScheme(\Imagick::INTERLACE_PLANE);
// Try between 0 or 5 radius. If you find radius of 5
// produces too blurry pictures decrease to 0 until you
// find a good balance between size and quality.
$im->gaussianBlurImage(0.05, 5);
// Include this part if you also want to specify a maximum size for the images
$size = $im->getImageGeometry();
$maxWidth = 1920;
$maxHeight = 1080;
// ----------
// | |
// ----------
if($size['width'] >= $size['height']){
if($size['width'] > $maxWidth){
$im->resizeImage($maxWidth, 0, \Imagick::FILTER_LANCZOS, 1);
}
}
// ------
// | |
// | |
// | |
// | |
// ------
else{
if($size['height'] > $maxHeight){
$im->resizeImage(0, $maxHeight, \Imagick::FILTER_LANCZOS, 1);
}
}
You can use COALESCE
in conjunction with NULLIF
for a short, efficient solution:
COALESCE( NULLIF(yourField,'') , '0' )
The NULLIF
function will return null if yourField
is equal to the second value (''
in the example), making the COALESCE
function fully working on all cases:
QUERY | RESULT
---------------------------------------------------------------------------------
SELECT COALESCE(NULLIF(null ,''),'0') | '0'
SELECT COALESCE(NULLIF('' ,''),'0') | '0'
SELECT COALESCE(NULLIF('foo' ,''),'0') | 'foo'
You can also use this query
USE MASTER
GO
xp_readerrorlog 0, 1, N'Server is listening on'
GO
Source : sqlauthority blog
I can recommend Ninject. It's incredibly fast and easy to use but only if you don't need XML configuration, else you should use Windsor.
One simple but elegant way is to create a config.php
file (or whatever you call it) that just returns an array:
<?php
return array(
'host' => 'localhost',
'username' => 'root',
);
And then:
$configs = include('config.php');
Try this:
class JSONListView(ListView):
queryset = Users.objects.all()
def get(self, request, *args, **kwargs):
data = {}
data["users"] = get_json_list(queryset)
return JSONResponse(data)
def get_json_list(query_set):
list_objects = []
for obj in query_set:
dict_obj = {}
for field in obj._meta.get_fields():
try:
if field.many_to_many:
dict_obj[field.name] = get_json_list(getattr(obj, field.name).all())
continue
dict_obj[field.name] = getattr(obj, field.name)
except AttributeError:
continue
list_objects.append(dict_obj)
return list_objects
if you need a unique global temp table, create your own with a Uniqueidentifier Prefix/Suffix and drop post execution if an if object_id(.... The only drawback is using Dynamic sql and need to drop explicitly.
It wont work since you use URL link with "file://". Instead you should match your directory to your HTML file, for example:
Lets say my file placed in:
C:/myuser/project/file.html
And my wanted image is in:
C:/myuser/project2/image.png
All I have to do is matching the directory this way:
<img src="../project2/image.png" />
<div id="elem" class="className"></div>
With Javascript
document.getElementById('elem').className;
With jQuery
$('#elem').attr('class');
OR
$('#elem').get(0).className;
The problem you run into when setting width to 50% is the rounding of subpixels. If the width of your container is i.e. 99 pixels, a width of 50% can result in 2 containers of 50 pixels each.
Using float is probably easiest, and not such a bad idea. See this question for more details on how to fix the problem then.
If you don't want to use float, try using a width of 49%. This will work cross-browser as far as I know, but is not pixel-perfect..
html:
<div id="a">A</div>
<div id="b">B</div>
css:
#a, #b {
width: 49%;
display: inline-block;
}
#a {background-color: red;}
#b {background-color: blue;}
I would have to say SimpleXML takes the cake because it is firstly an extension, written in C, and is very fast. But second, the parsed document takes the form of a PHP object. So you can "query" like $root->myElement
.
If any of you looking for Bootstrap-4. Here it is
<div class="row no-gutters">
<div class="col-10">
<img class="img-fluid" src="/resources/img1.jpg" alt="">
</div>
</div>
You can use this function to disable the form:
function disableForm(formID){
$('#' + formID).children(':input').attr('disabled', 'disabled');
}
Note that it uses jQuery.
You need to write a selector which selects the correct <input>
first. Ideally you use the element's ID $('#element_id')
, failing that the ID of it's container $('#container_id input')
, or the element's class $('input.class_name')
.
Your element has none of these and no context, so it's hard to tell you how to select it.
Once you have figured out the proper selector, you'd use the attr method to access the element's attributes. To get the name, you'd use $(selector).attr('name')
which would return (in your example) 'xxxxx'
.
Since 9.0 this is even easier:
SELECT id,
string_agg(some_column, ',')
FROM the_table
GROUP BY id
You need to set an own WebViewClient for your WebView by extending the WebViewClient class.
You need to implement the two methods onPageStarted (show here) and onPageFinished (dismiss here).
More guidance for this topic can be found in Google's WebView tutorial
Recent article on this subject by Chris Reath at Coding Without Comments.
Note: Coding Without Comments is no longer valid. However, The article being linked to has been cloned by another user.
This looks like a pretty clean solution: UIDevice BIdentifier
// Return the local MAC addy
// Courtesy of FreeBSD hackers email list
// Accidentally munged during previous update. Fixed thanks to erica sadun & mlamb.
- (NSString *) macaddress{
int mib[6];
size_t len;
char *buf;
unsigned char *ptr;
struct if_msghdr *ifm;
struct sockaddr_dl *sdl;
mib[0] = CTL_NET;
mib[1] = AF_ROUTE;
mib[2] = 0;
mib[3] = AF_LINK;
mib[4] = NET_RT_IFLIST;
if ((mib[5] = if_nametoindex("en0")) == 0) {
printf("Error: if_nametoindex error\n");
return NULL;
}
if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
printf("Error: sysctl, take 1\n");
return NULL;
}
if ((buf = malloc(len)) == NULL) {
printf("Could not allocate memory. error!\n");
return NULL;
}
if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
printf("Error: sysctl, take 2");
free(buf);
return NULL;
}
ifm = (struct if_msghdr *)buf;
sdl = (struct sockaddr_dl *)(ifm + 1);
ptr = (unsigned char *)LLADDR(sdl);
NSString *outstring = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",
*ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
free(buf);
return outstring;
}
You can also simply use @NonNull
with the lombok library instead, at least for the @NotNull
scenario. More details: https://projectlombok.org/api/lombok/NonNull.html
In Terminal:
nano ~/.bash_profile
Add lines:
export ANDROID_HOME=/YOUR_PATH_TO/android-sdk
export PATH=$ANDROID_HOME/platform-tools:$PATH
export PATH=$ANDROID_HOME/tools:$PATH
Check it worked:
source ~/.bash_profile
echo $ANDROID_HOME
Look at stat
for checking if the directory exists,
And mkdir
, to create a directory.
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
struct stat st = {0};
if (stat("/some/directory", &st) == -1) {
mkdir("/some/directory", 0700);
}
You can see the manual of these functions with the man 2 stat
and man 2 mkdir
commands.
In addition to the differences already noted, there's another extremely important difference that I just now discovered the hard way: unlike np.mean
, np.average
doesn't allow the dtype
keyword, which is essential for getting correct results in some cases. I have a very large single-precision array that is accessed from an h5
file. If I take the mean along axes 0 and 1, I get wildly incorrect results unless I specify dtype='float64'
:
>T.shape
(4096, 4096, 720)
>T.dtype
dtype('<f4')
m1 = np.average(T, axis=(0,1)) # garbage
m2 = np.mean(T, axis=(0,1)) # the same garbage
m3 = np.mean(T, axis=(0,1), dtype='float64') # correct results
Unfortunately, unless you know what to look for, you can't necessarily tell your results are wrong. I will never use np.average
again for this reason but will always use np.mean(.., dtype='float64')
on any large array. If I want a weighted average, I'll compute it explicitly using the product of the weight vector and the target array and then either np.sum
or np.mean
, as appropriate (with appropriate precision as well).
Google eventually came up with the answer. The syntax for string replacement in batch is this:
set v_myvar=replace me
set v_myvar=%v_myvar:ace=icate%
Which produces "replicate me". My script now looks like this:
@echo off
set v_params=%*
set v_params=%v_params:"=\"%
call bash -c "g++-linux-4.1 %v_params%"
Which replaces all instances of "
with \"
, properly escaped for bash.
When autocomplete changes a value, it fires a autocompletechange event, not the change event
$(document).ready(function () {
$('#tags').on('autocompletechange change', function () {
$('#tagsname').html('You selected: ' + this.value);
}).change();
});
Demo: Fiddle
Another solution is to use select event, because the change event is triggered only when the input is blurred
$(document).ready(function () {
$('#tags').on('change', function () {
$('#tagsname').html('You selected: ' + this.value);
}).change();
$('#tags').on('autocompleteselect', function (e, ui) {
$('#tagsname').html('You selected: ' + ui.item.value);
});
});
Demo: Fiddle
The solution that worked for me is as follows:
~\.VirtualBox\VirtualBox.xml
and ~\.VirtualBox\VirtualBox.xml-prev
.<HardDisks>...</HardDisks>
section to remove the duplicate entry of <HardDisk />
.Example:
<HardDisks>
<HardDisk uuid="{38f266bd-0959-4caf-a0de-27ac9d52e3663}" location="~/VirtualBox VMs/VM1/box-disk001.vmdk" format="VMDK" type="Normal"/>
<HardDisk uuid="{a6708d79-7393-4d96-89da-2539f75c5465e}" location="~/VirtualBox VMs/VM2/box-disk001.vmdk" format="VMDK" type="Normal"/>
<HardDisk uuid="{bdce5d4e-9a1c-4f57-acfd-e2acfc8920552}" location="~/VirtualBox VMs/VM2/box-disk001.vmdk" format="VMDK" type="Normal"/>
</HardDisks>
Note in the above fragment that the last two entries refer to the same VM but have different uuid's. One of them is invalid and should be removed. Which one is invalid can be found out by hit and trial -- first remove the second entry and try; if it doesn't work, remove the third entry.
Try this, it will convert True into 1 and False into 0:
data.frame$column.name.num <- as.numeric(data.frame$column.name)
Then you can convert into factor if you want:
data.frame$column.name.num.factor <- as .factor(data.frame$column.name.num)
This version
controls backtracking
/(["'])((?:(?!\1)[^\\]|(?:\\\\)*\\[^\\])*)\1/
Use -regex
:
From the man page:
-regex pattern
File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named './fubar3', you can use the
regular expression '.*bar.' or '.*b.*3', but not 'b.*r3'.
Also, I don't believe find
supports regex extensions such as \d
. You need to use [0-9]
.
find . -regex '.*test\.log\.[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]\.zip'
Thanks @Mark, I keep forgetting this again and again. After installing MongoDB with Homebrew:
A process consists of at least one thread (think of the main function). Multi threaded code will just spawn more threads. Mutexes are used to create locks around shared resources to avoid data corruption / unexpected / unwanted behaviour. Basically it provides for sequential execution in an asynchronous setup - the requirement for which stems from non-const non-atomic operations on shared data structures.
A vivid description of what mutexes would be the case of people (threads) queueing up to visit the restroom (shared resource). While one person (thread) is using the bathroom easing him/herself (non-const non-atomic operation), he/she should ensure the door is locked (mutex), otherwise it could lead to being caught in full monty (unwanted behaviour)
Surprised no one mentioned Illustrator's Save As > Format dropdown > .svg option.
Outputs an .svg file that contains the path (and the rest of the svg definition) within an .svg (xml) file.
The path itself is within <path d>
.
What about this solution? It does not rely on knowledge of @staticmethod
decorator implementation. Inner class StaticMethod plays as a container of static initialization functions.
class Klass(object):
class StaticMethod:
@staticmethod # use as decorator
def _stat_func():
return 42
_ANS = StaticMethod._stat_func() # call the staticmethod
def method(self):
ret = self.StaticMethod._stat_func() + Klass._ANS
return ret
5 years later-version:
Today, there are JS libraries for you, if you don't want to get into the nitty gritty of the different methods described on this page.
On of these is https://github.com/hubspot/offline. It checks for the connectivity of a pre-defined URI, by default your favicon. It automatically detects when the user's connectivity has been reestablished and provides neat events like up
and down
, which you can bind to in order to update your UI.
It should be noted that the documentation recommends using a Layout
rather than Canvas.drawText
directly. My full answer about using a StaticLayout
is here, but I will provide a summary below.
String text = "This is some text.";
TextPaint textPaint = new TextPaint();
textPaint.setAntiAlias(true);
textPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
textPaint.setColor(0xFF000000);
int width = (int) textPaint.measureText(text);
StaticLayout staticLayout = new StaticLayout(text, textPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
staticLayout.draw(canvas);
Here is a fuller example in the context of a custom view:
public class MyView extends View {
String mText = "This is some text.";
TextPaint mTextPaint;
StaticLayout mStaticLayout;
// use this constructor if creating MyView programmatically
public MyView(Context context) {
super(context);
initLabelView();
}
// this constructor is used when created from xml
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
initLabelView();
}
private void initLabelView() {
mTextPaint = new TextPaint();
mTextPaint.setAntiAlias(true);
mTextPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
mTextPaint.setColor(0xFF000000);
// default to a single line of text
int width = (int) mTextPaint.measureText(mText);
mStaticLayout = new StaticLayout(mText, mTextPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
// New API alternate
//
// StaticLayout.Builder builder = StaticLayout.Builder.obtain(mText, 0, mText.length(), mTextPaint, width)
// .setAlignment(Layout.Alignment.ALIGN_NORMAL)
// .setLineSpacing(1, 0) // multiplier, add
// .setIncludePad(false);
// mStaticLayout = builder.build();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// Tell the parent layout how big this view would like to be
// but still respect any requirements (measure specs) that are passed down.
// determine the width
int width;
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthRequirement = MeasureSpec.getSize(widthMeasureSpec);
if (widthMode == MeasureSpec.EXACTLY) {
width = widthRequirement;
} else {
width = mStaticLayout.getWidth() + getPaddingLeft() + getPaddingRight();
if (widthMode == MeasureSpec.AT_MOST) {
if (width > widthRequirement) {
width = widthRequirement;
// too long for a single line so relayout as multiline
mStaticLayout = new StaticLayout(mText, mTextPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
}
}
}
// determine the height
int height;
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightRequirement = MeasureSpec.getSize(heightMeasureSpec);
if (heightMode == MeasureSpec.EXACTLY) {
height = heightRequirement;
} else {
height = mStaticLayout.getHeight() + getPaddingTop() + getPaddingBottom();
if (heightMode == MeasureSpec.AT_MOST) {
height = Math.min(height, heightRequirement);
}
}
// Required call: set width and height
setMeasuredDimension(width, height);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// do as little as possible inside onDraw to improve performance
// draw the text on the canvas after adjusting for padding
canvas.save();
canvas.translate(getPaddingLeft(), getPaddingTop());
mStaticLayout.draw(canvas);
canvas.restore();
}
}
In my case the issue was caused by using a file path starting at the directory where the script was executing rather than at the root of the project.
My directory stucture was like this: projectfolder/ +-- package.json +-- scriptFolder/ ¦ +-- myScript.js
And I was calling fs.createReadStream('users.csv')
instead of the correct fs.createReadStream('scriptFolder/users.csv')
It may happen because that branch is not on your local. before merging use
git fetch origin
I was not satisfied, so I finally used this:
>>> a=numpy.array([[1,2,3],[4,5,6]])
>>> a
array([[1, 2, 3],
[4, 5, 6]])
>>> tuple(a.reshape(1, -1)[0])
(1, 2, 3, 4, 5, 6)
I don't know if it's quicker, but it looks more effective ;)
As an alternative to the other (very good) answers, you could cast to uintptr_t
or intptr_t
(from stdint.h
/inttypes.h
) and use the corresponding integer conversion specifiers. This would allow more flexibility in how the pointer is formatted, but strictly speaking an implementation is not required to provide these typedefs.
Check this out : readdir()
This bit of code should list all entries in a certain directory:
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
echo "$entry\n";
}
}
closedir($handle);
}
Edit: miah's solution is much more elegant than mine, you should use his solution instead.
If you use Spring you can use DataSourceInitializer
:
@Bean
public DataSourceInitializer dataSourceInitializer(@Qualifier("dataSource") final DataSource dataSource) {
ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
resourceDatabasePopulator.addScript(new ClassPathResource("/data.sql"));
DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
dataSourceInitializer.setDataSource(dataSource);
dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);
return dataSourceInitializer;
}
Used to set up a database during initialization and clean up a database during destruction.
numpy.linspace()
gives you a one-dimensional NumPy array. For example:
>>> my_array = numpy.linspace(1, 10, 10)
>>> my_array
array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
Therefore:
for index,point in my_array
cannot work. You would need some kind of two-dimensional array with two elements in the second dimension:
>>> two_d = numpy.array([[1, 2], [4, 5]])
>>> two_d
array([[1, 2], [4, 5]])
Now you can do this:
>>> for x, y in two_d:
print(x, y)
1 2
4 5
In case that you want combine a List of CompletableFutures, you can do this :
List<CompletableFuture<Void>> futures = new ArrayList<>();
// ... Add futures to this ArrayList of CompletableFutures
// CompletableFuture.allOf() method demand a variadic arguments
// You can use this syntax to pass a List instead
CompletableFuture<Void> allFutures = CompletableFuture.allOf(
futures.toArray(new CompletableFuture[futures.size()]));
// Wait for all individual CompletableFuture to complete
// All individual CompletableFutures are executed in parallel
allFutures.get();
For more details on Future & CompletableFuture, useful links:
1. Future: https://www.baeldung.com/java-future
2. CompletableFuture: https://www.baeldung.com/java-completablefuture
3. CompletableFuture: https://www.callicoder.com/java-8-completablefuture-tutorial/
I've just found the answer to this with some more exhaustive googling:
Melvyn Harbour has a thorough explanation of why MVC works with dates the way it does, and how you can override this if necessary:
http://weblogs.asp.net/melvynharbour/archive/2008/11/21/mvc-modelbinder-and-localization.aspx
When looking for the value to parse, the framework looks in a specific order namely:
- RouteData (not shown above)
- URI query string
- Request form
Only the last of these will be culture aware however. There is a very good reason for this, from a localization perspective. Imagine that I have written a web application showing airline flight information that I publish online. I look up flights on a certain date by clicking on a link for that day (perhaps something like http://www.melsflighttimes.com/Flights/2008-11-21), and then want to email that link to my colleague in the US. The only way that we could guarantee that we will both be looking at the same page of data is if the InvariantCulture is used. By contrast, if I'm using a form to book my flight, everything is happening in a tight cycle. The data can respect the CurrentCulture when it is written to the form, and so needs to respect it when coming back from the form.
Suppose you want to install Laravel Collective. It's currently at version 6.x but you want version 5.8. You can run the following command:
composer require "laravelcollective/html":"^5.8.0"
A good example is shown here in the documentation: https://laravelcollective.com/docs/5.5/html
Just wondering why you are using 2 directives?
It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.
Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).
It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.
Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.
Whenever one writes [A-Z]
or [a-z]
, one explicitly commits to
processing nothing but 7-bit ASCII data from the 1960s. If that’s
really ok, then fine. But if it’s not ok, then Unicode character
properties exist to help you with handling modern character data.
There are three cases in Unicode, not two. Furthermore, you also have
noncased letters. Letters in general are specified by the \pL
property,
and each of these also belongs to exactly one of five subcategories:
\p{Lu}
; eg: AÇ?ÞSSS??ST\p{Lt}
; eg: ??Ss?St
(actually Ss
and St
are an upper- and then a lowercase letter,
but they are what you get if you ask for the titlecase of ß and
?, respectively)\p{Ll}
; eg: aaç??sþß??\p{Lm}
; eg: ????"'???\p{Lo}
; eg: ?????You can take the complement of any of these, but do be careful, because
something like \P{Lu}
does not mean a letter that isn’t uppercase!
It means any character that isn’t an uppercase letter.
For a letter that’s either of uppercase or titlecase, use
[\p{Lu}\p{Lt}]
. So you could use for your pattern:
^([\p{Lu}\p{Lt}]\p{Ll}+)+$
If you don’t mean to limit the letters following the first to the “casing” letters alone, then you might prefer:
^([\p{Lu}\p{Lt}][\p{Ll}\p{Lm}\p{Lo}]+)+$
If you’re trying to match so-called “CamelCase” identifiers, then
the actual rules depend on the programming language, but usually include
the underscore character and the decimal numbers (\p{Nd}
), and may also
include a literal dollar sign and other language-dependent characters.
If so, you may wish to add some of these to one or the other of the two
character classes provided above.
For example, you may wish to add underscore to both but digits only to the second, leaving you with:
^([_\p{Lu}\p{Lt}][_\p{Nd}\p{Ll}\p{Lm}\p{Lo}]+)+$
If, though, you are dealing with certain “words” from various RFCs and ISO
standards, these are often specified as containing ASCII only. If so,
you can get by with the literal [A-Z]
idea. It’s just not kind to
impose that restriction if it doesn’t actually exist.
I have managed to achieve this using this XML code only. It might be the case that eclipse does not render the height to show it expanding to fit; however, when you actually run this on a device, it properly renders and provides the desired result. (well at least for me)
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="@drawable/whatever" />
</FrameLayout>
In Symfony 3.3 you can use
$projectRoot = $this->get('kernel')->getProjectDir();
to get the web/project root.
$('#videoLink').click(function () {_x000D_
var src = 'https://www.youtube.com/embed/VI04yNch1hU;autoplay=1';_x000D_
// $('#introVideo').modal('show'); <-- remove this line_x000D_
$('#introVideo iframe').attr('src', src);_x000D_
});_x000D_
_x000D_
$('#introVideo button.close').on('hidden.bs.modal', function () {_x000D_
$('#introVideo iframe').removeAttr('src');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet">_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>_x000D_
_x000D_
<!-- triggering Link -->_x000D_
<a id="videoLink" href="#0" class="video-hp" data-toggle="modal" data-target="#introVideo"><img src="img/someImage.jpg">toggle video</a>_x000D_
_x000D_
<!-- Intro video -->_x000D_
<div class="modal fade" id="introVideo" tabindex="-1" role="dialog" aria-labelledby="introductionVideo" aria-hidden="true">_x000D_
<div class="modal-dialog modal-lg">_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<div class="embed-responsive embed-responsive-16by9">_x000D_
<iframe class="embed-responsive-item allowfullscreen"></iframe>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
One way to do it is list the log for your branch and count the lines.
git log <branch_name> --oneline | wc -l
You can override the default css rules with this:
.table tbody tr > td.success {
background-color: #dff0d8 !important;
}
.table tbody tr > td.error {
background-color: #f2dede !important;
}
.table tbody tr > td.warning {
background-color: #fcf8e3 !important;
}
.table tbody tr > td.info {
background-color: #d9edf7 !important;
}
.table-hover tbody tr:hover > td.success {
background-color: #d0e9c6 !important;
}
.table-hover tbody tr:hover > td.error {
background-color: #ebcccc !important;
}
.table-hover tbody tr:hover > td.warning {
background-color: #faf2cc !important;
}
.table-hover tbody tr:hover > td.info {
background-color: #c4e3f3 !important;
}
!important
is needed as bootstrap actually colours the cells individually (afaik it's not possible to just apply background-color to a tr). I couldn't find any colour variables in my version of bootstrap but that's the basic idea anyway.
It can be like this
obj = model.objects.filter(id=emp_id)[0]
or
obj = model.objects.latest('id')
You could use a CURSOR in this case:
DECLARE @id INT
DECLARE @name NVARCHAR(100)
DECLARE @getid CURSOR
SET @getid = CURSOR FOR
SELECT table.id,
table.name
FROM table
OPEN @getid
FETCH NEXT
FROM @getid INTO @id, @name
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC stored_proc @varName=@id, @otherVarName='test', @varForName=@name
FETCH NEXT
FROM @getid INTO @id, @name
END
CLOSE @getid
DEALLOCATE @getid
Modified to show multiple parameters from the table.
https://developers.google.com/chrome-developer-tools/docs/settings
None of these solutions would work for us (other than disabling the schema checking altogether). In the end we had a miss-match in our version of Newtonsoft.json
Our AppConfig did not get updated correctly:
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
</dependentAssembly>
The solution was to correct the assembly version to the one we were actually deploying
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="10.0.0.0" />
</dependentAssembly>
You can also use the provided CLI tool mysqlcheck
to run the optimizations. It's got a ton of switches but at its most basic you just pass in the database, username, and password.
Adding this to cron or the Windows Scheduler can make this an automated process. (MariaDB but basically the same thing.)
As others already answered well, they both are interchangeable.
Nonetheless, it's worth mentioning that there could be a case where you may want to use the explicit statement, i.e. pointer != NULL
.
You can't define an object literal with a dynamic key. Do this :
var o = {};
o[key] = value;
return o;
There's no shortcut (edit: there's one now, with ES6, see the other answer).
For me using Select2.full.js Version 4.0.3 none of the above solutions was working the way it should be. So I wrote a combination of the solutions above. First of all I modified Select2.full.js to transfer the internal focus and blur events to jquery events as "Thomas Molnar" did in his answer.
EventRelay.prototype.bind = function (decorated, container, $container) {
var self = this;
var relayEvents = [
'open', 'opening',
'close', 'closing',
'select', 'selecting',
'unselect', 'unselecting',
'focus', 'blur'
];
And then I added the following code to handle focus and blur and focussing the next element
$("#myId").select2( ... ).one("select2:focus", select2Focus).on("select2:blur", function ()
{
var select2 = $(this).data('select2');
if (select2.isOpen() == false)
{
$(this).one("select2:focus", select2Focus);
}
}).on("select2:close", function ()
{
setTimeout(function ()
{
// Find the next element and set focus on it.
$(":focus").closest("tr").next("tr").find("select:visible,input:visible").focus();
}, 0);
});
function select2Focus()
{
var select2 = $(this).data('select2');
setTimeout(function() {
if (!select2.isOpen()) {
select2.open();
}
}, 0);
}
Use .valid()
from the jQuery Validation plugin:
$("#form_id").valid();
Checks whether the selected form is valid or whether all selected elements are valid. validate() needs to be called on the form before checking it using this method.
Where the form with id='form_id'
is a form that has already had .validate()
called on it.
My approach:
define a default constraint on the ModDate
column with a value of GETDATE()
- this handles the INSERT
case
have a AFTER UPDATE
trigger to update the ModDate
column
Something like:
CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
UPDATE dbo.TimeEntry
SET ModDate = GETDATE()
WHERE ID IN (SELECT DISTINCT ID FROM Inserted)
This error could be an indication that variable with the same name has been used in your code earlier, but for other purposes. Possibly, a variable has been given a name that coincides with the existing function used later in the code.
Use
onselectstart="return false"
it prevents copying your content.
This works for me and you don't need the inline script:
Javascript:
$(document).ready(function() {
$('.showme').bind('click', function() {
var id=$(this).attr("id");
var num=$(this).attr("class");
var poststr="request="+num+"&moreinfo="+id;
$.ajax({
url:"testme.php",
cache:0,
data:poststr,
success:function(result){
document.getElementById("stuff").innerHTML=result;
}
});
});
});
HTML:
<div class='request_1 showme' id='rating_1'>More stuff 1</div>
<div class='request_2 showme' id='rating_2'>More stuff 2</div>
<div class='request_3 showme' id='rating_3'>More stuff 3</div>
<div id="stuff">Here is some stuff that will update when the links above are clicked</div>
The request is sent to testme.php:
header("Cache-Control: no-cache");
header("Pragma: nocache");
$request_id = preg_replace("/[^0-9]/","",$_REQUEST['request']);
$request_moreinfo = preg_replace("/[^0-9]/","",$_REQUEST['moreinfo']);
if($request_id=="1")
{
echo "show 1";
}
elseif($request_id=="2")
{
echo "show 2";
}
else
{
echo "show 3";
}
REGEXP_COUNT should do the trick:
select REGEXP_COUNT('123-345-566', '-') from dual;
First of all check if the filename already exists, If yes then create a file and close it at the same time then append your text using AppendAllText
. For more info check the code below.
string FILE_NAME = "Log" + System.DateTime.Now.Ticks.ToString() + "." + "txt";
string str_Path = HostingEnvironment.ApplicationPhysicalPath + ("Log") + "\\" +FILE_NAME;
if (!File.Exists(str_Path))
{
File.Create(str_Path).Close();
File.AppendAllText(str_Path, jsonStream + Environment.NewLine);
}
else if (File.Exists(str_Path))
{
File.AppendAllText(str_Path, jsonStream + Environment.NewLine);
}
The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:
A data frame of four rows:
df = pd.DataFrame({'A': [1,2,3,4]})
Now trying to assign a list/array of two elements to it:
df['B'] = [3,4] # or df['B'] = np.array([3,4])
Both errors out:
ValueError: Length of values does not match length of index
Because the data frame has four rows but the list and array has only two elements.
Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:
df['B'] = pd.Series([3,4])
df
# A B
#0 1 3.0
#1 2 4.0
#2 3 NaN # NaN because the value at index 2 and 3 doesn't exist in the Series
#3 4 NaN
For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:
df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))
# A B
#0 1 1.0
#1 2 5.0
#2 7 9.0
#3 8 NaN
a= [2,3,4,5,6,2,3,2,4,2]
search=2
pos=0
positions=[]
while (search in a):
pos+=a.index(search)
positions.append(pos)
a=a[a.index(search)+1:]
pos+=1
print "search found at:",positions
Your quotes only need to surround the value part of the attribute-equals selector, [attr='val']
, like this:
$('a#check_var').click(function() {
alert($("input:radio[name='r']:checked").val()+ ' '+
$("input:radio[name='s']:checked").val());
});?
The accepted answer will also list the files that exist in both directories, but have different content. To list ONLY the files that exist in dir1 you can use:
diff -r dir1 dir2 | grep 'Only in' | grep dir1 | awk '{print $4}' > difference1.txt
Explanation:
You can also drag and drop "Execution Time" item from Built-in Fields list.
The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc
A set of simple examples:
Using Gson:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class Gson {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
com.google.gson.Gson gson = new com.google.gson.Gson();
Response respuesta = gson.fromJson(json, Response.class);
System.out.println(respuesta.getExample());
System.out.println(respuesta.getFr());
} catch (IOException ex) {
}
return null;
}
public class Response{
private String example;
private String fr;
public String getExample() {
return example;
}
public void setExample(String example) {
this.example = example;
}
public String getFr() {
return fr;
}
public void setFr(String fr) {
this.fr = fr;
}
}
}
Using json-simple:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonSimple {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
try {
JSONParser parser = new JSONParser();
Object resultObject = parser.parse(json);
if (resultObject instanceof JSONArray) {
JSONArray array=(JSONArray)resultObject;
for (Object object : array) {
JSONObject obj =(JSONObject)object;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
}else if (resultObject instanceof JSONObject) {
JSONObject obj =(JSONObject)resultObject;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
} catch (Exception e) {
// TODO: handle exception
}
} catch (IOException ex) {
}
return null;
}
}
etc...
There are no performance implications since the compiler will translate your lambda expression into an equivalent delegate. Lambda expressions are nothing more than a language feature that the compiler translates into the exact same code that you are used to working with.
The compiler will convert the code you have to something like this:
public partial class MyPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//snip
MyButton.Click += new EventHandler(delegate (Object o, EventArgs a)
{
//snip
});
}
}
You can escape shell metacharacters with ^
:
echo ^<?xml version="1.0" encoding="utf-8" ?^> > myfile.xml
Note that since echo
is a shell built-in it doesn't follow the usual conventions regarding quoting, so just quoting the argument will output the quotes instead of removing them.
@Mayur "4.2 [Using query with complex JOIN]" with Common Table Expressions (CTEs) did the trick for me.
WITH cte AS (
SELECT e.id, e.postcode
FROM employees e
LEFT JOIN locations lc ON lc.postcode=cte.postcode
WHERE e.id=1
)
UPDATE employee_location SET lat=lc.lat, longitude=lc.longi
FROM cte
WHERE employee_location.id=cte.id;
Hope this helps... :D
Use jline3:
Example:
Terminal terminal = TerminalBuilder.builder()
.jna(true)
.system(true)
.build();
// raw mode means we get keypresses rather than line buffered input
terminal.enterRawMode();
reader = terminal .reader();
...
int read = reader.read();
....
reader.close();
terminal.close();
f = open('{}.csv'.format(), 'wb')
Based on previous answers, here are reusable "procedures" and a usage example for calculating the elapsed time:
@echo off
setlocal
set starttime=%TIME%
echo Start Time: %starttime%
REM ---------------------------------------------
REM --- PUT THE CODE YOU WANT TO MEASURE HERE ---
REM ---------------------------------------------
set endtime=%TIME%
echo End Time: %endtime%
call :elapsed_time %starttime% %endtime% duration
echo Duration: %duration%
endlocal
echo on & goto :eof
REM --- HELPER PROCEDURES ---
:time_to_centiseconds
:: %~1 - time
:: %~2 - centiseconds output variable
setlocal
set _time=%~1
for /F "tokens=1-4 delims=:.," %%a in ("%_time%") do (
set /A "_result=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
)
endlocal & set %~2=%_result%
goto :eof
:centiseconds_to_time
:: %~1 - centiseconds
:: %~2 - time output variable
setlocal
set _centiseconds=%~1
rem now break the centiseconds down to hors, minutes, seconds and the remaining centiseconds
set /A _h=%_centiseconds% / 360000
set /A _m=(%_centiseconds% - %_h%*360000) / 6000
set /A _s=(%_centiseconds% - %_h%*360000 - %_m%*6000) / 100
set /A _hs=(%_centiseconds% - %_h%*360000 - %_m%*6000 - %_s%*100)
rem some formatting
if %_h% LSS 10 set _h=0%_h%
if %_m% LSS 10 set _m=0%_m%
if %_s% LSS 10 set _s=0%_s%
if %_hs% LSS 10 set _hs=0%_hs%
set _result=%_h%:%_m%:%_s%.%_hs%
endlocal & set %~2=%_result%
goto :eof
:elapsed_time
:: %~1 - time1 - start time
:: %~2 - time2 - end time
:: %~3 - elapsed time output
setlocal
set _time1=%~1
set _time2=%~2
call :time_to_centiseconds %_time1% _centi1
call :time_to_centiseconds %_time2% _centi2
set /A _duration=%_centi2%-%_centi1%
call :centiseconds_to_time %_duration% _result
endlocal & set %~3=%_result%
goto :eof
In your specific case, you can set the containing a
element to be:
a {
display: block;
text-align: center;
}
Interface is like an abstraction that is not providing any functionality. Hence It does not 'implement' but extend the other abstractions or interfaces.
obj1 != null
is the right way.
String defines IsNullOrEmpty
as a nicer way to say
obj1 == null || obj == String.Empty
so it does more than just check for nullity.
There may be other classes that define a method to check for a sematically "blank or null" object, but that would depend on the semantics of the class, and is by no means universal.
It's also possible to create extension method to do this kind of thing if it helps the readability of your code. For example, a similar approach to collections:
public static bool IsNullOrEmpty (this ICollection collection)
{
return collection == null || collection.Count == 0;
}
"/tmp/mysql.sock" will be created automatically when you start the MySQL server. So remember to do that before starting the rails server.
The parent div (I assume the outermost div) is display: block
and will fill up all available area of its container (in this case, the body) that it can. Use a different display type -- inline-block
is probably what you are going for:
Use the Get-ChildItem cmdlet with the -Recurse
switch:
Get-ChildItem -Path V:\Myfolder -Filter CopyForbuild.bat -Recurse -ErrorAction SilentlyContinue -Force
Some useful are:
Free:
Paid:
The best entries in my opinion are Flexigrid and jQuery Grid.
There was conflict in java version. Resolved after using 1.8 for maven.
Ambu,
I was having the same issue as you, and this is the code I used to figure it out. Although, I don't use the footer row section for my purposes, I did include it in this code.
DataTable dt = new DataTable();
// add the columns to the datatable
if (GridView1.HeaderRow != null)
{
for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
{
dt.Columns.Add(GridView1.HeaderRow.Cells[i].Text);
}
}
// add each of the data rows to the table
foreach (GridViewRow row in GridView1.Rows)
{
DataRow dr;
dr = dt.NewRow();
for (int i = 0; i < row.Cells.Count; i++)
{
dr[i] = row.Cells[i].Text.Replace(" ","");
}
dt.Rows.Add(dr);
}
// add the footer row to the table
if (GridView1.FooterRow != null)
{
DataRow dr;
dr = dt.NewRow();
for (int i = 0; i < GridView1.FooterRow.Cells.Count; i++)
{
dr[i] = GridView1.FooterRow.Cells[i].Text.Replace(" ","");
}
dt.Rows.Add(dr);
}
I'm assuming that by empty you mean "has no properties of its own".
// Speed up calls to hasOwnProperty
var hasOwnProperty = Object.prototype.hasOwnProperty;
function isEmpty(obj) {
// null and undefined are "empty"
if (obj == null) return true;
// Assume if it has a length property with a non-zero value
// that that property is correct.
if (obj.length > 0) return false;
if (obj.length === 0) return true;
// If it isn't an object at this point
// it is empty, but it can't be anything *but* empty
// Is it empty? Depends on your application.
if (typeof obj !== "object") return true;
// Otherwise, does it have any properties of its own?
// Note that this doesn't handle
// toString and valueOf enumeration bugs in IE < 9
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) return false;
}
return true;
}
Examples:
isEmpty(""), // true
isEmpty(33), // true (arguably could be a TypeError)
isEmpty([]), // true
isEmpty({}), // true
isEmpty({length: 0, custom_property: []}), // true
isEmpty("Hello"), // false
isEmpty([1,2,3]), // false
isEmpty({test: 1}), // false
isEmpty({length: 3, custom_property: [1,2,3]}) // false
If you only need to handle ECMAScript5 browsers, you can use Object.getOwnPropertyNames
instead of the hasOwnProperty
loop:
if (Object.getOwnPropertyNames(obj).length > 0) return false;
This will ensure that even if the object only has non-enumerable properties isEmpty
will still give you the correct results.
map
and filter
instead of list comprehensions.An objective reason why you should prefer them even though they're not "Pythonic" is this:
They require functions/lambdas as arguments, which introduce a new scope.
I've gotten bitten by this more than once:
for x, y in somePoints:
# (several lines of code here)
squared = [x ** 2 for x in numbers]
# Oops, x was silently overwritten!
but if instead I had said:
for x, y in somePoints:
# (several lines of code here)
squared = map(lambda x: x ** 2, numbers)
then everything would've been fine.
You could say I was being silly for using the same variable name in the same scope.
I wasn't. The code was fine originally -- the two x
s weren't in the same scope.
It was only after I moved the inner block to a different section of the code that the problem came up (read: problem during maintenance, not development), and I didn't expect it.
Yes, if you never make this mistake then list comprehensions are more elegant.
But from personal experience (and from seeing others make the same mistake) I've seen it happen enough times that I think it's not worth the pain you have to go through when these bugs creep into your code.
Use map
and filter
. They prevent subtle hard-to-diagnose scope-related bugs.
Don't forget to consider using imap
and ifilter
(in itertools
) if they are appropriate for your situation!
sys.argv
represents the command line options you execute a script with.
sys.argv[0]
is the name of the script you are running. All additional options are contained in sys.argv[1:]
.
You are attempting to open a file that uses sys.argv[1]
(the first argument) as what looks to be the directory.
Try running something like this:
python ConcatenateFiles.py /tmp
Nick's solutuion can be simplified more, with nothing fancy, you would only need a single converter:
[ValueConversion(typeof(Enum), typeof(IEnumerable<Enum>))]
public class EnumToCollectionConverter : MarkupExtension, IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var r = Enum.GetValues(value.GetType());
return r;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
}
You then use this wherever you want your combo box to appear:
<ComboBox ItemsSource="{Binding PagePosition, Converter={converter:EnumToCollectionConverter}, Mode=OneTime}" SelectedItem="{Binding PagePosition}" />
Find the source code from github for credit card validiations , it will work 100%
JSON.parse()
function will do.
or
Using Jquery,
var obj = jQuery.parseJSON( '{ "name": "Vinod" }' );
alert( obj.name === "Vinod" );
You can do that but the changes will affect for new data that is inserted on the database. On the long run follow as suggested above.
Also there are certain tricks you can override the collation, such as parameters for stored procedures or functions, alias data types, and variables are assigned the default collation of the database. To change the collation of an alias type, you must drop the alias and re-create it.
You can override the default collation of a literal string by using the COLLATE clause. If you do not specify a collation, the literal is assigned the database default collation. You can use DATABASEPROPERTYEX to find the current collation of the database.
You can override the server, database, or column collation by specifying a collation in the ORDER BY clause of a SELECT statement.
Just add this to config
<system.net>
<defaultProxy useDefaultCredentials="true" >
</defaultProxy>
</system.net>
I don't have code for this, however it could be abstracted in 10 lines or less. Make the mouse draw a box .. however you move it. when you click (left) the box vanishes, when you click (right) the box changes color.
Students want something practical, something they can hack and customize, something that says this "is not your typical boring class".
Xen's mini-os kernel does this now, but it would require additional abstraction to fit your needs.
You could also try plotting a manderbolt (julia) set while getting the paramaters of the quadratic plane from ambient noise (if the machines have a microphone and sound card) .. their voice generates a fractal. Again, its going to be tricky to do this in 10 lines (in the actual function they edit), but not impossible.
In the real world, you are going to use existing libraries. So I think, 10 lines in main() (or whatever language you use) is more practical. We make what exists work for us, while writing what does not exist or does not work for us. You may as well introduce that concept at the beginning.
Also, lines? int main(void) { unsigned int i; for (i=0; i < 10; i++); return 0; } Perhaps, 10 function calls would be a more realistic goal? This is not an obfuscated code contest.
Good luck!
If you are looking to add or remove class accordingly if the url contains certain params or not .This is what you can do
<a th:href="@{/admin/home}" th:class="${#httpServletRequest.requestURI.contains('home')} ? 'nav-link active' : 'nav-link'" >
If the url contains 'home' then active class will be added and vice versa.
That is a binary operator in hibernate you should use
is not null
Have a look at 14.10. Expressions
Its another way to declare the constructor. You can also use the class name, for ex:
class Cat
{
function Cat()
{
echo 'meow';
}
}
and
class Cat
{
function __construct()
{
echo 'meow';
}
}
Are equivalent. They are called whenever a new instance of the class is created, in this case, they will be called with this line:
$cat = new Cat();
You should learn about EAFP vs LBYL.
from sys import stdin, stdout
def main(infile=stdin, outfile=stdout):
if isinstance(infile, basestring):
infile=open(infile,'r')
if isinstance(outfile, basestring):
outfile=open(outfile,'w')
for lineno, line in enumerate(infile, 1):
line = line.strip()
try:
print >>outfile, int(line,16)
except ValueError:
return "Bad value at line %i: %r" % (lineno, line)
if __name__ == "__main__":
from sys import argv, exit
exit(main(*argv[1:]))
You are exceeding the SQL limit of 4000 bytes which applies to LISTAGG
as well.
SQL> SELECT listagg(text, ',') WITHIN GROUP (
2 ORDER BY NULL)
3 FROM
4 (SELECT to_char(to_date(level,'j'), 'jsp') text FROM dual CONNECT BY LEVEL < 250
5 )
6 /
SELECT listagg(text, ',') WITHIN GROUP (
*
ERROR at line 1:
ORA-01489: result of string concatenation is too long
As a workaround, you could use XMLAGG.
For example,
SQL> SET LONG 2000000
SQL> SET pagesize 50000
SQL> SELECT rtrim(xmlagg(XMLELEMENT(e,text,',').EXTRACT('//text()')
2 ).GetClobVal(),',') very_long_text
3 FROM
4 (SELECT to_char(to_date(level,'j'), 'jsp') text FROM dual CONNECT BY LEVEL < 250
5 )
6 /
VERY_LONG_TEXT
--------------------------------------------------------------------------------
one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thirteen,fourteen
,fifteen,sixteen,seventeen,eighteen,nineteen,twenty,twenty-one,twenty-two,twenty
-three,twenty-four,twenty-five,twenty-six,twenty-seven,twenty-eight,twenty-nine,
thirty,thirty-one,thirty-two,thirty-three,thirty-four,thirty-five,thirty-six,thi
rty-seven,thirty-eight,thirty-nine,forty,forty-one,forty-two,forty-three,forty-f
our,forty-five,forty-six,forty-seven,forty-eight,forty-nine,fifty,fifty-one,fift
y-two,fifty-three,fifty-four,fifty-five,fifty-six,fifty-seven,fifty-eight,fifty-
nine,sixty,sixty-one,sixty-two,sixty-three,sixty-four,sixty-five,sixty-six,sixty
-seven,sixty-eight,sixty-nine,seventy,seventy-one,seventy-two,seventy-three,seve
nty-four,seventy-five,seventy-six,seventy-seven,seventy-eight,seventy-nine,eight
y,eighty-one,eighty-two,eighty-three,eighty-four,eighty-five,eighty-six,eighty-s
even,eighty-eight,eighty-nine,ninety,ninety-one,ninety-two,ninety-three,ninety-f
our,ninety-five,ninety-six,ninety-seven,ninety-eight,ninety-nine,one hundred,one
hundred one,one hundred two,one hundred three,one hundred four,one hundred five
,one hundred six,one hundred seven,one hundred eight,one hundred nine,one hundre
d ten,one hundred eleven,one hundred twelve,one hundred thirteen,one hundred fou
rteen,one hundred fifteen,one hundred sixteen,one hundred seventeen,one hundred
eighteen,one hundred nineteen,one hundred twenty,one hundred twenty-one,one hund
red twenty-two,one hundred twenty-three,one hundred twenty-four,one hundred twen
ty-five,one hundred twenty-six,one hundred twenty-seven,one hundred twenty-eight
,one hundred twenty-nine,one hundred thirty,one hundred thirty-one,one hundred t
hirty-two,one hundred thirty-three,one hundred thirty-four,one hundred thirty-fi
ve,one hundred thirty-six,one hundred thirty-seven,one hundred thirty-eight,one
hundred thirty-nine,one hundred forty,one hundred forty-one,one hundred forty-tw
o,one hundred forty-three,one hundred forty-four,one hundred forty-five,one hund
red forty-six,one hundred forty-seven,one hundred forty-eight,one hundred forty-
nine,one hundred fifty,one hundred fifty-one,one hundred fifty-two,one hundred f
ifty-three,one hundred fifty-four,one hundred fifty-five,one hundred fifty-six,o
ne hundred fifty-seven,one hundred fifty-eight,one hundred fifty-nine,one hundre
d sixty,one hundred sixty-one,one hundred sixty-two,one hundred sixty-three,one
hundred sixty-four,one hundred sixty-five,one hundred sixty-six,one hundred sixt
y-seven,one hundred sixty-eight,one hundred sixty-nine,one hundred seventy,one h
undred seventy-one,one hundred seventy-two,one hundred seventy-three,one hundred
seventy-four,one hundred seventy-five,one hundred seventy-six,one hundred seven
ty-seven,one hundred seventy-eight,one hundred seventy-nine,one hundred eighty,o
ne hundred eighty-one,one hundred eighty-two,one hundred eighty-three,one hundre
d eighty-four,one hundred eighty-five,one hundred eighty-six,one hundred eighty-
seven,one hundred eighty-eight,one hundred eighty-nine,one hundred ninety,one hu
ndred ninety-one,one hundred ninety-two,one hundred ninety-three,one hundred nin
ety-four,one hundred ninety-five,one hundred ninety-six,one hundred ninety-seven
,one hundred ninety-eight,one hundred ninety-nine,two hundred,two hundred one,tw
o hundred two,two hundred three,two hundred four,two hundred five,two hundred si
x,two hundred seven,two hundred eight,two hundred nine,two hundred ten,two hundr
ed eleven,two hundred twelve,two hundred thirteen,two hundred fourteen,two hundr
ed fifteen,two hundred sixteen,two hundred seventeen,two hundred eighteen,two hu
ndred nineteen,two hundred twenty,two hundred twenty-one,two hundred twenty-two,
two hundred twenty-three,two hundred twenty-four,two hundred twenty-five,two hun
dred twenty-six,two hundred twenty-seven,two hundred twenty-eight,two hundred tw
enty-nine,two hundred thirty,two hundred thirty-one,two hundred thirty-two,two h
undred thirty-three,two hundred thirty-four,two hundred thirty-five,two hundred
thirty-six,two hundred thirty-seven,two hundred thirty-eight,two hundred thirty-
nine,two hundred forty,two hundred forty-one,two hundred forty-two,two hundred f
orty-three,two hundred forty-four,two hundred forty-five,two hundred forty-six,t
wo hundred forty-seven,two hundred forty-eight,two hundred forty-nine
If you want to concatenate multiple columns which itself have 4000 bytes, then you can concatenate the XMLAGG output of each column to avoid the SQL limit of 4000 bytes.
For example,
WITH DATA AS
( SELECT 1 id, rpad('a1',4000,'*') col1, rpad('b1',4000,'*') col2 FROM dual
UNION
SELECT 2 id, rpad('a2',4000,'*') col1, rpad('b2',4000,'*') col2 FROM dual
)
SELECT ID,
rtrim(xmlagg(XMLELEMENT(e,col1,',').EXTRACT('//text()') ).GetClobVal(), ',')
||
rtrim(xmlagg(XMLELEMENT(e,col2,',').EXTRACT('//text()') ).GetClobVal(), ',')
AS very_long_text
FROM DATA
GROUP BY ID
ORDER BY ID;
In your last example:
var latestCust = db.Customers
.OrderByDescending(x=> x.CreatedOn)
.FirstOrDefault();//Single or First, or doesn't matter?
Yes it does. If you try to use SingleOrDefault()
and the query results in more than record you would get and exception. The only time you can safely use SingleOrDefault()
is when you are expecting only 1 and only 1 result...
In my case, I was looping through a series of objects from an XML file, but some of the instances apparently were not objects which was causing the error. Checking if the object was empty before processing it fixed the problem.
In other words, without checking if the object was empty, the script would error out on any empty object with the error as given below.
Trying to get property of non-object
For Example:
if (!empty($this->xml_data->thing1->thing2))
{
foreach ($this->xml_data->thing1->thing2 as $thing)
{
}
}
This indicates the linux has delivered a SIGTERM
to your process. This is usually at the request of some other process (via kill()
) but could also be sent by your process to itself (using raise()
). This signal requests an orderly shutdown of your process.
If you need a quick cheatsheet of signal numbers, open a bash shell and:
$ kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL
5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE
9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH
29) SIGIO 30) SIGPWR 31) SIGSYS 34) SIGRTMIN
35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4
39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8
43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6
59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
63) SIGRTMAX-1 64) SIGRTMAX
You can determine the sender by using an appropriate signal handler like:
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
void sigterm_handler(int signal, siginfo_t *info, void *_unused)
{
fprintf(stderr, "Received SIGTERM from process with pid = %u\n",
info->si_pid);
exit(0);
}
int main (void)
{
struct sigaction action = {
.sa_handler = NULL,
.sa_sigaction = sigterm_handler,
.sa_mask = 0,
.sa_flags = SA_SIGINFO,
.sa_restorer = NULL
};
sigaction(SIGTERM, &action, NULL);
sleep(60);
return 0;
}
Notice that the signal handler also includes a call to exit()
. It's also possible for your program to continue to execute by ignoring the signal, but this isn't recommended in general (if it's a user doing it there's a good chance it will be followed by a SIGKILL if your process doesn't exit, and you lost your opportunity to do any cleanup then).
From the jQuery documentation - http://api.jquery.com/jQuery.ajax/
contentType When sending data to the server, use this content type.
dataType The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response
"text": A plain text string.
So you want contentType to be application/json
and dataType to be text
:
$.ajax({
type : "POST",
url : /v1/user,
dataType : "text",
contentType: "application/json",
data : dataAttribute,
success : function() {
},
error : function(error) {
}
});
Adding screen shots(examples) and some more context for the answer of @Thomas G.
import pandas as pd
is ran properly before checking below shortcut.Place the cursor in middle of parenthesis ()
before you use shortcut.
shift + tab
Display short document and few params
shift + tab + tab
Expands document with scroll bar
shift + tab + tab + tab
Provides document with a Tooltip: "will linger for 10secs while you type". which means it allows you write params and waits for 10secs.
shift + tab + tab + tab + tab
It opens a small window in bottom with option(top righ corner of small window) to open full documentation in new browser tab.
For example for ClickCell Event in Windows Forms.
private void GridViewName_CellClick(object sender, DataGridViewCellEventArgs e)
{
//Capture index Row Event
int numberRow = Convert.ToInt32(e.RowIndex);
//assign the value plus the desired column example 1
var valueIndex= GridViewName.Rows[numberRow ].Cells[1].Value;
MessageBox.Show("ID: " +valueIndex);
}
Regards :)
It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.
Edit: This is what the forums say:
By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.
To disable:
/system/bin/bugmailer.sh must be deleted/renamed.
There should be a folder on your SD card called "bug reports".
Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948
And this one: http://forum.xda-developers.com/showthread.php?t=1405639
# This program reads columns in a csv file
import csv
ifile = open('years.csv', "r")
reader = csv.reader(ifile)
# initialization and declaration of variables
rownum = 0
year = 0
dec = 0
jan = 0
total_years = 0`
for row in reader:
if rownum == 0:
header = row #work with header row if you like
else:
colnum = 0
for col in row:
if colnum == 0:
year = float(col)
if colnum == 1:
dec = float(col)
if colnum == 2:
jan = float(col)
colnum += 1
# end of if structure
# now we can process results
if rownum != 0:
print(year, dec, jan)
total_years = total_years + year
print(total_years)
# time to go after the next row/bar
rownum += 1
ifile.close()
A bit late but nonetheless... You need to create and identify the csv file named "years.csv":
Year Dec Jan 1 50 60 2 25 50 3 30 30 4 40 20 5 10 10
The problem is that .NET will always round a double
to 15 significant decimal digits before applying your formatting, regardless of the precision requested by your format and regardless of the exact decimal value of the binary number.
I'd guess that the Visual Studio debugger has its own format/display routines that directly access the internal binary number, hence the discrepancies between your C# code, your C code and the debugger.
There's nothing built-in that will allow you to access the exact decimal value of a double
, or to enable you to format a double
to a specific number of decimal places, but you could do this yourself by picking apart the internal binary number and rebuilding it as a string representation of the decimal value.
Alternatively, you could use Jon Skeet's DoubleConverter
class (linked to from his "Binary floating point and .NET" article). This has a ToExactString
method which returns the exact decimal value of a double
. You could easily modify this to enable rounding of the output to a specific precision.
double i = 10 * 0.69;
Console.WriteLine(DoubleConverter.ToExactString(i));
Console.WriteLine(DoubleConverter.ToExactString(6.9 - i));
Console.WriteLine(DoubleConverter.ToExactString(6.9));
// 6.89999999999999946709294817992486059665679931640625
// 0.00000000000000088817841970012523233890533447265625
// 6.9000000000000003552713678800500929355621337890625
right-click the view in the object-explorer, select "script view as...", then "create to" and then "new query editor window"
the @Alt-Cat answer work for me!
R.attr.borderlessButtonStyle doesn't contain shadow.
and the document of button is great.
Also, you can set this style on your custom button, in second constructor.
public CustomButton(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.borderlessButtonStyle);
}
itemgetter()
is somewhat faster than lambda tup: tup[1]
, but the increase is relatively modest (around 10 to 25 percent).
(IPython session)
>>> from operator import itemgetter
>>> from numpy.random import randint
>>> values = randint(0, 9, 30000).reshape((10000,3))
>>> tpls = [tuple(values[i,:]) for i in range(len(values))]
>>> tpls[:5] # display sample from list
[(1, 0, 0),
(8, 5, 5),
(5, 4, 0),
(5, 7, 7),
(4, 2, 1)]
>>> sorted(tpls[:5], key=itemgetter(1)) # example sort
[(1, 0, 0),
(4, 2, 1),
(5, 4, 0),
(8, 5, 5),
(5, 7, 7)]
>>> %timeit sorted(tpls, key=itemgetter(1))
100 loops, best of 3: 4.89 ms per loop
>>> %timeit sorted(tpls, key=lambda tup: tup[1])
100 loops, best of 3: 6.39 ms per loop
>>> %timeit sorted(tpls, key=(itemgetter(1,0)))
100 loops, best of 3: 16.1 ms per loop
>>> %timeit sorted(tpls, key=lambda tup: (tup[1], tup[0]))
100 loops, best of 3: 17.1 ms per loop
It's not about a plugin. It's about prompt tricks in the shell.
For a cool setup in bash, check out the dotfiles
project of this guy:
https://github.com/mathiasbynens/dotfiles
To get a fancy prompt, include the .bash_prompt
in your ~/.bash_profile
or ~/.bashrc
.
To get the exact same prompt as in your question, change the export PS1
line at the end of .bash_prompt
like this:
export PS1="\[${BOLD}${MAGENTA}\]\u\[$WHITE\]@\[$ORANGE\]\h\[$WHITE\]: [\[$GREEN\]\w\[$WHITE\]\$([[ -n \$(git branch 2> /dev/null) ]] && echo \" - \")\[$PURPLE\]\$(parse_git_branch)\[$WHITE\]] \$ \[$RESET\]"
I ended up using all the .bash*
files from this repository about a month ago, and it's been really useful for me.
For Git, there are extra goodies in .gitconfig
.
And since you're a mac user, there are even more goodies in .osx
.
As others have noted, "SKU" stands for stock keeping unit. Here's what I find currently (3 February 2017) in the Apple documentation regarding the "SKU Number:"
SKU Number
A unique ID for your app in the Apple system that is not seen by users. You can use letters, numbers, hyphens, periods, and underscores. The SKU can’t
start with a hyphen, period, or underscore. Use a value that is meaningful to your organization. Can’t be edited after saving the iTunes Connect record.
(internet archive link:) iTunes Connect Properties
@Alan's answer will do what you're looking for, but this solution fails when you use the responsive capabilities of Bootstrap. In your case, you're using the xs
sizes so you won't notice, but if you used anything else (e.g. col-sm
, col-md
, etc), you'd understand.
Another approach is to play with margins and padding. See the updated fiddle: http://jsfiddle.net/jz8j247x/1/
.left-side {
background-color: blue;
padding-bottom: 1000px;
margin-bottom: -1000px;
height: 100%;
}
.something {
height: 100%;
background-color: red;
padding-bottom: 1000px;
margin-bottom: -1000px;
height: 100%;
}
.row {
background-color: green;
overflow: hidden;
}
Simple solution to this problem, working on iOS7 as well as 6, is to set custom title view in viewDidLoad:
- (void)viewDidLoad {
[super viewDidLoad];
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
titleLabel.text = self.title;
titleLabel.backgroundColor = [UIColor clearColor];
[titleLabel sizeToFit];
self.navigationItem.titleView = titleLabel;
}
Then, in viewWillAppear: you can safely call
self.navigationController.navigationBar.topItem.title = @" ";
Because your title view is custom view, it won't get overwritten when moving back in the navigation stack.
The problem is how you've attached the listener:
<input type="checkbox" ... onchange="doalert(this.id)">
Inline listeners are effectively wrapped in a function which is called with the element as this. That function then calls the doalert function, but doesn't set its this so it will default to the global object (window in a browser).
Since the window object doesn't have a checked property, this.checked
always resolves to false.
If you want this within doalert to be the element, attach the listener using addEventListener:
window.onload = function() {
var input = document.querySelector('#g01-01');
if (input) {
input.addEventListener('change', doalert, false);
}
}
Or if you wish to use an inline listener:
<input type="checkbox" ... onchange="doalert.call(this, this.id)">
On the command line, enter
whoami
or
echo "$USER"
To save these values to a variable, do
myvariable=$(whoami)
or
myvariable=$USER
Of course, you don't need to make a variable since that is what the $USER
variable is for.
I tried various method it didn't work.But this worked.Hope it will work for you as well. The file/directory must be at this locations:
projec/your_app/templates project/your_app/static
import os
PROJECT_DIR = os.path.realpath(os.path.dirname(_____file_____))
STATIC_ROOT = '/your_path/static/'
example:
STATIC_ROOT = '/home/project_name/your_app/static/'
STATIC_URL = '/static/'
STATICFILES_DIRS =(
PROJECT_DIR+'/static',
##//don.t forget comma
)
TEMPLATE_DIRS = (
PROJECT_DIR+'/templates/',
)
inside body
{% load staticfiles %}
//for image
img src="{% static "fb.png" %}" alt="image here"
//note that fb.png is at /home/project/app/static/fb.png
If fb.png was inside /home/project/app/static/image/fb.png then
img src="{% static "images/fb.png" %}" alt="image here"
I got this error recently by introducing an old plugin to wordpress. It loaded an older version of jquery, which happened to be placed before the jquery mouse file. There was no jquery widget file loaded with the second version, which caused the error.
No error for using the extra jquery library -- that's a problem especially if a silent fail might have happened, causing a not so silent fail later on.
A potential way around it for wordpress might be to be explicit about the dependencies that way the jquery mouse would follow the widget which would follow the correct core leaving the other jquery to be loaded afterwards. Still might cause a production error later if you don't catch that and change the default function for jquery for the second version in all the files associated with it.
You need use Stream to send file (archive) in a response, what is more you have to use appropriate Content-type in your response header.
There is an example function that do it:
const fs = require('fs');
// Where fileName is name of the file and response is Node.js Reponse.
responseFile = (fileName, response) => {
const filePath = "/path/to/archive.rar" // or any file format
// Check if file specified by the filePath exists
fs.exists(filePath, function(exists){
if (exists) {
// Content-type is very interesting part that guarantee that
// Web browser will handle response in an appropriate manner.
response.writeHead(200, {
"Content-Type": "application/octet-stream",
"Content-Disposition": "attachment; filename=" + fileName
});
fs.createReadStream(filePath).pipe(response);
} else {
response.writeHead(400, {"Content-Type": "text/plain"});
response.end("ERROR File does not exist");
}
});
}
}
The purpose of the Content-Type field is to describe the data contained in the body fully enough that the receiving user agent can pick an appropriate agent or mechanism to present the data to the user, or otherwise deal with the data in an appropriate manner.
"application/octet-stream" is defined as "arbitrary binary data" in RFC 2046, purpose of this content-type is to be saved to disk - it is what you really need.
"filename=[name of file]" specifies name of file which will be downloaded.
For more information please see this stackoverflow topic.
If you're a bad person (I'm a bad person.), you can get as simple as this: (->@)()
As in,
(->@)().im_a_terrible_programmer = yes
console.log im_a_terrible_programmer
This works, because when invoking a Reference
to a Function
‘bare’ (that is, func()
, instead of new func()
or obj.func()
), something commonly referred to as the ‘function-call invocation pattern’, always binds this
to the global object for that execution context.
The CoffeeScript above simply compiles to (function(){ return this })()
; so we're exercising that behavior to reliably access the global object.
This SQL query gives output similar to \dx
:
SELECT e.extname AS "Name", e.extversion AS "Version", n.nspname AS "Schema", c.description AS "Description"
FROM pg_catalog.pg_extension e
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace
LEFT JOIN pg_catalog.pg_description c ON c.objoid = e.oid AND c.classoid = 'pg_catalog.pg_extension'::pg_catalog.regclass
ORDER BY 1;
Thanks to https://blog.dbi-services.com/listing-the-extensions-available-in-postgresql/
This might work for you (GNU sed):
sed -ne '16224,16482w newfile' -e '16482q' file
or taking advantage of bash:
sed -n $'16224,16482w newfile\n16482q' file
Starting with ElasticSearch 7.4, the best method to rename an index is to copy the index using the newly introduced Clone Index API, then to delete the original index using the Delete Index API.
The main advantage of the Clone Index API over the use of the Snapshot API or the Reindex API for the same purpose is speed, since the Clone Index API hardlinks segments from the source index to the target index, without reprocessing any of its content (on filesystems that support hardlinks, obviously; otherwise, files are copied at the file system level, which is still much more efficient that the alternatives). Clone Index also guarantee that the target index is identical in every point to the source index (that is, there is no need to manually copy settings and mappings, contrary to the Reindex approach), and doesn't require a local snapshot directory be configured.
Side note: even though this procedure is much faster than previous solutions, it still implies down time. There are real use cases that justify renaming indices (for example, as a step in a split, shrink or backup workflow), but renaming indices should not be part of day-to-day operations. If your workflow requires frequent index renaming, then you should consider using Indices Aliases instead.
Here is an example of a complete sequence of operations to rename index source_index
to target_index
. It can be executed using some ElasticSearch specific console, such as the one integrated in Kibana. See this gist for an alternative version of this example, using curl
instead of an Elastic Search console.
# Make sure the source index is actually open
POST /source_index/_open
# Put the source index in read-only mode
PUT /source_index/_settings
{
"settings": {
"index.blocks.write": "true"
}
}
# Clone the source index to the target name, and set the target to read-write mode
POST /source_index/_clone/target_index
{
"settings": {
"index.blocks.write": null
}
}
# Wait until the target index is green;
# it should usually be fast (assuming your filesystem supports hard links).
GET /_cluster/health/target_index?wait_for_status=green&timeout=30s
# If it appears to be taking too much time for the cluster to get back to green,
# the following requests might help you identify eventual outstanding issues (if any)
GET /_cat/indices/target_index
GET /_cat/recovery/target_index
GET /_cluster/allocation/explain
# Delete the source index
DELETE /source_index
When using HTTPS instead of ON the binding, put it IN the binding with the httpsTransport
tag:
<binding name="MyServiceBinding">
<security defaultAlgorithmSuite="Basic256Rsa15"
authenticationMode="MutualCertificate" requireDerivedKeys="true"
securityHeaderLayout="Lax" includeTimestamp="true"
messageProtectionOrder="SignBeforeEncrypt"
messageSecurityVersion="WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10"
requireSignatureConfirmation="false">
<localClientSettings detectReplays="true" />
<localServiceSettings detectReplays="true" />
<secureConversationBootstrap keyEntropyMode="CombinedEntropy" />
</security>
<textMessageEncoding messageVersion="Soap11WSAddressing10">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647"
maxArrayLength="2147483647" maxBytesPerRead="4096"
maxNameTableCharCount="16384"/>
</textMessageEncoding>
<httpsTransport maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647" maxBufferPoolSize="2147483647"
requireClientCertificate="false" />
</binding>
Just a reminder: Implicit type var
in multiple declaration is not allowed. There might be the following compilation errors.
var Foo = 0, Bar = 0;
Implicitly-typed variables cannot have multiple declarators
Similarly,
var Foo, Bar;
Implicitly-typed variables must be initialized
Set the second function parameter to true if you require an associative array
Some versions of php require a 2nd paramter of true if you require an associative array
$json = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';
$array = json_decode( $json, true );
Surfing the web, you will find many technical justifications for Quadro price. Real answer is in "demand for reliable and task specific graphic cards".
Imagine you have an architectural firm with many fat projects on deadline. Your computers are only used in working with one specific CAD software. If foundation of your business is supposed to rely on these computers, you would want to make sure this foundation is strong.
For such clients, Nvidia engineered cards like Quadro, providing what they call "Professional Solution". And if you are among the targeted clients, you would really appreciate reliability of these graphic cards.
Many believe Geforce have become powerful and reliable enough to take Quadro's place. But in the end, it depends on the software you are mostly going to use and importance of reliability in what you do.
countDecimals = value => {
if (Math.floor(value) === value) return 0;
let stringValue = value.toString().split(".")[1];
if (stringValue) {
return value.toString().split(".")[1].length
? value.toString().split(".")[1].length
: 0;
} else {
return 0;
}
};
formatNumber=(ans)=>{
let decimalPlaces = this.countDecimals(ans);
ans = 1 * ans;
if (decimalPlaces !== 0) {
let onePlusAns = ans + 1;
let decimalOnePlus = this.countDecimals(onePlusAns);
if (decimalOnePlus < decimalPlaces) {
ans = ans.toFixed(decimalPlaces - 1).replace(/\.?0*$/, "");
} else {
let tenMulAns = ans * 10;
let decimalTenMul = this.countDecimals(tenMulAns);
if (decimalTenMul + 1 < decimalPlaces) {
ans = ans.toFixed(decimalPlaces - 1).replace(/\.?0*$/, "");
}
}
}
}
_x000D_
I just add 1 to the value and count the decimal digits present in the original value and the added value. If I find the decimal digits after adding one less than the original decimal digits, I just call the toFixed() with (original decimals - 1). I also check by multiplying the original value by 10 and follow the same logic in case adding one doesn't reduce redundant decimal places. A simple workaround to handle floating-point number rounding in JS. Works in most cases I tried.
As ibram stated, add the manifest thru solution explorer:
This creates a default manifest. Now, edit the manifest.
It is usually not recommended to call flush explicitly unless it is necessary. Hibernate usually auto calls Flush at the end of the transaction and we should let it do it's work. Now, there are some cases where you might need to explicitly call flush where a second task depends upon the result of the first Persistence task, both being inside the same transaction.
For example, you might need to persist a new Entity and then use the Id of that Entity to do some other task inside the same transaction, on that case it's required to explicitly flush the entity first.
@Transactional
void someServiceMethod(Entity entity){
em.persist(entity);
em.flush() //need to explicitly flush in order to use id in next statement
doSomeThingElse(entity.getId());
}
Also Note that, explicitly flushing does not cause a database commit, a database commit is done only at the end of a transaction, so if any Runtime error occurs after calling flush the changes would still Rollback.
You should follow the guidelines on Add a secondary horizontal axis:
To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.
Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.
On the Layout tab, in the Axes group, click Axes.
Click Secondary Horizontal Axis, and then click the display option that you want.
You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.
In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:
Click the chart.
This displays the Chart Tools, adding the Design, Layout, and Format tabs.
On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.
On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.
Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.
On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.
A secondary vertical axis is displayed in the chart.
To change the display of the secondary vertical axis, do the following:
On the Layout tab, in the Axes group, click Axes.
Click Secondary Vertical Axis, and then click the display option that you want.
To change the axis options of the secondary vertical axis, do the following:
Right-click the secondary vertical axis, and then click Format Axis.
Under Axis Options, select the options that you want to use.
Yes, that should work. But if you need to see the absolute path, this is all you need:
(Get-Item .).FullName
MSDN Documentation for SQL Server says
Many Transact-SQL statements that include subqueries can be alternatively formulated as joins. Other questions can be posed only with subqueries. In Transact-SQL, there is usually no performance difference between a statement that includes a subquery and a semantically equivalent version that does not. However, in some cases where existence must be checked, a join yields better performance. Otherwise, the nested query must be processed for each result of the outer query to ensure elimination of duplicates. In such cases, a join approach would yield better results.
so if you need something like
select * from t1 where exists select * from t2 where t2.parent=t1.id
try to use join instead. In other cases, it makes no difference.
I say: Creating functions for subqueries eliminate the problem of cluttter and allows you to implement additional logic to subqueries. So I recommend creating functions for subqueries whenever possible.
Clutter in code is a big problem and the industry has been working on avoiding it for decades.
React Portals can let you render to elements outside the root React node (such at <title>
), as if they were actual React nodes. So now you can set the title cleanly and without any additional dependencies:
Here's an example:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class Title extends Component {
constructor(props) {
super(props);
this.titleEl = document.getElementsByTagName("title")[0];
}
render() {
let fullTitle;
if(this.props.pageTitle) {
fullTitle = this.props.pageTitle + " - " + this.props.siteTitle;
} else {
fullTitle = this.props.siteTitle;
}
return ReactDOM.createPortal(
fullTitle || "",
this.titleEl
);
}
}
Title.defaultProps = {
pageTitle: null,
siteTitle: "Your Site Name Here",
};
export default Title;
Just put the component in the page and set pageTitle
:
<Title pageTitle="Dashboard" />
<Title pageTitle={item.name} />
Funny the answer is hidden in among the answers.
str.replace("•", "something")
would work if you use the right semantics.
str.replace(u"\u2022","something")
works wonders ;) , thnx to RParadox for the hint.
#image {
width: 100%;
height: 100px; //static
object-fit: cover;
}
A modern alternative:
const textToFind = 'Google';
const dd = document.getElementById ('MyDropDown');
dd.selectedIndex = [...dd.options].findIndex (option => option.text === textToFind);
Not sure what your desired output is, but if you're using list comprehension, the order follows the order of nested loops, which you have backwards. So I got the what I think you want with:
[float(y) for x in l for y in x]
The principle is: use the same order you'd use in writing it out as nested for loops.
you can use..
<div style="width: 100%;">
<div style="float:left; width: 80%">
</div>
<div style="float:right;">
</div>
</div>
<div style="clear:both"></div>
now element below this will not be affected.
In your database what is the type of "IDNO"? You may need to escape the sql here:
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
The HTML specification never specifies any content formats. That's not its job. There's plenty of standards organizations that are more qualified than the W3C to specify video formats.
That's what content negotiation is for.
<img>
element.<style>
element.<script>
element.<object>
and embed
elements.<audio>
element.Why should it specify one for the <video>
element?
WAMP server generally provide addond for different php/mysql versions. However you mentioned you have downloaded latest wamp server. As of now, latest Wamp server v2.5 provide PHP version 5.5.12
So you need to upgrade it manually as follow:
Although not asked, I'd recommend to vagrant/puppet or docker for local development. Check puphpet.com for details. It has slight learning curve but it will give you much better control of different versions of every tool.
Aligning to 6 bytes is not weird, because it is aligning to addresses multiple to 4.
So basically you have 34 bytes in your structure and the next structure should be placed on the address, that is multiple to 4. The closest value after 34 is 36. And this padding area counts into the size of the structure.
try this:
sedSelectNumbers='s".* \(+[0-9]*[.][0-9]*\) .*"\1,"'
sedClearLastComma='s"\(.*\),$"\1"'
cat file.txt |sed "$sedSelectNumbers" |tr -d "\n" |sed "$sedClearLastComma"
the good thing is the easy part of deleting newline "\n" characters!
EDIT: another great way to join lines into a single line with sed is this: |sed ':a;N;$!ba;s/\n/ /g'
got from here.
Context
provides information about the Actvity
or Application
to newly created components.
Relevant Context
should be provided to newly created components (whether application context or activity context)
Since Activity
is a subclass of Context
, one can use this
to get that activity's context
We have experienced the same issue when moving the sql server in-house.
A good solution that we ended up using is splitting the sql file into chunks. There are several ways to do that. Use
http://www.ozerov.de/bigdump/ seems good (but never used it)
http://www.rusiczki.net/2007/01/24/sql-dump-file-splitter/ used it and it was very useful to get structure out of the mess and you can take it from there.
Hope this helps :)
In Windows server 2012. Go to ISS -> Modules -> Remove the ServiceModel3-0.
Rsync is better since it will only copy only the updated parts of the updated file, instead of the whole file. It also uses compression and encryption if you want. Check out this tutorial.
Since the id
is sufficient for detecting duplicates, and the id
is hashable: run 'em through a dictionary that has the id
as the key. The value for each key is the original dictionary.
deduped_dicts = dict((item["id"], item) for item in list_of_dicts).values()
In Python 3, values()
doesn't return a list; you'll need to wrap the whole right-hand-side of that expression in list()
, and you can write the meat of the expression more economically as a dict comprehension:
deduped_dicts = list({item["id"]: item for item in list_of_dicts}.values())
Note that the result likely will not be in the same order as the original. If that's a requirement, you could use a Collections.OrderedDict
instead of a dict
.
As an aside, it may make a good deal of sense to just keep the data in a dictionary that uses the id
as key to begin with.
I had this problem (403 error for each package) and I found nothing great in the internet to solve it.
My .npmrc
file inside my user folder was wrong and misunderstood.
I changed this npmrc line from
proxy=http://XX.XX.XXX.XXX:XXX/
to :
proxy = XX.XX.XXX.XXX:XXXX
Use preg_replace()
and instead of [ \t\n\r]
use \s
:
$output = preg_replace('!\s+!', ' ', $input);
From Regular Expression Basic Syntax Reference:
\d, \w and \s
Shorthand character classes matching digits, word characters (letters, digits, and underscores), and whitespace (spaces, tabs, and line breaks). Can be used inside and outside character classes.
Here is example how you can do localization by yourself.
jQuery(function($) {_x000D_
$('input.datetimepicker').datepicker({_x000D_
duration: '',_x000D_
changeMonth: false,_x000D_
changeYear: false,_x000D_
yearRange: '2010:2020',_x000D_
showTime: false,_x000D_
time24h: true_x000D_
});_x000D_
_x000D_
$.datepicker.regional['cs'] = {_x000D_
closeText: 'Zavrít',_x000D_
prevText: '<Dríve',_x000D_
nextText: 'Pozdeji>',_x000D_
currentText: 'Nyní',_x000D_
monthNames: ['leden', 'únor', 'brezen', 'duben', 'kveten', 'cerven', 'cervenec', 'srpen',_x000D_
'zárí', 'ríjen', 'listopad', 'prosinec'_x000D_
],_x000D_
monthNamesShort: ['led', 'úno', 'bre', 'dub', 'kve', 'cer', 'cvc', 'srp', 'zár', 'ríj', 'lis', 'pro'],_x000D_
dayNames: ['nedele', 'pondelí', 'úterý', 'streda', 'ctvrtek', 'pátek', 'sobota'],_x000D_
dayNamesShort: ['ne', 'po', 'út', 'st', 'ct', 'pá', 'so'],_x000D_
dayNamesMin: ['ne', 'po', 'út', 'st', 'ct', 'pá', 'so'],_x000D_
weekHeader: 'Týd',_x000D_
dateFormat: 'dd/mm/yy',_x000D_
firstDay: 1,_x000D_
isRTL: false,_x000D_
showMonthAfterYear: false,_x000D_
yearSuffix: ''_x000D_
};_x000D_
_x000D_
$.datepicker.setDefaults($.datepicker.regional['cs']);_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link data-require="jqueryui@*" data-semver="1.10.0" rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.0/css/smoothness/jquery-ui-1.10.0.custom.min.css" />_x000D_
<script data-require="jqueryui@*" data-semver="1.10.0" src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.0/jquery-ui.js"></script>_x000D_
<script src="datepicker-cs.js"></script>_x000D_
<script type="text/javascript">_x000D_
$(document).ready(function() {_x000D_
console.log("test");_x000D_
$("#test").datepicker({_x000D_
dateFormat: "dd.m.yy",_x000D_
minDate: 0,_x000D_
showOtherMonths: true,_x000D_
firstDay: 1_x000D_
});_x000D_
});_x000D_
</script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<h1>Here is your datepicker</h1>_x000D_
<input id="test" type="text" />_x000D_
</body>_x000D_
</html>
_x000D_
Something like this:
HTML:
<select id="choice">
<option value="0" selected="selected">Choose...</option>
<option value="1">Something</option>
<option value="2">Something else</option>
<option value="3">Another choice</option>
</select>
CSS:
#choice option { color: black; }
.empty { color: gray; }
JavaScript:
$("#choice").change(function () {
if($(this).val() == "0") $(this).addClass("empty");
else $(this).removeClass("empty")
});
$("#choice").change();
Working example: http://jsfiddle.net/Zmf6t/
You can do following:
private Date getMeYesterday(){
return new Date(System.currentTimeMillis()-24*60*60*1000);
}
Note: if you want further backward date multiply number of day with 24*60*60*1000 for example:
private Date getPreviousWeekDate(){
return new Date(System.currentTimeMillis()-7*24*60*60*1000);
}
Similarly, you can get future date by adding the value to System.currentTimeMillis(), for example:
private Date getMeTomorrow(){
return new Date(System.currentTimeMillis()+24*60*60*1000);
}
A simple base R solution using the substring()
function (who knew this function even existed?):
RIGHT = function(x,n){
substring(x,nchar(x)-n+1)
}
This takes advantage of basically being substr()
underneath but has a default end value of 1,000,000.
Examples:
> RIGHT('Hello World!',2)
[1] "d!"
> RIGHT('Hello World!',8)
[1] "o World!"
I am just providing another case where you can get this error message. The solution will be the same as Adam has mentioned above. This is from a real code and I renamed the class name.
class FooReader {
public:
/** Constructor */
FooReader() : d(new FooReaderPrivate(this)) { } // will not compile here
.......
private:
FooReaderPrivate* d;
};
====== In a separate file =====
class FooReaderPrivate {
public:
FooReaderPrivate(FooReader*) : parent(p) { }
private:
FooReader* parent;
};
The above will no pass the compiler and get error: invalid use of incomplete type FooReaderPrivate. You basically have to put the inline portion into the *.cpp implementation file. This is OK. What I am trying to say here is that you may have a design issue. Cross reference of two classes may be necessary some cases, but I would say it is better to avoid them at the start of the design. I would be wrong, but please comment then I will update my posting.
Along with the above answers , you can do this too
=> [*'1'.."5"] #remember *
=> ["1", "2", "3", "4", "5"]
As @ashishduh mentioned above, using android:autoLink="phone
is also a good solution. But this option comes with one drawback, it doesn't work with all phone number lengths. For instance, a phone number of 11 numbers won't work with this option. The solution is to prefix your phone numbers with the country code.
Example:
08034448845
won't work
but +2348034448845
will
The code from Alex works great. Just note that when you use request.getParameter you must use a request dispatcher
//Pass results back to the client
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("TestPages/ServiceServlet.jsp");
dispatcher.forward(request, response);
I used this method to change choosing Text Field
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
if ([textField isEqual:self.emailRegisterTextField]) {
[self.usernameRegisterTextField becomeFirstResponder];
} else if ([textField isEqual:self.usernameRegisterTextField]) {
[self.passwordRegisterTextField becomeFirstResponder];
} else {
[textField resignFirstResponder];
// To click button for registration when you clicking button "Done" on the keyboard
[self createMyAccount:self.registrationButton];
}
return YES;
}
You could use a Regexp.
var result = /^(\d{2})-(\d{2})-(\d{4})$/.exec($("#datepicker").val());
if (result) {
from = new Date(
parseInt(result[3], 10),
parseInt(result[2], 10) - 1,
parseInt(result[1], 10)
);
}
Please make sure that id datatype is Long instead of String, if that will be string then @GeneratedValue annotation will not work and the sql generating for
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private String id;
create table VMS_AUDIT_RECORDS (id **varchar(255)** not null auto_increment primary key (id))
that needs to be
create table VMS_AUDIT_RECORDS (id **bigint** not null auto_increment primary key (id))
You can do this:
select *
from user_source
where upper(text) like upper('%SOMETEXT%');
Alternatively, SQL Developer has a built-in report to do this under:
View > Reports > Data Dictionary Reports > PLSQL > Search Source Code
The 11G docs for USER_SOURCE are here
Try this one
cd android && ./gradlew clean && ./gradlew :app:bundleRelease
If you're using rails you can also use in_groups_of:
foo.in_groups_of(3)
mydata$sCode == "CA"
will return a boolean array, with a TRUE
value everywhere that the condition is met. To illustrate:
> mydata = data.frame(sCode = c("CA", "CA", "AC"))
> mydata$sCode == "CA"
[1] TRUE TRUE FALSE
There are a couple of ways to deal with this:
sum(mydata$sCode == "CA")
, as suggested in the comments; because
TRUE
is interpreted as 1 and FALSE
as 0, this should return the
numer of TRUE
values in your vector.
length(which(mydata$sCode == "CA"))
; the which()
function
returns a vector of the indices where the condition is met, the
length of which is the count of "CA"
.
Edit to expand upon what's happening in #2:
> which(mydata$sCode == "CA")
[1] 1 2
which()
returns a vector identify each column where the condition is met (in this case, columns 1 and 2 of the dataframe). The length()
of this vector is the number of occurences.
If you can organize the values in the array in sorted order, then you can use Arrays.binarySearch()
. Otherwise you'll have to write a loop and to a linear search. If you plan to have a large (more than a few dozen) strings in the array, consider using a Set instead.
Major browsers are providing increased support now.
http://radar.oreilly.com/2009/05/google-bets-big-on-html-5.html
findstr /spin /c:"string" [files]
The parameters have the following meanings:
s
= recursivep
= skip non-printable charactersi
= case insensitiven
= print line numbersAnd the string to search for is the bit you put in quotes after /c:
Use eval as below. Eval should be used with caution, a simple search about "eval is evil" should throw some pointers.
function ExecuteJavascriptString()
{
var s = "alert('hello')";
eval(s);
}
Let's say you have a shiny Foo class. Well you have 3 options:
1) You want to use the method (or attribute) of a class inside the definition of that class:
class Foo(object):
attribute1 = 1 # class attribute (those don't use 'self' in declaration)
def __init__(self):
self.attribute2 = 2 # instance attribute (those are accessible via first
# parameter of the method, usually called 'self'
# which will contain nothing but the instance itself)
def set_attribute3(self, value):
self.attribute3 = value
def sum_1and2(self):
return self.attribute1 + self.attribute2
2) You want to use the method (or attribute) of a class outside the definition of that class
def get_legendary_attribute1():
return Foo.attribute1
def get_legendary_attribute2():
return Foo.attribute2
def get_legendary_attribute1_from(cls):
return cls.attribute1
get_legendary_attribute1() # >>> 1
get_legendary_attribute2() # >>> AttributeError: type object 'Foo' has no attribute 'attribute2'
get_legendary_attribute1_from(Foo) # >>> 1
3) You want to use the method (or attribute) of an instantiated class:
f = Foo()
f.attribute1 # >>> 1
f.attribute2 # >>> 2
f.attribute3 # >>> AttributeError: 'Foo' object has no attribute 'attribute3'
f.set_attribute3(3)
f.attribute3 # >>> 3
As stated here: Package names are written in all lower case to avoid conflict with the names of classes or interfaces.
Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com
.
Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name (for example, com.example.region.mypackage).
Packages in the Java language itself begin with java. or javax.
In some cases, the internet domain name may not be a valid package name. This can occur if the domain name contains a hyphen or other special character, if the package name begins with a digit or other character that is illegal to use as the beginning of a Java name, or if the package name contains a reserved Java keyword, such as "int". In this event, the suggested convention is to add an underscore. For example:
try this:
"String goes here".PadLeft(20,' ');
"String goes here".PadRight(20,' ');
for the center get the length of the string and do padleft and padright with the necessary characters
int len = "String goes here".Length;
int whites = len /2;
"String goes here".PadRight(len + whites,' ').PadLeft(len + whites,' ');
I know this is an old thread, but I stumbled across it and thought I'd share my method which I have found to be a very fast way to use find
to find only non-binary files:
find . -type f -exec grep -Iq . {} \; -print
The -I
option to grep tells it to immediately ignore binary files and the .
option along with the -q
will make it immediately match text files so it goes very fast. You can change the -print
to a -print0
for piping into an xargs -0
or something if you are concerned about spaces (thanks for the tip, @lucas.werkmeister!)
Also the first dot is only necessary for certain BSD versions of find
such as on OS X, but it doesn't hurt anything just having it there all the time if you want to put this in an alias or something.
EDIT: As @ruslan correctly pointed out, the -and
can be omitted since it is implied.
It looks to me like the background images aren't actually background images...the site has the background images and the quotes in sibling divs with the children of the div containing the images having been assigned position: fixed; The quotes div is also given a transparent background.
wrapper div{
image wrapper div{
div for individual image{ <--- Fixed position
image <--- relative position
}
}
quote wrapper div{
div for individual quote{
quote
}
}
}
You need to bind the modal hide call to the onclick
event.
Assuming you are using jQuery you can do that with:
$('#closemodal').click(function() {
$('#modalwindow').modal('hide');
});
Also make sure the click event is bound after the document has finished loading:
$(function() {
// Place the above code inside this block
});
enter code here
You can simply do it by using:
Object.prototype.extend = function(object) {
// loop through object
for (var i in object) {
// check if the extended object has that property
if (object.hasOwnProperty(i)) {
// mow check if the child is also and object so we go through it recursively
if (typeof this[i] == "object" && this.hasOwnProperty(i) && this[i] != null) {
this[i].extend(object[i]);
} else {
this[i] = object[i];
}
}
}
return this;
};
update: I checked for
this[i] != null
sincenull
is an object
Then use it like:
var options = {
foo: 'bar',
baz: 'dar'
}
var defaults = {
foo: false,
baz: 'car',
nat: 0
}
defaults.extend(options);
This well result in:
// defaults will now be
{
foo: 'bar',
baz: 'dar',
nat: 0
}
Slight modification of Laurynas' plugin based on Igor's code. This accommodates possible labels associated with the radio buttons being targeted:
(function ($) {
$.fn.uncheckableRadio = function () {
return this.each(function () {
var radio = this;
$('label[for="' + radio.id + '"]').add(radio).mousedown(function () {
$(radio).data('wasChecked', radio.checked);
});
$('label[for="' + radio.id + '"]').add(radio).click(function () {
if ($(radio).data('wasChecked'))
radio.checked = false;
});
});
};
})(jQuery);
This is old question, but if somebody finds it today chances are php will be run via php-fpm and mod_fastcgi. In that case nothing here will help with extending execution time because Apache will terminate connection to a process which does not output anything for 30 seconds. Only way to extend it is to change -idle-timeout in apache (module/site/vhost) config.
FastCgiExternalServer /usr/lib/cgi-bin/php7-fcgi -socket /run/php/php7.0-fpm.sock -idle-timeout 900 -pass-header Authorization
More details - Increase PHP-FPM idle timeout setting
ResultSet
to your main program or do your stuff in the same method.You can convert BigDecimal
to double
using .doubleValue()
. But believe me, don't use it if you have currency manipulations. It should always be performed on BigDecimal
objects directly. Precision loss in these calculations are big time problems in currency related calculations.
Another solution not using IFS and still preserving the spaces:
$ var="a bc,def,ghij"
$ while read line; do echo line="$line"; done < <(echo "$var" | tr ',' '\n')
line=a bc
line=def
line=ghij
Many popular Java webapps, including Jenkins and Nexus, use this mechanism:
Optionally, check a servlet context-param / init-param. This allows configuring multiple webapp instances per servlet container, using context.xml
which can be done by modifying the WAR or by changing server settings (in case of Tomcat).
Check an environment variable (using System.getenv), if it is set, then use that folder as your application data folder. e.g. Jenkins uses JENKINS_HOME
and Nexus uses PLEXUS_NEXUS_WORK
. This allows flexible configuration without any changes to WAR.
Otherwise, use a subfolder inside user's home folder, e.g. $HOME/.yourapp
. In Java code this will be:
final File appFolder = new File(System.getProperty("user.home"), ".yourapp");