For Python >= 2.7, use subprocess.check_output()
.
http://docs.python.org/2/library/subprocess.html#subprocess.check_output
These guys gave you the reason why is failing but not how to solve it. This problem may appear even if you have a jdk which matches JVM which you are trying it into.
Project -> Properties -> Java Compiler
Enable project specific settings.
Then select Compiler Compliance Level to 1.6 or 1.5, build and test your app.
Now, it should be fine.
This worked for me.
Here I assume my attachment is of a PDF
type format.
Comments are made to understand it clearly.
public class MailAttachmentTester {
public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "[email protected]";
// Sender's email ID needs to be mentioned
String from = "[email protected]";
final String username = "[email protected]";//change accordingly
final String password = "test";//change accordingly
// Assuming you are sending email through relay.jangosmtp.net
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
// Get the Session object.
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
// Set Subject: header field
message.setSubject("Attachment");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setText("Please find the attachment below");
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "D:/test.PDF";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
System.out.println("Email Sent Successfully !!");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
It's also possible to select attributes regardless of their content, in modern browsers
with:
[data-my-attribute] {
/* Styles */
}
[anything] {
/* Styles */
}
For example: http://codepen.io/jasonm23/pen/fADnu
Works on a very significant percentage of browsers.
Note this can also be used in a JQuery selector, or using document.querySelector
New Table...
Because if you don't make a copy then the indices can still be manipulated elsewhere even if you assign the dataFrame to a different name.
For example:
df2 = df
func1(df2)
func2(df)
func1 can modify df by modifying df2, so to avoid that:
df2 = df.copy()
func1(df2)
func2(df)
They are identical. JPG is simply a holdover from the days of DOS when file extensions were required to be 3 characters long. You can find out more information about the JPEG standard here. A question very similar to this one was asked over at SuperUser, where the accepted answer should give you some more detailed information.
using pendingRequests is not correct because as mentioned in Angular documentation, this property is primarily meant to be used for debugging purposes.
What I recommend is to use an interceptor to know if there is any active Async call.
module.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push(function ($q, $rootScope) {
if ($rootScope.activeCalls == undefined) {
$rootScope.activeCalls = 0;
}
return {
request: function (config) {
$rootScope.activeCalls += 1;
return config;
},
requestError: function (rejection) {
$rootScope.activeCalls -= 1;
return rejection;
},
response: function (response) {
$rootScope.activeCalls -= 1;
return response;
},
responseError: function (rejection) {
$rootScope.activeCalls -= 1;
return rejection;
}
};
});
}]);
and then check whether activeCalls is zero or not in the directive through a $watch.
module.directive('loadingSpinner', function ($http) {
return {
restrict: 'A',
replace: true,
template: '<div class="loader unixloader" data-initialize="loader" data-delay="500"></div>',
link: function (scope, element, attrs) {
scope.$watch('activeCalls', function (newVal, oldVal) {
if (newVal == 0) {
$(element).hide();
}
else {
$(element).show();
}
});
}
};
});
I may be misunderstanding your question but it seems you should just be able to use a relative path as long as the production and development servers use the same path structure.
<script language="javascript" src="js/myLib.js" />
Use this code it will help for getting any type of device's screen resolution
[[UIScreen mainScreen] bounds].size.height
[[UIScreen mainScreen] bounds].size.width
Solution for MySQL Workbench 6.3E
For this particular case, if using re
module is overkill, how about using split
(or rsplit
) method as
se='</html>'
z.write(article.split(se)[0]+se)
For example,
#!/usr/bin/python
article='''<html>Larala
Ponta Monta
</html>Kurimon
Waff Moff
'''
z=open('out.txt','w')
se='</html>'
z.write(article.split(se)[0]+se)
outputs out.txt
as
<html>Larala
Ponta Monta
</html>
I would recommend to look at the error_logs
, specifically at the upstream part where it shows specific upstream that is timing out.
Then based on that you can adjust proxy_read_timeout
, fastcgi_read_timeout
or uwsgi_read_timeout
.
Also make sure your config is loaded.
More details here Nginx upstream timed out (why and how to fix)
In the job configuration one can define various build triggers. With periodically build you can schedule the build by defining the date or day of the week and the time to execute the build.
The format is as follows:
MINUTE (0-59), HOUR (0-23), DAY (1-31), MONTH (1-12), DAY OF THE WEEK (0-6)
The letter H, representing the word Hash can be inserted instead of any of the values, it will calculate the parameter based on the hash code of your project name, this is so that if you are building several projects on your build machine at the same time, lets say midnight each day, they do not all start there build execution at the same time, each project starts its execution at a different minute depending on its hash code. You can also specify the value to be between numbers, i.e. H(0,30) will return the hash code of the project where the possible hashes are 0-30
Examples:
start build daily at 08:30 in the morning, Monday - Friday:
weekday daily build twice a day, at lunchtime 12:00 and midnight 00:00, Sunday to Thursday:
start build daily in the late afternoon between 4:00 p.m. - 4:59 p.m. or 16:00 -16:59 depending on the projects hash:
start build at midnight:
or start build at midnight, every Saturday:
every first of every month between 2:00 a.m. - 02:30 a.m. :
Matt Turner's answer is definitely the right answer. However, in the spirit of Ken Williams' answer, you could also do:
capture.output(cat(sdata, sep=""))
#include <iostream>
#include <sys/time.h>
using namespace std;
int main ()
{
unsigned long int sec= time(NULL);
cout<<sec<<endl;
}
If the page under the overlayer can be "fixed" at the top, when you open the overlay you can set
.disableScroll { position: fixed; overflow-y:scroll }
provide this class to the scrollable body, you should still see the right scrollbar but the content is not scrollable.
To maintain the position of the page do this in jquery
$('body').css('top', - ($(window).scrollTop()) + 'px').addClass('disableScroll');
When you close the overlay just revert these properties with
var top = $('body').position().top;
$('body').removeClass('disableScroll').css('top', 0).scrollTop(Math.abs(top));
I just proposed this way only because you wouldn't need to change any scroll event
Resetting IIS
a. From the Start menu, choose All Programs, and then choose Accessories. b. Right-click Command Prompt, and then choose Run as administrator.
At the command prompt, type the following command to change to the Microsoft.NET\Framework64\v4.0.30319 folder, and then press Enter.
cd\Windows\Microsoft.NET\Framework64\v4.0.30319
At the command prompt, type the following command, and then press Enter.
aspnet_regiis.exe -iru
At the command prompt, type the following command, and then press Enter. iisreset
If you installed Node from their website, try this:
sudo rm -rf /usr/local/{bin/{node,npm},lib/node_modules/npm,lib/node,share/man/*/node.*}
This worked for me, but if you have any questions, my GitHub is 'mnafricano'.
Easiest way excpecially if you don't know images widths is to put the caption in it's own div element an define it to be cleared:both !
...
<div class="pics">
<img class="marq" src="pic_1.jpg" />
<div class="caption">My image 1</div>
</div>
<div class="pics">
<img class="marq" src="pic_2.jpg" />
<div class="caption">My image 2</div>
</div>
...
and in style-block define
div.caption: {
float: left;
clear: both;
}
Java and Kotlin runs on Java Virtual Machine (JVM).
Converting a Kotlin file to Java file involves two steps i.e. compiling the Kotlin code to the JVM bytecode and then decompile the bytecode to the Java code.
Steps to convert your Kotlin source file to Java source file:
Reasoning for my CSS styles not being applied, even though they were being loaded:
The media
attribute on the link
tag which was loading the stylesheet had an incorrect value. I had inadvertently set it to 1
instead of all
. This meant the browser was ignoring those styles in that linked stylesheet.
Broken:
<link rel="stylesheet" type="text/css" href="css/style.css" media="1" />
Corrected:
<link rel="stylesheet" type="text/css" href="css/style.css" media="all" />
Tnx @Raj_89 , Your trick was very good , can be better , only by use extra style , that make it on other dom objects , exactly like a common select option tag in html ...
select{
position:absolute;
}
u can see result here : http://jsfiddle.net/aTzc2/
Instead of invoking the sp_helptext locally with a remote argument, invoke it remotely with a local argument:
EXEC [ServerName].[DatabaseName].dbo.sp_HelpText 'storedProcName'
You need to add an additional parameter:
$http.get(url).then(
function(response) {
console.log('get',response)
},
function(data) {
// Handle error here
})
#include<stdio.h>
void main()
{
char a;
clrscr();
printf("enter a character:");
scanf("%c",&a);
if(a>=65&&a<=90)
printf("%c",a+32);
else
printf("type a capital letter");
getch();
}
// helper class, so we don't have to do a whole lot of autoboxing
private static class Count {
public int count = 0;
}
public boolean haveSameElements(final List<String> list1, final List<String> list2) {
// (list1, list1) is always true
if (list1 == list2) return true;
// If either list is null, or the lengths are not equal, they can't possibly match
if (list1 == null || list2 == null || list1.size() != list2.size())
return false;
// (switch the two checks above if (null, null) should return false)
Map<String, Count> counts = new HashMap<>();
// Count the items in list1
for (String item : list1) {
if (!counts.containsKey(item)) counts.put(item, new Count());
counts.get(item).count += 1;
}
// Subtract the count of items in list2
for (String item : list2) {
// If the map doesn't contain the item here, then this item wasn't in list1
if (!counts.containsKey(item)) return false;
counts.get(item).count -= 1;
}
// If any count is nonzero at this point, then the two lists don't match
for (Map.Entry<String, Count> entry : counts.entrySet()) {
if (entry.getValue().count != 0) return false;
}
return true;
}
See ?boxplot
for all the help you need.
outline: if ‘outline’ is not true, the outliers are not drawn (as
points whereas S+ uses lines).
boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)
And for extending the range of the whiskers and suppressing the outliers inside this range:
range: this determines how far the plot whiskers extend out from the
box. If ‘range’ is positive, the whiskers extend to the most
extreme data point which is no more than ‘range’ times the
interquartile range from the box. A value of zero causes the
whiskers to extend to the data extremes.
# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)
Unicode defines a single huge character set, assigning one unique integer value to every graphical symbol (that is a major simplification, and isn't actually true, but it's close enough for the purposes of this question). UTF-8/16/32 are simply different ways to encode this.
In brief, UTF-32 uses 32-bit values for each character. That allows them to use a fixed-width code for every character.
UTF-16 uses 16-bit by default, but that only gives you 65k possible characters, which is nowhere near enough for the full Unicode set. So some characters use pairs of 16-bit values.
And UTF-8 uses 8-bit values by default, which means that the 127 first values are fixed-width single-byte characters (the most significant bit is used to signify that this is the start of a multi-byte sequence, leaving 7 bits for the actual character value). All other characters are encoded as sequences of up to 4 bytes (if memory serves).
And that leads us to the advantages. Any ASCII-character is directly compatible with UTF-8, so for upgrading legacy apps, UTF-8 is a common and obvious choice. In almost all cases, it will also use the least memory. On the other hand, you can't make any guarantees about the width of a character. It may be 1, 2, 3 or 4 characters wide, which makes string manipulation difficult.
UTF-32 is opposite, it uses the most memory (each character is a fixed 4 bytes wide), but on the other hand, you know that every character has this precise length, so string manipulation becomes far simpler. You can compute the number of characters in a string simply from the length in bytes of the string. You can't do that with UTF-8.
UTF-16 is a compromise. It lets most characters fit into a fixed-width 16-bit value. So as long as you don't have Chinese symbols, musical notes or some others, you can assume that each character is 16 bits wide. It uses less memory than UTF-32. But it is in some ways "the worst of both worlds". It almost always uses more memory than UTF-8, and it still doesn't avoid the problem that plagues UTF-8 (variable-length characters).
Finally, it's often helpful to just go with what the platform supports. Windows uses UTF-16 internally, so on Windows, that is the obvious choice.
Linux varies a bit, but they generally use UTF-8 for everything that is Unicode-compliant.
So short answer: All three encodings can encode the same character set, but they represent each character as different byte sequences.
After making above improvement such as checking if mysql service
is running or not, you just need to give a small password while creating connection, it is ' '
or 1 time press on space-bar in case of GUI or workbench. After which you just need to validate your machine with server (validated HOST). For that purpose click on 'New Server Instance'
and it will configure server/HOST on your behalf itself.
I have done this successfully just a few couple of minutes ago. My workbench software is able to show all pre-installed databases
etc now.
hope it will work for you as well.
Thanks!!!
Being forced to have only 1 return statement at the end of a method and making the code fall down to that.
Also not being able to re-use case statements in a switch and let it drop through; I had to write a convoluted script that did a sort of loop of the switch to handle both cases in the right order.
Lastly, when I started using C, I found it very odd to declare my variables at the top of a method and absolutely hated it. I'd spent a good couple of years in C++ and just declared them wherever I wanted; Unless for optimisation reasons I now declare all method variables at the top of a method with details of what they all do - makes maintenance A LOT easier.
My application has a couple views that required a customized navigation bar in the UI for look & feel, however without navigation controller. And the application is required to support iOS version prior to iOS 11, so the handy safe area layout guide could not be used, and I have to adjust the position and height of navigation bar programmatically.
I attached the Navigation Bar to its superview directly, skipping the safe area layout guide as mentioned above. And the status bar height could be retrieved from UIApplication easily, but the default navigation bar height is really a pain-ass...
It struck me for almost half a night, with a number of searching and testing, until I finally got the hint from another post (not working to me though), that you could actually get the height from UIView.sizeThatFits(), like this:
- (void)viewWillLayoutSubviews {
self.topBarHeightConstraint.constant = [UIApplication sharedApplication].statusBarFrame.size.height;
self.navBarHeightConstraint.constant = [self.navigationBar sizeThatFits:CGSizeZero].height;
[super viewWillLayoutSubviews];
}
Finally, a perfect navigation bar looking exactly the same as the built-in one!
A performance comparison:
import itertools
import timeit
big_list = [[0]*1000 for i in range(1000)]
timeit.repeat(lambda: list(itertools.chain.from_iterable(big_list)), number=100)
timeit.repeat(lambda: list(itertools.chain(*big_list)), number=100)
timeit.repeat(lambda: (lambda b: map(b.extend, big_list))([]), number=100)
timeit.repeat(lambda: [el for list_ in big_list for el in list_], number=100)
[100*x for x in timeit.repeat(lambda: sum(big_list, []), number=1)]
Producing:
>>> import itertools
>>> import timeit
>>> big_list = [[0]*1000 for i in range(1000)]
>>> timeit.repeat(lambda: list(itertools.chain.from_iterable(big_list)), number=100)
[3.016212113769325, 3.0148865239060227, 3.0126415732791028]
>>> timeit.repeat(lambda: list(itertools.chain(*big_list)), number=100)
[3.019953987082083, 3.528754223385439, 3.02181439266457]
>>> timeit.repeat(lambda: (lambda b: map(b.extend, big_list))([]), number=100)
[1.812084445152557, 1.7702404451095965, 1.7722977998725362]
>>> timeit.repeat(lambda: [el for list_ in big_list for el in list_], number=100)
[5.409658160700605, 5.477502077679354, 5.444318360412744]
>>> [100*x for x in timeit.repeat(lambda: sum(big_list, []), number=1)]
[399.27587954973444, 400.9240571138051, 403.7521153804846]
This is with Python 2.7.1 on Windows XP 32-bit, but @temoto in the comments above got from_iterable
to be faster than map+extend
, so it's quite platform and input dependent.
Stay away from sum(big_list, [])
Case String:
String password = "ill stay in StringPool after Death !!!";
// some long code goes
// ...Now I want to remove traces of password
password = null;
password = "";
// above attempts wil change value of password
// but the actual password can be traced from String pool through memory dump, if not garbage collected
Case CHAR ARRAY:
char[] passArray = {'p','a','s','s','w','o','r','d'};
// some long code goes
// ...Now I want to remove traces of password
for (int i=0; i<passArray.length;i++){
passArray[i] = 'x';
}
// Now you ACTUALLY DESTROYED traces of password form memory
At macOS Catalina, I followed this steps to set secure_file_priv
1.Stop MySQL service
sudo /usr/local/mysql/support-files/mysql.server stop
2.Restart MYSQL assigning --secure_file_priv system variables
sudo /usr/local/mysql/support-files/mysql.server start --secure-file-priv=YOUR_FILE_DIRECTORY
Note: Adding empty value fix the issue for me, and MYSQL will export data to directory /usr/local/mysql/data/YOUR_DB_TABLE/EXPORT_FILE
sudo /usr/local/mysql/support-files/mysql.server start --secure-file-priv=
Thanks
One other way to work around this is using something like this when using mysqlclient in python.
suppose the data you want to enter is like this <ol><li><strong style="background-color: rgb(255, 255, 0);">Saurav\'s List</strong></li></ol>
. It contains both double qoute and single quote.
You can use the following method to escape the quotes:
statement = """ Update chats set html='{}' """.format(html_string.replace("'","\\\'"))
Note: three \ characters are needed to escape the single quote which is there in unformatted python string.
Here is a plotrix solution:
set.seed(0815)
x <- 1:10
F <- runif(10,1,2)
L <- runif(10,0,1)
U <- runif(10,2,3)
require(plotrix)
plotCI(x, F, ui=U, li=L)
And here is a ggplot solution:
set.seed(0815)
df <- data.frame(x =1:10,
F =runif(10,1,2),
L =runif(10,0,1),
U =runif(10,2,3))
require(ggplot2)
ggplot(df, aes(x = x, y = F)) +
geom_point(size = 4) +
geom_errorbar(aes(ymax = U, ymin = L))
UPDATE: Here is a base solution to your edits:
set.seed(1234)
x <- rnorm(20)
df <- data.frame(x = x,
y = x + rnorm(20))
plot(y ~ x, data = df)
# model
mod <- lm(y ~ x, data = df)
# predicts + interval
newx <- seq(min(df$x), max(df$x), length.out=100)
preds <- predict(mod, newdata = data.frame(x=newx),
interval = 'confidence')
# plot
plot(y ~ x, data = df, type = 'n')
# add fill
polygon(c(rev(newx), newx), c(rev(preds[ ,3]), preds[ ,2]), col = 'grey80', border = NA)
# model
abline(mod)
# intervals
lines(newx, preds[ ,3], lty = 'dashed', col = 'red')
lines(newx, preds[ ,2], lty = 'dashed', col = 'red')
Ran into the same bug here. This worked for me.
.navbar {
position: static;
}
By setting the position to static, it means the navbar will fall into the flow of the document as it normally would.
Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.
Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .
if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .
if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .
after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).
if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.
If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.
If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.
If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property.
if you further face any difficulty then you need to provide more information about your web site and sql server .
I think this is the simplest way to get to what you want.
Credit to JMK's answer for the first part, and the hyperlink part was adapted from http://msdn.microsoft.com/en-us/library/office/ff822490(v=office.15).aspx
'Gets the entire path to the file including the filename using the open file dialog
Dim filename As String
filename = Application.GetOpenFilename
'Adds a hyperlink to cell b5 in the currently active sheet
With ActiveSheet
.Hyperlinks.Add Anchor:=.Range("b5"), _
Address:=filename, _
ScreenTip:="The screenTIP", _
TextToDisplay:=filename
End With
Call below method just after calling the method for opening new window, this will close the current window.
private void close(){
WindowEvent windowEventClosing = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(windowEventClosing);
}
Also in properties of JFrame, make sure defaultCloseOperation is set as DISPOSE.
It sounds like you need to make use of advanced where clauses.
Given that search in field1
and field2
is constant we will leave them as is, but we are going to adjust your search in datefield
a little.
Try this:
$query = Model::where('field1', 1)
->whereNull('field2')
->where(function ($query) {
$query->where('datefield', '<', $date)
->orWhereNull('datefield');
}
);
If you ever need to debug a query and see why it isn't working, it can help to see what SQL it is actually executing. You can chain ->toSql()
to the end of your eloquent query to generate the SQL.
What did it for me was the following, I've added the following directive in both the http <VirtualHost *:80>
and https <VirtualHost *:443>
virtual host blocks:
ServerName your-app.com
ServerAlias www.your-app.com
Header always unset X-Frame-Options
Header set X-Frame-Options "SAMEORIGIN"
The reasoning behind this? Well by default if set, the server does not reset the X-Frame-Options
header so we need to first always remove the default value, in my case it was DENY
, and then with the next rule we set it to the desired value, in my case SAMEORIGIN
. Of course you can use the Header set X-Frame-Options ALLOW-FROM ...
rule as well.
I have combined all the above answers into a script that polls the counters and writes the measurements in the terminal:
$totalRam = (Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property capacity -Sum).Sum
while($true) {
$date = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$cpuTime = (Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples.CookedValue
$availMem = (Get-Counter '\Memory\Available MBytes').CounterSamples.CookedValue
$date + ' > CPU: ' + $cpuTime.ToString("#,0.000") + '%, Avail. Mem.: ' + $availMem.ToString("N0") + 'MB (' + (104857600 * $availMem / $totalRam).ToString("#,0.0") + '%)'
Start-Sleep -s 2
}
This produces the following output:
2020-02-01 10:56:55 > CPU: 0.797%, Avail. Mem.: 2,118MB (51.7%)
2020-02-01 10:56:59 > CPU: 0.447%, Avail. Mem.: 2,118MB (51.7%)
2020-02-01 10:57:03 > CPU: 0.089%, Avail. Mem.: 2,118MB (51.7%)
2020-02-01 10:57:07 > CPU: 0.000%, Avail. Mem.: 2,118MB (51.7%)
You can hit Ctrl+C
to abort the loop.
So, you can connect to any Windows machine with this command:
Enter-PSSession -ComputerName MyServerName -Credential MyUserName
...paste it in, and run it, to get a "live" measurement. If connecting to the machine doesn't work directly, take a look here.
I found this to solve my related problem. I added it to the relevant <Directory>
section:
<IfModule mod_php5.c>
php_admin_flag engine on
</IfModule>
Trying it worked with:
rm -r !(Applications|"Virtualbox VMs"|Downloads|Documents|Desktop|Public)
but names with spaces are (as always) tough. Tried also with Virtualbox\ VMs
instead the quotes. It deletes always that directory (Virtualbox VMs
).
example of textarea for disable the resize option
<textarea CLASS="foo"></textarea>
<style>
textarea.foo
{
resize:none;
}
</style>
You can also use the not operator. It will check if a variable is null, or, in the case of a string, is empty. It makes your code more compact and easier to read.
For example:
var pass = "";
if(!pass)
return false;
else
return true;
This would return false because the string is empty. It would also return false if the variable pass was null.
Here are some ways of doing this:
For example, for using Roboto, install the package using
yarn add typeface-roboto
or
npm install typeface-roboto --save
In index.js:
import "typeface-roboto";
There are npm packages for a lot of open source fonts and most of Google fonts. You can see all fonts here. All the packages are from that project.
For example Google fonts, you can go to fonts.google.com where you can find links that you can put in your public/index.html
It'll be like
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
or
<style>
@import url('https://fonts.googleapis.com/css?family=Montserrat');
</style>
Download the font. For example, for google fonts, you can go to fonts.google.com. Click on the download button to download the font.
Move the font to fonts
directory in your src
directory
src
|
`----fonts
| |
| `-Lato/Lato-Black.ttf
| -Lato/Lato-BlackItalic.ttf
| -Lato/Lato-Bold.ttf
| -Lato/Lato-BoldItalic.ttf
| -Lato/Lato-Italic.ttf
| -Lato/Lato-Light.ttf
| -Lato/Lato-LightItalic.ttf
| -Lato/Lato-Regular.ttf
| -Lato/Lato-Thin.ttf
| -Lato/Lato-ThinItalic.ttf
|
`----App.css
Now, in App.css
, add this
@font-face {
font-family: 'Lato';
src: local('Lato'), url(./fonts/Lato-Regular.otf) format('opentype');
}
@font-face {
font-family: 'Lato';
font-weight: 900;
src: local('Lato'), url(./fonts/Lato-Bold.otf) format('opentype');
}
@font-face {
font-family: 'Lato';
font-weight: 900;
src: local('Lato'), url(./fonts/Lato-Black.otf) format('opentype');
}
For ttf
format, you have to mention format('truetype')
. For woff
, format('woff')
Now you can use the font in classes.
.modal-title {
font-family: Lato, Arial, serif;
font-weight: black;
}
Install package using
yarn add webfontloader
or
npm install webfontloader --save
In src/index.js
, you can import this and specify the fonts needed
import WebFont from 'webfontloader';
WebFont.load({
google: {
families: ['Titillium Web:300,400,700', 'sans-serif']
}
});
public static String join (List<String> list, String separator) {
String listToString = "";
if (list == null || list.isEmpty()) {
return listToString;
}
for (String element : list) {
listToString += element + separator;
}
listToString = listToString.substring(0, separator.length());
return listToString;
}
It's much nicer to be able to just store the function itself, since they're first-class objects in python.
import mypackage
myfunc = mypackage.mymodule.myfunction
myfunc(parameter1, parameter2)
But, if you have to import the package dynamically, then you can achieve this through:
mypackage = __import__('mypackage')
mymodule = getattr(mypackage, 'mymodule')
myfunction = getattr(mymodule, 'myfunction')
myfunction(parameter1, parameter2)
Bear in mind however, that all of that work applies to whatever scope you're currently in. If you don't persist them somehow, you can't count on them staying around if you leave the local scope.
My TS lint was complaining about other solutions, so the solution that was working for me was:
item: Array<Type1 | Type2>
if there's only one type, it's fine to use:
item: Type1[]
Use Apache Common IO's FileUtils
:
import org.apache.commons.io.FileUtils
FileUtils.copyURLToFile(url, f);
The method downloads the content of url
and saves it to f
.
In the same statement in which you execute finish(), execute your animation there too. Then, in the new activity, run another animation. See this code:
fadein.xml
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">
<alpha android:fromAlpha="1.0"
android:toAlpha="0.0"
android:duration="500"/> //Time in milliseconds
</set>
In your finish-class
private void finishTask() {
if("blabbla".equals("blablabla"){
finish();
runFadeInAnimation();
}
}
private void runFadeInAnimation() {
Animation a = AnimationUtils.loadAnimation(this, R.anim.fadein);
a.reset();
LinearLayout ll = (LinearLayout) findViewById(R.id.yourviewhere);
ll.clearAnimation();
ll.startAnimation(a);
}
fadeout.xml
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">
<alpha android:fromAlpha="0.0"
android:toAlpha="1.0"
android:duration="500"/>
</set>
In your new Activity-class you create a similiar method like the runFadeAnimation I wrote and then you run it in onCreate and don't forget to change the resources id to fadeout.
Substract a day from the first of next month:
DateTime lastDay = new DateTime(MyDate.Year,MyDate.Month+1,1).AddDays(-1);
Also, in case you need it to work for December too:
DateTime lastDay = new DateTime(MyDate.Year,MyDate.Month,1).AddMonths(1).AddDays(-1);
Code signing entitlements are no longer necessary for Ad Hoc builds in Xcode 4 - see details notes in Apple Technical Note TN2250
You can use C++20 std::format
or the fmt::format
function from the {fmt} library, std::format
is based on:
#include <fmt/core.h>
int main()
std::string s = fmt::format("{:.2f}", 3.14159265359); // s == "3.14"
}
where 2
is a precision.
If it's already in the classpath, then just obtain it from the classpath instead of from the disk file system. Don't fiddle with relative paths in java.io.File
. They are dependent on the current working directory over which you have totally no control from inside the Java code.
Assuming that ListStopWords.txt
is in the same package as your FileLoader
class, then do:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.getPath());
Or if all you're ultimately after is actually an InputStream
of it:
InputStream input = getClass().getResourceAsStream("ListStopWords.txt");
This is certainly preferred over creating a new File()
because the url
may not necessarily represent a disk file system path, but it could also represent virtual file system path (which may happen when the JAR is expanded into memory instead of into a temp folder on disk file system) or even a network path which are both not per definition digestable by File
constructor.
If the file is -as the package name hints- is actually a fullworthy properties file (containing key=value
lines) with just the "wrong" extension, then you could feed the InputStream
immediately to the load()
method.
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("ListStopWords.txt"));
Note: when you're trying to access it from inside static
context, then use FileLoader.class
(or whatever YourClass.class
) instead of getClass()
in above examples.
select name, count(*) from table group by name;
i think should do it
The :before
pseudo element isn't needed for the clearfix hack itself.
It's just an additional nice feature helping to prevent margin-collapsing of the first child element. Thus the top margin of an child block element of the "clearfixed" element is guaranteed to be positioned below the top border of the clearfixed element.
display:table
is being used because display:block
doesn't do the trick. Using display:block
margins will collapse even with a :before
element.
There is one caveat: if vertical-align:baseline
is used in table cells with clearfixed <div>
elements, Firefox won't align well. Then you might prefer using display:block
despite loosing the anti-collapsing feature. In case of further interest read this article: Clearfix interfering with vertical-align.
Simple is that:
IF OBJECT_ID(dbo.TableName, 'U') IS NOT NULL
DROP TABLE dbo.TableName
where dbo.TableName
is your desired table and 'U' is type
of your table
.
I have studied a number of Go projects and there is a fair bit of variation. You can kind of tell who is coming from C and who is coming from Java, as the former dump just about everything in the projects root directory in a main
package, and the latter tend to put everything in a src
directory. Neither is optimal however. Each have consequences because they affect import paths and how others can reuse them.
To get the best results I have worked out the following approach.
myproj/
main/
mypack.go
mypack.go
Where mypack.go
is package mypack
and main/mypack.go
is (obviously) package main
.
If you need additional support files you have two choices. Either keep them all in the root directory, or put private support files in a lib
subdirectory. E.g.
myproj/
main/
mypack.go
myextras/
someextra.go
mypack.go
mysupport.go
Or
myproj.org/
lib/
mysupport.go
myextras/
someextra.go
main/
mypack.go
mypage.go
Only put the files in a lib
directory if they are not intended to be imported by another project. In other words, if they are private support files. That's the idea behind having lib
--to separate public from private interfaces.
Doing things this way will give you a nice import path, myproj.org/mypack
to reuse the code in other projects. If you use lib
then internal support files will have an import path that is indicative of that, myproj.org/lib/mysupport
.
When building the project, use main/mypack
, e.g. go build main/mypack
. If you have more than one executable you can also separate those under main
without having to create separate projects. e.g. main/myfoo/myfoo.go
and main/mybar/mybar.go
.
--feature
and --no-feature
at the same time (last one wins)This allows users to make a shell alias with --feature
, and overriding it with --no-feature
.
parser.add_argument('--feature', default=True, action=argparse.BooleanOptionalAction)
I recommend mgilson's answer:
parser.add_argument('--feature', dest='feature', action='store_true')
parser.add_argument('--no-feature', dest='feature', action='store_false')
parser.set_defaults(feature=True)
--feature
and --no-feature
at the same timeYou can use a mutually exclusive group:
feature_parser = parser.add_mutually_exclusive_group(required=False)
feature_parser.add_argument('--feature', dest='feature', action='store_true')
feature_parser.add_argument('--no-feature', dest='feature', action='store_false')
parser.set_defaults(feature=True)
You can use this helper if you are going to set many of them:
def add_bool_arg(parser, name, default=False):
group = parser.add_mutually_exclusive_group(required=False)
group.add_argument('--' + name, dest=name, action='store_true')
group.add_argument('--no-' + name, dest=name, action='store_false')
parser.set_defaults(**{name:default})
add_bool_arg(parser, 'useful-feature')
add_bool_arg(parser, 'even-more-useful-feature')
I found this post very helpful as I needed to investigate dependencies from a 3rd party supplied library (32 vs 64 bit execution path(s)).
I put together a Q&D recursing bash script based on the 'readelf -d' suggestion on a RHEL 6 distro.
It is very basic and will test every dependency every time even if it might have been tested before (i.e very verbose). Output is very basic too.
#! /bin/bash
recurse ()
# Param 1 is the nuumber of spaces that the output will be prepended with
# Param 2 full path to library
{
#Use 'readelf -d' to find dependencies
dependencies=$(readelf -d ${2} | grep NEEDED | awk '{ print $5 }' | tr -d '[]')
for d in $dependencies; do
echo "${1}${d}"
nm=${d##*/}
#libstdc++ hack for the '+'-s
nm1=${nm//"+"/"\+"}
# /lib /lib64 /usr/lib and /usr/lib are searched
children=$(locate ${d} | grep -E "(^/(lib|lib64|usr/lib|usr/lib64)/${nm1})")
rc=$?
#at least locate... didn't fail
if [ ${rc} == "0" ] ; then
#we have at least one dependency
if [ ${#children[@]} -gt 0 ]; then
#check the dependeny's dependencies
for c in $children; do
recurse " ${1}" ${c}
done
else
echo "${1}no children found"
fi
else
echo "${1}locate failed for ${d}"
fi
done
}
# Q&D -- recurse needs 2 params could/should be supplied from cmdline
recurse "" !!full path to library you want to investigate!!
redirect the output to a file and grep for 'found' or 'failed'
Use and modify, at your own risk of course, as you wish.
You can truncate the date part:
select * from table1 where trunc(field1) = to_date('2012-01-01', 'YYYY-MM-DD')
The trouble with this approach is that any index on field1
wouldn't be used due to the function call.
Alternatively (and more index friendly)
select * from table1
where field1 >= to_timestamp('2012-01-01', 'YYYY-MM-DD')
and field1 < to_timestamp('2012-01-02', 'YYYY-MM-DD')
It depends on the way your page behaves. If you want this to happens asynchronously, you have to use AJAX. Try out "jQuery post()" on Google to find some tuts.
In other case, if this will happen when a user submits a form, you can send the variable in an hidden field or append ?variableName=someValue"
to then end of the URL you are opening. :
http://www.somesite.com/send.php?variableName=someValue
or
http://www.somesite.com/send.php?variableName=someValue&anotherVariable=anotherValue
This way, from PHP you can access this value as:
$phpVariableName = $_POST["variableName"];
for forms using POST method or:
$phpVariableName = $_GET["variableName"];
for forms using GET method or the append to url method I've mentioned above (querystring).
SurfaceView
probably does not work like a regular View
in this regard.
Instead, do the following:
SurfaceView
inside of a
FrameLayout
or RelativeLayout
in
your layout XML file, since both of
those allow stacking of widgets on
the Z-axisView
classFrameLayout
or
RelativeLayout
, but have it appear
after the SurfaceView
This will cause your custom View
class to appear to float above the SurfaceView
.
See here for a sample project that layers popup panels above a SurfaceView
used for video playback.
Since the true Binding URL for the web service is located in the file, you could do these simple steps from your local machine:
1) Save the file to your local computer for example:
C:\Documents and Settings\[user]\Desktop\Webservice1.asmx
2) In Visual Studio Right Click on your project > Choose Add Web Reference, A dialog will open.
3) In the URL Box Copy the local file location above C:\Documents and Settings[user]\Desktop\Webservice1.asmx, Click Next
4) Now you will see the functions appear, choose your name for the reference, Click add reference
5) You are done! you can start using it as a namespace in your application don't worry that you used a local file, because anyway the true URL for the service is located in the file at the Binding section
At least with Active Directory, I have been able to search by DistinguishedName by doing an LDAP query in this format (assuming that such a record exists with this distinguishedName):
"(distinguishedName=CN=Dev-India,OU=Distribution Groups,DC=gp,DC=gl,DC=google,DC=com)"
I've discovered that if your computer goes to sleep then the docker container goes out of sync.
https://forums.docker.com/t/time-in-container-is-out-of-sync/16566
I have made a post about it here Certificate always expires 5 days ago in Docker
The reason behind this is that meanwhile creating your own class, you had also accepted to create a default class as prescribed by your IDE and after writing your code in your own class, you are getting such an error. In order to eliminate this, go to the PROJECT folder ? src
? Default package. Keep only one class (in which you had written code) and delete others.
After that, run your program and it will definitely run without any error.
They represent [
and ]
. The encoding is called "URL encoding".
The cex
parameter will do that for you.
a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
col = 1:6, space = c(0, 2))
legend("topright",
legend = c("a", "b", "c", "d", "e", "f"),
fill = 1:6, ncol = 2,
cex = 0.75)
Create a function like so:
CREATE FUNCTION dbo.fn_FileExists(@path varchar(512))
RETURNS BIT
AS
BEGIN
DECLARE @result INT
EXEC master.dbo.xp_fileexist @path, @result OUTPUT
RETURN cast(@result as bit)
END;
GO
Edit your table and add a computed column (IsExists BIT). Set the expression to:
dbo.fn_FileExists(filepath)
Then just select:
SELECT * FROM dbo.MyTable where IsExists = 1
Update:
To use the function outside a computed column:
select id, filename, dbo.fn_FileExists(filename) as IsExists
from dbo.MyTable
Update:
If the function returns 0 for a known file, then there is likely a permissions issue. Make sure the SQL Server's account has sufficient permissions to access the folder and files. Read-only should be enough.
And YES, by default, the 'NETWORK SERVICE' account will not have sufficient right into most folders. Right click on the folder in question and select 'Properties', then click on the 'Security' tab. Click 'Edit' and add 'Network Service'. Click 'Apply' and retest.
The third inet_pton
parameter is a pointer to an in_addr
structure. After a successful inet_pton
call, the in_addr
structure will be populated with the address information. The structure's S_addr
field contains the IP address in network byte order (reverse order).
Example :
#include <arpa/inet.h>
uint32_t NodeIpAddress::getIPv4AddressInteger(std::string IPv4Address) {
int result;
uint32_t IPv4Identifier = 0;
struct in_addr addr;
// store this IP address in sa:
result = inet_pton(AF_INET, IPv4Address.c_str(), &(addr));
if (result == -1) {
gpLogFile->Write(LOGPREFIX, LogFile::LOGLEVEL_ERROR, _T("Failed to convert IP %hs to IPv4 Address. Due to invalid family of %d. WSA Error of %d"), IPv4Address.c_str(), AF_INET, result);
}
else if (result == 0) {
gpLogFile->Write(LOGPREFIX, LogFile::LOGLEVEL_ERROR, _T("Failed to convert IP %hs to IPv4"), IPv4Address.c_str());
}
else {
IPv4Identifier = ntohl(*((uint32_t *)&(addr)));
}
return IPv4Identifier;
}
Try using xmltype.createxml(xml)
.
As in,
select extract(xmltype.createxml(xml), '//fax').getStringVal() from mytab;
It worked for me.
If you want to improve or manipulate even further.
Try something like this.
Select *
from xmltable(xmlnamespaces('some-name-space' as "ns",
'another-name-space' as "ns1",
),
'/ns/ns1/foo/bar'
passing xmltype.createxml(xml)
columns id varchar2(10) path '//ns//ns1/id',
idboss varchar2(500) path '//ns0//ns1/idboss',
etc....
) nice_xml_table
Hope it helps someone.
You can use the following depending on your OS:
Windows:
Shift+ Alt + ? or Shift+ Alt + ?
Mac:
Shift + Option + ? or Shift +Option + ?
Linux:
Ctrl+Shift+Alt+? or Ctrl+Shift+Alt+?
Note: For some linux distros use Numpad arrows
You've already got it: A if test else B
is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:
{ (some_key if condition else default_key):(something_if_true if condition
else something_if_false) for key, value in dict_.items() }
The final if
clause acts as a filter, which is different from having the conditional expression.
You can do like
$timeout(function() {
angular.element('#btn2').triggerHandler('click');
});
This would be efficient I guess
String s;
s = "try this\n try me.";
s.replaceAll("[\\r\\n]+", "")
openssl s_client
instead of curl
.-msg
does the trick!-debug
helps to see what actually travels over the socket.-status
OCSP stapling should be standard nowadays.openssl s_client -connect example.com:443 -tls1_2 -status -msg -debug -CAfile <path to trusted root ca pem> -key <path to client private key pem> -cert <path to client cert pem>
Other useful switches
-tlsextdebug
-prexit
-state
While these are all viable answers, I decided to give my way of checking if local repo is in line with the remote, whithout fetching or pulling. In order to see where my branches are I use simply:
git remote show origin
What it does is return all the current tracked branches and most importantly - the info whether they are up to date, ahead or behind the remote origin ones. After the above command, this is an example of what is returned:
* remote origin
Fetch URL: https://github.com/xxxx/xxxx.git
Push URL: https://github.com/xxxx/xxxx.git
HEAD branch: master
Remote branches:
master tracked
no-payments tracked
Local branches configured for 'git pull':
master merges with remote master
no-payments merges with remote no-payments
Local refs configured for 'git push':
master pushes to master (local out of date)
no-payments pushes to no-payments (local out of date)
Hope this helps someone.
Assuming that Windows doesn't really know how to deal with TTC files (which I honestly find strange), you can "split" the combined fonts in an easy way if you use fontforge.
The steps are:
unzip "STHeiti Medium.ttc.zip"
).File > Open
).File > Generate Fonts...
.Repeat the steps of loading 4--6 for the other font and you will have your TTFs readily usable for you.
Note that I emphasized generating instead of saving above: saving the font will create a file in Fontforge's specific SFD format, which is probably useless to you, unless you want to develop fonts with Fontforge.
If you want to have a more programmatic/automatic way of manipulating fonts, then you might be interested in my answer to a similar (but not exactly the same) question.
Further comments: One reason why some people may be interested in performing the splitting mentioned above (or using a font converter after all) is to convert the fonts to web formats (like WOFF). That's great, but be careful to see if the license of the fonts that you are splitting/converting allows such wide redistribution.
Of course, for Free ("as in Freedom") fonts, you don't need to worry (and one of the most prominent licenses of such fonts is the OFL).
If you are using the Qt
toolkit specifically PySide
, you can do the following:
from PySide import QtGui
import sys
app = QtGui.QApplication(sys.argv)
screen_rect = app.desktop().screenGeometry()
width, height = screen_rect.width(), screen_rect.height()
you can use tar, with --exclude option , and then untar it in destination. eg
cd /source_directory
tar cvf test.tar --exclude=dir_to_exclude *
mv test.tar /destination
cd /destination
tar xvf test.tar
see the man page of tar for more info
If you just want to run adb
command. Open command prompt and run following command:
C:\Users\<user_name>\AppData\Local\Android\sdk\platform-tools\adb devices
NOTE: Make sure to replace <user_name> in above command.
!undefined
is true in javascript, so if you want to know whether your variable or object is undefined and want to take actions, you could do something like this:
if(<object or variable>) {
//take actions if object is not undefined
} else {
//take actions if object is undefined
}
Some readable python:
def JoeCalimar(l):
masterList = []
for i in l:
for j in l:
masterList.append(1.*i/j)
pos = masterList.index(min(masterList))
a = pos/len(masterList)
b = pos%len(masterList)
return (l[a],l[b])
Let me know if something is not clear.
for me the solution was to include skip = 0 (number of rows to skip at the top of the file. Can be set >0)
mydata <- read.csv(file = "file.csv", header = TRUE, sep = ",", skip = 22)
Use set_index
with stack
for MultiIndex Series
, then for DataFrame
add reset_index
with rename
:
df1 = (df.set_index(["location", "name"])
.stack()
.reset_index(name='Value')
.rename(columns={'level_2':'Date'}))
print (df1)
location name Date Value
0 A test Jan-2010 12
1 A test Feb-2010 20
2 A test March-2010 30
3 B foo Jan-2010 18
4 B foo Feb-2010 20
5 B foo March-2010 25
You can use the getimagesize
function like this:
list($width, $height) = getimagesize('path to image');
echo "width: " . $width . "<br />";
echo "height: " . $height;
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
You need to add Content-Type to the header.
First, have you compiled the class using the command line javac compiler? Second, it seems that your main method has an incorrect signature - it should be taking in an array of String objects, rather than just one:
public static void main(String[] args){
Once you've changed your code to take in an array of String objects, then you need to make sure that you're printing an element of the array, rather than array itself:
System.out.println(args[0])
If you want to print the whole list of command line arguments, you'd need to use a loop, e.g.
for(int i = 0; i < args.length; i++){
System.out.print(args[i]);
}
System.out.println();
This function will return the byte size of any UTF-8 string you pass to it.
function byteCount(s) {
return encodeURI(s).split(/%..|./).length - 1;
}
To do this you should alter the vertical-align property of the input.
<dd><label class="<?=$email_confirm_class;?>" style="text-align:right; padding-right:3px">Confirm Email</label><input class="text" type="text" style="vertical-align: middle; border:none;" name="email_confirm" id="email_confirm" size="18" value="<?=$_POST['email_confirm'];?>" tabindex="4" /> *</dd>
Here is a more complete version. It has been tested in IE 8 and it works. see the difference by removing the vertical-align: middle from the input:
<html><head></head><body><dl><dt>test</dt><dd><label class="test" style="text-align:right; padding-right:3px">Confirm Email</label><input class="text" type="text" style="vertical-align: middle; font-size: 22px" name="email_confirm" id="email_confirm" size="28" value="test" tabindex="4" /> *</dd></dl></body></html>
Install Tkinter
. I've included the win32api for as a Windows-only solution.
#!/usr/bin/env python
"""Get the current mouse position."""
import logging
import sys
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
level=logging.DEBUG,
stream=sys.stdout)
def get_mouse_position():
"""
Get the current position of the mouse.
Returns
-------
dict :
With keys 'x' and 'y'
"""
mouse_position = None
import sys
if sys.platform in ['linux', 'linux2']:
pass
elif sys.platform == 'Windows':
try:
import win32api
except ImportError:
logging.info("win32api not installed")
win32api = None
if win32api is not None:
x, y = win32api.GetCursorPos()
mouse_position = {'x': x, 'y': y}
elif sys.platform == 'Mac':
pass
else:
try:
import Tkinter # Tkinter could be supported by all systems
except ImportError:
logging.info("Tkinter not installed")
Tkinter = None
if Tkinter is not None:
p = Tkinter.Tk()
x, y = p.winfo_pointerxy()
mouse_position = {'x': x, 'y': y}
print("sys.platform={platform} is unknown. Please report."
.format(platform=sys.platform))
print(sys.version)
return mouse_position
print(get_mouse_position())
Create a generator using
g = myfunct()
Everytime you would like an item, use
next(g)
(or g.next()
in Python 2.5 or below).
If the generator exits, it will raise StopIteration
. You can either catch this exception if necessary, or use the default
argument to next()
:
next(g, default_value)
Just thought I'd add that you can do this in Chrome as well:
Ctrl + Shift + I (Developer Tools) > Sources> Event Listener Breakpoints (on the right).
You can also view all events that have already been attached by simply right clicking on the element and then browsing its properties (the panel on the right).
For example:
Not sure if it's quite as powerful as the firebug option, but has been enough for most of my stuff.
Another option that is a bit different but surprisingly awesome is Visual Event: http://www.sprymedia.co.uk/article/Visual+Event+2
It highlights all of the elements on a page that have been bound and has popovers showing the functions that are called. Pretty nifty for a bookmark! There's a Chrome plugin as well if that's more your thing - not sure about other browsers.
AnonymousAndrew has also pointed out monitorEvents(window);
here
array_walk(
$myArray,
function (&$entry) {
$entry = iconv('Windows-1250', 'UTF-8', $entry);
}
);
They should have the same time, the update is supposed to be atomic, meaning that whatever how long it takes to perform, the action is supposed to occurs as if all was done at the same time.
If you're experiencing a different behaviour, it's time to change for another DBMS.
If you are using IIS Express as the web server on your development machine I would change to Local IIS. This worked for me.
Make sure your iframe is already loaded. Old but reliable way without jQuery:
<iframe src="samedomain.com/page.htm" id="iframe" onload="access()"></iframe>
<script>
function access() {
var iframe = document.getElementById("iframe");
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
console.log(innerDoc.body);
}
</script>
You can add scripts and css in back end and front end with this following code: This is simple class and the functions are called in object oriented way.
class AtiBlogTest {
function register(){
//for backend
add_action( 'admin_enqueue_scripts', array($this,'backendEnqueue'));
//for frontend
add_action( 'wp_enqueue_scripts', array($this,'frontendEnqueue'));
}
function backendEnqueue(){
wp_enqueue_style( 'AtiBlogTestStyle', plugins_url( '/assets/css/admin_mystyle.css', __FILE__ ));
wp_enqueue_script( 'AtiBlogTestScript', plugins_url( '/assets/js/admin_myscript.js', __FILE__ ));
}
function frontendEnqueue(){
wp_enqueue_style( 'AtiBlogTestStyle', plugins_url( '/assets/css/front_mystyle.css', __FILE__ ));
wp_enqueue_script( 'AtiBlogTestScript', plugins_url( '/assets/js/front_myscript.js', __FILE__ ));
}
}
if(class_exists('AtiBlogTest')){
$atiblogtest=new AtiBlogTest();
$atiblogtest->register();
}
In my case, I needed a requirement to parse out the page title AND and have all the other goodness of jQuery, minus it firing scripts. Here is my solution that seems to work.
$.get('/somepage.htm', function (data) {
// excluded code to extract title for simplicity
var bodySI = data.indexOf('<body>') + '<body>'.length,
bodyEI = data.indexOf('</body>'),
body = data.substr(bodySI, bodyEI - bodySI),
$body;
body = body.replace(/<script[^>]*>/gi, ' <!-- ');
body = body.replace(/<\/script>/gi, ' --> ');
//console.log(body);
$body = $('<div>').html(body);
console.log($body.html());
});
This kind of shortcuts worries about script because you are not trying to remove out the script tags and content, instead you are replacing them with comments rendering schemes to break them useless as you would have comments delimiting your script declarations.
Let me know if that still presents a problem as it will help me too.
The code you have posted here and code on your site both are different. There is a break <br>
after second image, so the third image into new line, remove this <br>
and it will display correctly.
I know it's old news but to add my two cents. By default I use the commands LIKE[cd]
rather than just [c]
. The [d]
compares letters with accent symbols. This works especially well in my Warcraft App where people spell their name "Vòódòó" making it nearly impossible to search for their name in a tableview. The [d]
strips their accent symbols during the predicate. So a predicate of @"name LIKE[CD] %@", object.name
where object.name == @"voodoo"
will return the object containing the name Vòódòó.
From the Apple documentation: like[cd] means “case- and diacritic-insensitive like.”) For a complete description of the string syntax and a list of all the operators available, see Predicate Format String Syntax.
The official Jenkins documentation only mentions single line commands like the following:
// Declarative //
and (see)
pipeline {
/* insert Declarative Pipeline here */
}
The syntax of the Jenkinsfile is based on Groovy so it is also possible to use groovy syntax for comments. Quote:
/* a standalone multiline comment
spanning two lines */
println "hello" /* a multiline comment starting
at the end of a statement */
println 1 /* one */ + 2 /* two */
or
/**
* such a nice comment
*/
To do with javascript you could do something like this:
<script type="Text/javascript">
var text = <?= $text_from_db; ?>
</script>
Then you can use whatever you want in your javascript to put the text var into the textbox.
I guess the method std:remove works but it was giving some compatibility issue with the includes so I ended up writing this little function:
string removeCharsFromString(const string str, char* charsToRemove )
{
char c[str.length()+1]; // + terminating char
const char *p = str.c_str();
unsigned int z=0, size = str.length();
unsigned int x;
bool rem=false;
for(x=0; x<size; x++)
{
rem = false;
for (unsigned int i = 0; charsToRemove[i] != 0; i++)
{
if (charsToRemove[i] == p[x])
{
rem = true;
break;
}
}
if (rem == false) c[z++] = p[x];
}
c[z] = '\0';
return string(c);
}
Just use as
myString = removeCharsFromString(myString, "abc\r");
and it will remove all the occurrence of the given char list.
This might also be a bit more efficient as the loop returns after the first match, so we actually do less comparison.
I added this to my vimrc
file.
command! H let @/=""
After you do a search and want to clear the highlights from your search just do :H
You can use sp_help
in SQL Server 2008.
sp_help <table_name>;
Keyboard shortcut for the above command: select table name (i.e highlight it) and press ALT+F1.
You must use the equals operator not the assignment like
if(document.form1.radio1[0].checked == true) {
alert("You have selected Option 1");
}
If expression
returns a boolean, you can just return the result of it.
Example
return (a > b)
Nobody has mentioned or quoted Code Complete so I'll do it.
Minimize the number of returns in each routine. It's harder to understand a routine if, reading it at the bottom, you're unaware of the possibility that it returned somewhere above.
Use a return when it enhances readability. In certain routines, once you know the answer, you want to return it to the calling routine immediately. If the routine is defined in such a way that it doesn't require any cleanup, not returning immediately means that you have to write more code.
The solution is to add height:100%;
to all the parent elements of your .wrapper-div
as well. So:
html{
height: 100%;
}
body{
margin:0;
padding:0;
overflow:hidden;
height:100%;
}
#container{
width:1000px;
margin:0 auto;
height:100%;
}
Try this (Note: I don't have right now Visual Studio ,so code is copy paste from my archive(I haven't test it) :
Private Sub DataGridView1_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
Dim drv As DataRowView
If e.RowIndex >= 0 Then
If e.RowIndex <= ds.Tables("Products").Rows.Count - 1 Then
drv = ds.Tables("Products").DefaultView.Item(e.RowIndex)
Dim c As Color
If drv.Item("Quantity").Value < 5 Then
c = Color.LightBlue
Else
c = Color.Pink
End If
e.CellStyle.BackColor = c
End If
End If
End Sub
The same problem can occur if you have downloaded JUnit jar from the JUnit website, but forgotten to download the Hamcrest jar - both are required (the instructions say to download both, but I skipped ahead! Oops)
You don't really want to be reallocing memory every time you remove something. If you know the rough size of your deck then choose an appropriate size for your array and keep a pointer to the current end of the list. This is a stack.
If you don't know the size of your deck, and think it could get really big as well as keeps changing size, then you will have to do something a little more complex and implement a linked-list.
In C, you have two simple ways to declare an array.
On the stack, as a static array
int myArray[16]; // Static array of 16 integers
On the heap, as a dynamically allocated array
// Dynamically allocated array of 16 integers
int* myArray = calloc(16, sizeof(int));
Standard C does not allow arrays of either of these types to be resized. You can either create a new array of a specific size, then copy the contents of the old array to the new one, or you can follow one of the suggestions above for a different abstract data type (ie: linked list, stack, queue, etc).
Md5 is a hashing algorithm. There is no way to retrieve the original input from the hashed result.
If you want to add a "forgotten password?" feature, you could send your user an email with a temporary link to create a new password.
Note: Sending passwords in plain text is a BAD idea :)
Using Encoding.UTF8.GetBytes
is faster than using MemoryStream
.
Here, I am using NewtonsoftJson to convert input object to JSON string and then getting bytes from JSON string.
byte[] SerializeObject(object value) =>Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(value));
Method | Mean | Error | StdDev | Median | Gen 0 | Allocated |
--------------------------|----------|-----------|-----------|----------|--------|-----------|
ObjectToByteArray | 4.983 us | 0.1183 us | 0.2622 us | 4.887 us | 0.9460 | 3.9 KB |
ObjectToByteArrayWithJson | 1.548 us | 0.0309 us | 0.0690 us | 1.528 us | 0.3090 | 1.27 KB |
stdout is the standard output file stream. Obviously, it's first and default pointer to output is the screen, however you can point it to a file as desired!
Please read:
http://www.cplusplus.com/reference/cstdio/stdout/
C++ is very similar to C however, object oriented.
AFAIK, RewriteBase is only used to fix cases where mod_rewrite is running in a .htaccess
file not at the root of a site and it guesses the wrong web path (as opposed to filesystem path) for the folder it is running in. So if you have a RewriteRule in a .htaccess in a folder that maps to http://example.com/myfolder
you can use:
RewriteBase myfolder
If mod_rewrite isn't working correctly.
Trying to use it to achieve something unusual, rather than to fix this problem sounds like a recipe to getting very confused.
You can simply use the ID attribute to the form and attach the <textarea>
tag to the form like this:
<form name="commentform" action="#" method="post" target="_blank" id="1321">
<textarea name="forcom" cols="40" rows="5" form="1321" maxlength="188">
Enter your comment here...
</textarea>
<input type="submit" value="OK">
<input type="reset" value="Clear">
</form>
The example 1 will not compile. This version of it compiles and runs. It uses lambda features to abbreviate it.
/*
* [RollYourOwnTimeouts.java]
*
* Summary: How to roll your own timeouts.
*
* Copyright: (c) 2016 Roedy Green, Canadian Mind Products, http://mindprod.com
*
* Licence: This software may be copied and used freely for any purpose but military.
* http://mindprod.com/contact/nonmil.html
*
* Requires: JDK 1.8+
*
* Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/
*
* Version History:
* 1.0 2016-06-28 initial version
*/
package com.mindprod.example;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static java.lang.System.*;
/**
* How to roll your own timeouts.
* Based on code at http://stackoverflow.com/questions/19456313/simple-timeout-in-java
*
* @author Roedy Green, Canadian Mind Products
* @version 1.0 2016-06-28 initial version
* @since 2016-06-28
*/
public class RollYourOwnTimeout
{
private static final long MILLIS_TO_WAIT = 10 * 1000L;
public static void main( final String[] args )
{
final ExecutorService executor = Executors.newSingleThreadExecutor();
// schedule the work
final Future<String> future = executor.submit( RollYourOwnTimeout::requestDataFromWebsite );
try
{
// where we wait for task to complete
final String result = future.get( MILLIS_TO_WAIT, TimeUnit.MILLISECONDS );
out.println( "result: " + result );
}
catch ( TimeoutException e )
{
err.println( "task timed out" );
future.cancel( true /* mayInterruptIfRunning */ );
}
catch ( InterruptedException e )
{
err.println( "task interrupted" );
}
catch ( ExecutionException e )
{
err.println( "task aborted" );
}
executor.shutdownNow();
}
/**
* dummy method to read some data from a website
*/
private static String requestDataFromWebsite()
{
try
{
// force timeout to expire
Thread.sleep( 14_000L );
}
catch ( InterruptedException e )
{
}
return "dummy";
}
}
Recommending SequenceEqual is ok, but thinking that it may ever be faster than usual for(;;) loop is too naive.
Here is the reflected code:
public static bool SequenceEqual<TSource>(this IEnumerable<TSource> first,
IEnumerable<TSource> second, IEqualityComparer<TSource> comparer)
{
if (comparer == null)
{
comparer = EqualityComparer<TSource>.Default;
}
if (first == null)
{
throw Error.ArgumentNull("first");
}
if (second == null)
{
throw Error.ArgumentNull("second");
}
using (IEnumerator<TSource> enumerator = first.GetEnumerator())
using (IEnumerator<TSource> enumerator2 = second.GetEnumerator())
{
while (enumerator.MoveNext())
{
if (!enumerator2.MoveNext() || !comparer.Equals(enumerator.Current, enumerator2.Current))
{
return false;
}
}
if (enumerator2.MoveNext())
{
return false;
}
}
return true;
}
As you can see it uses 2 enumerators and fires numerous method calls which seriously slow everything down. Also it doesn't check length at all, so in bad cases it can be ridiculously slower.
Compare moving two iterators with beautiful
if (a1[i] != a2[i])
and you will know what I mean about performance.
It can be used in cases where performance is really not so critical, maybe in unit test code, or in cases of some short list in rarely called methods.
Create a function like this
function cssClass(...c) {
return c.join(" ")
}
Call it when needed.
<div className={cssClass("head",Style.element,"black")}><div>
I don't know if this has changed. But from my experience. nested elements have a maximum opacity equal to the fathers.
Which mean:
<div id="a">
<div id="b">
</div></div>
Div#a has 0.6 opacity
div#b has 1 opacity
Has #b is within #a then it's maximum opacity is always 0.6
If #b would have 0.5 opacity. In reallity it would be 0.6*0.5 == 0.3 opacity
You might also consider split-path -parent $psISE.CurrentFile.Fullpath
if any of the other methods fail. In particular, if you run a file to load a bunch of functions and then execute those functions with-in the ISE shell (or if you run-selected), it seems the Get-Script-Directory
function as above doesn't work.
set vimdiff to ignore case
Having started vim diff with
gvim -d main.sql backup.sql &
I find that annoyingly one file has MySQL keywords in lowercase the other uppercase showing differences on practically every other line
:set diffopt+=icase
this updates the screen dynamically & you can just as easily switch it off again
Sometimes the column you are looking for may be part of the name of many other things that you are not interested in.
For example I was recently looking for a column called "BQR", which also forms part of many other columns such as "BQR_OWNER", "PROP_BQR", etc.
So I would like to have the checkbox that word processors have to indicate "Whole words only".
Unfortunately LIKE has no such functionality, but REGEXP_LIKE can help.
SELECT *
FROM user_source
WHERE regexp_like(text, '(\s|\.|,|^)bqr(\s|,|$)');
This is the regular expression to find this column and exclude the other columns with "BQR" as part of the name:
(\s|\.|,|^)bqr(\s|,|$)
The regular expression matches white-space (\s), or (|) period (.), or (|) comma (,), or (|) start-of-line (^), followed by "bqr", followed by white-space, comma or end-of-line ($).
Here is my way of validating a form with a disabled button. Check out the snippet below:
var inp = document.getElementsByTagName("input");_x000D_
var btn = document.getElementById("btn");_x000D_
// Disable the button dynamically using javascript_x000D_
btn.disabled = "disabled";_x000D_
_x000D_
function checkForm() {_x000D_
for (var i = 0; i < inp.length; i++) {_x000D_
if (inp[i].checkValidity() == false) {_x000D_
btn.disabled = "disabled";_x000D_
} else {_x000D_
btn.disabled = false;_x000D_
}_x000D_
}_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="UTF-8"/>_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>_x000D_
<title>JavaScript</title>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<h1>Javascript form validation</h1>_x000D_
<p>Javascript constraint form validation example:</p>_x000D_
_x000D_
<form onkeyup="checkForm()" autocomplete="off" novalidate>_x000D_
<input type="text" name="fname" placeholder="First Name" required><br><br>_x000D_
<input type="text" name="lname" placeholder="Last Name" required><br><br>_x000D_
<button type="submit" id="btn">Submit</button>_x000D_
</form>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Example explained:
var inp = document.getElementsByTagName("input");
var btn = document.getElementById("btn");
for (var i = 0; i < inp.length; i++) {
// Code
}
checkValidity()
method to check if the input elements
(with a required
attribute) are valid or not (Code is inserted inside the
for loop). If it is invalid, then the button will remain disabled, else the
attribute is removed.
for (var i = 0; i < inp.length; i++) {
if (inp[i].checkValidity() == false) {
btn.disabled = "disabled";
} else {
btn.disabled = false;
}
}
select n1.name, n1.author_id, cast(count_1 as numeric)/total_count
from (select id, name, author_id, count(1) as count_1
from names
group by id, name, author_id) n1
inner join (select distinct(author_id), count(1) as total_count
from names) n2
on (n2.author_id = n1.author_id)
Where true
used distinct
if more inner join, because more join group performance is slow
To extend the given answer with few useful tricks:
var markers = //some array;
var bounds = new google.maps.LatLngBounds();
for(i=0;i<markers.length;i++) {
bounds.extend(markers[i].getPosition());
}
//center the map to a specific spot (city)
map.setCenter(center);
//center the map to the geometric center of all markers
map.setCenter(bounds.getCenter());
map.fitBounds(bounds);
//remove one zoom level to ensure no marker is on the edge.
map.setZoom(map.getZoom()-1);
// set a minimum zoom
// if you got only 1 marker or all markers are on the same address map will be zoomed too much.
if(map.getZoom()> 15){
map.setZoom(15);
}
//Alternatively this code can be used to set the zoom for just 1 marker and to skip redrawing.
//Note that this will not cover the case if you have 2 markers on the same address.
if(count(markers) == 1){
map.setMaxZoom(15);
map.fitBounds(bounds);
map.setMaxZoom(Null)
}
UPDATE:
Further research in the topic show that fitBounds() is a asynchronic
and it is best to make Zoom manipulation with a listener defined before calling Fit Bounds.
Thanks @Tim, @xr280xr, more examples on the topic : SO:setzoom-after-fitbounds
google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
this.setZoom(map.getZoom()-1);
if (this.getZoom() > 15) {
this.setZoom(15);
}
});
map.fitBounds(bounds);
Ultimately, what you're trying to do with the EXTRA blank lines between each one is a little confusing :)
I think what you really want to do is use Get-ItemProperty. You'll get errors when values are missing, but you can suppress them with -ErrorAction 0
or just leave them as reminders. Because the Registry provider returns extra properties, you'll want to stick in a Select-Object that uses the same properties as the Get-Properties.
Then if you want each property on a line with a blank line between, use Format-List (otherwise, use Format-Table to get one per line).
gci -path hklm:\software\microsoft\windows\currentversion\uninstall |
gp -Name DisplayName, InstallDate |
select DisplayName, InstallDate |
fl | out-file addrem.txt
Here's what worked for me to copy and overwrite a file from B:\ to Z:\ drive in a batch script.
echo F| XCOPY B:\utils\MyFile.txt Z:\Backup\CopyFile.txt /Y
The "/Y" parameter at the end overwrites the destination file, if it exists.
The main difference between statement level trigger is below :
statement level trigger : based on name it works if any statement is executed. Does not depends on how many rows or any rows effected.It executes only once. Exp : if you want to update salary of every employee from department HR and at the end you want to know how many rows get effected means how many got salary increased then use statement level trigger. please note that trigger will execute even if zero rows get updated because it is statement level trigger is called if any statement has been executed. No matters if it is affecting any rows or not.
Row level trigger : executes each time when an row is affected. if zero rows affected.no row level trigger will execute.suppose if u want to delete one employye from emp table whose department is HR and u want as soon as employee deleted from emp table the count in dept table from HR section should be reduce by 1.then you should opt for row level trigger.
document.getElementById("idframe").contentWindow.document.getElementById("idelement").value;
as @chepner says in his comment you are comparing $i to a fixed string.
To expand and rectify the situation you should use [[ ]] with the regex operator =~
eg:
for i in $(ls);do
if [[ $i =~ .*\.java$ ]];then
echo "I want to do something with the file $i"
fi
done
the regex to the right of =~ is tested against the value of the left hand operator and should not be quoted, ( quoted will not error but will compare against a fixed string and so will most likely fail"
but @chepner 's answer above using glob is a much more efficient mechanism.
var junk=new Array();
junk.push('This is a string.');
Et cetera.
Without an ORDER BY
the whole idea of TOP
doesn't make much sense. You need to have a consistent definition of which direction is "up" and which is "down" for the concept of top to be meaningful.
Nonetheless SQL Server allows it but doesn't guarantee a deterministic result.
The UPDATE TOP
syntax in the accepted answer does not support an ORDER BY
clause but it is possible to get deterministic semantics here by using a CTE or derived table to define the desired sort order as below.
;WITH CTE AS
(
SELECT TOP 100 *
FROM T1
ORDER BY F2
)
UPDATE CTE SET F1='foo'
There's a workaround for those who want to use Chrome. This extension allows you to request any site with AJAX from any source, since it adds 'Access-Control-Allow-Origin: *'
header to the response.
As an alternative, you can add this argument to your Chrome launcher: --disable-web-security
. Note that I'd only use this for development purposes, not for normal "web surfing". For reference see Run Chromium with Flags.
As a final note, by installing the extension mentioned on the first paragraph, you can easily enable/disable CORS.
I've used PDFBox with good success. Here's a sample of what the code looks like (back from version 0.7.2), that likely came from one of the provided examples:
// load the document
System.out.println("Reading document: " + filename);
PDDocument doc = null;
doc = PDDocument.load(filename);
// look at all the document information
PDDocumentInformation info = doc.getDocumentInformation();
COSDictionary dict = info.getDictionary();
List l = dict.keyList();
for (Object o : l) {
//System.out.println(o.toString() + " " + dict.getString(o));
System.out.println(o.toString());
}
// look at the document catalog
PDDocumentCatalog cat = doc.getDocumentCatalog();
System.out.println("Catalog:" + cat);
List<PDPage> lp = cat.getAllPages();
System.out.println("# Pages: " + lp.size());
PDPage page = lp.get(4);
System.out.println("Page: " + page);
System.out.println("\tCropBox: " + page.getCropBox());
System.out.println("\tMediaBox: " + page.getMediaBox());
System.out.println("\tResources: " + page.getResources());
System.out.println("\tRotation: " + page.getRotation());
System.out.println("\tArtBox: " + page.getArtBox());
System.out.println("\tBleedBox: " + page.getBleedBox());
System.out.println("\tContents: " + page.getContents());
System.out.println("\tTrimBox: " + page.getTrimBox());
List<PDAnnotation> la = page.getAnnotations();
System.out.println("\t# Annotations: " + la.size());
From the documentation:
It is necessary to keep in mind that the browsers do not know how to correctly show this error.
I suspect this is what's happening, if you inspect the HTTP to-and-fro using tools such as Firebug or Live HTTP Headers (both Firefox extensions) you'll be able to see what's really going on.
After reading all available answers I found out, that most flexible, in my case, was to use custom @Exclude
annotation. So, I implemented simple strategy for this (I didn't want to mark all fields using @Expose
nor I wanted to use transient
which conflicted with in app Serializable
serialization) :
Annotation:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Exclude {
}
Strategy:
public class AnnotationExclusionStrategy implements ExclusionStrategy {
@Override
public boolean shouldSkipField(FieldAttributes f) {
return f.getAnnotation(Exclude.class) != null;
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
}
Usage:
new GsonBuilder().setExclusionStrategies(new AnnotationExclusionStrategy()).create();
There is no need to add a listener to the ?android:attr/ratingBarStyleSmall
. Just add
android:isIndicator=false
and it will capture click events, e.g.
<RatingBar
android:id="@+id/myRatingBar"
style="?android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numStars="5"
android:isIndicator="false" />
Config file:
worker_processes 4; # 2 * Number of CPUs
events {
worker_connections 19000; # It's the key to high performance - have a lot of connections available
}
worker_rlimit_nofile 20000; # Each connection needs a filehandle (or 2 if you are proxying)
# Total amount of users you can serve = worker_processes * worker_connections
more info: Optimizing nginx for high traffic loads
While we are working with tomcat 6 and jdk 1.8 versions, some of the features will not work and this error you are getting is one. you need to change the jdk version to stable version(preferable jdk 1.6 or jdk 1.8_65) in eclipse to resolve this error.
in eclipse step 1: properties -> java build path -> jre system library(remove) step 2: add -> jre system library -> alternate jre -> installed jre -> add -> Standard VM -> (in jre home, place jdk path) -> finish
now clean and check the project
Another Note: z-index must be considered when looking at children objects relative to other objects.
For example
<div class="container">
<div class="branch_1">
<div class="branch_1__child"></div>
</div>
<div class="branch_2">
<div class="branch_2__child"></div>
</div>
</div>
If you gave branch_1__child
a z-index of 99
and you gave branch_2__child
a z-index of 1, but you also gave your branch_2
a z-index of 10
and your branch_1
a z-index of 1
, your branch_1__child
still will not show up in front of your branch_2__child
Anyways, what I'm trying to say is; if a parent of an element you'd like to be placed in front has a lower z-index than its relative, that element will not be placed higher.
The z-index is relative to its containers. A z-index placed on a container farther up in the hierarchy basically starts a new "layer"
Incep[inception]tion
Here's a fiddle to play around:
You can do something like this:
rspec/spec/features/controller/spec_file_name.rb
rspec/spec/features/controller_name.rb #run all the specs in this controller
in sys too:
import sys
# its win32, maybe there is win64 too?
is_windows = sys.platform.startswith('win')
Apache Virtual Host documentation Setting up a virtual host (vhost) provides several benefits:
VirtualHost Directive Contains directives that apply only to a specific hostname or IP address
Location Directive Applies the enclosed directives only to matching URLs
Example changes over configuration file - D:\xampp\apache\conf\extra\httpd-vhosts.conf
<VirtualHost *:80>
ServerAdmin localhost
DocumentRoot "D:/xampp/htdocs"
ServerName localhost
</VirtualHost>
<VirtualHost localhost:80>
ServerAdmin [email protected]
DocumentRoot "/www/docs/host.example.com"
#DocumentRoot "D:\xampp\htdocs\phpPages"
ServerName host.example.com
ErrorLog "logs/host.example.com-error_log"
TransferLog "logs/host.example.com-access_log"
</VirtualHost>
# To get view of PHP application in the Browser.
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "D:\xampp\htdocs\app1"
ServerName app1.yash.com
ServerAlias app1.yash.com
ErrorLog "logs/app1.yash.com-error.log"
CustomLog "logs/app1.yash.com-access.log" combined
# App1 communication proxy call to Java War applications from XAMP
<Location /ServletApp1>
ProxyPass http://app1.yashJava.com:8080/ServletApp1
ProxyPassReverse http://app1.yashJava.com:8080/ServletApp1
Order Allow,Deny
Allow from all
</Location>
</VirtualHost>
<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "D:\xampp\htdocs\app2"
ServerName app2.yash.com
ErrorLog "logs/app2.yash.com-error.log"
CustomLog "logs/app2.yash.com-access.log" combined
# App1 communication proxy call to Java War applications from XAMP
<Location /ServletApp2>
ProxyPass http://app1.yashJava.com:8080/ServletApp2
ProxyPassReverse http://app1.yashJava.com:8080/ServletApp2
Order Allow,Deny
Allow from all
</Location>
</VirtualHost>
Update Your Windows Hosts File « Open your Windows hosts file located in C:\Windows\System32\drivers\etc\hosts.
# localhost name resolution is handled within DNS itself.
# 127.0.0.1 localhost
# ::1 localhost
127.0.0.1 test.com
127.0.0.1 example.com
127.0.0.1 myssl.yash.com
D:\xampp\apache\conf\httpd.conf, [httpd-ssl.conf](http://httpd.apache.org/docs/2.2/mod/mod_ssl.html)
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost> directive.
# Listen 0.0.0.0:80 | [::]:80
Listen 80
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule speling_module modules/mod_speling.so
# ServerAdmin: Your address, where problems with the server should be e-mailed.
# This address appears on some server-generated pages, such as error documents.
# e.g. [email protected]
ServerAdmin postmaster@localhost
ServerName localhost:80
DocumentRoot "D:/xampp/htdocs"
<Directory "D:/xampp/htdocs">
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride All
Require all granted
</Directory>
# Virtual hosts
Include "conf/extra/httpd-vhosts.conf"
# ===== httpd-ssl.conf - SSL Virtual Host Context =====
# Note: Configurations that use IPv6 but not IPv4-mapped addresses need two
# Listen directives: "Listen [::]:443" and "Listen 0.0.0.0:443"
Listen 443
## SSL Virtual Host Context
<VirtualHost _default_:443>
DocumentRoot "D:\xampp\htdocs\projectFolderSSL"
ServerName myssl.yash.com:443
ServerAlias myssl.yash.com:443
ServerAdmin webmaster@localhost
ErrorLog "logs/error.log"
<IfModule log_config_module>
CustomLog "logs/access.log" combined
</IfModule>
## Redirecting URL from Web server to Application server over different machine.
# myssl.yash.com:443/ServletWebApp
<Location /path>
ProxyPass http://java.yash2.com:8444/ServletWebApp
ProxyPassReverse http://java.yash2.com:8444/ServletWebApp
Order Allow,Deny
Allow from all
</Location>
#SSLCertificateFile "conf/ssl.crt/server.crt"
SSLCertificateFile "D:\SSL_Vendor\yash.crt"
#SSLCertificateKeyFile "conf/ssl.key/server.key"
SSLCertificateKeyFile "D:\SSL_Vendor\private-key.key"
#SSLCertificateChainFile "conf/ssl.crt/server-ca.crt"
SSLCertificateChainFile "D:\SSL_Vendor\intermediate.crt"
</VirtualHost>
# ===== httpd-ssl.conf - SSL Virtual Host Context =====
@see
foreach (array('one', 'two', 'three') as $v) {
switch ($v) {
case (function ($v) {
if ($v == 'two') return $v;
return 'one';
})($v):
echo "$v min \n";
break;
}
}
this works fine for languages supporting enclosures
Update: In Rails 5, this command will be accessible through this command:
rails db:purge db:create db:migrate RAILS_ENV=test
As of the newest rails 4.2 release you can now run:
rake db:purge
Source: commit
# desc "Empty the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:drop:all to drop all databases in the config). Without RAILS_ENV it defaults to purging the development and test databases."
task :purge => [:load_config] do
ActiveRecord::Tasks::DatabaseTasks.purge_current
end
It can be used together like mentioned above:
rake db:purge db:create db:migrate RAILS_ENV=test
According to pip documentation example 3:
pip install --upgrade django
But based on my experience, using this method will also upgrade any package related to it. Example:
Assume you want to upgrade somepackage
that require Django >= 1.2.4
using this kind of method it will also upgrade somepackage
and django
to the newest update. Just to be safe, do:
# Assume you want to keep Django 1.2.4
pip install --upgrade somepackage django==1.2.4
Doing this will upgrade somepackage
and keeping Django to the 1.2.4 version.
https://github.com/IdentityModel/IdentityModel adds extensions to HttpClient
to acquire tokens using different flows and the documentation is great too. It's very handy because you don't have to think how to implement it yourself. I'm not aware if any official MS implementation exists.
select 'ALTER TABLE ' + OBJECT_NAME(o.object_id) +
' ALTER COLUMN ' + c.name + ' DATETIME2 ' +
CASE WHEN c.is_nullable = 0 THEN 'NOT NULL' ELSE 'NULL' END
from sys.objects o
inner join sys.columns c on o.object_id = c.object_id
inner join sys.types t on c.system_type_id = t.system_type_id
where o.type='U'
and c.name = 'Timestamp'
and t.name = 'datetime'
order by OBJECT_NAME(o.object_id)
courtesy of devio
Just in case you ever want to do this not on Android it's helpful to think about which day where as not all devices mark their calendar in local time.
From Java 8 onwards:
LocalDate.now(ZoneId.of("America/Detroit")).getDayOfWeek()
Reference types do not store the object directly into the variable to which it is assigned, so the object variable in the example below, doesn’t actually contain the object instance. Instead, it holds a pointer (or reference) to the location in memory, where the object exists.
var object = new Object();
if you assign one reference typed variable to another, each variable gets a copy of the pointer, and both still reference to the same object in memory.
var object1 = new Object();
var object2 = object1;
JavaScript is a garbage-collected language, so you don’t really need to worry about memory allocations when you use reference types. However, it’s best to dereference objects that you no longer need so that the garbage collector can free up that memory. The best way to do this is to set the object variable to null.
var object1 = new Object();
// do something
object1 = null; // dereference
Dereferencing objects is especially important in very large applications that use millions of objects.
from The Principles of Object-Oriented JavaScript - NICHOLAS C. ZAKAS
This is what worked for me in Chrome and Firefox! This will open the little print window and close it automatically once you've clicked print.
var printContents = document.getElementById('div-id-selector').innerHTML;
var popupWin = window.open('', '_blank', 'width=800,height=800,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no,top=50');
popupWin.window.focus();
popupWin.document.open();
popupWin.document.write('<!DOCTYPE html><html><head><title>TITLE OF THE PRINT OUT</title>'
+'<link rel="stylesheet" type="text/css" href="app/directory/file.css" />'
+'</head><body onload="window.print(); window.close();"><div>'
+ printContents + '</div></html>');
popupWin.document.close();
create a logfile in php, to do it you need to pass data on function and it will create log file for you.
function wh_log($log_msg)
{
$log_filename = "log";
if (!file_exists($log_filename))
{
// create directory/folder uploads.
mkdir($log_filename, 0777, true);
}
$log_file_data = $log_filename.'/log_' . date('d-M-Y') . '.log';
// if you don't add `FILE_APPEND`, the file will be erased each time you add a log
file_put_contents($log_file_data, $log_msg . "\n", FILE_APPEND);
}
// call to function
wh_log("this is my log message");
Most likely you need to use this trick:
dbms_output.put_line('Hi' || chr(10) ||
'good' || chr(10) ||
'morning' || chr(10) ||
'friends' || chr(10));
For those that struggle with the "SettingWithCopy" warning, here's a workaround which may not be so efficient, but still gets the job done.
Suppose you with to overwrite column_1 and column_3, but retain column_2 and column_4
columns_to_overwrite = ["column_1", "column_3"]
First delete the columns that you intend to replace...
original_df.drop(labels=columns_to_overwrite, axis="columns", inplace=True)
... then re-insert the columns, but using the values that you intended to overwrite
original_df[columns_to_overwrite] = other_data_frame[columns_to_overwrite]
problem is with dos line ending. Following will convert it for unix
dos2unix file_name
NB: you may need to install dos2unix first with yum install dos2unix
another way to do it is using sed
command to search and replace the dos line ending characters to unix format:
$sed -i -e 's/\r$//' your_script.sh
class Person:
def init(self,name,age,weight,sex,mob_no,place):
self.name = str(name)
self.age = int(age)
self.weight = int(weight)
self.sex = str(sex)
self.mob_no = int(mob_no)
self.place = str(place)
p1 = Person(Muthuswamy,50,70,Male,94*****23,India)
print(p1.name)
print(p1.place)
Muthuswamy
India
If you want to round it to lower, just cast it.
float my_float = 42.8f;
int my_int;
my_int = (int)my_float; // => my_int=42
For other purpose, if you want to round it to nearest, you can make a little function or a define like this:
#define FLOAT_TO_INT(x) ((x)>=0?(int)((x)+0.5):(int)((x)-0.5))
float my_float = 42.8f;
int my_int;
my_int = FLOAT_TO_INT(my_float); // => my_int=43
Be careful, ideally you should verify float is between INT_MIN and INT_MAX before casting it.
I know that this is an old question, but if you are building an API, as the author of the question does, use output transformers to perform such tasks.
Transofrmer is a layer between your actual database query result and a controller. It allows to easily control and modify what is going to be output to a user or an API consumer.
I recommend Fractal as a solid foundation of your output transformation layer. You can read the documentation here.
This is something of a religious debate. Both approaches have their problems.
Bloch has another relevant piece of advice in Effective Java Second Edition:
Include language file source in your head script of the HTML body.
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"></script>
Example on JSFiddle
You can do:
$ pip install "package>=0.2,<0.3"
And pip
will look for the best match, assuming the version is at least 0.2, and less than 0.3.
This also applies to pip requirements files. See the full details on version specifiers in PEP 440.
I simply used this:
git add app/src/release/*
You simply need to specify the folder to add and then use *
to add everything that is inside recursively.
No, you can simply use com.fasterxml.jackson.databind.ObjectMapper
.
Most likely you forgot to fix your import
-statements, delete all references to codehaus and you're golden.
Just move the extra condition into the JOIN ON criteria, this way the existence of b is not required to return a result
SELECT a.* FROM a
LEFT JOIN b ON a.group_id=b.group_id AND b.user_id!=$_SESSION{['user_id']}
WHERE a.keyword LIKE '%".$keyword."%'
GROUP BY group_id
I believe this would be the simplest solution:
<configuration>
<contextName>selenium-plugin</contextName>
<!-- Logging configuration -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<Target>System.out</Target>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<encoder>
<pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%level] %msg%n</pattern>
</encoder>
</appender>
<appender name="STDERR" class="ch.qos.logback.core.ConsoleAppender">
<Target>System.err</Target>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<encoder>
<pattern>[%d{yyyy-MM-dd HH:mm:ss.SSS}] [%level] [%thread] %logger{10} [%file:%line] %msg%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT"/>
<appender-ref ref="STDERR" />
</root>
</configuration>
Maybe this code could help:
lastBusDay = datetime.datetime.today()
shift = datetime.timedelta(max(1,(lastBusDay.weekday() + 6) % 7 - 3))
lastBusDay = lastBusDay - shift
The idea is that on Mondays yo have to go back 3 days, on Sundays 2, and 1 in any other day.
The statement (lastBusDay.weekday() + 6) % 7
just re-bases the Monday from 0 to 6.
Really don't know if this will be better in terms of performance.
An alternative answer would be this.
<div id="container">
<div id="centered"> </div>
</div>
and the css:
#container {
height: 400px;
width: 400px;
background-color: lightblue;
text-align: center;
}
#container:before {
height: 100%;
content: '';
display: inline-block;
vertical-align: middle;
}
#centered {
width: 100px;
height: 100px;
background-color: blue;
display: inline-block;
vertical-align: middle;
margin: 0 auto;
}
So to put it all together, checking for Nan, infinity and complex numbers (it would seem they are specified with j, not i, i.e. 1+2j) it results in:
def is_number(s):
try:
n=str(float(s))
if n == "nan" or n=="inf" or n=="-inf" : return False
except ValueError:
try:
complex(s) # for complex
except ValueError:
return False
return True
As Matt has said, use Console.Write
. I would also recommend explicitly flushing the output, however - I believe WriteLine
does this automatically, but I'd seen oddities when just using Console.Write
and then waiting. So Matt's code becomes:
Console.Write("What is your name? ");
Console.Out.Flush();
var name = Console.ReadLine();
If you want to get a list of all tablespaces used in the current database instance, you can use the DBA_TABLESPACES view as shown in the following SQL script example:
SQL> connect SYSTEM/fyicenter
Connected.
SQL> SELECT TABLESPACE_NAME, STATUS, CONTENTS
2 FROM USER_TABLESPACES;
TABLESPACE_NAME STATUS CONTENTS
------------------------------ --------- ---------
SYSTEM ONLINE PERMANENT
UNDO ONLINE UNDO
SYSAUX ONLINE PERMANENT
TEMP ONLINE TEMPORARY
USERS ONLINE PERMANENT
http://dba.fyicenter.com/faq/oracle/Show-All-Tablespaces-in-Current-Database.html
The argument to remove()
is a filter document, so passing in an empty document means 'remove all':
db.user.remove({})
However, if you definitely want to remove everything you might be better off dropping the collection. Though that probably depends on whether you have user defined indexes on the collection i.e. whether the cost of preparing the collection after dropping it outweighs the longer duration of the remove()
call vs the drop()
call.
More details in the docs.
Plus: when you install requests with python3, the command is:
pip3 install requests
not
pip install requests
TemplateBinding is not quite the same thing. MSDN docs are often written by people that have to quiz monosyllabic SDEs about software features, so the nuances are not quite right.
TemplateBindings are evaluated at compile time against the type specified in the control template. This allows for much faster instantiation of compiled templates. Just fumble the name in a templatebinding and you'll see that the compiler will flag it.
The binding markup is resolved at runtime. While slower to execute, the binding will resolve property names that are not visible on the type declared by the template. By slower, I'll point out that its kind of relative since the binding operation takes very little of the application's cpu. If you were blasting control templates around at high speed you might notice it.
As a matter of practice use the TemplateBinding when you can but don't fear the Binding.
Note that $(element).offset()
tells you the position of an element relative to the document. This works great in most circumstances, but in the case of position:fixed
you can get unexpected results.
If your document is longer than the viewport and you have scrolled vertically toward the bottom of the document, then your position:fixed
element's offset()
value will be greater than the expected value by the amount you have scrolled.
If you are looking for a value relative to the viewport (window), rather than the document on a position:fixed element, you can subtract the document's scrollTop()
value from the fixed element's offset().top
value. Example: $("#el").offset().top - $(document).scrollTop()
If the position:fixed
element's offset parent is the document, you want to read parseInt($.css('top'))
instead.
First of all, try the standard way:
git reset HEAD --hard # To remove all not committed changes!
git clean -fd # To remove all untracked (non-git) files and folders!
Warning: Above commands can results in data/files loss only if you don't have them committed! If you're not sure, make the backup first of your whole repository folder.
Then pull it again.
If above won't help and you don't care about your untracked files/directories (make the backup first just in case), try the following simple steps:
cd your_git_repo # where 'your_git_repo' is your git repository folder
rm -rfv * # WARNING: only run inside your git repository!
git pull # pull the sources again
This will REMOVE all git files (excempt .git/
dir, where you have all commits) and pull it again.
Why git reset HEAD --hard
could fail in some cases?
Custom rules in .gitattributes file
Having eol=lf
rule in .gitattributes could cause git to modify some file changes by converting CRLF line-endings into LF in some text files.
If that's the case, you've to commit these CRLF/LF changes (by reviewing them in git status
), or try: git config core.autcrlf false
to temporary ignore them.
File system incompability
When you're using file-system which doesn't support permission attributes.
In example you have two repositories, one on Linux/Mac (ext3
/hfs+
) and another one on FAT32/NTFS based file-system.
As you notice, there are two different kind of file systems, so the one which doesn't support Unix permissions basically can't reset file permissions on system which doesn't support that kind of permissions, so no matter how --hard
you try, git always detect some "changes".
We, the Javascript lovers, don't have to use Ruby (Jekyll or Octopress) to generate static pages in Github pages, we can use Node.js and Harp, for example:
These are the steps. Abstract:
Clone the Repository
git clone https://github.com/your-github-user-name/your-github-user-name.github.io.git
Initialize a Harp app (locally):
harp init _harp
make sure to name the folder with an underscore at the beginning; when you deploy to GitHub Pages, you don’t want your source files to be served.
Compile your Harp app
harp compile _harp ./
Deploy to Gihub
git add -A
git commit -a -m "First Harp + Pages commit"
git push origin master
And this is a cool tutorial with details about nice stuff like layouts, partials, Jade and Less.
If you have old key, you should recreate your API Key. Also be aware of proxies.
callback from adapter to activity can be done using registering listener in form of interface: Make an interface:
public MyInterface{
public void yourmethod(//incase needs parameters );
}
In Adapter Let's Say MyAdapter:
public MyAdapter extends BaseAdapter{
private MyInterface listener;
MyAdapter(Context context){
try {
this. listener = (( MyInterface ) context);
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement MyInterface");
}
//do this where u need to fire listener l
try {
listener . yourmethod ();
} catch (ClassCastException exception) {
// do something
}
In Activity Implement your method:
MyActivity extends AppCompatActivity implements MyInterface{
yourmethod(){
//do whatever you want
}
}
In app.component.html
:
<select type="number" [(ngModel)]="selectedLevel">
<option *ngFor="let level of levels" [ngValue]="level">{{level.name}}</option>
</select>
And app.component.ts
:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
levelNum:number;
levels:Array<Object> = [
{num: 0, name: "AA"},
{num: 1, name: "BB"}
];
toNumber(){
this.levelNum = +this.levelNum;
console.log(this.levelNum);
}
selectedLevel = this.levels[0];
selectedLevelCustomCompare = {num: 1, name: "BB"}
compareFn(a, b) {
console.log(a, b, a && b && a.num == b.num);
return a && b && a.num == b.num;
}
}
Found this in another thread, and it works great on desktop and mobile - which is something that didn't seem true with some of the other solutions. Add this script to the end of your page:
<!--Script stops video from playing when modal is closed-->
<script>
$("#myModal").on('hidden.bs.modal', function (e) {
$("#myModal iframe").attr("src", $("#myModal iframe").attr("src"));
});
</script>
Swift 3.0
if let url = URL(string: "https://www.reddit.com") {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:])
} else {
UIApplication.shared.openURL(url)
}
}
This supports devices running older versions of iOS as well
This solution gives correct results over the entire range [0,UINT_MAX] without requiring digits to be buffered.
It also works for wider types or signed types (with positive values) with appropriate type changes.
This kind of approach is particularly useful on tiny environments (e.g. Arduino bootloader) because it doesn't end up pulling in all the printf() bloat (when printf() isn't used for demo output) and uses very little RAM. You can get a look at value just by blinking a single led :)
#include <limits.h>
#include <stdio.h>
int
main (void)
{
unsigned int score = 42; // Works for score in [0, UINT_MAX]
printf ("score via printf: %u\n", score); // For validation
printf ("score digit by digit: ");
unsigned int div = 1;
unsigned int digit_count = 1;
while ( div <= score / 10 ) {
digit_count++;
div *= 10;
}
while ( digit_count > 0 ) {
printf ("%d", score / div);
score %= div;
div /= 10;
digit_count--;
}
printf ("\n");
return 0;
}
Here is an async helper function written in typescript that seems to do the trick for me. I guess this will not work for long-lived processes but still might be handy for someone?
import * as child_process from "child_process";
private async spawn(command: string, args: string[]): Promise<{code: number | null, result: string}> {
return new Promise((resolve, reject) => {
const spawn = child_process.spawn(command, args)
let result: string
spawn.stdout.on('data', (data: any) => {
if (result) {
reject(Error('Helper function does not work for long lived proccess'))
}
result = data.toString()
})
spawn.stderr.on('data', (error: any) => {
reject(Error(error.toString()))
})
spawn.on('exit', code => {
resolve({code, result})
})
})
}
What you are trying to do is an extension of string slicing in Python:
Say all strings are of length 10, last char to be removed:
>>> st[:9]
'abcdefghi'
To remove last N
characters:
>>> N = 3
>>> st[:-N]
'abcdefg'
public class RemoveRepeatedCharacters {
/**
* This method removes duplicates in a given string in one single pass.
* Keeping two indexes, go through all the elements and as long as subsequent characters match, keep
* moving the indexes in opposite directions. When subsequent characters don't match, copy value at higher index
* to (lower + 1) index.
* Time Complexity = O(n)
* Space = O(1)
*
*/
public static void removeDuplicateChars(String text) {
char[] ch = text.toCharArray();
int i = 0; //first index
for(int j = 1; j < ch.length; j++) {
while(i >= 0 && j < ch.length && ch[i] == ch[j]) {
i--;
j++;
System.out.println("i = " + i + " j = " + j);
}
if(j < ch.length) {
ch[++i] = ch[j];
}
}
//Print the final string
for(int k = 0; k <= i; k++)
System.out.print(ch[k]);
}
public static void main(String[] args) {
String text = "abccbdeefgg";
removeDuplicateChars(text);
}
}
<div *ngIf="currentStatus !== ('status1' || 'status2' || 'status3' || 'status4')">
There might be more than one index map to your value, it make more sense to return a list:
In [48]: a
Out[48]:
c1 c2
0 0 1
1 2 3
2 4 5
3 6 7
4 8 9
In [49]: a.c1[a.c1 == 8].index.tolist()
Out[49]: [4]
try setting this
CATALINA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8
-server -Xms1536m -Xmx1536m
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"
in {$tomcat-folder}\bin\setenv.sh
(create it if necessary).
See http://www.mkyong.com/tomcat/tomcat-javalangoutofmemoryerror-permgen-space/ for more details.
First of all, the provided long code:
<xsl:choose>
<xsl:when test="OU_NAME='OU_ADDR1'"> --comparing two elements coming from XML
<!--remove if adrees already contain operating unit name <xsl:value-of select="OU_NAME"/> <fo:block/>-->
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="OU_NAME"/>
<fo:block/>
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
</xsl:otherwise>
</xsl:choose>
is equivalent to this, much shorter code:
<xsl:if test="not(OU_NAME='OU_ADDR1)'">
<xsl:value-of select="OU_NAME"/>
</xsl:if>
<xsl:if test="OU_ADDR1 !='' ">
<xsl:value-of select="OU_ADDR1"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR2 !='' ">
<xsl:value-of select="OU_ADDR2"/>
<fo:block/>
</xsl:if>
<xsl:if test="LE_ADDR3 !='' ">
<xsl:value-of select="OU_ADDR3"/>
<fo:block/>
</xsl:if>
<xsl:if test="OU_TOWN_CITY !=''">
<xsl:value-of select="OU_TOWN_CITY"/>,
<fo:leader leader-pattern="space" leader-length="2.0pt"/>
</xsl:if>
<xsl:value-of select="OU_REGION2"/>
<fo:leader leader-pattern="space" leader-length="3.0pt"/>
<xsl:value-of select="OU_POSTALCODE"/>
<fo:block/>
<xsl:value-of select="OU_COUNTRY"/>
Now, to your question:
how to compare two elements coming from xml as string
In Xpath 1.0 strings can be compared only for equality (or inequality), using the operator =
and the function not()
together with the operator =
.
$str1 = $str2
evaluates to true()
exactly when the string $str1
is equal to the string $str2
.
not($str1 = $str2)
evaluates to true()
exactly when the string $str1
is not equal to the string $str2
.
There is also the !=
operator. It generally should be avoided because it has anomalous behavior whenever one of its operands is a node-set.
Now, the rules for comparing two element nodes are similar:
$el1 = $el2
evaluates to true()
exactly when the string value of $el1
is equal to the string value of $el2
.
not($el1 = $el2)
evaluates to true()
exactly when the string value of $el1
is not equal to the string value of $el2
.
However, if one of the operands of =
is a node-set, then
$ns = $str
evaluates to true()
exactly when there is at least one node in the node-set $ns1
, whose string value is equal to the string $str
$ns1 = $ns2
evaluates to true()
exactly when there is at least one node in the node-set $ns1
, whose string value is equal to the string value of some node from $ns2
Therefore, the expression:
OU_NAME='OU_ADDR1'
evaluates to true()
only when there is at least one element child of the current node that is named OU_NAME
and whose string value is the string 'OU_ADDR1'.
This is obviously not what you want!
Most probably you want:
OU_NAME=OU_ADDR1
This expression evaluates to true
exactly there is at least one OU_NAME
child of the current node and one OU_ADDR1
child of the current node with the same string value.
Finally, in XPath 2.0, strings can be compared also using the value comparison operators lt
, le
, eq
, gt
, ge
and the inherited from XPath 1.0 general comparison operator =
.
Trying to evaluate a value comparison operator when one or both of its arguments is a sequence of more than one item results in error.
if your using sqlsrv_connect you have to download and install MS sql driver for your php. download it here http://www.microsoft.com/en-us/download/details.aspx?id=20098 extract it to your php folder or ext in xampp folder then add this on the end of the line in your php.ini file
extension=php_pdo_sqlsrv_55_ts.dll
extension=php_sqlsrv_55_ts.dll
im using xampp version 5.5 so its name php_pdo_sqlsrv_55_ts.dll & php_sqlsrv_55_ts.dll
if you are using xampp version 5.5 dll files is not included in the link...hope it helps
I use this: if you declare var x = 0; before the functions declarations, the variable works for all the code files, but the variable will be declare every time that you edit a cell in the spreadsheet