Swift 3:
NotificationCenter.default.addObserver(self, selector: #selector(viewController.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(viewController.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
func keyboardWillShow(_ notification: NSNotification){
// Do something here
}
func keyboardWillHide(_ notification: NSNotification){
// Do something here
}
This answer to this similar question provides code for drawing a blurred shadow behind a UILabel. The author uses CGContextSetShadow() to generate the shadow for the drawn text.
$('input[type=text],select', '.sys');
for looping:
$('input[type=text],select', '.sys').each(function() {
// code
});
As per the documentation, most browsers will display the <ul>
, <ol>
and <li>
elements with the following default values:
Default CSS settings for UL or OL tag:
ul, ol {
display: block;
list-style: disc outside none;
margin: 1em 0;
padding: 0 0 0 40px;
}
ol {
list-style-type: decimal;
}
Default CSS settings for LI tag:
li {
display: list-item;
}
Style nested list items as well:
ul ul, ol ul {
list-style-type: circle;
margin-left: 15px;
}
ol ol, ul ol {
list-style-type: lower-latin;
margin-left: 15px;
}
Note: The result will be perfect if we use the above styles with a class. Also see different List-Item markers.
you can use OFFSET
and FETCH NEXT
SELECT id
FROM tablename
ORDER BY column
OFFSET 1 ROWS
FETCH NEXT 1 ROWS ONLY;
NOTE:
OFFSET can only be used with ORDER BY clause. It cannot be used on its own.
OFFSET value must be greater than or equal to zero. It cannot be negative, else return error.
The OFFSET argument is used to identify the starting point to return rows from a result set. Basically, it exclude the first set of records.
The FETCH argument is used to return a set of number of rows. FETCH can’t be used itself, it is used in conjuction with OFFSET.
Use
if(isset($_POST['submit'])) // name of your submit button
Edit : After Android Studios 1.5 android support Vector Asset Studio.
Follow this, which says:
To start Vector Asset Studio:
- In Android Studio, open an Android app project.
- In the Project window, select the Android view.
- Right-click the res folder and select New > Vector Asset.
Go to Settings > Plugin > Browse Repository > Search Android Drawable Import
This plugin consists of 4 main features.
How to Use Material Icons Drawable Import : (Android Studio 1.2)
You need to convert your private key to PKCS8 format using following command:
openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file -nocrypt > pkcs8_key
After this your java program can read it.
Button Code
<button id="submit" name="submit" type="submit" value="Submit">Submit</button>
Disable Button
if(When You Disable the button this Case){
$(':input[type="submit"]').prop('disabled', true);
}else{
$(':input[type="submit"]').prop('disabled', false);
}
Note: You Case may Be Multiple this time more condition may need
FormData method .entries
and the for of
expression is not supported in IE11 and Safari.
Here is a simplier version to support Safari, Chrome, Firefox and Edge
function formDataToJSON(formElement) {
var formData = new FormData(formElement),
convertedJSON = {};
formData.forEach(function(value, key) {
convertedJSON[key] = value;
});
return convertedJSON;
}
Warning: this answer doesn't work in IE11.
FormData doesn't have a forEach
method in IE11.
I'm still searching for a final solution to support all major browsers.
A simple solution but it gets the job done, assigns a known length and precision and avoids the chance of going exponential format (which is a risk when you use %g):
// Since we are only interested in 3 decimal places, this function
// can avoid any potential miniscule floating point differences
// which can return false when using "=="
int DoubleEquals(double i, double j)
{
return (fabs(i - j) < 0.000001);
}
void PrintMaxThreeDecimal(double d)
{
if (DoubleEquals(d, floor(d)))
printf("%.0f", d);
else if (DoubleEquals(d * 10, floor(d * 10)))
printf("%.1f", d);
else if (DoubleEquals(d * 100, floor(d* 100)))
printf("%.2f", d);
else
printf("%.3f", d);
}
Add or remove "elses" if you want a max of 2 decimals; 4 decimals; etc.
For example if you wanted 2 decimals:
void PrintMaxTwoDecimal(double d)
{
if (DoubleEquals(d, floor(d)))
printf("%.0f", d);
else if (DoubleEquals(d * 10, floor(d * 10)))
printf("%.1f", d);
else
printf("%.2f", d);
}
If you want to specify the minimum width to keep fields aligned, increment as necessary, for example:
void PrintAlignedMaxThreeDecimal(double d)
{
if (DoubleEquals(d, floor(d)))
printf("%7.0f", d);
else if (DoubleEquals(d * 10, floor(d * 10)))
printf("%9.1f", d);
else if (DoubleEquals(d * 100, floor(d* 100)))
printf("%10.2f", d);
else
printf("%11.3f", d);
}
You could also convert that to a function where you pass the desired width of the field:
void PrintAlignedWidthMaxThreeDecimal(int w, double d)
{
if (DoubleEquals(d, floor(d)))
printf("%*.0f", w-4, d);
else if (DoubleEquals(d * 10, floor(d * 10)))
printf("%*.1f", w-2, d);
else if (DoubleEquals(d * 100, floor(d* 100)))
printf("%*.2f", w-1, d);
else
printf("%*.3f", w, d);
}
To clone a repository and place it in a specified directory use "git clone [url] [directory]". For example
git clone https://github.com/ryanb/railscasts-episodes.git Rails
will create a directory named "Rails" and place it in the new directory. Click here for more information.
You can also take a look at x-ray: https://github.com/lapwinglabs/x-ray
When pthread_exit() is called, the calling threads stack is no longer addressable as "active" memory for any other thread. The .data, .text and .bss parts of "static" memory allocations are still available to all other threads. Thus, if you need to pass some memory value into pthread_exit() for some other pthread_join() caller to see, it needs to be "available" for the thread calling pthread_join() to use. It should be allocated with malloc()/new, allocated on the pthread_join threads stack, 1) a stack value which the pthread_join caller passed to pthread_create or otherwise made available to the thread calling pthread_exit(), or 2) a static .bss allocated value.
It's vital to understand how memory is managed between a threads stack, and values store in .data/.bss memory sections which are used to store process wide values.
I found that this question was still relevant but not clearly answered in my case.
Using SQL Server 2012 with an orphaned SQL_USER this was the fix;
USE databasename -- The database I had recently attached
EXEC sp_change_users_login 'Report' -- Display orphaned users
EXEC sp_change_users_login 'Auto_Fix', 'UserName', NULL, 'Password'
On saveAndFlush
, changes will be flushed to DB immediately in this command. With save
, this is not necessarily true, and might stay just in memory, until flush
or commit
commands are issued.
But be aware, that even if you flush the changes in transaction and do not commit them, the changes still won't be visible to the outside transactions until the commit in this transaction.
In your case, you probably use some sort of transactions mechanism, which issues commit
command for you if everything works out fine.
this seemed to work for me, its similar to another answer but has some distinct differences:
- (void)viewDidLayoutSubviews
{
[self.collectionView layoutIfNeeded];
NSArray *visibleItems = [self.collectionView indexPathsForVisibleItems];
NSIndexPath *currentItem = [visibleItems objectAtIndex:0];
NSIndexPath *nextItem = [NSIndexPath indexPathForItem:someInt inSection:currentItem.section];
[self.collectionView scrollToItemAtIndexPath:nextItem atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
}
I've had a similar problem, but I wanted to use NDK version r9d due to project requirements.
In local.properties
the path was set to ndk.dir=C\:\\Android\\ndk\\android-ndk-r9d
but that lead to the problem:
No toolchains found in the NDK toolchains folder for ABI with prefix: [toolchain-name]
The solution was to:
sdk\ndk-bundle\toolchains
to \ndk\android-ndk-r9d\toolchains
It looks to me that the copied toolchains are not used, but for some reason it is needed to for them be there.
You may find that using the `group' aes will help you get the result you want. For example:
tu <- expand.grid(Land = gl(2, 1, labels = c("DE", "BB")),
Altersgr = gl(5, 1, labels = letters[1:5]),
Geschlecht = gl(2, 1, labels = c('m', 'w')),
Jahr = 2000:2009)
set.seed(42)
tu$Wert <- unclass(tu$Altersgr) * 200 + rnorm(200, 0, 10)
ggplot(tu, aes(x = Jahr, y = Wert, color = Altersgr, group = Altersgr)) +
geom_point() + geom_line() +
facet_grid(Geschlecht ~ Land)
Which produces the plot found here:
On Windows:
Assign value to PGPASSWORD: C:\>set PGPASSWORD=pass
Run command: C:\>psql -d database -U user
Ready
Or in one line,
set PGPASSWORD=pass&& psql -d database -U user
Note the lack of space before the && !
Put content from other site in iframe
<iframe src="/othersiteurl" width="100%" height="300">
<p>Your browser does not support iframes.</p>
</iframe>
Unlike a list or a dictionary, a generator can be infinite. Doing this wouldn't work:
def gen():
x = 0
while True:
yield x
x += 1
g1 = gen()
list(g1) # never ends
Also, reading a generator changes it, so there's not a perfect way to view it. To see a sample of the generator's output, you could do
g1 = gen()
[g1.next() for i in range(10)]
You can use the "User-Defined Language" option available at the notepad++. You do not need to do the xml-based hacks, where the formatting would be available only in the searched window, with the formatting rules.
Sample for your reference here.
I got the following message, similar to your one:
program: malloc.c:2372: sysmalloc: Assertion `(old_top == (((mbinptr) (((char *) &((av)->bins[((1) - 1) * 2])) - __builtin_offsetof (struct malloc_chunk, fd)))) && old_size == 0) || ((unsigned long) (old_size) >= (unsigned long)((((__builtin_offsetof (struct malloc_chunk, fd_nextsize))+((2 *(sizeof(size_t))) - 1)) & ~((2 *(sizeof(size_t))) - 1))) && ((old_top)->size & 0x1) && ((unsigned long) old_end & pagemask) == 0)' failed.
Made a mistake some method call before, when using malloc. Erroneously overwrote the multiplication sign '*' with a '+', when updating the factor after sizeof()-operator on adding a field to unsigned char array.
Here is the code responsible for the error in my case:
UCHAR* b=(UCHAR*)malloc(sizeof(UCHAR)+5); b[INTBITS]=(some calculation); b[BUFSPC]=(some calculation); b[BUFOVR]=(some calculation); b[BUFMEM]=(some calculation); b[MATCHBITS]=(some calculation);
In another method later, I used malloc again and it produced the error message shown above. The call was (simple enough):
UCHAR* b=(UCHAR*)malloc(sizeof(UCHAR)*50);
Think using the '+'-sign on the 1st call, which lead to mis-calculus in combination with immediate initialization of the array after (overwriting memory that was not allocated to the array), brought some confusion to malloc's memory map. Therefore the 2nd call went wrong.
For my issue, I had to zero out the log:
sudo bash -c ' > /Applications/XAMPP/xamppfiles/logs/php_error_log '
using flexbox:
h2 {
display: flex;
align-items: center;
}
h2 span {
content:"";
flex: 1 1 auto;
border-top: 1px solid #000;
}
html:
<h2>Title <span></span></h2>
You have 2 things you must check:
/etc/environment
file has the correct JAVA_HOME
and PATH
values referring to your Java installation directory.It's possible to prevent webpage scaling in safari on iOS 10, but it's going to involve more work on your part. I guess the argument is that a degree of difficulty should stop cargo-cult devs from dropping "user-scalable=no" into every viewport tag and making things needlessly difficult for vision-impaired users.
Still, I would like to see Apple change their implementation so that there is a simple (meta-tag) way to disable double-tap-to-zoom. Most of the difficulties relate to that interaction.
You can stop pinch-to-zoom with something like this:
document.addEventListener('touchmove', function (event) {
if (event.scale !== 1) { event.preventDefault(); }
}, false);
Note that if any deeper targets call stopPropagation on the event, the event will not reach the document and the scaling behavior will not be prevented by this listener.
Disabling double-tap-to-zoom is similar. You disable any tap on the document occurring within 300 milliseconds of the prior tap:
var lastTouchEnd = 0;
document.addEventListener('touchend', function (event) {
var now = (new Date()).getTime();
if (now - lastTouchEnd <= 300) {
event.preventDefault();
}
lastTouchEnd = now;
}, false);
If you don't set up your form elements right, focusing on an input will auto-zoom, and since you have mostly disabled manual zoom, it will now be almost impossible to unzoom. Make sure the input font size is >= 16px.
If you're trying to solve this in a WKWebView in a native app, the solution given above is viable, but this is a better solution: https://stackoverflow.com/a/31943976/661418. And as mentioned in other answers, in iOS 10 beta 6, Apple has now provided a flag to honor the meta tag.
Update May 2017: I replaced the old 'check touches length on touchstart' method of disabling pinch-zoom with a simpler 'check event.scale on touchmove' approach. Should be more reliable for everyone.
I took Mr. Fooz's code and also added Arlen's solution too and here are the timings that I've gotten for Octave:
clc; clear all;
V = rand(1024*1024*32,1);
N = 10;
tic; for i=1:N, V1 = V/norm(V); end; toc % 7.0 s
tic; for i=1:N, V2 = V/sqrt(sum(V.*V)); end; toc % 6.4 s
tic; for i=1:N, V3 = V/sqrt(V'*V); end; toc % 5.5 s
tic; for i=1:N, V4 = V/sqrt(sum(V.^2)); end; toc % 6.6 s
tic; for i=1:N, V1 = V/norm(V); end; toc % 7.1 s
tic; for i=1:N, d = 1/norm(V); V1 = V*d;end; toc % 4.7 s
Then, because of something I'm currently looking at, I tested out this code for ensuring that each row sums to 1:
clc; clear all;
m = 2048;
V = rand(m);
N = 100;
tic; for i=1:N, V1 = V ./ (sum(V,2)*ones(1,m)); end; toc % 8.2 s
tic; for i=1:N, V2 = bsxfun(@rdivide, V, sum(V,2)); end; toc % 5.8 s
tic; for i=1:N, V3 = bsxfun(@rdivide, V, V*ones(m,1)); end; toc % 5.7 s
tic; for i=1:N, V4 = V ./ (V*ones(m,m)); end; toc % 77.5 s
tic; for i=1:N, d = 1./sum(V,2);V5 = bsxfun(@times, V, d); end; toc % 2.83 s
tic; for i=1:N, d = 1./(V*ones(m,1));V6 = bsxfun(@times, V, d);end; toc % 2.75 s
tic; for i=1:N, V1 = V ./ (sum(V,2)*ones(1,m)); end; toc % 8.2 s
Just a tip:
In Visual Studio to comment a text, you can highlight the text you want to comment, and then use Ctrl + K followed by Ctrl + C. To uncomment, you can use Ctrl + K followed by Ctrl + U.
I see a lot of responses that recommend just using a ForegroundService. In order to use a ForegroundService there has to be a notification associated with it. Users will see this notification. Depending on the situation, they may become annoyed with your app and uninstall it.
The easiest solution is to use the new Architecture Component called WorkManager. You can check out the documentation here: https://developer.android.com/topic/libraries/architecture/workmanager/
You just define your worker class that extends Worker.
public class CompressWorker extends Worker {
public CompressWorker(
@NonNull Context context,
@NonNull WorkerParameters params) {
super(context, params);
}
@Override
public Worker.Result doWork() {
// Do the work here--in this case, compress the stored images.
// In this example no parameters are passed; the task is
// assumed to be "compress the whole library."
myCompress();
// Indicate success or failure with your return value:
return Result.SUCCESS;
// (Returning RETRY tells WorkManager to try this task again
// later; FAILURE says not to try again.)
}
}
Then you schedule when you want to run it.
OneTimeWorkRequest compressionWork =
new OneTimeWorkRequest.Builder(CompressWorker.class)
.build();
WorkManager.getInstance().enqueue(compressionWork);
Easy! There are a lot of ways you can configure workers. It supports recurring jobs and you can even do complex stuff like chaining if you need it. Hope this helps.
Here's an alternative, instead of adding an incomplete.flag
file to every dir you want to exclude, generate a file that contains a listing of all the directories you want to exclude and then use the excludesfile
attribute. Something like this:
<fileset dir="${basedir}" excludesfile="FileWithExcludedDirs.properties">
<include name="locale/"/>
<exclude name="locale/*/incomplete.flag">
</fileset>
Hope it helps.
Move excel variables which are global declare in your form to local like in my form I have:
Dim xls As New MyExcel.Interop.Application
Dim xlb As MyExcel.Interop.Workbook
above two lines were declare global in my form so i moved these two lines to local function and now tool is working fine.
Guido has written The Inside Story on New-Style Classes, a really great article about new-style and old-style class in Python.
Python 3 has only new-style class. Even if you write an 'old-style class', it is implicitly derived from object
.
New-style classes have some advanced features lacking in old-style classes, such as super
, the new C3 mro, some magical methods, etc.
// usage: log('inside coolFunc',this,arguments);
// http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
log.history = log.history || []; // store logs to an array for reference
log.history.push(arguments);
if(this.console){
console.log( Array.prototype.slice.call(arguments) );
}
};
Using window.log will allow you to perform the same action as console.log, but it checks if the browser you are using has the ability to use console.log first, so as not to error out for compatibility reasons (IE 6, etc.).
If your classes are in the same package, you won't need to import. To call a method from class B in class A, you should use classB.methodName(arg)
It's just the required syntax:
void Func(int (&myArray)[100])
^ Pass array of 100 int
by reference the parameters name is myArray
;
void Func(int* myArray)
^ Pass an array. Array decays to a pointer. Thus you lose size information.
void Func(int (*myFunc)(double))
^ Pass a function pointer. The function returns an int
and takes a double
. The parameter name is myFunc
.
Click above in the red circle. Your folder will appear in Solution Explorer.
Right click on your folder -> Include in project.
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script>_x000D_
var currFFZoom = 1;_x000D_
var currIEZoom = 100;_x000D_
_x000D_
function plus(){_x000D_
//alert('sad');_x000D_
var step = 0.02;_x000D_
currFFZoom += step;_x000D_
$('body').css('MozTransform','scale(' + currFFZoom + ')');_x000D_
var stepie = 2;_x000D_
currIEZoom += stepie;_x000D_
$('body').css('zoom', ' ' + currIEZoom + '%');_x000D_
_x000D_
};_x000D_
function minus(){_x000D_
//alert('sad');_x000D_
var step = 0.02;_x000D_
currFFZoom -= step;_x000D_
$('body').css('MozTransform','scale(' + currFFZoom + ')');_x000D_
var stepie = 2;_x000D_
currIEZoom -= stepie;_x000D_
$('body').css('zoom', ' ' + currIEZoom + '%');_x000D_
};_x000D_
</script>_x000D_
</head>_x000D_
<body>_x000D_
<!--zoom controls-->_x000D_
<a id="minusBtn" onclick="minus()">------</a>_x000D_
<a id="plusBtn" onclick="plus()">++++++</a>_x000D_
</body>_x000D_
</html>
_x000D_
in Firefox will not change the zoom only change scale!!!
Not to beat a dead horse, but the solution you're describing sounds a lot like Node-Webkit.
From the Git Page:
node-webkit is an app runtime based on Chromium and node.js. You can write native apps in HTML and JavaScript with node-webkit. It also lets you call Node.js modules directly from the DOM and enables a new way of writing native applications with all Web technologies.
These instructions specifically detail the creation of a single file app that a user can execute, and this portion describes the external dependencies.
I'm not sure if it's the exact solution, but it seems pretty close.
Hope it helps!
Google Chrome has a two ways to check for unused CSS.
1. Audit Tab: > Right Click + Inspect Element on the page, find the "Audit" tab, and run the audit, making sure "Web Page Performance" is checked.
Lists all unused CSS tags - see image below.
Update: - - - - - - - - - - - - - - OR - - - - - - - - - - - - - -
2. Coverage Tab: > Right Click + Inspect Element on the page, find the three dots on the far right (circled in image) and open Console Drawer (or hit Esc), finally click the three dots left side in the drawer (circled in image) to open Coverage tool.
Chrome launched a tool to see unused CSS and JS - Chrome 59 Update Allows you to start and stop a recording (red square in image) to allow better coverage of a user experience on the page.
Shows all used and unused CSS/JS in the files - see image below.
I would look into any number of online sitemap generation tools. Personally, I've used this one (java based)in the past, but if you do a google search for "sitemap builder" I'm sure you'll find lots of different options.
you can also mention the path at runtime using -D
properties as below
-Djavax.net.ssl.trustStore=/home/user/SSL/my-cacerts
-Djavax.net.ssl.keyStore=/home/user/SSL/server_keystore.jks
In my apache spark application, I used to provide the path of certs and keystore using --conf
option and extraJavaoptions
in spark-submit as below
--conf 'spark.driver.extraJavaOptions=
-Djavax.net.ssl.trustStore=/home/user/SSL/my-cacerts
-Djavax.net.ssl.keyStore=/home/user/SSL/server_keystore.jks'
You can use \centering
with your parbox to do this.
(Sorry for the Google cached link; the original one I had doesn't work anymore.)
java.sql.Date
If your table has a column of type DATE
:
java.lang.String
The method java.sql.Date.valueOf(java.lang.String)
received a string representing a date in the format yyyy-[m]m-[d]d
. e.g.:
ps.setDate(2, java.sql.Date.valueOf("2013-09-04"));
java.util.Date
Suppose you have a variable endDate
of type java.util.Date
, you make the conversion thus:
ps.setDate(2, new java.sql.Date(endDate.getTime());
Current
If you want to insert the current date:
ps.setDate(2, new java.sql.Date(System.currentTimeMillis()));
// Since Java 8
ps.setDate(2, java.sql.Date.valueOf(java.time.LocalDate.now()));
java.sql.Timestamp
If your table has a column of type TIMESTAMP
or DATETIME
:
java.lang.String
The method java.sql.Timestamp.valueOf(java.lang.String)
received a string representing a date in the format yyyy-[m]m-[d]d hh:mm:ss[.f...]
. e.g.:
ps.setTimestamp(2, java.sql.Timestamp.valueOf("2013-09-04 13:30:00");
java.util.Date
Suppose you have a variable endDate
of type java.util.Date
, you make the conversion thus:
ps.setTimestamp(2, new java.sql.Timestamp(endDate.getTime()));
Current
If you require the current timestamp:
ps.setTimestamp(2, new java.sql.Timestamp(System.currentTimeMillis()));
// Since Java 8
ps.setTimestamp(2, java.sql.Timestamp.from(java.time.Instant.now()));
ps.setTimestamp(2, java.sql.Timestamp.valueOf(java.time.LocalDateTime.now()));
For those, who are reading this in 2018+. There are two new pagination-hassle-free APIs available: one in AWS SDK for Java 1.x and another one in 2.x.
There is a new API in Java SDK that allows you to iterate through objects in S3 bucket without dealing with pagination:
AmazonS3 s3 = AmazonS3ClientBuilder.standard().build();
S3Objects.inBucket(s3, "the-bucket").forEach((S3ObjectSummary objectSummary) -> {
// TODO: Consume `objectSummary` the way you need
System.out.println(objectSummary.key);
});
This iteration is lazy:
The list of
S3ObjectSummary
s will be fetched lazily, a page at a time, as they are needed. The size of the page can be controlled with thewithBatchSize(int)
method.
The API changed, so here is an SDK 2.x version:
S3Client client = S3Client.builder().region(Region.US_EAST_1).build();
ListObjectsV2Request request = ListObjectsV2Request.builder().bucket("the-bucket").prefix("the-prefix").build();
ListObjectsV2Iterable response = client.listObjectsV2Paginator(request);
for (ListObjectsV2Response page : response) {
page.contents().forEach((S3Object object) -> {
// TODO: Consume `object` the way you need
System.out.println(object.key());
});
}
ListObjectsV2Iterable
is lazy as well:
When the operation is called, an instance of this class is returned. At this point, no service calls are made yet and so there is no guarantee that the request is valid. As you iterate through the iterable, SDK will start lazily loading response pages by making service calls until there are no pages left or your iteration stops. If there are errors in your request, you will see the failures only after you start iterating through the iterable.
You should implement a Custom List View, such that you define a Layout once and draw it for every row in the list view.
If using eclipse to deploy your application . We can use this maven plugin
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.10</version>
<configuration>
<wtpversion>2.0</wtpversion>
<wtpContextName>newContextroot</wtpContextName>
</configuration>
</plugin>
now go to your project root folder and open cmd prompt at that location type this command :
mvn eclipse:eclipse -Dwtpversion=2.0
You may need to restart eclipse , or in server view delete server and create agian to see affect. I wonder this exercise make sense in real life but works.
If you wanna create new list, use Stream.map
method:
List<Fruit> newList = fruits.stream()
.map(f -> new Fruit(f.getId(), f.getName() + "s", f.getCountry()))
.collect(Collectors.toList())
If you wanna modify current list, use Collection.forEach
:
fruits.forEach(f -> f.setName(f.getName() + "s"))
Some people find the following alternative syntax easier to see what is going on:
select t1.value,t2.value
from MyTable t1
inner join MyTable t2 on
t1.id = t2.id
where t1.id = @id
For "zip" files, you can use import zipfile
and your code will be working simply with these lines:
import zipfile
import pandas as pd
with zipfile.ZipFile("Crime_Incidents_in_2013.zip") as z:
with z.open("Crime_Incidents_in_2013.csv") as f:
train = pd.read_csv(f, header=0, delimiter="\t")
print(train.head()) # print the first 5 rows
And the result will be:
X,Y,CCN,REPORT_DAT,SHIFT,METHOD,OFFENSE,BLOCK,XBLOCK,YBLOCK,WARD,ANC,DISTRICT,PSA,NEIGHBORHOOD_CLUSTER,BLOCK_GROUP,CENSUS_TRACT,VOTING_PRECINCT,XCOORD,YCOORD,LATITUDE,LONGITUDE,BID,START_DATE,END_DATE,OBJECTID
0 -77.054968548763071,38.899775938598317,0925135...
1 -76.967309569035052,38.872119553647011,1003352...
2 -76.996184958456539,38.927921847721443,1101010...
3 -76.943077541353617,38.883686046653935,1104551...
4 -76.939209158039446,38.892278093281632,1125028...
YES the warning is backwards.
And in fact it shouldn't even be a warning in the first place. Because all this warning is saying (but backwards unfortunately) is that the CRLF characters in your file with Windows line endings will be replaced with LF's on commit. Which means it's normalized to the same line endings used by *nix and MacOS.
Nothing strange is going on, this is exactly the behavior you would normally want.
This warning in it's current form is one of two things:
;)
If you are checking against a lot of intervals, I suggest using an interval tree.
to change the focus make the textView in xml focusable
<TextView
**android:focusable="true"**
android:id="@+id/tv_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
and in java in on create
textView.requestFocus();
or simply hide the keyboard
public void hideKeyBoard(Activity act) {
act.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
InputMethodManager imm = (InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE);
}
That's correct, your response is an object with fields:
{
"page": 1,
"results": [ ... ]
}
So you in fact want to iterate the results
field only:
this.data = res.json()['results'];
... or even easier:
this.data = res.json().results;
\0
is zero character. In C
it is mostly used to indicate the termination of a character string. Of course it is a regular character and may be used as such but this is rarely the case.
The simpler versions of the built-in string manipulation functions in C
require that your string is null-terminated(or ends with \0
).
Try This:
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
EDIT
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
Swift 4
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
Swift 4.2
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
Define above Both Methods.
It solves the problem.
PS: Top and bottom constraints is required for this to work.
My issue was simple: the Master page and Master.Designer.cs class had the correct Namespace, but the Master.cs class had the wrong namespace.
On supporting browsers, you can use DOM elements' classList
property.
$(element)[0].classList
It is an array-like object listing all of the classes the element has.
If you need to support old browser versions that don't support the classList
property, the linked MDN page also includes a shim for it - although even the shim won't work on Internet Explorer versions below IE 8.
On Windows at least, pip
stores the execution path in the executable pip.exe
when it is installed.
Edit this file using a hex editor or WordPad (you have to save it as plain text then to retain binary data), change the path to Python with quotes and spaces like this:
#!"C:\Program Files (x86)\Python33\python.exe"
to an escaped path without spaces and quotes and pad with spaces (dots at the end should be spaces):
#!C:\Progra~2\Python33\python.exe.............
For "C:\Program Files", this path would probably be "C:\Progra~1" (shortened path names in DOS / Windows 3.x notation use tilde and numbers). Windows provides this alternative notation for backwards compatibility with DOS / Windows 3.x apps.
Note that as this is a binary file, you should not change the file size which may break the executable, hence the padding.
Save with administrator privileges, make sure it is actually saved at the target location and try again.
You might also need to set the PATH
variable to use the ~
notation for the path to pip
.
try this:
public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
return ms.ToArray();
}
public Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
In general error is which nobody can control or guess when it occurs.Exception can be guessed and can be handled. In Java Exception and Error are sub class of Throwable.It is differentiated based on the program control.Error such as OutOfMemory Error which no programmer can guess and can handle it.It depends on dynamically based on architectire,OS and server configuration.Where as Exception programmer can handle it and can avoid application's misbehavior.For example if your code is looking for a file which is not available then IOException is thrown.Such instances programmer can guess and can handle it.
The three words have orthogonal meanings.
public
means that the method will be visible from classes in other packages.
static
means that the method is not attached to a specific instance, and it has no "this
". It is more or less a function.
void
is the return type. It means "this method returns nothing".
Also known as Frozen Binaries but not the same as as the output of a true compiler- they run byte code through a virtual machine (PVM). Run the same as a compiled program just larger because the program is being compiled along with the PVM. Py2exe can freeze standalone programs that use the tkinter, PMW, wxPython, and PyGTK GUI libraties; programs that use the pygame game programming toolkit; win32com client programs; and more. The Stackless Python system is a standard CPython implementation variant that does not save state on the C language call stack. This makes Python more easy to port to small stack architectures, provides efficient multiprocessing options, and fosters novel programming structures such as coroutines. Other systems of study that are working on future development: Pyrex is working on the Cython system, the Parrot project, the PyPy is working on replacing the PVM altogether, and of course the founder of Python is working with Google to get Python to run 5 times faster than C with the Unladen Swallow project. In short, py2exe is the easiest and Cython is more efficient for now until these projects improve the Python Virtual Machine (PVM) for standalone files.
If you mean that you wanna attach this to your panel (Window that you are working with).
then you have to create an inner class that extend from IKeyListener interface and then add that method in to the class.
Then, attach that class to you panel by: this.addKeyListener(new subclass());
To get an iPhone's device name programmatically
UIDevice *deviceInfo = [UIDevice currentDevice];
NSLog(@"Device name: %@", deviceInfo.name);
// Device name: my iPod
All of these answers are wrong!
Like I said in my comment, the reason you're getting that error because the URL fails the "Same origin policy", but you can still us the AJAX function to hit another domain, see Nick Cravers answer on this similar question:
You need to trigger JSONP behavior with $.getJSON() by adding &callback=? on the querystring, like this:
$.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&titles="+title+"&format=json&callback=?", function(data) { doSomethingWith(data); });
You can test it here.
Without using JSONP you're hitting the same-origin policy which is blocking the XmlHttpRequest from getting any data back.
With this in mind, the follow code should work:
var fbURL="https://graph.facebook.com/16453004404_481759124404/comments?access_token=my_token";
$.ajax({
url: fbURL+"&callback=?",
data: "message="+commentdata,
type: 'POST',
success: function (resp) {
alert(resp);
},
error: function(e) {
alert('Error: '+e);
}
});
FindControl does not search within nested controls recursively. It does only find controls that's NamigContainer is the Control on that you are calling FindControl.
Theres a reason that ASP.Net does not look into your nested controls recursively by default:
Consider you want to encapsulate your GridViews, Formviews, UserControls etc. inside of other UserControls for reusability reasons. If you would have implemented all logic in your page and accessed these controls with recursive loops, it'll very difficult to refactor that. If you have implemented your logic and access methods via the event-handlers(f.e. RowDataBound of GridView), it'll be much simpler and less error-prone.
Add following to get best warnings, you will not regret it. If you can, compile WISE (warning is error)
- Wall -pedantic -Weffc++ -Werror
you can use linkbutton for navigating to another section in the same page by using PostBackUrl="#Section2"
You have to put the second div on top of the first one because the both have an z-index of zero so that the order in the dom will decide which is on top. This also affects the relative positioned div because its z-index relates to elements inside the parent div.
<div class="absolute" style="top: 54px"></div>
<div class="absolute">
<div id="relative"></div>
</div>
Css stays the same.
I had the same problem, all you need to do is define classpath environment variable for tomcat, you can do it by adding a file, in my case C:\apache-tomcat-7.0.30\bin\setenv.bat
, containing:
set "CLASSPATH=%CLASSPATH%;%CATALINA_HOME%\lib\mysql-connector-java-5.1.14-bin.jar"
then code, in my case:
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name", "root", "");
works fine.
Try something like
find . \( -type f -name \*_peaks.bed -print \) -or \( -type d -and \( -name tmp -or -name scripts \) -and -prune \)
and don't be too surprised if I got it a bit wrong. If the goal is an exec (instead of print), just substitute it in place.
Use getattr
if you have an attribute in string form:
>>> class User(object):
name = 'John'
>>> u = User()
>>> param = 'name'
>>> getattr(u, param)
'John'
Otherwise use the dot .
:
>>> class User(object):
name = 'John'
>>> u = User()
>>> u.name
'John'
Accessing The Current Route(v5.3 onwards)
You may use the current, currentRouteName, and currentRouteAction methods on the Route facade to access information about the route handling the incoming request:
$route = Route::current();
$name = Route::currentRouteName();
$action = Route::currentRouteAction();
Refer to the API documentation for both the underlying class of the Route facade and Route instance to review all accessible methods.
Reference : https://laravel.com/docs/5.2/routing#accessing-the-current-route
Updated answer for 2017
The following will parse an XML string into an XML document in all major browsers. Unless you need support for IE <= 8 or some obscure browser, you could use the following function:
function parseXml(xmlStr) {
return new window.DOMParser().parseFromString(xmlStr, "text/xml");
}
If you need to support IE <= 8, the following will do the job:
var parseXml;
if (typeof window.DOMParser != "undefined") {
parseXml = function(xmlStr) {
return new window.DOMParser().parseFromString(xmlStr, "text/xml");
};
} else if (typeof window.ActiveXObject != "undefined" &&
new window.ActiveXObject("Microsoft.XMLDOM")) {
parseXml = function(xmlStr) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
};
} else {
throw new Error("No XML parser found");
}
Once you have a Document
obtained via parseXml
, you can use the usual DOM traversal methods/properties such as childNodes
and getElementsByTagName()
to get the nodes you want.
Example usage:
var xml = parseXml("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);
If you're using jQuery, from version 1.5 you can use its built-in parseXML()
method, which is functionally identical to the function above.
var xml = $.parseXML("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);
Try:
msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]
The +
operator is overridden in python to concatenate strings.
You can use the following code to get the value of the first column of the selected row of your table.
int column = 0;
int row = table.getSelectedRow();
String value = table.getModel().getValueAt(row, column).toString();
@Id
@Column(name = "COLUMN_NAME", nullable = false)
public Long getId() {
return id;
}
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, targetEntity = SomeCustomEntity.class)
@JoinColumn(name = "COLUMN_NAME", referencedColumnName = "COLUMN_NAME", nullable = false, updatable = false, insertable = false)
@org.hibernate.annotations.Cascade(value = org.hibernate.annotations.CascadeType.ALL)
public List<SomeCustomEntity> getAbschreibareAustattungen() {
return abschreibareAustattungen;
}
If you have already mapped a column and have accidentaly set the same values for name and referencedColumnName in @JoinColumn hibernate gives the same stupid error
Error:
Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: com.testtest.SomeCustomEntity column: COLUMN_NAME (should be mapped with insert="false" update="false")
This is the best method I have come up with so far to incorporate extra GET methods while supporting the normal REST methods as well. Add the following routes to your WebApiConfig:
routes.MapHttpRoute("DefaultApiWithId", "Api/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });
routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}");
routes.MapHttpRoute("DefaultApiGet", "Api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });
routes.MapHttpRoute("DefaultApiPost", "Api/{controller}", new {action = "Post"}, new {httpMethod = new HttpMethodConstraint(HttpMethod.Post)});
I verified this solution with the test class below. I was able to successfully hit each method in my controller below:
public class TestController : ApiController
{
public string Get()
{
return string.Empty;
}
public string Get(int id)
{
return string.Empty;
}
public string GetAll()
{
return string.Empty;
}
public void Post([FromBody]string value)
{
}
public void Put(int id, [FromBody]string value)
{
}
public void Delete(int id)
{
}
}
I verified that it supports the following requests:
GET /Test
GET /Test/1
GET /Test/GetAll
POST /Test
PUT /Test/1
DELETE /Test/1
Note That if your extra GET actions do not begin with 'Get' you may want to add an HttpGet attribute to the method.
You have two options:
Define a named class. Pass your parameter to the constructor of the named class.
Have your anonymous class close over your "parameter". Be sure to mark it as final
.
if (android.os.Build.VERSION.SDK_INT >= 21) {
storeViewHolder.storeNameTextView.setImageDrawable(context.getResources().getDrawable(array[position], context.getTheme()));
} else {
storeViewHolder.storeNameTextView.setImageDrawable(context.getResources().getDrawable(array[position]));
}
Try putting your text in another div inside your span:
i.e.
<span><div>some text</div></span>
Since String.format
is only an extension function (see here) which internally calls java.lang.String.format
you could write your own extension function using Java's DecimalFormat if you need more flexibility:
fun Double.format(fracDigits: Int): String {
val df = DecimalFormat()
df.setMaximumFractionDigits(fracDigits)
return df.format(this)
}
println(3.14159.format(2)) // 3.14
You can make use of
Set dateformat <date-format> ;
in you sp function or stored procedure to get things done.
The Hibernate Validator requires — but does not include — an Expression Language (EL) implementation. Adding a dependency on one will will fix the issue.
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>jakarta.el</artifactId>
<version>3.0.3</version>
</dependency>
This requirement is documented in the Getting started with Hibernate Validator documentation. In a Java EE environment, it would be provided by the container. In a standalone application such as yours, it needs to be provided.
Hibernate Validator also requires an implementation of the Unified Expression Language (JSR 341) for evaluating dynamic expressions in constraint violation messages.
When your application runs in a Java EE container such as WildFly, an EL implementation is already provided by the container.
In a Java SE environment, however, you have to add an implementation as dependency to your POM file. For instance, you can add the following dependency to use the JSR 341 reference implementation:
<dependency> <groupId>org.glassfish</groupId> <artifactId>jakarta.el</artifactId> <version>${version.jakarta.el-api}</version> </dependency>
There are other EL implementations that can be used other than Glassfish. For instance, Spring Boot versions 2.2.x and earlier by default used embedded Tomcat (it's since switched to use the Jakarta EL reference implementation). That version of EL can be used as follows:
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-el</artifactId>
<version>9.0.41</version>
</dependency>
That said, in a Spring Boot project, typically one would use the spring-boot-starter-validation
dependency rather than specifying the Hibernate validator & EL libraries directly. That dependency includes both hibernate-validator
and the EL implementation.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>2.4.2.RELEASE</version>
</dependency>
Supposedly you can do this on windows with the growl for windows javascript API:
http://ajaxian.com/archives/growls-for-windows-and-a-web-notification-api
Your users will have to install growl though.
Eventually this is going to be part of google gears, in the form of the NotificationAPI:
http://code.google.com/p/gears/wiki/NotificationAPI
So I would recommend using the growl approach for now, falling back to window title updates if possible, and already engineering in attempts to use the Gears Notification API, for when it eventually becomes available.
.
character as a wildcard to match any single character.Example regex: a.c
abc // match
a c // match
azc // match
ac // no match
abbc // no match
[]
to match any characters in a set.\w
to match any single alphanumeric character: 0-9
, a-z
, A-Z
, and _
(underscore).\d
to match any single digit.\s
to match any single whitespace character.Example 1 regex: a[bcd]c
abc // match
acc // match
adc // match
ac // no match
abbc // no match
Example 2 regex: a[0-7]c
a0c // match
a3c // match
a7c // match
a8c // no match
ac // no match
a55c // no match
Use the hat in square brackets [^]
to match any single character except for any of the characters that come after the hat ^
.
Example regex: a[^abc]c
aac // no match
abc // no match
acc // no match
a c // match
azc // match
ac // no match
azzc // no match
(Don't confuse the ^
here in [^]
with its other usage as the start of line character: ^
= line start, $
= line end.)
Use the optional character ?
after any character to specify zero or one occurrence of that character. Thus, you would use .?
to match any single character optionally.
Example regex: a.?c
abc // match
a c // match
azc // match
ac // match
abbc // no match
When entered as the reference of a Named range
, it refers to range on the sheet the named range is used on.
For example, create a named range MyName
refering to =SUM(!B1:!K1)
Place a formula on Sheet1
=MyName
. This will sum Sheet1!B1:K1
Now place the same formula (=MyName
) on Sheet2
. That formula will sum Sheet2!B1:K1
Note: (as pnuts commented) this and the regular SheetName!B1:K1
format are relative, so reference different cells as the =MyName
formula is entered into different cells.
WARNING: size()
was deprecated in jQuery 1.8 and removed in jQuery 3.0, use .length
instead
Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/
$(document).ready(function () {
size_li = $("#myList li").size();
x=3;
$('#myList li:lt('+x+')').show();
$('#loadMore').click(function () {
x= (x+5 <= size_li) ? x+5 : size_li;
$('#myList li:lt('+x+')').show();
});
$('#showLess').click(function () {
x=(x-5<0) ? 3 : x-5;
$('#myList li').not(':lt('+x+')').hide();
});
});
$(document).ready(function () {
size_li = $("#myList li").size();
x=3;
$('#myList li:lt('+x+')').show();
$('#loadMore').click(function () {
x= (x+5 <= size_li) ? x+5 : size_li;
$('#myList li:lt('+x+')').show();
$('#showLess').show();
if(x == size_li){
$('#loadMore').hide();
}
});
$('#showLess').click(function () {
x=(x-5<0) ? 3 : x-5;
$('#myList li').not(':lt('+x+')').hide();
$('#loadMore').show();
$('#showLess').show();
if(x == 3){
$('#showLess').hide();
}
});
});
CSS
#showLess {
color:red;
cursor:pointer;
display:none;
}
Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/2/
jQuery has a resize event handler which you can attach to the window, .resize(). So, if you put $(window).resize(function(){/* YOUR CODE HERE */})
then your code will be run every time the window is resized.
So, what you want is to run the code after the first page load and whenever the window is resized. Therefore you should pull the code into its own function and run that function in both instances.
// This function positions the footer based on window size
function positionFooter(){
var $containerHeight = $(window).height();
if ($containerHeight <= 818) {
$('.footer').css({
position: 'static',
bottom: 'auto',
left: 'auto'
});
}
else {
$('.footer').css({
position: 'absolute',
bottom: '3px',
left: '0px'
});
}
}
$(document).ready(function () {
positionFooter();//run when page first loads
});
$(window).resize(function () {
positionFooter();//run on every window resize
});
See: Cross-browser window resize event - JavaScript / jQuery
That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:
DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87
Double check your table definition. Maybe you just missed adding something.
I also tried google-ing this problem and saw this:
http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode
The second parameter must be a URI, not a domain name. i.e.
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, "http://api.foursquare.com/", username, password)
I had the same problem with VS 2015 Community with Node Tools.
I saw some issues about this problem in the NTVS github repository, and it may related to analysis file in the project. In fact, I have deleted this file every project load and it gets faster, but I think the safest way to improve it is ignoring some directory files like the link below.
https://github.com/Microsoft/nodejstools/wiki/Projects#ignoring-directories-for-analysis
Unblock multi-line comment
Ctrl+5
Multi-line comment
Ctrl+4
NOTE: For my version of Spyder (3.1.4) if I highlighted the entire multi-line comment and used Ctrl+5 the block remained commented out. Only after highlighting a small portion of the multi-line comment did Ctrl+5 work.
The type of the elements of an std::map
(which is also the type of an expression obtained by dereferencing an iterator of that map) whose key is K
and value is V
is std::pair<const K, V>
- the key is const
to prevent you from interfering with the internal sorting of map values.
std::pair<>
has two members named first
and second
(see here), with quite an intuitive meaning. Thus, given an iterator i
to a certain map, the expression:
i->first
Which is equivalent to:
(*i).first
Refers to the first (const
) element of the pair
object pointed to by the iterator - i.e. it refers to a key in the map. Instead, the expression:
i->second
Which is equivalent to:
(*i).second
Refers to the second element of the pair
- i.e. to the corresponding value in the map.
The documentation for required()
states:
To force a user to select an option from a select box, provide an empty options like
<option value="">Choose...</option>
By having value="none"
in your <option>
tag, you are preventing the validation call from ever being made. You can also remove your custom validation rule, simplifying your code. Here's a jsFiddle showing it in action:
If you can't change the value
attribute to the empty string, I don't know what to tell you...I couldn't find any way to get it to validate otherwise.
Vim's <leader>
key is a way of creating a namespace for commands you want to define. Vim already maps most keys and combinations of Ctrl + (some key), so <leader>(some key)
is where you (or plugins) can add custom behavior.
For example, if you find yourself frequently deleting exactly 3 words and 7 characters, you might find it convenient to map a command via nmap <leader>d 3dw7x
so that pressing the leader key followed by d will delete 3 words and 7 characters. Because it uses the leader key as a prefix, you can be (relatively) assured that you're not stomping on any pre-existing behavior.
The default key for <leader>
is \
, but you can use the command :let mapleader = ","
to remap it to another key (,
in this case).
Usevim's page on the leader key has more information.
This is slighly more OS independent way:
# do this init somewhere
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
font = pygame.font.Font(pygame.font.get_default_font(), 36)
# now print the text
text_surface = font.render('Hello world', antialias=True, color=(0, 0, 0))
screen.blit(text_surface, dest=(0,0))
To ensure easy and correct installation for python use pip from the get go
To install pip:
$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python2 get-pip.py # for python 2.7
$ sudo python3 get-pip.py # for python 3.x
To install scipy using pip:
$ pip2 install scipy # for python 2.7
$ pip3 install scipy # for python 3.x
Command + / or Ctrl + shift + 7 doesn't work for me (debian + colombian keyboard). In my case I changed the Atom keymap.cson file adding the following:
'.editor':
'ctrl-7': 'editor:toggle-line-comments'
and now it works!
I had a similar issue in windows 7 + ubuntu 12.04 as guest. I resolved by
Although it doesn't apply to this specific example, Option 1 allows you to initialize member variables of reference type (or const
type, as pointed out below). Option 2 doesn't. In general, Option 1 is the more powerful approach.
Download visual studio c++ express version 2006,2010 etc. then goto create new project and create c++ project select cmd project check empty rename cc with c extension file name
To select a value from the dropdown use the index like this:
if we have the
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true"></asp:DropDownList>
you would use :
DropDownList1.Items[DropDownList1.SelectedIndex].Value
this would return the value for the selected index.
Well I tried using
String converted = URLDecoder.decode("toconvert","UTF-8");
I hope this is what you were actually looking for?
In the current documentation we can specify a build.json with the keystore:
{
"android": {
"debug": {
"keystore": "..\android.keystore",
"storePassword": "android",
"alias": "mykey1",
"password" : "password",
"keystoreType": ""
},
"release": {
"keystore": "..\android.keystore",
"storePassword": "",
"alias": "mykey2",
"password" : "password",
"keystoreType": ""
}
}
}
And then, execute the commando with --buildConfig argumente, this way:
cordova run android --buildConfig
You can use array_count_values function
$array = array('apple', 'orange', 'pear', 'banana', 'apple',
'pear', 'kiwi', 'kiwi', 'kiwi');
print_r(array_count_values($array));
will output
Array
(
[apple] => 2
[orange] => 1
[pear] => 2
etc...
)
This was my solution after a lot of struggling to reduce the rating bar in small size without even ugly padding
<RatingBar
android:id="@+id/listitemrating"
style="@android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleX=".5"
android:scaleY=".5"
android:transformPivotX="0dp"
android:transformPivotY="0dp"
android:isIndicator="true"
android:max="5" />
For the record, jQuery has an is()
function for this:
a.is(b)
Note that a
is already a jQuery instance.
There is no "right" way -- there are only conventions. You've stated the most common convention, and the one that I follow in my own code: all static finals should be in all caps. I imagine other teams follow other conventions.
The problem I had was I was removing an item from the list that was no longer associated with the adapter to make sure you are modifying the correct adapter you can implement a method like this in your adapter:
public void removeItemAtPosition(int position) {
items.remove(position);
}
And call it in your fragment or activity like this:
adapter.removeItemAtPosition(position);
Here's a possible way to do it:
$string=exec('getmac');
$mac=substr($string, 0, 17);
echo $mac;
BigInteger
is immutable. The javadocs states that add() "[r]eturns a BigInteger whose value is (this + val)." Therefore, you can't change sum
, you need to reassign the result of the add
method to sum
variable.
sum = sum.add(BigInteger.valueOf(i));
I recommend looking at the dataset array.
The dataset array is a data type that ships with Statistics Toolbox. It is specifically designed to store hetrogeneous data in a single container.
The Statistics Toolbox demo page contains a couple vidoes that show some of the dataset array features. The first is titled "An Introduction to Dataset Arrays". The second is titled "An Introduction to Joins".
Try this:
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "127.0.0.1";
conn_string.Port = 3306;
conn_string.UserID = "root";
conn_string.Password = "myPassword";
conn_string.Database = "myDB";
MySqlConnection MyCon = new MySqlConnection(conn_string.ToString());
try
{
MyCon.Open();
MessageBox.Show("Open");
MyCon.Close();
MessageBox.Show("Close");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I think you are confused about how the compiler puts things together. When you use -c
flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o
files thus don't mix with -c
, and compiler warns you about that. Symbols from object file are not moved to other object files like that.
All object files should be on the final linker invocation, which is not the case here, so linker (called via g++
front-end) complains about missing symbols.
Here's a small example (calling g++
explicitly for clarity):
PROG ?= myprog
OBJS = worker.o main.o
all: $(PROG)
.cpp.o:
g++ -Wall -pedantic -ggdb -O2 -c -o $@ $<
$(PROG): $(OBJS)
g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS)
There's also makedepend
utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M
gcc
option for building make
rules.
Some feedback on the segment of code, though for the most part, it should work...
void main(int c,char **args)
int main
- the standard defines main
as returning an int
.c
and args
are typically named argc
and argv
, respectfully, but you are allowed to name them anything...
{
DIR *dir;
struct dirent *dent;
char buffer[50];
strcpy(buffer,args[1]);
args[1]
is longer than 50 bytes, buffer
will not be able to hold it, and you will write to memory that you shouldn't. There's no reason I can see to copy the buffer here, so you can sidestep these issues by just not using strcpy
......
dir=opendir(buffer); //this part
If this returning NULL
, it can be for a few reasons:
./your_program my directory
, which will fail, because it tries to opendir("my")
)The way you have synchronized is correct. But there is a catch
However in real world you would generally query the map before putting in the value. Hence you would need to do two operations and hence a synchronized block is needed. So the way you have used it is correct. However.
a. It has a API 'putIfAbsent' which would do the same stuff but in a more efficient manner.
b. Its Efficient: dThe CocurrentMap just locks keys hence its not blocking the whole map's world. Where as you have blocked keys as well as values.
c. You could have passed the reference of your map object somewhere else in your codebase where you/other dev in your tean may end up using it incorrectly. I.e he may just all add() or get() without locking on the map's object. Hence his call won't run mutually exclusive to your sync block. But using a concurrent implementation gives you a peace of mind that it can never be used/implemented incorrectly.
I tried changing /etc/environment
:
JAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64"
on the slave node, it works.
Each TCP connection requires an initial handshake before data is transmitted. Also, the TCP header contains a lot of overhead intended for different signals and message delivery detection. For a message exchange, UDP will probably suffice if a small chance of failure is acceptable. If receipt must be verified, TCP is your best option.
Your problem here is that to_datetime
silently failed so the dtype remained as str/object
, if you set param errors='coerce'
then if the conversion fails for any particular string then those rows are set to NaT
.
df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
So you need to find out what is wrong with those specific row values.
See the docs
This is more of an observation than an answer, but it may help others who were as frustrated as I was.
I kept getting this error from two tests in my suite. I thought I had simply broken the tests with the refactoring I was doing, so after backing out changes didn't work, I reverted to earlier code, twice (two revisions back) thinking it'd get rid of the error. Doing so changed nothing. I chased my tail all day yesterday, and part of this morning without resolving the issue.
I got frustrated and checked out the code onto a laptop this morning. Ran the entire test suite (about 180 tests), no errors. So the errors were never in the code or tests. Went back to my dev box and rebooted it to clear anything in memory that might have been causing the issue. No change, same errors on the same two tests. So I deleted the directory from my machine, and checked it back out. Voila! No errors.
No idea what caused it, or how to fix it, but deleting the working directory and checking it back out fixed whatever it was.
Hope this helps someone.
Mockito [3.4.0] can mock static methods!
Replace mockito-core
dependency with mockito-inline:3.4.0
.
Class with static method:
class Buddy {
static String name() {
return "John";
}
}
Use new method Mockito.mockStatic()
:
@Test
void lookMomICanMockStaticMethods() {
assertThat(Buddy.name()).isEqualTo("John");
try (MockedStatic<Buddy> theMock = Mockito.mockStatic(Buddy.class)) {
theMock.when(Buddy::name).thenReturn("Rafael");
assertThat(Buddy.name()).isEqualTo("Rafael");
}
assertThat(Buddy.name()).isEqualTo("John");
}
Mockito replaces the static method within the try
block only.
If you are facing this issue while using Kotlin and have
kotlin.incremental=true
kapt.incremental.apt=true
in the gradle.properties, then you need to remove this temporarily to fix the build.
After the successful build, you can again add these properties to speed up the build time while using Kotlin.
A very very good document regarding this topic is Troubleshooting Guide for Java from (originally) Sun. See the chapter "Troubleshooting System Crashes" for information about hs_err_pid*
Files.
See Appendix C - Fatal Error Log
Per the guide, by default the file will be created in the working directory of the process if possible, or in the system temporary directory otherwise. A specific location can be chosen by passing in the -XX:ErrorFile product flag. It says:
If the -XX:ErrorFile= file flag is not specified, the system attempts to create the file in the working directory of the process. In the event that the file cannot be created in the working directory (insufficient space, permission problem, or other issue), the file is created in the temporary directory for the operating system.
Since you already had a running version of WAMP and it stopped working, you probably had VCRUNTIME140.dll already installed. In that case:
This did the trick for me.
Imagine what happens if x[l] is neither 0 nor 1 in the loop. In that case a and b will never be assigned to and have an undefined value. You must initialize them both with some value, for example 0.
import pylab as plb
plb.rcParams['font.size'] = 12
or
import matplotlib.pyplot as mpl
mpl.rcParams['font.size'] = 12
I usually go with something like the implementation given in Josh Bloch's fabulous Effective Java. It's fast and creates a pretty good hash which is unlikely to cause collisions. Pick two different prime numbers, e.g. 17 and 23, and do:
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hash = 17;
// Suitable nullity checks etc, of course :)
hash = hash * 23 + field1.GetHashCode();
hash = hash * 23 + field2.GetHashCode();
hash = hash * 23 + field3.GetHashCode();
return hash;
}
}
As noted in comments, you may find it's better to pick a large prime to multiply by instead. Apparently 486187739 is good... and although most examples I've seen with small numbers tend to use primes, there are at least similar algorithms where non-prime numbers are often used. In the not-quite-FNV example later, for example, I've used numbers which apparently work well - but the initial value isn't a prime. (The multiplication constant is prime though. I don't know quite how important that is.)
This is better than the common practice of XOR
ing hashcodes for two main reasons. Suppose we have a type with two int
fields:
XorHash(x, x) == XorHash(y, y) == 0 for all x, y
XorHash(x, y) == XorHash(y, x) for all x, y
By the way, the earlier algorithm is the one currently used by the C# compiler for anonymous types.
This page gives quite a few options. I think for most cases the above is "good enough" and it's incredibly easy to remember and get right. The FNV alternative is similarly simple, but uses different constants and XOR
instead of ADD
as a combining operation. It looks something like the code below, but the normal FNV algorithm operates on individual bytes, so this would require modifying to perform one iteration per byte, instead of per 32-bit hash value. FNV is also designed for variable lengths of data, whereas the way we're using it here is always for the same number of field values. Comments on this answer suggest that the code here doesn't actually work as well (in the sample case tested) as the addition approach above.
// Note: Not quite FNV!
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hash = (int) 2166136261;
// Suitable nullity checks etc, of course :)
hash = (hash * 16777619) ^ field1.GetHashCode();
hash = (hash * 16777619) ^ field2.GetHashCode();
hash = (hash * 16777619) ^ field3.GetHashCode();
return hash;
}
}
Note that one thing to be aware of is that ideally you should prevent your equality-sensitive (and thus hashcode-sensitive) state from changing after adding it to a collection that depends on the hash code.
As per the documentation:
You can override GetHashCode for immutable reference types. In general, for mutable reference types, you should override GetHashCode only if:
- You can compute the hash code from fields that are not mutable; or
- You can ensure that the hash code of a mutable object does not change while the object is contained in a collection that relies on its hash code.
The link to the FNV article is broken but here is a copy in the Internet Archive: Eternally Confuzzled - The Art of Hashing
I found this to work for me:
iconv -f ISO-8859-14 Agreement.txt -t UTF-8 -o agreement.txt
I had previously moved my mysql directory and forgot to change ALL references to the old location in \mysql\bin\my.ini.
change these three lines:
datadir = "/programs/xampp/mysql/data"
innodb_data_home_dir = "/programs/xampp/mysql/data"
innodb_log_group_home_dir = "/programs/xampp/mysql/data"
Change "/programs/xampp/mysql/data" to new location this one was commented but I changed it anyways
#innodb_log_arch_dir = "/programs/xampp/mysql/data"
The utf8mb4
character set is useful because nowadays we need support for storing not only language characters but also symbols, newly introduced emojis, and so on.
A nice read on How to support full Unicode in MySQL databases by Mathias Bynens can also shed some light on this.
I'm Using Redmi 3s mobile. I got same problem.
Solution: This issue is common on Xiaomi phones running MIUI 8. This can resolved by turning off MIUI optimizations from Developer Options in Settings app. Then recompile the app and voila it works.
Settings --> Additional settings --> Developer options --> Turn Off MIUI optimization
Or
Settings --> Developer options --> Turn Off MIUI optimization
Is the value of your particular COMMENT column null?
Sometimes NOT LIKE doesn't know how to behave properly around nulls.
None except @Akira Sendoh has answered how to actually get ALL docs. But even that solution crashes my ES 6.3 service without logs. The only thing that worked for me using the low-level elasticsearch-py
library was through scan helper that uses scroll()
api:
from elasticsearch.helpers import scan
doc_generator = scan(
es_obj,
query={"query": {"match_all": {}}},
index="my-index",
)
# use the generator to iterate, dont try to make a list or you will get out of RAM
for doc in doc_generator:
# use it somehow
However, the cleaner way nowadays seems to be through elasticsearch-dsl
library, that offers more abstract, cleaner calls, e.g: http://elasticsearch-dsl.readthedocs.io/en/latest/search_dsl.html#hits
These answers are correct for the cases they state but there is a still a problem if you run the script from another script using the 'source' keyword (so that it runs in the same shell). In this case, you get the $0 of the calling script. And in this case, I don't think it is possible to get the name of the script itself.
This is an edge case and should not be taken TOO seriously. If you run the script from another script directly (without 'source'), using $0 will work.
The API only works during user interaction, so it cannot be used maliciously. Try the following code:
addEventListener("click", function() {
var el = document.documentElement,
rfs = el.requestFullscreen
|| el.webkitRequestFullScreen
|| el.mozRequestFullScreen
|| el.msRequestFullscreen
;
rfs.call(el);
});
In addition to @ShinDarth answer.
I did what he said but my package did not updated the angular version, and I know that this post is about angular-cli
, but i think that this can help too.
-ng new projectname
that generated a package.-npm install
.Now my ng serve
is working again, maybe there is a better way to do all that, if someone know, please share, because this is a pain to do with all projects that need update.
See full gist here and live example here.
#hero { width:100%;height:100%;background:url('{$img_ps_dir}cms/how-it-works/hero.jpg') no-repeat top center; }
.videoWrapper { position:relative;padding-bottom:56.25%;padding-top:25px;max-width:100%; }
<div id="hero">
<div class="container">
<div class="row-fluid">
<script src="https://www.youtube.com/iframe_api"></script>
<center>
<div class="videoWrapper">
<div id="player"></div>
</div>
</center>
<script>
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
videoId:'xxxxxxxxxxx',playerVars: { controls:0,autoplay:0,disablekb:1,enablejsapi:1,iv_load_policy:3,modestbranding:1,showinfo:0,rel:0,theme:'light' }
} );
resizeHeroVideo();
}
</script>
</div>
</div>
</div>
var player = null;
$( document ).ready(function() {
resizeHeroVideo();
} );
$(window).resize(function() {
resizeHeroVideo();
});
function resizeHeroVideo() {
var content = $('#hero');
var contentH = viewportSize.getHeight();
contentH -= 158;
content.css('height',contentH);
if(player != null) {
var iframe = $('.videoWrapper iframe');
var iframeH = contentH - 150;
if (isMobile) {
iframeH = 163;
}
iframe.css('height',iframeH);
var iframeW = iframeH/9 * 16;
iframe.css('width',iframeW);
}
}
resizeHeroVideo is called only after the Youtube player has fully loaded (on page load does not work), and whenever the browser window is resized. When it runs, it calculates the height and width of the iframe and assigns the appropriate values maintaining the correct aspect ratio. This works whether the window is resized horizontally or vertically.
Not sure about how to have read.csv
interpret it properly, but you can use gsub
to replace ","
with ""
, and then convert the string to numeric
using as.numeric
:
y <- c("1,200","20,000","100","12,111")
as.numeric(gsub(",", "", y))
# [1] 1200 20000 100 12111
This was also answered previously on R-Help (and in Q2 here).
Alternatively, you can pre-process the file, for instance with sed
in unix.
There are a few things you can try with this, seems to happen alot and the solution varies for everyone it seems.
If you are still using the IIS virtual directory make sure its pointed to the correct directory and also check the ASP.NET version it is set to, make sure it is set to ASP.NET 2.0.
Clear out your bin/debug/obj all of them. Do a Clean solution and then a Build Solution.
Check your project file in a text editor and make sure where its looking for the global file is correct, sometimes it doesnt change the directory.
Remove the global from the solution and add it back after saving and closing. make sure all the script tags in the ASPX file point to the correct one after.
You can try running the Convert to Web Application tool, that redoes all of the code and project files.
IIS Express is using the wrong root directory (see answer in VS 2012 launching app based on wrong path)
Make sure you close VS after you try them.
Those are some things I know to try. Hope one of them works for you.
I believe the easiest way is to use PyHive.
To install you'll need these libraries:
pip install sasl
pip install thrift
pip install thrift-sasl
pip install PyHive
Please note that although you install the library as PyHive
, you import the module as pyhive
, all lower-case.
If you're on Linux, you may need to install SASL separately before running the above. Install the package libsasl2-dev using apt-get or yum or whatever package manager for your distribution. For Windows there are some options on GNU.org, you can download a binary installer. On a Mac SASL should be available if you've installed xcode developer tools (xcode-select --install
in Terminal)
After installation, you can connect to Hive like this:
from pyhive import hive
conn = hive.Connection(host="YOUR_HIVE_HOST", port=PORT, username="YOU")
Now that you have the hive connection, you have options how to use it. You can just straight-up query:
cursor = conn.cursor()
cursor.execute("SELECT cool_stuff FROM hive_table")
for result in cursor.fetchall():
use_result(result)
...or to use the connection to make a Pandas dataframe:
import pandas as pd
df = pd.read_sql("SELECT cool_stuff FROM hive_table", conn)
Note: This solution is better for older versions of JSTL. For versions greater then 1.1 I recommend using fn:length(MyBean.somelist)
as suggested by Bill James.
This article has some more detailed information, including another possible solution;
The problem is that we are trying to invoke the list's size method (which is a valid LinkedList method), but it's not a JavaBeans-compliant getter method, so the expression list.size-1 cannot be evaluated.
There are two ways to address this dilemma. First, you can use the RT Core library, like this:
<c_rt:out value='<%= list[list.size()-1] %>'/>
Second, if you want to avoid Java code in your JSP pages, you can implement a simple wrapper class that contains a list and provides access to the list's size property with a JavaBeans-compliant getter method. That bean is listed in Listing 2.25.
The problem with c_rt method is that you need to get the variable from request manually, because it doesn't recognize it otherwise. At this point you are putting in a lot of code for what should be built in functionality. This is a GIANT flaw in the EL.
I ended up using the "wrapper" method, here is the class for it;
public class CollectionWrapper {
Collection collection;
public CollectionWrapper(Collection collection) {
this.collection = collection;
}
public Collection getCollection() {
return collection;
}
public int getSize() {
return collection.size();
}
}
A third option that no one has mentioned yet is to put your list size into the model (assuming you are using MVC) as a separate attribute. So in your model you would have "someList" and then "someListSize". That may be simplest way to solve this issue.
This is very old post but if anyone ran into similar problem and need quick answer:
listBox1.IndexFromPoint(new Point(e.X,e.Y))>=0
e.Clicks == 2
I created a VB script and run it either from command line or from a Java process. I also tried to catch errors when creating the shortcut so I can have a better error handling.
Set oWS = WScript.CreateObject("WScript.Shell")
shortcutLocation = Wscript.Arguments(0)
'error handle shortcut creation
On Error Resume Next
Set oLink = oWS.CreateShortcut(shortcutLocation)
If Err Then WScript.Quit Err.Number
'error handle setting shortcut target
On Error Resume Next
oLink.TargetPath = Wscript.Arguments(1)
If Err Then WScript.Quit Err.Number
'error handle setting start in property
On Error Resume Next
oLink.WorkingDirectory = Wscript.Arguments(2)
If Err Then WScript.Quit Err.Number
'error handle saving shortcut
On Error Resume Next
oLink.Save
If Err Then WScript.Quit Err.Number
I run the script with the following commmand:
cscript /b script.vbs shortcutFuturePath targetPath startInProperty
It is possible to have it working even without setting the 'Start in' property in some cases.
Steps: 1. Open a command prompt with administrator's rights.
Steps: 2. Run the command: setx /M PATH "path\to;%PATH%"
[Note: Be sure to alter the command so that path\to reflects the folder path from your root.]
Example : setx /M PATH "C:\Program Files;%PATH%"
chrome://settings/content/sound
I assume you mean list
and not array
? There is such a thing as an array in Python, but more often than not you want a list instead of an array.
The way to check if a list contains a value is to use in
:
if paid[j] in d:
# ...
Another variant to POST this content type and which does not use a dictionary would be:
StringContent postData = new StringContent(JSON_CONTENT, Encoding.UTF8, "application/x-www-form-urlencoded");
using (HttpResponseMessage result = httpClient.PostAsync(url, postData).Result)
{
string resultJson = result.Content.ReadAsStringAsync().Result;
}
Do this:
sudo rm /var/lib/mongodb/mongod.lock
sudo service mongod restart
If you are on Ubuntu 16.04 which you can figure out by runnign this:
lsb_release -a
You need to Create a new file at /lib/systemd/system/mongod.service
with the following contents:
[Unit]
Description=High-performance, schema-free document-oriented database
After=network.target
Documentation=https://docs.mongodb.org/manual
[Service]
User=mongodb
Group=mongodb
ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf
[Install]
WantedBy=multi-user.target
You can use a temporary deletion list:
List<String> keyList = new ArrayList<String>;
for(Map.Entry<String,String> entry : hashTable){
if(entry.getValue().equals("delete")) // replace with your own check
keyList.add(entry.getKey());
}
for(String key : keyList){
hashTable.remove(key);
}
You can find more information about Hashtable methods in the Java API
Bind & protected-mode both are the essential steps. But if ufw is enabled then you will have to make redis port allow in ufw.
ufw status
if Status: active
then allow redis-port ufw allow 6379
vi /etc/redis/redis.conf
bind 127.0.0.1
to bind 0.0.0.0
protected-mode yes
to protected-mode no
The problem here is that the "on" is applied to all elements that exists AT THE TIME. When you create an element dynamically, you need to run the on again:
$('form').on('submit',doFormStuff);
createNewForm();
// re-attach to all forms
$('form').off('submit').on('submit',doFormStuff);
Since forms usually have names or IDs, you can just attach to the new form as well. If I'm creating a lot of dynamic stuff, I'll include a setup or bind function:
function bindItems(){
$('form').off('submit').on('submit',doFormStuff);
$('button').off('click').on('click',doButtonStuff);
}
So then whenever you create something (buttons usually in my case), I just call bindItems to update everything on the page.
createNewButton();
bindItems();
I don't like using 'body' or document elements because with tabs and modals they tend to hang around and do things you don't expect. I always try to be as specific as possible unless its a simple 1 page project.
var table = $("#datatable").DataTable({
"paging": false,
"ordering": false,
"searching": false
});
A little bit simpler and more effective variation of @yannis solution:
SELECT
title,
description,
CHAR_LENGTH(description) - CHAR_LENGTH( REPLACE ( description, 'value', '1234') )
AS `count`
FROM <table>
The difference is that I replace the "value" string with a 1-char shorter string ("1234" in this case). This way you don't need to divide and round to get an integer value.
Generalized version (works for every needle string):
SET @needle = 'value';
SELECT
description,
CHAR_LENGTH(description) - CHAR_LENGTH(REPLACE(description, @needle, SPACE(LENGTH(@needle)-1)))
AS `count`
FROM <table>
Rather than using JavaScript perhaps try something like
<a href="#">
<input type="submit" value="save" style="background: transparent none; border: 0px none; text-decoration: inherit; color: inherit; cursor: inherit" />
</a>
To generate jar file in eclipse right click on the project for which you want to generate, Select Export>Java>Runnable Jar File,
Its create jar which includes all the dependencies from Pom.xml, But please make sure license issue if you are using third-party dependency for your application.
For folks who find this posting through the search engines, another possible cause of this problem is from importing the wrong package version of @Transient
. Make sure that you import javax.persistence.transient
and not some other package.
How do I set up the basic authorization?
All you need to do is use -u, --user USER[:PASSWORD]
. Behind the scenes curl
builds the Authorization
header with base64 encoded credentials for you.
Example:
curl -u username:password -i -H 'Accept:application/json' http://example.com
I solved the issue myself by deleting all old devices (the folders of previously made devices) from my .android/avd folder.
PAGEIOLATCH_SH
wait type usually comes up as the result of fragmented or unoptimized index.
Often reasons for excessive PAGEIOLATCH_SH
wait type are:
In order to try and resolve having high PAGEIOLATCH_SH
wait type, you can check:
PAGEIOLATCH_SH
wait typesAlways keep in mind that in case of high safety Mirroring or synchronous-commit availability in AlwaysOn AG, increased/excessive PAGEIOLATCH_SH
can be expected.
You can find more details about this topic in the article Handling excessive SQL Server PAGEIOLATCH_SH wait types
location='#'
This solution is improvement of pollirrata answer and have some drawback: no smooth scroll and change page location, but is shortest
There is a way that's pretty memory inefficient.
single file:
import hashlib
def file_as_bytes(file):
with file:
return file.read()
print hashlib.md5(file_as_bytes(open(full_path, 'rb'))).hexdigest()
list of files:
[(fname, hashlib.md5(file_as_bytes(open(fname, 'rb'))).digest()) for fname in fnamelst]
Recall though, that MD5 is known broken and should not be used for any purpose since vulnerability analysis can be really tricky, and analyzing any possible future use your code might be put to for security issues is impossible. IMHO, it should be flat out removed from the library so everybody who uses it is forced to update. So, here's what you should do instead:
[(fname, hashlib.sha256(file_as_bytes(open(fname, 'rb'))).digest()) for fname in fnamelst]
If you only want 128 bits worth of digest you can do .digest()[:16]
.
This will give you a list of tuples, each tuple containing the name of its file and its hash.
Again I strongly question your use of MD5. You should be at least using SHA1, and given recent flaws discovered in SHA1, probably not even that. Some people think that as long as you're not using MD5 for 'cryptographic' purposes, you're fine. But stuff has a tendency to end up being broader in scope than you initially expect, and your casual vulnerability analysis may prove completely flawed. It's best to just get in the habit of using the right algorithm out of the gate. It's just typing a different bunch of letters is all. It's not that hard.
Here is a way that is more complex, but memory efficient:
import hashlib
def hash_bytestr_iter(bytesiter, hasher, ashexstr=False):
for block in bytesiter:
hasher.update(block)
return hasher.hexdigest() if ashexstr else hasher.digest()
def file_as_blockiter(afile, blocksize=65536):
with afile:
block = afile.read(blocksize)
while len(block) > 0:
yield block
block = afile.read(blocksize)
[(fname, hash_bytestr_iter(file_as_blockiter(open(fname, 'rb')), hashlib.md5()))
for fname in fnamelst]
And, again, since MD5 is broken and should not really ever be used anymore:
[(fname, hash_bytestr_iter(file_as_blockiter(open(fname, 'rb')), hashlib.sha256()))
for fname in fnamelst]
Again, you can put [:16]
after the call to hash_bytestr_iter(...)
if you only want 128 bits worth of digest.
Please find below JavaScript
example to make a JSONP
call without JQuery:
Also, you can refer my GitHub
repository for reference.
https://github.com/shedagemayur/JavaScriptCode/tree/master/jsonp
window.onload = function(){_x000D_
var callbackMethod = 'callback_' + new Date().getTime();_x000D_
_x000D_
var script = document.createElement('script');_x000D_
script.src = 'https://jsonplaceholder.typicode.com/users/1?callback='+callbackMethod;_x000D_
_x000D_
document.body.appendChild(script);_x000D_
_x000D_
window[callbackMethod] = function(data){_x000D_
delete window[callbackMethod];_x000D_
document.body.removeChild(script);_x000D_
console.log(data);_x000D_
}_x000D_
}
_x000D_
Five columns are clearly not the part of bootstrap by design.
But with Bootstrap v4 (alpha), there are 2 things to help with a complicated grid layout
In simple term, I'm using
<style>
.flexc { display: flex; align-items: center; padding: 0; justify-content: center; }
.flexc a { display: block; flex: auto; text-align: center; flex-basis: 0; }
</style>
<div class="container flexc hidden-sm-down">
<!-- content to show in MD and larger viewport -->
<a href="#">Link/Col 1</a>
<a href="#">Link/Col 2</a>
<a href="#">Link/Col 3</a>
<a href="#">Link/Col 4</a>
<a href="#">Link/Col 5</a>
</div>
<div class="container hidden-md-up">
<!-- content to show in SM and smaller viewport, I don't think 5 cols in smaller viewport are gonna be alright :) -->
</div>
Be it 5,7,9,11,13 or something odds, it'll be okay. I'm quite sure that 12-grids standard is able to serve more than 90% of use case - so let's design that way - develop more easier too!
The nice flex tutorial is here "https://css-tricks.com/snippets/css/a-guide-to-flexbox/"
net stop <your service> && net start <your service>
No net restart
, unfortunately.
Same issue. What was actually happening was that the test running was trying to discover tests in a web site project I have loaded (there was some jasmine specs for angular inside the site).
This was causing the runner to hang trying to load some NodeJS Container
Updating containers from Microsoft.NodejsTools.TestAdapter.TestContainer
I removed the website from the solution (obviously, just the solution, not deleting the website!)
I also had some corrupt configuration data that I had to clear out under the TestStore folder in the .vs directory.
After completing these two steps things magically started working again
Following query helped me. Instead of using LIKE
, you can use ~*
.
select id, name from hosts where name ~* 'julia|lena|jack';
You could make use of Typescript's optional chaining. Example:
const name = person?.name;
If the property name
exists on the person
object you would get its value but if not it would automatically return undefined.
You could make use of this resource for a better understanding.
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html
We use
SELECT * FROM MyTable WHERE ISNULL(MyColumn, ' ') = ' ';
to return all rows where MyColumn is NULL or all rows where MyColumn is an empty string. To many an "end user", the NULL vs. empty string issue is a distinction without a need and point of confusion.
There's no built-in JavaScript function to do this, but you can write your own fairly easily:
function pad(n) {
return (n < 10) ? ("0" + n) : n;
}
Meanwhile there is a native JS function that does that. See String#padStart
console.log(String(5).padStart(2, '0'));
_x000D_
I'm using Object.keys(chars).map(...)
to loop in render
// chars = {a:true, b:false, ..., z:false}
render() {
return (
<div>
{chars && Object.keys(chars).map(function(char, idx) {
return <span key={idx}>{char}</span>;
}.bind(this))}
"Some text value"
</div>
);
}
delimiter //
CREATE procedure yourdatabase.while_example()
wholeblock:BEGIN
declare str VARCHAR(255) default '';
declare x INT default 0;
SET x = 1;
WHILE x <= 5 DO
SET str = CONCAT(str,x,',');
SET x = x + 1;
END WHILE;
select str;
END//
Which prints:
mysql> call while_example();
+------------+
| str |
+------------+
| 1,2,3,4,5, |
+------------+
delimiter //
CREATE procedure yourdb.repeat_loop_example()
wholeblock:BEGIN
DECLARE x INT;
DECLARE str VARCHAR(255);
SET x = 5;
SET str = '';
REPEAT
SET str = CONCAT(str,x,',');
SET x = x - 1;
UNTIL x <= 0
END REPEAT;
SELECT str;
END//
Which prints:
mysql> call repeat_loop_example();
+------------+
| str |
+------------+
| 5,4,3,2,1, |
+------------+
delimiter //
CREATE procedure yourdatabase.for_loop_example()
wholeblock:BEGIN
DECLARE x INT;
DECLARE str VARCHAR(255);
SET x = -5;
SET str = '';
loop_label: LOOP
IF x > 0 THEN
LEAVE loop_label;
END IF;
SET str = CONCAT(str,x,',');
SET x = x + 1;
ITERATE loop_label;
END LOOP;
SELECT str;
END//
Which prints:
mysql> call for_loop_example();
+-------------------+
| str |
+-------------------+
| -5,-4,-3,-2,-1,0, |
+-------------------+
1 row in set (0.00 sec)
Do the tutorial: http://www.mysqltutorial.org/stored-procedures-loop.aspx
If I catch you pushing this kind of MySQL for-loop constructs into production, I'm going to shoot you with the foam missile launcher. You can use a pipe wrench to bang in a nail, but doing so makes you look silly.
fix json values, it's add \ before u{xxx} to all +" "
$item = preg_replace_callback('/"(.+?)":"(u.+?)",/', function ($matches) {
$matches[2] = preg_replace('/(u)/', '\u', $matches[2]);
$matches[2] = preg_replace('/(")/', '"', $matches[2]);
$matches[2] = json_decode('"' . $matches[2] . '"');
return '"' . $matches[1] . '":"' . $matches[2] . '",';
}, $item);
The following code returns 1 if the table exists or 0 if the table does not exist.
SELECT CASE WHEN tbl_name = "name" THEN 1 ELSE 0 END FROM sqlite_master WHERE tbl_name = "name" AND type = "table"
A lot of roll-your-own solutions here for converting data to CSV, but just about all of them will have various caveats in terms of the type of data they will correctly format without tripping up Excel or the likes.
Why not use something proven: Papa Parse
Papa.unparse(data[, config])
Then just combine this with one of the local download solutions here eg. the one by @ArneHB looks good.
I had a duplicate directory (~web/web) and it removed the nested duplicate when I ran rm -rf web
while inside the first web folder.
Not exactly zipping, but you can compact files in Windows with the compact command:
compact /c /s:<directory or file>
And to uncompress:
compact /u /s:<directory or file>
NOTE: These commands only mark/unmark files or directories as compressed in the file system. They do not produces any kind of archive (like zip, 7zip, rar, etc.)
I am using OSX -v 10.10.4. The solution above is a quick & easy.
Happening OSX does not have the connection library by default.
First you should install the connector:
brew install mysql-connector-c
Then install with pip mysql
pip install mysql-python
AttributeError("'str' object has no attribute 'read'",)
This means exactly what it says: something tried to find a .read
attribute on the object that you gave it, and you gave it an object of type str
(i.e., you gave it a string).
The error occurred here:
json.load (jsonofabitch)['data']['children']
Well, you aren't looking for read
anywhere, so it must happen in the json.load
function that you called (as indicated by the full traceback). That is because json.load
is trying to .read
the thing that you gave it, but you gave it jsonofabitch
, which currently names a string (which you created by calling .read
on the response
).
Solution: don't call .read
yourself; the function will do this, and is expecting you to give it the response
directly so that it can do so.
You could also have figured this out by reading the built-in Python documentation for the function (try help(json.load)
, or for the entire module (try help(json)
), or by checking the documentation for those functions on http://docs.python.org .
If you can use JavaScript, the following might be the most portable option today (tested Firefox 31, Chrome 36):
contenteditable="true"
http://jsfiddle.net/cirosantilli/eaxgesoq/
<style>
div#editor {
white-space: pre;
word-wrap: normal;
overflow-x: scroll;
}
<style>
<div contenteditable="true"></div>
There seems to be no standard, portable CSS solution:
wrap
attribute is not standard
white-space: pre;
does not work for Firefox 31 for textarea
. Fiddle, open feature request.
Also, if you can use Javascript, you might as well use the ACE editor:
http://jsfiddle.net/cirosantilli/bL9vr8o8/
<script src="http://cdnjs.cloudflare.com/ajax/libs/ace/1.1.3/ace.js"></script>
<div id="editor">content</div>
<script>
var editor = ace.edit('editor')
editor.renderer.setShowGutter(false)
</script>
Probably works with ACE because it does not use a textarea
either which is underspecified / incoherently implemented, but not sure if it is uses contenteditable
.
The data series names are defined by the column headers. Add the names to the column headers that you would like to use as titles for each of your data series, select all of the data (including the headers), then re-generate your graph. The names in the headers should then appear as the names in the legend for each series.
You should keep your Spring files in another folder, marked as "source" (just like "src" or "resources").
WEB-INF is not a source folder, therefore it will not be included in the classpath (i.e. JUnit will not look for anything there).
select * from my_table where my_field Like '[a-z][a-z]%'
<?php mkdir("testing"); ?>
<= this, actually creates a folder called "testing".
<?php
$file = fopen("test.txt","w");
echo fwrite($file,"Hello World. Testing!");
fclose($file);
?>
Use the a
or a+
switch to add/append to file.
<?php
// change the name below for the folder you want
$dir = "new_folder_name";
$file_to_write = 'test.txt';
$content_to_write = "The content";
if( is_dir($dir) === false )
{
mkdir($dir);
}
$file = fopen($dir . '/' . $file_to_write,"w");
// a different way to write content into
// fwrite($file,"Hello World.");
fwrite($file, $content_to_write);
// closes the file
fclose($file);
// this will show the created file from the created folder on screen
include $dir . '/' . $file_to_write;
?>
Yes there is a difference in the performance of both:
jQuery('#id').show()
is slower than jQuery('#id').css("display","block")
as in former case extra work is to be done for retrieving the initial state from the jquery cache as display is not a binary attribute it can be inline
,block
,none
,table
, etc.
similar is the case with hide()
method.
Since some of the answers are outdated, I would like to provide my own -
To integrate ZXing library into your Android app as suggested by their Wiki, you need to add 2 Java files to your project:
Then in Android Studio add the following line to build.gradle file:
dependencies {
....
compile 'com.google.zxing:core:3.2.1'
}
Or if still using Eclipse with ADT-plugin add core.jar file to the libs subdirectory of your project (here fullscreen Windows and fullscreen Mac):
Finally add this code to your MainActivity.java:
public void scanQRCode(View v) {
IntentIntegrator integrator = new IntentIntegrator(MainActivity.this);
integrator.initiateScan(IntentIntegrator.QR_CODE_TYPES);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult result =
IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (result != null) {
String contents = result.getContents();
if (contents != null) {
showDialog(R.string.result_succeeded, result.toString());
} else {
showDialog(R.string.result_failed,
getString(R.string.result_failed_why));
}
}
}
private void showDialog(int title, CharSequence message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton(R.string.ok_button, null);
builder.show();
}
The resulting app will ask to install and start Barcode Scanner app by ZXing (which will return to your app automatically after scanning):
Additionally, if you would like to build and run the ZXing Test app as inspiration for your own app:
Then you need 4 Java files from GitHub:
And 3 Jar files from Maven repository:
(You can build the Jar files yourself with mvn package
- if your check out ZXing from GitHub and install ant and maven tools at your computer).
Note: if your project does not recognize the Jar files, you might need to up the Java version in the Project Properties:
There is a product from http://www.shunra.com called VE Desktop which can be used to simulate varying network conditions. It allows you to tweak latencies, bandwidth and packetloss with a simple UI. Only caveat is, its not free. Hope this helps.
On one line: Dir['app/models/\*.rb'].map {|f| File.basename(f, '.*').camelize.constantize }
The following will match on any string that starts with mailto
, ftp
or http
:
RegEx reg = new RegEx("^(mailto|ftp|http)");
To break it down:
^
matches start of line(mailto|ftp|http)
matches any of the items separated by a |
I would find StartsWith
to be more readable in this case.
Change table_name
and field
to match your table name and field in question:
UPDATE table_name SET field = REPLACE(field, 'foo', 'bar') WHERE INSTR(field, 'foo') > 0;
This is precisely what position: fixed
was designed for:
#footer {
position: fixed;
bottom: 0;
width: 100%;
}
Here's the fiddle: http://jsfiddle.net/uw8f9/
Following on from Richard's comment. Here's the easy way to convert your file to UNIX line endings. If you're like me you created it in Windows Notepad and then tried to run it in Linux - bad idea.
Unix script file (*.sh;*.bsh)
chmod 755 the_script_filename
./the_script_filename
Any other problems try this link.
Typically if you have database connections or other objects declared that, whether used safely or created prior to your exception, will need to be cleaned up (disposed of), then returning your error handling code back to the ProcExit entry point will allow you to do your garbage collection in both cases.
If you drop out of your procedure by falling to Exit Sub, you may risk having a yucky build-up of instantiated objects that are just sitting around in your program's memory.
I got the same error due to it being a conflict with miniconda3 install so when you type "which virtualenv" and if you've installed miniconda and it's pointing to that install you can either remove it (if your like me and haven't moved to it yet) or change your environment variable to point to the install you want.
I've had better luck with calling the gotoDate
in the viewRender
callback:
$('#calendar').fullCalendar({
firstDay: 0,
defaultView: 'basicWeek',
header: {
left: '',
center: 'basicDay,basicWeek,month',
right: 'today prev,next'
},
viewRender: function(view, element) {
$('#calendar').fullCalendar( 'gotoDate', 2014, 4, 24 );
}
});
Calling gotoDate
outside of the callback didn't have the expected results due to a race condition.
The time zone is a session parameter. So, you can change the timezone for the current session.
See the doc.
set timezone TO 'GMT';
Or, more closely following the SQL standard, use the SET TIME ZONE
command. Notice two words for "TIME ZONE" where the code above uses a single word "timezone".
SET TIME ZONE 'UTC';
The doc explains the difference:
SET TIME ZONE extends syntax defined in the SQL standard. The standard allows only numeric time zone offsets while PostgreSQL allows more flexible time-zone specifications. All other SET features are PostgreSQL extensions.
You can install as pip install mysqlclient
The best way I have found so far is to use React Context but to isolate it inside a high order provider component.