I know this is an old post and you marked the question as answered. I was looking for the same thing recently and I found the histedit
extension very useful. The process is explained here:
http://knowledgestockpile.blogspot.com/2010/12/changing-commit-message-of-revision-in.html
I believe the more modern and simpler way to do this now is hg uncommit
. Note this leaves behind an empty commit which can be useful if you want to reuse the commit message later. If you don't, use hg uncommit --no-keep
to not leave the empty commit.
hg uncommit [OPTION]... [FILE]...
uncommit part or all of a local changeset
This command undoes the effect of a local commit, returning the affected files to their uncommitted state. This means that files modified or deleted in the changeset will be left unchanged, and so will remain modified in the working directory. If no files are specified, the commit will be left empty, unless --no-keep
Sorry, I am not sure what the equivalent is TortoiseHg.
There is also zzos. (Full disclosure: I wrote it). It only decompiles the actual resources, not the dex part (baksmali, which I did not write, does an excellent job of handling that part).
Zzos is much less known than apktool, but there are some APKs that are better handled by it (and vice versa - more on that later). Mostly, APKs containing custom resource types (not modifiers) were not handled by apktool the last time I checked, and are handled by zzos. There are also some cases with escaping that zzos handles better.
On the negative side of things, zzos (current version) requires a few support tools to install. It is written in perl (as opposed to APKTool, which is written in Java), and uses aapt for the actual decompilation. It also does not decompile attrib resources yet (which APKTool does).
The meaning of the name is "aapt", Android's resource compiler, shifted down one letter.
I ended up putting my env stuff in .profile
and mutated SHELL
something like
SHELL ["/bin/bash", "-c", "-l"]
# Install ruby version specified in .ruby-version
RUN rvm install $(<.ruby-version)
# Install deps
RUN rvm use $(<.ruby-version) && gem install bundler && bundle install
CMD rvm use $(<.ruby-version) && ./myscript.rb
You have copy this sample code from Here,right?
now, as you can see there property
file they have define, have you done same thing?
if not then add below code in your project with property file for log4j
So the content of log4j.properties file would be as follows:
# Define the root logger with appender file
log = /usr/home/log4j
log4j.rootLogger = DEBUG, FILE
# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/log.out
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
make changes as per your requirement like log
path
Problem: The accepted answer does not actually fix the indentation in the current document.
Solution: Run Format Document
to re-process the document according to current (new) settings.
Problem: The HTML docs in my projects are of type "Django HTML" not "HTML" and there is no formatter available.
Solution: Switch them to syntax "HTML", format them, then switch back to "Django HTML."
Problem: The HTML formatter doesn't know how to handle Django template tags and undoes much of my carefully applied nesting.
Solution: Install the Indent 4-2 extension, which performs indentation strictly, without regard to the current language syntax (which is what I want in this case).
No, you don't need to add them as a remote. That would be clumbersome and a pain to do each time.
git fetch [email protected]:theirusername/reponame.git theirbranch:ournameforbranch
This creates a local branch named ournameforbranch
which is exactly the same as what theirbranch
was for them. For the question example, the last argument would be foo:foo
.
Note :ournameforbranch
part can be further left off if thinking up a name that doesn't conflict with one of your own branches is bothersome. In that case, a reference called FETCH_HEAD
is available. You can git log FETCH_HEAD
to see their commits then do things like cherry-picked
to cherry pick their commits.
Oftentimes, you want to fix something of theirs and push it right back. That's possible too:
git fetch [email protected]:theirusername/reponame.git theirbranch
git checkout FETCH_HEAD
# fix fix fix
git push [email protected]:theirusername/reponame.git HEAD:theirbranch
If working in detached state worries you, by all means create a branch using :ournameforbranch
and replace FETCH_HEAD
and HEAD
above with ournameforbranch
.
I just learned something new about the ternary operator. The short form that omits the middle operand is truly elegant, and is one of the many reasons that C remains relevant. FYI, I first really got my head around this in the context of a routine implemented in C#, which also supports the ternary operator. Since the ternary operator is in C, it stands to reason that it would be in other languages that are essentially extensions thereof (e. g., Objective-C, C#).
I would prefer using "&&" -operator on inline if-statement. In my opinnion it gives cleaner codebase this way.
Generally you could be doing something like this
render(){
return(
<div>
<button className={this.state.active && 'active'}
onClick={ () => this.setState({active: !this.state.active}) }>Click me</button>
</div>
)
}
Just keep in mind arrow function is ES6 feature and remember to set 'this.state.active' value in class constructor(){}
this.state = { active: false }
or if you want to inject css in JSX you are able to do it this way
<button style={this.state.active && style.button} >button</button>
and you can declare style json variable
const style = { button: { background:'red' } }
remember using camelCase on JSX stylesheets.
I wonder why no one added the alternative of using the function chr()
:
echo 'Hello World!' . chr(10);
or, more efficient if you're going to repeat it a million times:
define('C_NewLine', chr(10));
...
echo 'Hello World!' . C_NewLine;
This avoids the silly-looking notation of concatenating a single- and double-quoted string.
open -n -a Terminal
and you can pass the target directory as parameter
open -n -a Terminal /Users
None of these answers worked for me (generally there was a missing reference or something along those lines)
But this quite simply did:
Using FolderBrowserDialog in WPF application
Add a reference to System.Windows.Forms
and use this code:
var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
No need to track down missing packages. Or add enormous classes
This gives me a modern folder selector that also allows you to create a new folder
I'm yet to see the impact when deployed to other machines
How to get the first date of the current month correctly?
LocalDate.now()
.with( TemporalAdjusters.firstDayOfMonth() )
Or…
YearMonth.now().atDay( 1 )
Or…
LocalDate.now().with ( ChronoField.DAY_OF_MONTH , 1 )
The java.time framework in Java 8 and later supplants the old java.util.Date/.Calendar classes. The old classes have proven to be troublesome, confusing, and flawed. Avoid them.
The java.time framework is inspired by the highly-successful Joda-Time library, defined by JSR 310, extended by the ThreeTen-Extra project, and explained in the Tutorial.
LocalDate
For a date-only value, without time-of-day, use the LocalDate
class. While LocalDate
has no assigned time zone, we must specify a time zone in order to determine a date such as “today”. For example, a new day dawns earlier in Paris than in Montréal.
Time zone is crucial in determining today's date. For any given moment, the date varies around the world by zone. Omitting the time zone means the JVM’s current time zone is automatically applied in determining the current date. Any code in the JVM can change the default at runtime, so you are walking on shifting sands. Better to specify your desired/expected time zone explicitly than rely implicitly on the current default.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId zoneId = ZoneId.of ( "America/Montreal" );
LocalDate today = LocalDate.now ( zoneId );
LocalDate firstOfCurrentMonth = today.with ( ChronoField.DAY_OF_MONTH , 1 );
Dump to console.
System.out.println ( "For zoneId: " + zoneId + " today is: " + today + " and first of this month is " + firstOfCurrentMonth );
For zoneId: America/Montreal today is: 2015-11-08 and first of this month is 2015-11-01
Alternatively, use a TemporalAdjuster
. For your purpose, you will find handy implementations in the TemporalAdjusters
class (note plural s
), specifically firstDayOfMonth
.
LocalDate firstOfCurrentMonth = today.with( TemporalAdjusters.firstDayOfMonth() ) ;
ZonedDateTime
If you need a time of day, remember that 00:00:00.000
is not always the first moment of the day because of Daylight Saving Time (DST) and perhaps other anomalies. So let java.time determine the correct time of the first moment of the day.
ZonedDateTime zdt = firstOfCurrentMonth.atStartOfDay ( zoneId );
2015-11-01T00:00-04:00[America/Montreal]
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Doing maven update or reimporting the project did not help. @Sydney's answer is right; in addition I have to recreate the project in different workspace as said in JavaServer Faces 2.2 requires Dynamic Web Module 2.5 or newer
Maybe worth looking at QRGen, which is built on top of ZXing and supports UTF-8 with this kind of syntax:
// if using special characters don't forget to supply the encoding
VCard johnSpecial = new VCard("Jöhn D?e")
.setAdress("ëåäö? Sträät 1, 1234 Döestüwn");
QRCode.from(johnSpecial).withCharset("UTF-8").file();
What i have done is that import a new project into eclipse workspace, and that path of that was be
android-sdk-macosx/extras/google/google_play_services/libproject/google-play-services_lib
and add as library in your project.. that it .. simple!! you might require to add support library in your project.
I find this to be the most efficient for finding if a value exists, logic can easily be inverted to find if a value doesn't exist (ie IS NULL);
SELECT * FROM primary_table st1
LEFT JOIN comparision_table st2 ON (st1.relevant_field = st2.relevant_field)
WHERE st2.primaryKey IS NOT NULL
*Replace relevant_field with the name of the value that you want to check exists in your table
*Replace primaryKey with the name of the primary key column on the comparison table.
/** * This toString-Method works for every Class, where you want to display all the fields and its values */ public String toString() {
StringBuffer sb = new StringBuffer();
Field[] fields = getClass().getDeclaredFields(); //Get all fields incl. private ones
for (Field field : fields){
try {
field.setAccessible(true);
String key=field.getName();
String value;
try{
value = (String) field.get(this);
} catch (ClassCastException e){
value="";
}
sb.append(key).append(": ").append(value).append("\n");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return sb.toString(); }
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
If you want to use jquery $("..").is(":focus")
.
You can take a look at this stack
This is a better solution, using:
$("table tr:first-child").has('img')
You should have :
<div id="header">
<?php
// integer starts at 0 before counting
$i = 0;
$dir = 'uploads/';
if ($handle = opendir($dir)) {
while (($file = readdir($handle)) !== false){
if (!in_array($file, array('.', '..')) && !is_dir($dir.$file))
$i++;
}
}
// prints out how many were in the directory
echo "There were $i files";
?>
</div>
I got this error because I was using require('https')
where I should have been using require('http')
.
R defines a ~
(tilde) operator for use in formulas. Formulas have all sorts of uses, but perhaps the most common is for regression:
library(datasets)
lm( myFormula, data=iris)
help("~")
or help("formula")
will teach you more.
@Spacedman has covered the basics. Let's discuss how it works.
First, being an operator, note that it is essentially a shortcut to a function (with two arguments):
> `~`(lhs,rhs)
lhs ~ rhs
> lhs ~ rhs
lhs ~ rhs
That can be helpful to know for use in e.g. apply
family commands.
Second, you can manipulate the formula as text:
oldform <- as.character(myFormula) # Get components
myFormula <- as.formula( paste( oldform[2], "Sepal.Length", sep="~" ) )
Third, you can manipulate it as a list:
myFormula[[2]]
myFormula[[3]]
Finally, there are some helpful tricks with formulae (see help("formula")
for more):
myFormula <- Species ~ .
For example, the version above is the same as the original version, since the dot means "all variables not yet used." This looks at the data.frame you use in your eventual model call, sees which variables exist in the data.frame but aren't explicitly mentioned in your formula, and replaces the dot with those missing variables.
Strings are compared lexicographically using the numeric equivalents (the result of the built-in function ord()) of their characters. Unicode and 8-bit strings are fully interoperable in this behavior.
Below is to check the current limit
csv.field_size_limit()
Out[20]: 131072
Below is to increase the limit. Add it to the code
csv.field_size_limit(100000000)
Try checking the limit again
csv.field_size_limit()
Out[22]: 100000000
Now you won't get the error "_csv.Error: field larger than field limit (131072)"
An Ad-Hoc query is:
I find I have started having this issue with Lion + Xcode 4.2. I have also experienced the issue in Xcode 4.3.
I have tried all the suggestions but none of them have worked other than a full reboot.
Here is how you determine if you require a reboot quickly.
List out all your Zombie processes:
ps -el | grep 'Z'
If you see your app listed as a Zombie process you will need to reboot your machine. The error message states "This generally means that another instance of this process was already running or is hung in the debugger". Well, Xcode is detecting this Zombie process which you can't kill. The only way you can then fix it is with a system reboot. :(
EDIT, 20120823: I have some better knowledge of Zombie processes so I wanted to update this answer. A Zombie process is created when a parent process does not call wait() (wait for process to change state) on a terminating child process. You can't run 'kill' directly on a Zombie process but if you kill the parent process, the zombie child process will be 'reaped' and removed from the process table.
I haven't seen this issue in a long while so haven't inspected to see what the parent process is in this scenario. The alternative to killing the parent process is to reboot your system. :)
require 'json/ext' # to use the C based extension instead of json/pure
puts {hash: 123}.to_json
In Perl 5.14 (it works in now in Perl 5.13), we'll be able to just use keys on the hash reference
use v5.13.7;
foreach my $key (keys $ad_grp_ref) {
...
}
As a heads up to others, I've oberserved that at least as manifested by TypeScript compiled by WebPack for Angular 2, you quietly get overWRITTEN instead of overLOADED methods.
myComponent {
method(): { console.info("no args"); },
method(arg): { console.info("with arg"); }
}
Calling:
myComponent.method()
seems to execute the method with arguments, silently ignoring the no-arg version, with output:
with arg
You should use java.time classes with Java 8 and later. To use java.time, add:
import java.time.* ;
Below is an example, how you can format date.
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
String date = "15-Oct-2018";
LocalDate localDate = LocalDate.parse(date, formatter);
System.out.println(localDate);
System.out.println(formatter.format(localDate));
As far as I can tell, there is no way to write a setter for a class property without creating a new metaclass.
I have found that the following method works. Define a metaclass with all of the class properties and setters you want. IE, I wanted a class with a title
property with a setter. Here's what I wrote:
class TitleMeta(type):
@property
def title(self):
return getattr(self, '_title', 'Default Title')
@title.setter
def title(self, title):
self._title = title
# Do whatever else you want when the title is set...
Now make the actual class you want as normal, except have it use the metaclass you created above.
# Python 2 style:
class ClassWithTitle(object):
__metaclass__ = TitleMeta
# The rest of your class definition...
# Python 3 style:
class ClassWithTitle(object, metaclass = TitleMeta):
# Your class definition...
It's a bit weird to define this metaclass as we did above if we'll only ever use it on the single class. In that case, if you're using the Python 2 style, you can actually define the metaclass inside the class body. That way it's not defined in the module scope.
View single commit:
https://github.com/<user>/<project>/commit/<hash>
View log:
https://github.com/<user>/<project>/commits/<hash>
View full repo:
https://github.com/<user>/<project>/tree/<hash>
<hash>
can be any length as long as it is unique.
It's the "frame" or "range" clause of window functions, which are part of the SQL standard and implemented in many databases, including Teradata.
A simple example would be to calculate the average amount in a frame of three days. I'm using PostgreSQL syntax for the example, but it will be the same for Teradata:
WITH data (t, a) AS (
VALUES(1, 1),
(2, 5),
(3, 3),
(4, 5),
(5, 4),
(6, 11)
)
SELECT t, a, avg(a) OVER (ORDER BY t ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
FROM data
ORDER BY t
... which yields:
t a avg
----------
1 1 3.00
2 5 3.00
3 3 4.33
4 5 4.00
5 4 6.67
6 11 7.50
As you can see, each average is calculated "over" an ordered frame consisting of the range between the previous row (1 preceding
) and the subsequent row (1 following
).
When you write ROWS UNBOUNDED PRECEDING
, then the frame's lower bound is simply infinite. This is useful when calculating sums (i.e. "running totals"), for instance:
WITH data (t, a) AS (
VALUES(1, 1),
(2, 5),
(3, 3),
(4, 5),
(5, 4),
(6, 11)
)
SELECT t, a, sum(a) OVER (ORDER BY t ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM data
ORDER BY t
yielding...
t a sum
---------
1 1 1
2 5 6
3 3 9
4 5 14
5 4 18
6 11 29
Here's another very good explanations of SQL window functions.
It's no longer necessary to format numbers by hand like this anymore. This answer was written way-back-when in the distant year of 2011 when IE was important and babel and bundlers were just a wonderful, hopeful dream.
I think it would be a mistake to delete this answer; however in case you find yourself here, I would like to kindly direct your attention to the second highest voted answer to this question as of this edit.
It will introduce you to the use of .toLocaleString()
with the options parameter of {minimumIntegerDigits: 2}
. Exciting stuff. Below I've recreated all three examples from my original answer using this method for your convenience.
[7, 7.5, -7.2345].forEach(myNumber => {
let formattedNumber = myNumber.toLocaleString('en-US', {
minimumIntegerDigits: 2,
useGrouping: false
})
console.log(
'Input: ' + myNumber + '\n' +
'Output: ' + formattedNumber
)
})
_x000D_
The best method I've found is something like the following:
(Note that this simple version only works for positive integers)
var myNumber = 7;
var formattedNumber = ("0" + myNumber).slice(-2);
console.log(formattedNumber);
_x000D_
For decimals, you could use this code (it's a bit sloppy though).
var myNumber = 7.5;
var dec = myNumber - Math.floor(myNumber);
myNumber = myNumber - dec;
var formattedNumber = ("0" + myNumber).slice(-2) + dec.toString().substr(1);
console.log(formattedNumber);
_x000D_
Lastly, if you're having to deal with the possibility of negative numbers, it's best to store the sign, apply the formatting to the absolute value of the number, and reapply the sign after the fact. Note that this method doesn't restrict the number to 2 total digits. Instead it only restricts the number to the left of the decimal (the integer part). (The line that determines the sign was found here).
var myNumber = -7.2345;
var sign = myNumber?myNumber<0?-1:1:0;
myNumber = myNumber * sign + ''; // poor man's absolute value
var dec = myNumber.match(/\.\d+$/);
var int = myNumber.match(/^[^\.]+/);
var formattedNumber = (sign < 0 ? '-' : '') + ("0" + int).slice(-2) + (dec !== null ? dec : '');
console.log(formattedNumber);
_x000D_
A method that I use is to load the table into R as a data.frame
, then use dbWriteTable
to push it to PostgreSQL. These two steps are shown below.
R's data.frame
objects are database-like, where named columns have explicit types, such as text or numbers. There are several ways to get a spreadsheet into R, such as XLConnect. However, a really simple method is to select the range of the Excel table (including the header), copy it (i.e. CTRL+C), then in R use this command to get it from the clipboard:
d <- read.table("clipboard", header=TRUE, sep="\t", quote="\"", na.strings="", as.is=TRUE)
If you have RStudio, you can easily view the d
object to make sure it is as expected.
Ensure you have RPostgreSQL installed from CRAN, then make a connection and send the data.frame
to the database:
library(RPostgreSQL)
conn <- dbConnect(PostgreSQL(), dbname="mydb")
dbWriteTable(conn, "some_table_name", d)
Now some_table_name
should appear in the database.
Some common clean-up steps can be done from pgAdmin or psql:
ALTER TABLE some_table_name RENAME "row.names" TO id;
ALTER TABLE some_table_name ALTER COLUMN id TYPE integer USING id::integer;
ALTER TABLE some_table_name ADD PRIMARY KEY (id);
This may become useful to someone in the future as the new framework, when setup through VS, gets a default web.config
, web.Debug.config
and web.Release.config
. In the web.release.config
you will find this line:
<compilation xdt:Transform="RemoveAttributes(debug)" />
this was seeming to override any inline changes I made. I commented this line out and we were gravy (in terms of seeing non-minified code in a "release" build)
It's not a cut and paste. The CASE
expression must return a value, and you are returning a string containing SQL (which is technically a value but of a wrong type). This is what you wanted to write, I think:
SELECT * FROM [Purchasing].[Vendor] WHERE
CASE
WHEN @url IS null OR @url = '' OR @url = 'ALL'
THEN PurchasingWebServiceURL LIKE '%'
WHEN @url = 'blank'
THEN PurchasingWebServiceURL = ''
WHEN @url = 'fail'
THEN PurchasingWebServiceURL NOT LIKE '%treyresearch%'
ELSE PurchasingWebServiceURL = '%' + @url + '%'
END
I also suspect that this might not work in some dialects, but can't test now (Oracle, I'm looking at you), due to not having booleans.
However, since @url
is not dependent on the table values, why not make three different queries, and choose which to evaluate based on your parameter?
For people who find this via search engines, you do not need VBA. You can just:
1.) select the query or table with your mouse
2.) click export data from the ribbon
3.) click excel from the export subgroup
4.) follow the wizard to select the output file and location.
You made the error, for the second call, to set the size of source to the size of the target.
Anyway i bet that you want the same aspect ratio for the scaled image, so you need to compute it :
var hRatio = canvas.width / img.width ;
var vRatio = canvas.height / img.height ;
var ratio = Math.min ( hRatio, vRatio );
ctx.drawImage(img, 0,0, img.width, img.height, 0,0,img.width*ratio, img.height*ratio);
i also suppose you want to center the image, so the code would be :
function drawImageScaled(img, ctx) {
var canvas = ctx.canvas ;
var hRatio = canvas.width / img.width ;
var vRatio = canvas.height / img.height ;
var ratio = Math.min ( hRatio, vRatio );
var centerShift_x = ( canvas.width - img.width*ratio ) / 2;
var centerShift_y = ( canvas.height - img.height*ratio ) / 2;
ctx.clearRect(0,0,canvas.width, canvas.height);
ctx.drawImage(img, 0,0, img.width, img.height,
centerShift_x,centerShift_y,img.width*ratio, img.height*ratio);
}
you can see it in a jsbin here : http://jsbin.com/funewofu/1/edit?js,output
You may also indicate the path to the gemfile in the same command e.g.
BUNDLE_GEMFILE="MyProject/Gemfile.ios" bundle install
You MUST add below part to enable NameVirtualHost
functionality with given IP.
NameVirtualHost IP_Address:443
For users of IntelliJ IDEA or Android Studio make these steps:
* From the menu Build/Generate signed APK
* You need to create a keystore path. From the dialog click Create new
. You will create a jks file that includes your keys. Select folder, define a password. So your keystore ok.
* Create new key by for your application by using alias, key password, your name etc.
* Click next.
* From the dialog either select Proguard or not.
Your signed APK file is ready.
Help file: https://www.jetbrains.com/idea/webhelp/generate-signed-apk-wizard.html
This was a real issue for me, and quite a sneaky problem to try and remedy...
The problem I had was that a module that was installed on my WiFi adapter was conflicting with the Microsoft Virtual Adapter (or whatever it's actually called).
To fix it:
R
ncpa.cpl
in to the box, and hit OK
.Properties
.The connection uses the following items:
. Look down the list for anything that seems out of the ordinary, and uncheck it. Hit OK
.netsh wlan start hostednetwork
command again.In my case my adapter was running a module called SoftEther Lightweight Network Protocol
, which I believe is used to help connect to VPN Gate VPN servers via the SoftEther software.
If literally nothing else works, then I'd suspect something similar to the problem I encountered, namely that a module on your network adapter is interfering with the hostednetwork aspect of your driver.
By checking other answers, I used object-fit in CSS:
video {
object-fit: fill;
}
From MDN (https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit):
The object-fit CSS property specifies how the contents of a replaced element should be fitted to the box established by its used height and width.
Value: fill
The replaced content is sized to fill the element’s content box: the object’s concrete object size is the element’s used width and height.
I'm not sure if PyQt does have a script like this, but after you install PySide there is a script in pythons script directory "uic.py". You can use this script to convert a .ui file to a .py file:
python uic.py input.ui -o output.py -x
I do not like use pure "a" tag, too much typing. So I come with solution. In view it look
<%: Html.ActionLink(node.Name, "Show", "Browse",
Dic.Route("id", node.Id), Dic.New("data-nodeId", node.Id)) %>
Implementation of Dic class
public static class Dic
{
public static Dictionary<string, object> New(params object[] attrs)
{
var res = new Dictionary<string, object>();
for (var i = 0; i < attrs.Length; i = i + 2)
res.Add(attrs[i].ToString(), attrs[i + 1]);
return res;
}
public static RouteValueDictionary Route(params object[] attrs)
{
return new RouteValueDictionary(Dic.New(attrs));
}
}
Do note that on newer Apache versions the RewriteLog
and RewriteLogLevel
have been removed, and in fact will now trigger an error when trying to start Apache (at least on my XAMPP installation with Apache 2.4.2):
AH00526: Syntax error on line xx of path/to/config/file.conf: Invalid command 'RewriteLog', perhaps misspelled or defined by a module not included in the server configuration`
Instead, you're now supposed to use the general LogLevel
directive, with a level of trace1
up to trace8
. 'debug' didn't display any rewrite messages in the log for me.
Example: LogLevel warn rewrite:trace3
For the official documentation, see here.
Of course this also means that now your rewrite logs will be written in the general error log file and you'll have to sort them out yourself.
parentElement
is new to Firefox 9 and to DOM4, but it has been present in all other major browsers for ages.
In most cases, it is the same as parentNode
. The only difference comes when a node's parentNode
is not an element. If so, parentElement
is null
.
As an example:
document.body.parentNode; // the <html> element
document.body.parentElement; // the <html> element
document.documentElement.parentNode; // the document node
document.documentElement.parentElement; // null
(document.documentElement.parentNode === document); // true
(document.documentElement.parentElement === document); // false
Since the <html>
element (document.documentElement
) doesn't have a parent that is an element, parentElement
is null
. (There are other, more unlikely, cases where parentElement
could be null
, but you'll probably never come across them.)
I think the previous answers address the topic very well. However, I'd add that in one case when you have Spring Security enabled in your application, you might have to specifically tell Spring to permit requests to other static resource directories like for example "/static/fonts".
In my case I had "/static/css", "/static/js", "/static/images" permited by default , but /static/fonts/** was blocked by my Spring Security implementation.
Below is an example of how I fixed this.
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
.....
@Override
protected void configure(final HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/", "/fonts/**").permitAll().
//other security configuration rules
}
.....
}
What about the Activity.finish()
method (quoting) :
Call this when your activity is done and should be closed.
Is this what you are looking for?
https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant
types is optional
I usually do this in the thread handling the json response:
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
If you need to do transformations on the image, you'll want to create a Drawable instead of a Bitmap.
I had the same problem. My solution was to make all vectors numeric.
Well you have to setup the click event first then you can trigger it and see what happens:
//good habits first let's cache our selector
var $myLink = $('#titleee').find('a');
$myLink.click(function (evt) {
evt.preventDefault();
alert($(this).attr('href'));
});
// now the manual trigger
$myLink.trigger('click');
This will work, independent of Excel version (2003, 2007, 2010). The first has 65536 rows in a sheet, while the latter two have a million rows or so. Sheet1.Rows.Count
returns this number dependent on the version.
numofrows = Sheet1.Range("A1").Offset(Sheet1.Rows.Count - 1, 0).End(xlUp).Row
or the equivalent but shorter
numofrows = Sheet1.Cells(Sheet1.Rows.Count,1).End(xlUp)
This searches up from the bottom of column A for the first non-empty cell, and gets its row number.
This also works if you have data that go further down in other columns. So for instance, if you take your example data and also write something in cell FY4763, the above will still correctly return 9 (not 4763, which any method involving the UsedRange
property would incorrectly return).
Note that really, if you want the cell reference, you should just use the following. You don't have to first get the row number, and then build the cell reference.
Set rngLastCell = Sheet1.Range("A1").Offset(Sheet1.Rows.Count - 1, 0).End(xlUp)
Note that this method fails in certain edge cases:
So watch out if you're planning to use row 1,048,576 for these things!
This is just fine but if you add option which is not in optgroup it gets buggy.
<select>_x000D_
<optgroup label="Level One">_x000D_
<option> A.1 </option>_x000D_
<optgroup label=" Level Two">_x000D_
<option> A.B.1 </option>_x000D_
</optgroup>_x000D_
<option> A.2 </option>_x000D_
</optgroup>_x000D_
<option> A </option>_x000D_
</select>
_x000D_
Would be much better if you used css and close optgroup right away :
<select>_x000D_
<optgroup label="Level One"></optgroup>_x000D_
<option style="padding-left:15px"> A.1 </option>_x000D_
<optgroup label="Level Two" style="padding-left:15px"></optgroup>_x000D_
<option style="padding-left:30px"> A.B.1 </option>_x000D_
<option style="padding-left:15px"> A.2 </option>_x000D_
<option> A </option>_x000D_
</select>
_x000D_
No, you would need to give the do function in the constructor and the do function in the prototype different names.
<init-param>
will be used if you want to initialize some parameter for a particular servlet. When request come to servlet first its init
method will be called then doGet/doPost
whereas if you want to initialize some variable for whole application you will need to use <context-param>
. Every servlet will have access to the context variable.
Assuming you have two log-files in:
cd to C: and use:
grep -r somethingtosearch temp/*.log
It will give you a list like:
temp/my.log:somethingtosearch
temp/alsoMy.log:somethingtosearch1
temp/alsoMy.log:somethingtosearch2
Can you explain why you want to do this?
You're playing around with instance variables/attributes which won't migrate from one class to another (they're bound not even to ClassA
, but to a particular instance of ClassA
that you created when you wrote ClassA()
). If you want to have changes in one class show up in another, you can use class variables:
class ClassA(object):
var1 = 1
var2 = 2
@classmethod
def method(cls):
cls.var1 = cls.var1 + cls.var2
return cls.var1
In this scenario, ClassB
will pick up the values on ClassA
from inheritance. You can then access the class variables via ClassA.var1
, ClassB.var1
or even from an instance ClassA().var1
(provided that you haven't added an instance method var1
which will be resolved before the class variable in attribute lookup.
I'd have to know a little bit more about your particular use case before I know if this is a course of action that I would actually recommend though...
You should probably try to get rid of the warning completely, but if that's not possible, you can prepend the call with @ (i.e. @dns_get_record(...)) and then use any information you can get to figure out if the warning happened or not.
An addition to the solution by @Rafael Teles. The syntactic sugar Collectors.mapping
does the same in one step:
//...
List<Employee> employees = persons.stream()
.filter(p -> p.getLastName().equals("l1"))
.collect(
Collectors.mapping(
p -> new Employee(p.getName(), p.getLastName(), 1000),
Collectors.toList()));
Detailed example can be found here
java script
document.getElementById("divID").html("this text will be added to div");
jquery
$("#divID").html("this text will be added to div");
Use .html()
without any arguments to see that you have entered.
You can use the browser console to quickly test these functions before using them in your code.
You actually don't have access to filesystem (for example reading and writing local files), however, due to HTML5 File Api specification, there are some file properties that you do have access to, and the file size is one of them.
For the HTML below
<input type="file" id="myFile" />
try the following:
//binds to onchange event of your input field
$('#myFile').bind('change', function() {
//this.files[0].size gets the size of your file.
alert(this.files[0].size);
});
As it is a part of the HTML5 specification, it will only work for modern browsers (v10 required for IE) and I added here more details and links about other file information you should know: http://felipe.sabino.me/javascript/2012/01/30/javascipt-checking-the-file-size/
Old browsers support
Be aware that old browsers will return a null
value for the previous this.files
call, so accessing this.files[0]
will raise an exception and you should check for File API support before using it
You can query the data dictionary/catalog views to find out when an object was created as well as the time of last DDL involving the object (example: alter table)
select *
from all_objects
where owner = '<name of schema owner>'
and object_name = '<name of table>'
The column "CREATED" tells you when the object was created. The column "LAST_DDL_TIME" tells you when the last DDL was performed against the object.
As for when a particular row was inserted/updated, you can use audit columns like an "insert_timestamp" column or use a trigger and populate an audit table
Simply specify the version in your current pom. The version specified here will override other.
Forcing a version
A version will always be honoured if it is declared in the current POM with a particular version - however, it should be noted that this will also affect other poms downstream if it is itself depended on using transitive dependencies.
Resources :
Just in case someone stumbles upon this like I did and doesn't realise, the two variations above are for different use cases.
The following:
.blue-border, .background {
border: 1px solid #00f;
background: #fff;
}
is for when you want to add styles to elements that have either the blue-border or background class, for example:
<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>
would all get a blue border and white background applied to them.
However, the accepted answer is different.
.blue-border.background {
border: 1px solid #00f;
background: #fff;
}
This applies the styles to elements that have both classes so in this example only the <div>
with both classes should get the styles applied (in browsers that interpret the CSS properly):
<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>
So basically think of it like this, comma separating applies to elements with one class OR another class and dot separating applies to elements with one class AND another class.
I'll give you another solution, Make your lambda invoke a function.
def multiple_statements(x, y):
print('hi')
print('there')
print(x)
print(y)
return 1
junky = lambda x, y: multiple_statements(x, y)
junky('a', 'b');
Not tested but should work
products.sort((a,b)=>a.title.rendered > b.title.rendered)
A quick fix to "plot overlap" is to use plt.tight_layout():
for i,var in enumerate(categorical_variables):
plt.title(var)
plt.xticks(rotation=45)
df[var].hist()
plt.subplot(len(categorical_variables)/2, 2, i+1)
plt.tight_layout()
It says “Android library projects cannot be launched” because Android library projects cannot be launched. That simple. You cannot run a library. If you want to test a library, create an Android project that uses the library, and execute it.
JDK 1.8 have some more enrich feature which doesn't support to many eclipse .
If you didn't find java compliance level as 1.8 in java compiler ,then go ahead and install the below eclipse 32bit or 64 bit depending on your system supports.
Try running one java program supports to java 8 like lambda expression as below and if no compilation error ,means your eclipse supports to java 1.8, something like this:
interface testI{
void show();
}
/*class A implements testI{
public void show(){
System.out.println("Hello");
}
}*/
public class LambdaDemo1 {
public static void main(String[] args) {
testI test ;
/*test= new A();
test.show();*/
test = () ->System.out.println("Hello,how are you?"); //lambda
test.show();
}
}
You can use Notification and NotificationManager to display the notification you want. You can then customize the sound you want to play with your notification.
@lenooh satisfied my query. I discovered this article while searching for 'python suppress newline'. I'm using IDLE3 on Raspberry Pi to develop Python 3.2 for PuTTY. I wanted to create a progress bar on the PuTTY command line. I didn't want the page scrolling away. I wanted a horizontal line to re-assure the user from freaking out that the program hasn't cruncxed to a halt nor been sent to lunch on a merry infinite loop - as a plea to 'leave me be, I'm doing fine, but this may take some time.' interactive message - like a progress bar in text.
The print('Skimming for', search_string, '\b! .001', end='')
initializes the message by preparing for the next screen-write, which will print three backspaces as ??? rubout and then a period, wiping off '001' and extending the line of periods. After search_string
parrots user input, the \b!
trims the exclamation point of my search_string
text to back over the space which print()
otherwise forces, properly placing the punctuation. That's followed by a space and the first 'dot' of the 'progress bar' which I'm simulating. Unnecessarily, the message is also then primed with the page number (formatted to a length of three with leading zeros) to take notice from the user that progress is being processed and which will also reflect the count of periods we will later build out to the right.
import sys
page=1
search_string=input('Search for?',)
print('Skimming for', search_string, '\b! .001', end='')
sys.stdout.flush() # the print function with an end='' won't print unless forced
while page:
# some stuff…
# search, scrub, and build bulk output list[], count items,
# set done flag True
page=page+1 #done flag set in 'some_stuff'
sys.stdout.write('\b\b\b.'+format(page, '03')) #<-- here's the progress bar meat
sys.stdout.flush()
if done: #( flag alternative to break, exit or quit)
print('\nSorting', item_count, 'items')
page=0 # exits the 'while page' loop
list.sort()
for item_count in range(0, items)
print(list[item_count])
#print footers here
if not (len(list)==items):
print('#error_handler')
The progress bar meat is in the sys.stdout.write('\b\b\b.'+format(page, '03'))
line. First, to erase to the left, it backs up the cursor over the three numeric characters with the '\b\b\b' as ??? rubout and drops a new period to add to the progress bar length. Then it writes three digits of the page it has progressed to so far. Because sys.stdout.write()
waits for a full buffer or the output channel to close, the sys.stdout.flush()
forces the immediate write. sys.stdout.flush()
is built into the end of print()
which is bypassed with print(txt, end='' )
. Then the code loops through its mundane time intensive operations while it prints nothing more until it returns here to wipe three digits back, add a period and write three digits again, incremented.
The three digits wiped and rewritten is by no means necessary - it's just a flourish which exemplifies sys.stdout.write()
versus print()
. You could just as easily prime with a period and forget the three fancy backslash-b ? backspaces (of course not writing formatted page counts as well) by just printing the period bar longer by one each time through - without spaces or newlines using just the sys.stdout.write('.'); sys.stdout.flush()
pair.
Please note that the Raspberry Pi IDLE3 Python shell does not honor the backspace as ? rubout but instead prints a space, creating an apparent list of fractions instead.
—(o=8> wiz
just edit the function cell in the fpdf.php file, look for the line that looks like this
function cell ($w, $h = 0, $txt = '', $border = 0, $ln = 0, $align = '', $fill = false, $link = '')
{
after finding the line
write after the {
,
$txt = utf8_decode($txt);
save the file and ready, the accents and the utf8 encoding will be working :)
I'd suggest to look at the Selenium API to see how they trigger a click on an element in a browser-compatible manner:
Look for the BrowserBot.prototype.triggerMouseEvent
function.
function str_replace_once($search, $replace, $subject) {
$pos = strpos($subject, $search);
if ($pos === false) {
return $subject;
}
return substr($subject, 0, $pos) . $replace . substr($subject, $pos + strlen($search));
}
jQuery now has a CDN access:
code.jquery.com/ui/[version]/themes/[theme name]/jquery-ui.css
And to make this a little more easy, Here you go:
I understand that my comment relate with windows, but may be someone be useful. For win run in cmd:
wmic process where "commandline like '%my_app.js%' AND name='node.exe' " CALL Terminate
then you can run your app again:
node my_app.js
Also you can use it in batch file, with escape quotes:
wmic process where "commandline like '%%my_app.js%%' AND name='node.exe' " CALL Terminate
node my_app.js
you can wrap -Andrie answer into a generic function
mbind<-function(...){
Reduce( function(x,y){cbind(x,y[match(row.names(x),row.names(y)),])}, list(...) )
}
Here, you can bind multiple frames with rownames as key
#An example for counting matched groups
import re
pattern = re.compile(r'(\w+).(\d+).(\w+).(\w+)', re.IGNORECASE)
search_str = "My 11 Char String"
res = re.match(pattern, search_str)
print(len(res.groups())) # len = 4
print (res.group(1) ) #My
print (res.group(2) ) #11
print (res.group(3) ) #Char
print (res.group(4) ) #String
I know no-one is asking for a jQuery solution here, but might be worth mentioning that with jQuery you can just ask for:$('#selectorid').val()
Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.
Environment.getDataDirectory()
Return the user data directory.
Try using required="true"
in bootstrap 3
Use Convert.TryFromBase64String from C# 7.2
public static bool IsBase64String(string base64)
{
Span<byte> buffer = new Span<byte>(new byte[base64.Length]);
return Convert.TryFromBase64String(base64, buffer , out int bytesParsed);
}
The best option now is to install the Microsoft Visual Studio add on called Productivity Power Tools.
With this comes "Solution Navigator" (alternative to Solution Explorer, with a lot of benefits) - which then you can use to filter the files to only show "Open". You can even filter files to show "Edited" and "Unsaved".
In C you can use memcpy
. In C++ use std::copy
from the <algorithm>
header.
Although it might look out of topic nobody bothered to check the ERRORLEVEL. When I used your suggestions I tried to check for errors straight after the MSI installation. I made it fail on purpose and noticed that on the command line all works beautifully whilst in a batch file msiexec dosn't seem to set errors. Tried different things there like
Nothing works and what mostly annoys me it's the fact that it works in the command line.
Here is a more complete version of focusing on the next element. It follows the spec guidelines and sorts the list of elements correctly by using tabindex. Also a reverse variable is defined if you want to get the previous element.
function focusNextElement( reverse, activeElem ) {
/*check if an element is defined or use activeElement*/
activeElem = activeElem instanceof HTMLElement ? activeElem : document.activeElement;
let queryString = [
'a:not([disabled]):not([tabindex="-1"])',
'button:not([disabled]):not([tabindex="-1"])',
'input:not([disabled]):not([tabindex="-1"])',
'select:not([disabled]):not([tabindex="-1"])',
'[tabindex]:not([disabled]):not([tabindex="-1"])'
/* add custom queries here */
].join(','),
queryResult = Array.prototype.filter.call(document.querySelectorAll(queryString), elem => {
/*check for visibility while always include the current activeElement*/
return elem.offsetWidth > 0 || elem.offsetHeight > 0 || elem === activeElem;
}),
indexedList = queryResult.slice().filter(elem => {
/* filter out all indexes not greater than 0 */
return elem.tabIndex == 0 || elem.tabIndex == -1 ? false : true;
}).sort((a, b) => {
/* sort the array by index from smallest to largest */
return a.tabIndex != 0 && b.tabIndex != 0
? (a.tabIndex < b.tabIndex ? -1 : b.tabIndex < a.tabIndex ? 1 : 0)
: a.tabIndex != 0 ? -1 : b.tabIndex != 0 ? 1 : 0;
}),
focusable = [].concat(indexedList, queryResult.filter(elem => {
/* filter out all indexes above 0 */
return elem.tabIndex == 0 || elem.tabIndex == -1 ? true : false;
}));
/* if reverse is true return the previous focusable element
if reverse is false return the next focusable element */
return reverse ? (focusable[focusable.indexOf(activeElem) - 1] || focusable[focusable.length - 1])
: (focusable[focusable.indexOf(activeElem) + 1] || focusable[0]);
}
sudo apt purge python2.7-minimal
Another solution would be to use divs, which do use zIndex to contain the SVG elements.As here: https://stackoverflow.com/a/28904640/4552494
Maybe you're not doing it as root?
Try sudo nginx -s reload
, if it still doesn't work, you might want to try sudo pkill -HUP nginx
.
You can only include a script file in an HTML page, not in another script file. That said, you can write JavaScript which loads your "included" script into the same page:
var imported = document.createElement('script');
imported.src = '/path/to/imported/script';
document.head.appendChild(imported);
There's a good chance your code depends on your "included" script, however, in which case it may fail because the browser will load the "imported" script asynchronously. Your best bet will be to simply use a third-party library like jQuery or YUI, which solves this problem for you.
// jQuery
$.getScript('/path/to/imported/script.js', function()
{
// script is now loaded and executed.
// put your dependent JS here.
});
if you use android make (mka) @echo $(NDK_PROJECT_PATH)
will not work and gives you error *** missing separator. Stop."
use this answer if you are trying to print variables in android make
NDK_PROJECT_PATH := some_value
$(warning $(NDK_PROJECT_PATH))
that worked for me
I'm not trying to provide a yet another alternative solution, but a "meta view" to this problem.
Answers already provided by Oded and Dimitre Novatchev are correct but what people really might mean with phrase "value is a number" is, how would I say it, open to interpretation.
In a way it all comes to this bizarre sounding question: "how do you want to express your numeric values?"
XPath function number()
processes numbers that have
Note that this doesn't include expressions for numerical values that
These are not just made up criteria. An element with content that is according to schema a valid xs:float
value might contain any of the above mentioned characteristics. Yet number()
would return value NaN
.
So answer to your question "How i can check with XPath if a node value is number?" is either "Use already mentioned solutions using number()
" or "with a single XPath 1.0 expression, you can't". Think about the possible number formats you might encounter, and if needed, write some kind of logic for validation/number parsing. Within XSLT processing, this can be done with few suitable extra templates, for example.
PS. If you only care about non-zero numbers, the shortest test is
<xsl:if test="number(myNode)">
<!-- myNode is a non-zero number -->
</xsl:if>
It will prints the string"something" three times.
JLabel[] labels = {new JLabel(), new JLabel(), new JLabel()};
for ( JLabel label : labels )
{
label.setText("something");
panel.add(label);
}
It is not so easy to give out specific addresses to people say for a conference or a specific project or product. It could be more secure to prevent hacking such as SQL injection attacks etc.
In 3.1 you just get rid of the 'images' part of the path. So an image that lives in /assets/images/example.png
will actually be accessible in a get request at this url - /assets/example.png
Because the assets/images
folder gets generated along with a new 3.1 app, this is the convention that they probably want you to follow. I think that's where image_tag
will look for it, but I haven't tested that yet.
Also, during the RailsConf keynote, I remember D2h saying the the public folder
should not have much in it anymore, mostly just error pages and a favicon.
The short answer is no. You can play a bit, if you want:
You can always do something like this:
private enum Base
{
A,
B,
C
}
private enum Consume
{
A = Base.A,
B = Base.B,
C = Base.C,
D,
E
}
But, it doesn't work all that great because Base.A != Consume.A
You can always do something like this, though:
public static class Extensions
{
public static T As<T>(this Consume c) where T : struct
{
return (T)System.Enum.Parse(typeof(T), c.ToString(), false);
}
}
In order to cross between Base and Consume...
You could also cast the values of the enums as ints, and compare them as ints instead of enum, but that kind of sucks too.
The extension method return should type cast it type T.
According to this video of Android Developers you should only make two changes
The Combinations
package is not part of the standard CRAN set of packages, but is rather part of a different repository, omegahat. To install it you need to use
install.packages("Combinations", repos = "http://www.omegahat.org/R")
See the documentation at http://www.omegahat.org/Combinations/
static variables are stored in the heap
Actually, you only need to use the default
argument to add_argument
as in this test.py
script:
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--example', default=1)
args = parser.parse_args()
print(args.example)
test.py --example
% 1
test.py --example 2
% 2
Details are here.
A bit late of a answer, but here is a reusable solution:
/**
* An extension of TextWatcher which stops further callbacks being called as
* a result of a change happening within the callbacks themselves.
*/
public abstract class EditableTextWatcher implements TextWatcher {
private boolean editing;
@Override
public final void beforeTextChanged(CharSequence s, int start,
int count, int after) {
if (editing)
return;
editing = true;
try {
beforeTextChange(s, start, count, after);
} finally {
editing = false;
}
}
protected abstract void beforeTextChange(CharSequence s, int start,
int count, int after);
@Override
public final void onTextChanged(CharSequence s, int start,
int before, int count) {
if (editing)
return;
editing = true;
try {
onTextChange(s, start, before, count);
} finally {
editing = false;
}
}
protected abstract void onTextChange(CharSequence s, int start,
int before, int count);
@Override
public final void afterTextChanged(Editable s) {
if (editing)
return;
editing = true;
try {
afterTextChange(s);
} finally {
editing = false;
}
}
public boolean isEditing() {
return editing;
}
protected abstract void afterTextChange(Editable s);
}
So when the above is used, any setText()
calls happening within the TextWatcher will not result in the TextWatcher being called again:
/**
* A setText() call in any of the callbacks below will not result in TextWatcher being
* called again.
*/
public class MyTextWatcher extends EditableTextWatcher {
@Override
protected void beforeTextChange(CharSequence s, int start, int count, int after) {
}
@Override
protected void onTextChange(CharSequence s, int start, int before, int count) {
}
@Override
protected void afterTextChange(Editable s) {
}
}
1.->
for accessing object member variables and methods via pointer
to object
Foo *foo = new Foo();
foo->member_var = 10;
foo->member_func();
2..
for accessing object member variables and methods via object instance
Foo foo;
foo.member_var = 10;
foo.member_func();
3.::
for accessing static variables and methods of a class/struct
or namespace
. It can also be used to access variables and functions from another scope (actually class, struct, namespace are scopes in that case)
int some_val = Foo::static_var;
Foo::static_method();
int max_int = std::numeric_limits<int>::max();
//lat=3434&lon=yy38&rd=1.0&|
in that format o/p is displaying
public class ReadText {
public static void main(String[] args) throws Exception {
FileInputStream f= new FileInputStream("D:/workplace/sample/bookstore.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(f));
String strline;
StringBuffer sb = new StringBuffer();
while ((strline = br.readLine()) != null)
{
String[] arraylist=StringUtils.split(strline, ",");
if(arraylist.length == 2){
sb.append("lat=").append(StringUtils.trim(arraylist[0])).append("&lon=").append(StringUtils.trim(arraylist[1])).append("&rt=1.0&|");
} else {
System.out.println("Error: "+strline);
}
}
System.out.println("Data: "+sb.toString());
}
}
You can either append a unique querystring (I believe this is what jQuery does with the cache: false option) to the request.
$http({
url: '...',
params: { 'foobar': new Date().getTime() }
})
A perhaps better solution is if you have access to the server, then you can make sure that necessary headers are set to prevent caching. If you're using ASP.NET MVC
this answer might help.
while read CMD; do
echo $CMD
done << EOF
data line 1
data line 2
..
EOF
If you restart service then it will work
$ service sshd restart
then check
$ ssh localhost
It will work
If you look at your XAMPP Control Panel, it's clearly stated that the port to the MySQL server is 3306
- you provided 3360
. The 3306
is default, and thus doesn't need to be specified. Even so, the 5th parameter of mysqli_connect()
is the port, which is where it should be specified.
You could just remove the port specification altogether, as you're using the default port, making it
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = 'test_db13';
References
<?php
$to1 = '[email protected]';
$subject = 'Tester subject';
// To send HTML mail, the Content-type header must be set
$headers .= "Reply-To: The Sender <[email protected]>\r\n";
$headers .= "Return-Path: The Sender <[email protected]>\r\n";
$headers .= "From: [email protected]" ."\r\n" .
$headers .= "Organization: Sender Organization\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=utf-8\r\n";
$headers .= "X-Priority: 3\r\n";
$headers .= "X-Mailer: PHP". phpversion() ."\r\n" ;
?>
From the git-branch manual page:
git branch --contains <commit>
Only list branches which contain the specified commit (HEAD if not specified). Implies
--list
.
git branch -r --contains <commit>
Lists remote tracking branches as well (as mentioned in user3941992's answer below) that is "local branches that have a direct relationship to a remote branch".
As noted by Carl Walsh, this applies only to the default refspec
fetch = +refs/heads/*:refs/remotes/origin/*
If you need to include other ref namespace (pull request, Gerrit, ...), you need to add that new refspec, and fetch again:
git config --add remote.origin.fetch "+refs/pull/*/head:refs/remotes/origin/pr/*"
git fetch
git branch -r --contains <commit>
See also this git ready article.
The
--contains
tag will figure out if a certain commit has been brought in yet into your branch. Perhaps you’ve got a commit SHA from a patch you thought you had applied, or you just want to check if commit for your favorite open source project that reduces memory usage by 75% is in yet.
$ git log -1 tests
commit d590f2ac0635ec0053c4a7377bd929943d475297
Author: Nick Quaranto <[email protected]>
Date: Wed Apr 1 20:38:59 2009 -0400
Green all around, finally.
$ git branch --contains d590f2
tests
* master
Note: if the commit is on a remote tracking branch, add the -a
option.
(as MichielB comments below)
git branch -a --contains <commit>
MatrixFrog comments that it only shows which branches contain that exact commit.
If you want to know which branches contain an "equivalent" commit (i.e. which branches have cherry-picked that commit) that's git cherry
:
Because
git cherry
compares the changeset rather than the commit id (sha1), you can usegit cherry
to find out if a commit you made locally has been applied<upstream>
under a different commit id.
For example, this will happen if you’re feeding patches<upstream>
via email rather than pushing or pulling commits directly.
__*__*__*__*__> <upstream>
/
fork-point
\__+__+__-__+__+__-__+__> <head>
(Here, the commits marked '-
' wouldn't show up with git cherry
, meaning they are already present in <upstream>
.)
To compile with Java 8 (lambdas etc) in IntelliJ IDEA 15;
CTRL + ALT + SHIFT + S
or File / Project Structure
Open Project tab
Set Project SDK to compatible java version (1.8)
Set Project language level to 8
Open Modules tab
Set Language level to 8, click OK
CTRL + ALT + S
or File / Settings
Build, Execution, Deployment / Compiler / Java Compiler
Change Target bytecode version to 1.8, click OK
Had the same problem and tried everything I browse in several forums till I found a clue, then finally solved the problem.
Basically I installed the SDK and worked ok, then my Windows Vista crashed, on restart I run SDK again but it only opened a CMD window which closed immediately.
So here's a list of useless things I did:
At this point I was seriously considering start learning objetive-c was not a bad idea, finally I did this:
it WORKED !! I'm not sure though if is necessary to uninstall SDK (since I had again to download all packages & platforms) and just clear the temp folder.
Hope this helps.
You need a more specific expression. Try grep " OK$"
or grep "[0-9]* OK"
. You want to choose a pattern that matches what you want, but won't match what you don't want. That pattern will depend upon what your whole file contents might look like.
You can also do: grep -w "OK"
which will only match a whole word "OK", such as "1 OK" but won't match "1OK" or "OKFINE".
$ cat test.txt | grep -w "OK"
1 OK
2 OK
4 OK
just configure your log4j property file path in beginning of main method: e.g.: PropertyConfigurator.configure("D:\files\log4j.properties");
Just completing Desmond Hume's answer to extend the String class for a RFC 3986 unreserved characters valid encoding function (needed if you are encoding query FORM parameters):
extension String {
var RFC3986UnreservedEncoded:String {
let unreservedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
let unreservedCharsSet: CharacterSet = CharacterSet(charactersIn: unreservedChars)
let encodedString: String = self.addingPercentEncoding(withAllowedCharacters: unreservedCharsSet)!
return encodedString
}
}
Use the TABLOCKX lock hint for your transaction. See this article for more information on locking.
<select class="form-control" [value]="defaultSelectedCurrency" formControlName="currency">
<option *ngFor="let item of currency" [value]="item.value" [selected]="item.isSelected">{{item.key}}</option>
</select>
currency = [
{ key: 'USD', value: 'USD', isSelected: true },
{ key: 'AUD', value: 'AUD', isSelected: false }
];
defaultSelectedCurrency: string;
ngOnInit() {
this.defaultSelectedCurrency = this.currency[0].value;
}
Object.equals() method checks only reference of object not primitive data type or Object value (Wrapper class object of primitive data, simple primitive data type (byte, short, int, long etc.)). So that we must override equals() method when we compare object based on primitive data type.
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
radioButton = (RadioButton) findViewById(checkedId);
Toast.makeText(getBaseContext(), radioButton.getText(), Toast.LENGTH_SHORT).show();
}
}
);
It's better also to separate your logic in another method, or maybe in another class.
This method will help you retreive the DataGridViewCell object in which the text was found.
/// <summary>
/// Check if a given text exists in the given DataGridView at a given column index
/// </summary>
/// <param name="searchText"></param>
/// <param name="dataGridView"></param>
/// <param name="columnIndex"></param>
/// <returns>The cell in which the searchText was found</returns>
private DataGridViewCell GetCellWhereTextExistsInGridView(string searchText, DataGridView dataGridView, int columnIndex)
{
DataGridViewCell cellWhereTextIsMet = null;
// For every row in the grid (obviously)
foreach (DataGridViewRow row in dataGridView.Rows)
{
// I did not test this case, but cell.Value is an object, and objects can be null
// So check if the cell is null before using .ToString()
if (row.Cells[columnIndex].Value != null && searchText == row.Cells[columnIndex].Value.ToString())
{
// the searchText is equals to the text in this cell.
cellWhereTextIsMet = row.Cells[columnIndex];
break;
}
}
return cellWhereTextIsMet;
}
private void button_click(object sender, EventArgs e)
{
DataGridViewCell cell = GetCellWhereTextExistsInGridView(textBox1.Text, myGridView, 2);
if (cell != null)
{
// Value exists in the grid
// you can do extra stuff on the cell
cell.Style = new DataGridViewCellStyle { ForeColor = Color.Red };
}
else
{
// Value does not exist in the grid
}
}
This should do what you want:
sed 's/two.*/BLAH/'
$ echo " one two three five
> four two five five six
> six one two seven four" | sed 's/two.*/BLAH/'
one BLAH
four BLAH
six one BLAH
The $
is unnecessary because the .*
will finish at the end of the line anyways, and the g
at the end is unnecessary because your first match will be the first two
to the end of the line.
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Holo.NoActionBar">
<item name="android:windowBackground">@android:color/black</item>
</style>
</resources>
You should use:
[UIApplication sharedApplication].window.rootViewController;
When there is a uiactionsheet on [UIApplication sharedApplication].keyWindow
, it is not right to use keyWindow as mentioned in this answer.
Most of the people already gave the answer but this one is just for making someone's life easier.
TL;DR
You must add the test folder as source.
Thats it, IntelliJ will consider them as test source.
Asset.objects.filter( project__name__contains="Foo" )
since 1.5.0 u can use the 'inline' keyword.
Example: @import (inline) "not-less-compatible.css";
You will use this when a CSS file may not be Less compatible; this is because although Less supports most known standards CSS, it does not support comments in some places and does not support all known CSS hacks without modifying the CSS. So you can use this to include the file in the output so that all CSS will be in one file.
(source: http://lesscss.org/features/#import-directives-feature)
select DATEDIFF(dd, '12/30/1899', mydatefield)
If you press Ctrl + Enter after you press something like "/wordforsearch", then you can find the word "wordforsearch" in the current line. Then press n for the next match; press N for previous match.
The following code will fetch you desired results with duplicate items and their index values.
for i in set(mylist):
if mylist.count(i) > 1:
print(i, mylist.index(i))
The View::make
function takes 3 arguments which according to the documentation are:
public View make(string $view, array $data = array(), array $mergeData = array())
In your case, the compact('selections')
is a 4th argument. It doesn't pass to the view and laravel throws an exception.
On the other hand, you can use with()
as many time as you like. Thus, this will work:
return View::make('gameworlds.mygame')
->with(compact('fixtures'))
->with(compact('teams'))
->with(compact('selections'));
If your application creates a database, this database is by default saved in the directory DATA/data/APP_NAME/databases/FILENAME.
The parts of the above directory are constructed based on the following rules. DATA is the path which the Environment.getDataDirectory() method returns. APP_NAME is your application name. FILENAME is the name you specify in your application code for the database.
create table foobar(
id INT PRIMARY KEY AUTO_INCREMENT,
moobar VARCHAR(500)
);
ALTER TABLE foobar AUTO_INCREMENT=10;
INSERT INTO foobar(moobar) values ("abc");
INSERT INTO foobar(moobar) values ("def");
INSERT INTO foobar(moobar) values ("xyz");
select * from foobar;
'10', 'abc'
'11', 'def'
'12', 'xyz'
This auto increments the id column by one starting at 10.
drop table foobar
create table foobar(
id INT PRIMARY KEY AUTO_INCREMENT,
moobar VARCHAR(500)
);
SET @@auto_increment_increment=5;
ALTER TABLE foobar AUTO_INCREMENT=10;
INSERT INTO foobar(moobar) values ("abc");
INSERT INTO foobar(moobar) values ("def");
INSERT INTO foobar(moobar) values ("xyz");
select * from foobar;
'11', 'abc'
'16', 'def'
'21', 'xyz'
This auto increments the id column by 5 each time, starting at 10.
This sounds like a ClassLoader conflict. I'd bet you have the javax.persistence api 1.x on the classpath somewhere, whereas Spring is trying to access ValidationMode
, which was only introduced in JPA 2.0.
Since you use Maven, do mvn dependency:tree
, find the artifact:
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
And remove it from your setup. (See Excluding Dependencies)
AFAIK there is no such general distribution for JPA 2, but you can use this Hibernate-specific version:
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
OK, since that doesn't work, you still seem to have some JPA-1 version in there somewhere. In a test method, add this code:
System.out.println(EntityManager.class.getProtectionDomain()
.getCodeSource()
.getLocation());
See where that points you and get rid of that artifact.
Ahh, now I finally see the problem. Get rid of this:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jpa</artifactId>
<version>2.0.8</version>
</dependency>
and replace it with
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
On a different note, you should set all test libraries (spring-test, easymock etc.) to
<scope>test</scope>
Applying the full_extent()
function in an answer by @Joe 3 years later from here, you can get exactly what the OP was looking for. Alternatively, you can use Axes.get_tightbbox()
which gives a little tighter bounding box
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from matplotlib.transforms import Bbox
def full_extent(ax, pad=0.0):
"""Get the full extent of an axes, including axes labels, tick labels, and
titles."""
# For text objects, we need to draw the figure first, otherwise the extents
# are undefined.
ax.figure.canvas.draw()
items = ax.get_xticklabels() + ax.get_yticklabels()
# items += [ax, ax.title, ax.xaxis.label, ax.yaxis.label]
items += [ax, ax.title]
bbox = Bbox.union([item.get_window_extent() for item in items])
return bbox.expanded(1.0 + pad, 1.0 + pad)
# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')
ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')
# Save the full figure...
fig.savefig('full_figure.png')
# Save just the portion _inside_ the second axis's boundaries
extent = full_extent(ax2).transformed(fig.dpi_scale_trans.inverted())
# Alternatively,
# extent = ax.get_tightbbox(fig.canvas.renderer).transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)
I'd post a pic but I lack the reputation points
Here, this should cover all the bases. It handles all types of issues for you, including (but not limited too) character substitution.
Works in Windows, *nix, and almost every other file system. Allows printable characters only.
def txt2filename(txt, chr_set='normal'):
"""Converts txt to a valid Windows/*nix filename with printable characters only.
args:
txt: The str to convert.
chr_set: 'normal', 'universal', or 'inclusive'.
'universal': ' -.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
'normal': Every printable character exept those disallowed on Windows/*nix.
'extended': All 'normal' characters plus the extended character ASCII codes 128-255
"""
FILLER = '-'
# Step 1: Remove excluded characters.
if chr_set == 'universal':
# Lookups in a set are O(n) vs O(n * x) for a str.
printables = set(' -.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')
else:
if chr_set == 'normal':
max_chr = 127
elif chr_set == 'extended':
max_chr = 256
else:
raise ValueError(f'The chr_set argument may be normal, extended or universal; not {chr_set=}')
EXCLUDED_CHRS = set(r'<>:"/\|?*') # Illegal characters in Windows filenames.
EXCLUDED_CHRS.update(chr(127)) # DEL (non-printable).
printables = set(chr(x)
for x in range(32, max_chr)
if chr(x) not in EXCLUDED_CHRS)
result = ''.join(x if x in printables else FILLER # Allow printable characters only.
for x in txt)
# Step 2: Device names, '.', and '..' are invalid filenames in Windows.
DEVICE_NAMES = 'CON,PRN,AUX,NUL,COM1,COM2,COM3,COM4,' \
'COM5,COM6,COM7,COM8,COM9,LPT1,LPT2,' \
'LPT3,LPT4,LPT5,LPT6,LPT7,LPT8,LPT9,' \
'CONIN$,CONOUT$,..,.'.split() # This list is an O(n) operation.
if result in DEVICE_NAMES:
result = f'-{result}-'
# Step 3: Maximum length of filename is 255 bytes in Windows and Linux (other *nix flavors may allow longer names).
result = result[:255]
# Step 4: Windows does not allow filenames to end with '.' or ' ' or begin with ' '.
result = re.sub(r'^[. ]', FILLER, result)
result = re.sub(r' $', FILLER, result)
return result
This solution needs no external libraries. It substitutes non-printable filenames too because they are not always simple to deal with.
I had to restart my queue worker using php artisan queue:restart
after running php artisan key:generate
to get jobs working.
The reason for this would be mostly due to the evil command pip install google
. I was facing a similar issue for google-cloud
, but the same steps are true for protobuf
as well. Both of our issues deal with a namespace conflict over the 'google' namespace.
If you executed the pip install google
command like I did then you are in the correct place. The google
package is actually not owned by Google which can be confirmed by the command pip show google
which outputs:
Name: google
Version: 1.9.3
Summary: Python bindings to the Google search engine.
Home-page: http://breakingcode.wordpress.com/
Author: Mario Vilas
Author-email: [email protected]
License: UNKNOWN
Location: <Path where this package is installed>
Requires: beautifulsoup4
Because of this package, the google
namespace is reserved and coincidentally google-cloud
also expects namespace google > cloud
and it results in a namespace collision for these two packages.
See in below screenshot namespace of google-protobuf
as google > protobuf
Solution :- Unofficial google
package need to be uninstalled which can be done by using pip uninstall google
after this you can reinstall google-cloud
using pip install google-cloud
or protobuf
using pip install protobuf
FootNotes :- Assuming you have installed the unofficial google
package by mistake and you don't actually need it along with google-cloud
package. If you need both unofficial google
and google-cloud
above solution won't work.
Furthermore, the unofficial 'google' package installs with it 'soupsieve' and 'beautifulsoup4'. You may want to also uninstall those packages.
Let me know if this solves your particular issue.
Make sure return type of you method is same what you want to return. Eg: `
public int get(int[] r)
{
return r[0];
}
`
Note : return type is int, not int[], so it is able to return int.
In general, prototype can be
public Type get(Type[] array, int index)
{
return array[index];
}
The command history is an interactive feature. Only complete commands are entered in the history. For example, the case
construct is entered as a whole, when the shell has finished parsing it. Neither looking up the history with the history
built-in (nor printing it through shell expansion (!:p
)) does what you seem to want, which is to print invocations of simple commands.
The DEBUG
trap lets you execute a command right before any simple command execution. A string version of the command to execute (with words separated by spaces) is available in the BASH_COMMAND
variable.
trap 'previous_command=$this_command; this_command=$BASH_COMMAND' DEBUG
…
echo "last command is $previous_command"
Note that previous_command
will change every time you run a command, so save it to a variable in order to use it. If you want to know the previous command's return status as well, save both in a single command.
cmd=$previous_command ret=$?
if [ $ret -ne 0 ]; then echo "$cmd failed with error code $ret"; fi
Furthermore, if you only want to abort on a failed commands, use set -e
to make your script exit on the first failed command. You can display the last command from the EXIT
trap.
set -e
trap 'echo "exit $? due to $previous_command"' EXIT
Note that if you're trying to trace your script to see what it's doing, forget all this and use set -x
.
For INNER
joins, no, the order doesn't matter. The queries will return same results, as long as you change your selects from SELECT *
to SELECT a.*, b.*, c.*
.
For (LEFT
, RIGHT
or FULL
) OUTER
joins, yes, the order matters - and (updated) things are much more complicated.
First, outer joins are not commutative, so a LEFT JOIN b
is not the same as b LEFT JOIN a
Outer joins are not associative either, so in your examples which involve both (commutativity and associativity) properties:
a LEFT JOIN b
ON b.ab_id = a.ab_id
LEFT JOIN c
ON c.ac_id = a.ac_id
is equivalent to:
a LEFT JOIN c
ON c.ac_id = a.ac_id
LEFT JOIN b
ON b.ab_id = a.ab_id
but:
a LEFT JOIN b
ON b.ab_id = a.ab_id
LEFT JOIN c
ON c.ac_id = a.ac_id
AND c.bc_id = b.bc_id
is not equivalent to:
a LEFT JOIN c
ON c.ac_id = a.ac_id
LEFT JOIN b
ON b.ab_id = a.ab_id
AND b.bc_id = c.bc_id
Another (hopefully simpler) associativity example. Think of this as (a LEFT JOIN b) LEFT JOIN c
:
a LEFT JOIN b
ON b.ab_id = a.ab_id -- AB condition
LEFT JOIN c
ON c.bc_id = b.bc_id -- BC condition
This is equivalent to a LEFT JOIN (b LEFT JOIN c)
:
a LEFT JOIN
b LEFT JOIN c
ON c.bc_id = b.bc_id -- BC condition
ON b.ab_id = a.ab_id -- AB condition
only because we have "nice" ON
conditions. Both ON b.ab_id = a.ab_id
and c.bc_id = b.bc_id
are equality checks and do not involve NULL
comparisons.
You can even have conditions with other operators or more complex ones like: ON a.x <= b.x
or ON a.x = 7
or ON a.x LIKE b.x
or ON (a.x, a.y) = (b.x, b.y)
and the two queries would still be equivalent.
If however, any of these involved IS NULL
or a function that is related to nulls like COALESCE()
, for example if the condition was b.ab_id IS NULL
, then the two queries would not be equivalent.
I have also been looking for an elegant solution to this problem. After much reflection, I found this approach best.
const func = me.onChange || (str => {});
func(str)
;
It means something like this:
std::vector<Movie *> movies;
Then you add to the vector as you read lines:
movies.push_back(new Movie(...));
Remember to delete all of the Movie*
objects once you are done with the vector.
As an addition to Jakub's answer, if you plan to use JavaConfig, you can also autowire that way:
import com.google.common.collect.Lists;
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;
<...>
@Configuration
public class MyConfiguration {
@Bean
public List<Stage> stages(final Stage1 stage1, final Stage2 stage2) {
return Lists.newArrayList(stage1, stage2);
}
}
java.util.Collection#Iterator is a good example of a Factory Method. Depending on the concrete subclass of Collection you use, it will create an Iterator implementation. Because both the Factory superclass (Collection) and the Iterator created are interfaces, it is sometimes confused with AbstractFactory. Most of the examples for AbstractFactory in the the accepted answer (BalusC) are examples of Factory, a simplified version of Factory Method, which is not part of the original GoF patterns. In Facory the Factory class hierarchy is collapsed and the factory uses other means to choose the product to be returned.
An abstract factory has multiple factory methods, each creating a different product. The products produced by one factory are intended to be used together (your printer and cartridges better be from the same (abstract) factory). As mentioned in answers above the families of AWT GUI components, differing from platform to platform, are an example of this (although its implementation differs from the structure described in Gof).
Use immediate children selector >
:
$('#tblOne > tbody > tr')
Description: Selects all direct child elements specified by "child" of elements specified by "parent".
In the 1st, 2nd, and 3rd Edition of ECMAScript, using $-prefixed variable names was explicitly discouraged by the spec except in the context of autogenerated code:
The dollar sign (
$
) and the underscore (_
) are permitted anywhere in an identifier. The dollar sign is intended for use only in mechanically generated code.
However, in the next version (the 5th Edition, which is current), this restriction was dropped, and the above passage replaced with
The dollar sign (
$
) and the underscore (_
) are permitted anywhere in an IdentifierName.
As such, the $ sign may now be used freely in variable names. Certain frameworks and libraries have their own conventions on the meaning of the symbol, noted in other answers here.
Sometime in the future. Applicable to Windows 8.1 machine. Run the following commands
npm install -g @angular/cli
Log out or restart your machine.
This should add the required env path, rather than doing it manually.
You can go to File -> Preferences -> Keyboard Shortcut. Once you are there, you can search for navigate. Then, you will see all shortcuts set for your VS Code environment related to navigation. In my case, it was only Alt + '-' to get my cursor back.
TL;DR
Long Version
Jenkins Pipeline testing becomes more and more of a pain. Unlike the classic declarative job configuration approach where the user was limited to what the UI exposed the new Jenkins Pipeline is a full fledged programming language for the build process where you mix the declarative part with your own code. As good developers we want to have some unit tests for this kind of code as well.
There are three steps you should follow when developing Jenkins Pipelines. The step 1. should cover 80% of the uses cases.
Examples
The pipelineUnit GitHub repo contains some Spock examples on how to use Jenkins Pipeline Unit testing framework
In my case this helped:
$ export LDFLAGS="-L/usr/local/opt/openssl/lib"
$ export CPPFLAGS="-I/usr/local/opt/openssl/include"
Then:
gem install mysql2 -v '0.5.2' --source 'https://rubygems.org/' -- --with-cppflags=-I/usr/local/opt/openssl/include --with-ldflags=-L/usr/local/opt/openssl/lib
Result:
Building native extensions with: '--with-cppflags=-I/usr/local/opt/openssl/include --with-ldflags=-L/usr/local/opt/openssl/lib'
This could take a while...
Successfully installed mysql2-0.5.2
Parsing documentation for mysql2-0.5.2
Installing ri documentation for mysql2-0.5.2
Done installing documentation for mysql2 after 0 seconds
1 gem installed
See this post (WARNING: Japanese language inside).
I have tried lots and lots of steps from different people posted on different websites. But none of them mention that I should add the certificate into the Trusted People keystore.
That's right, placing it under trusted CA is not enough for my case, I have to put the certs inside the Trusted People also.
That's:
To export the certificate:
I'm on IE9, Windows 7
You can also try to use a Polyfill like Fixed-Sticky. Especially when you are using Bootstrap4 the affix
component is no longer included:
Dropped the Affix jQuery plugin. We recommend using a position: sticky polyfill instead.
I used a formula that I got from www.geomidpoint.com and wrote the following C++ implementation. The array
and geocoords
are my own classes whose functionality should be self-explanatory.
/*
* midpoints calculated using formula from www.geomidpoint.com
*/
geocoords geocoords::calcmidpoint( array<geocoords>& points )
{
if( points.empty() ) return geocoords();
float cart_x = 0,
cart_y = 0,
cart_z = 0;
for( auto& point : points )
{
cart_x += cos( point.lat.rad() ) * cos( point.lon.rad() );
cart_y += cos( point.lat.rad() ) * sin( point.lon.rad() );
cart_z += sin( point.lat.rad() );
}
cart_x /= points.numelems();
cart_y /= points.numelems();
cart_z /= points.numelems();
geocoords mean;
mean.lat.rad( atan2( cart_z, sqrt( pow( cart_x, 2 ) + pow( cart_y, 2 ))));
mean.lon.rad( atan2( cart_y, cart_x ));
return mean;
}
It's the "null coalescing operator", added in php 7.0. The definition of how it works is:
It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
So it's actually just isset()
in a handy operator.
Those two are equivalent1:
$foo = $bar ?? 'something';
$foo = isset($bar) ? $bar : 'something';
Documentation: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce
In the list of new PHP7 features: http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op
And original RFC https://wiki.php.net/rfc/isset_ternary
EDIT: As this answer gets a lot of views, little clarification:
1There is a difference: In case of ??
, the first expression is evaluated only once, as opposed to ? :
, where the expression is first evaluated in the condition section, then the second time in the "answer" section.
I have found that Furius ISO mount works best for me. I am using a Debian based distro Knoppix. I use this to Open system.img
files all the time.
Furius ISO mount: https://packages.debian.org/sid/otherosfs/furiusisomount
"When I want to mount userdata.img by mount -o loop userdata.img /mnt/userdata (the same as system.img), it tells me mount: you must specify the filesystem type so I try the mount -t ext2 -o loop userdata.img /mnt/userdata, it said mount: wrong fs type, bad option, bad superblock on...
So, how to get the file from the inside of userdata.img?"
To load .img
files you have to select loop and load the .img
Select loop
Next you select mount Select mount
Furius ISO mount handles all the other options loading the .img
file to your /home/dir.
If what you are needing is an array of arrays, you can do this way:
key:
- [ 'value11', 'value12', 'value13' ]
- [ 'value21', 'value22', 'value23' ]
I had the same problem and found solution, placing NULL
instead of NOT NULL
on foreign key column. Here is a query:
ALTER TABLE `db`.`table1`
ADD COLUMN `col_table2_fk` INT UNSIGNED NULL,
ADD INDEX `col_table2_fk_idx` (`col_table2_fk` ASC),
ADD CONSTRAINT `col_table2_fk1`
FOREIGN KEY (`col_table2_fk`)
REFERENCES `db`.`table2` (`table2_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
MySQL has executed this query!
If using a Mac
pbpaste|sort -u|wc -l
Linux users replace pbpaste
with xclip xsel or similar
Windows users, it's possible but would take some scripting... start with http://brianreiter.org/2010/09/03/copy-and-paste-with-clipboard-from-powershell/
SELECT art.* , sec.section.title, cat.title, use1.name, use2.name as modifiedby
FROM article art
INNER JOIN section sec ON art.section_id = sec.section.id
INNER JOIN category cat ON art.category_id = cat.id
INNER JOIN user use1 ON art.author_id = use1.id
LEFT JOIN user use2 ON art.modified_by = use2.id
WHERE art.id = '1';
Hope This Might Help
swift 3
func borderColor(){
self.viewMenuItems.layer.cornerRadius = 13
self.viewMenuItems.layer.borderWidth = 1
self.viewMenuItems.layer.borderColor = UIColor.white.cgColor
}
For me this worked perfectly fine .
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivity(intent);
and add this permission to mainfest file:
<uses-permission android:name="android.permission.CAMERA">
It opens the camera,after capturing the image it saves the image to gallery with a new image set.
I am not sure about DO-WHILE IN MS SQL Server 2008 but you can change your WHILE loop logic, so as to USE like DO-WHILE loop.
Examples are taken from here: http://blog.sqlauthority.com/2007/10/24/sql-server-simple-example-of-while-loop-with-continue-and-break-keywords/
Example of WHILE Loop
DECLARE @intFlag INT SET @intFlag = 1 WHILE (@intFlag <=5) BEGIN PRINT @intFlag SET @intFlag = @intFlag + 1 END GO
ResultSet:
1 2 3 4 5
Example of WHILE Loop with BREAK keyword
DECLARE @intFlag INT SET @intFlag = 1 WHILE (@intFlag <=5) BEGIN PRINT @intFlag SET @intFlag = @intFlag + 1 IF @intFlag = 4 BREAK; END GO
ResultSet:
1 2 3
Example of WHILE Loop with CONTINUE and BREAK keywords
DECLARE @intFlag INT SET @intFlag = 1 WHILE (@intFlag <=5) BEGIN PRINT @intFlag SET @intFlag = @intFlag + 1 CONTINUE; IF @intFlag = 4 -- This will never executed BREAK; END GO
ResultSet:
1 2 3 4 5
But try to avoid loops at database level. Reference.
I got the same error when using %
as a percent character in my format string. The solution to this is to double up the %%
.
With the user.language
, user.country
and user.variant
properties.
Example:
java -Duser.language=th -Duser.country=TH -Duser.variant=TH SomeClass
Others have noted the correct answer, but have not clearly explained the all-important reason:
<
stands for the <
sign. Just remember: lt == less than>
stands for the >
Just remember: gt == greater than<
and >
characters in HTML?>
and <
characters are ‘reserved’ characters in HTML.<
and >
are used to denote the starting and ending of different elements: e.g. <h1>
and not for the displaying of the greater than or less than symbols. But what if you wanted to actually display those symbols? You would simply use <
and >
and the browser will know exactly how to display it.The R
graphics
package has the function axTicks
that returns the tick locations of the ticks that the axis
and plot
functions would set automatically. The other answers given to this question define the tick locations manually which might not be convenient in some situations.
myTicks = axTicks(1)
axis(1, at = myTicks, labels = formatC(myTicks, format = 'd'))
A minimal example would be
plot(10^(0:10), 0:10, log = 'x', xaxt = 'n')
myTicks = axTicks(1)
axis(1, at = myTicks, labels = formatC(myTicks, format = 'd'))
There is also an log
parameter in the axTicks
function but in this situation it does not need to be set to get the proper logarithmic axis tick location.
Your formula is wrong. You probably meant something like:
=IF(AND(NOT(ISBLANK(Q2));NOT(ISBLANK(R2)));IF(Q2<=R2;"1";"0");"")
Another equivalent:
=IF(NOT(OR(ISBLANK(Q2);ISBLANK(R2)));IF(Q2<=R2;"1";"0");"")
Or even shorter:
=IF(OR(ISBLANK(Q2);ISBLANK(R2));"";IF(Q2<=R2;"1";"0"))
OR EVEN SHORTER:
=IF(OR(ISBLANK(Q2);ISBLANK(R2));"";--(Q2<=R2))
df = df.loc[:, ~df.columns.str.contains('^Unnamed')]
In [162]: df
Out[162]:
colA ColB colC colD colE colF colG
0 44 45 26 26 40 26 46
1 47 16 38 47 48 22 37
2 19 28 36 18 40 18 46
3 50 14 12 33 12 44 23
4 39 47 16 42 33 48 38
if the first column in the CSV file has index values, then you can do this instead:
df = pd.read_csv('data.csv', index_col=0)
Please try this out to take into account all possible scenarios:
awk '{print $(NF-1)"\t"$NF}' file
or
awk 'BEGIN{OFS="\t"}' file
or
awk '{print $(NF-1), $NF} {print $(NF-1), $NF}' file
you can use 'transform' to achieve this. http://jsfiddle.net/aRcQ8/
css:
-moz-transform: rotate(-180deg);
-webkit-transform: rotate(-180deg);
transform: rotate(-180deg);
You can use preg_replace in this case;
$res = preg_replace("/[^0-9]/", "", "Every 6 Months" );
$res return 6 in this case.
If want also to include decimal separator or thousand separator check this example:
$res = preg_replace("/[^0-9.]/", "", "$ 123.099");
$res returns "123.099" in this case
Include period as decimal separator or thousand separator: "/[^0-9.]/"
Include coma as decimal separator or thousand separator: "/[^0-9,]/"
Include period and coma as decimal separator and thousand separator: "/[^0-9,.]/"
Interfaces cannot require instance variables to be defined -- only methods.
(Variables can be defined in interfaces, but they do not behave as might be expected: they are treated as final static
.)
Happy coding.
The easiest way to do it is using Storyboard and a Segue.
Just create a Segue from the FirstViewController (not the Navigation Controller) of your TabBarController to a LoginViewController with the login UI and name it "showLogin".
Create a method that returns a BOOL to validate if the user logged in and/or his/her session is valid... preferably on the AppDelegate. Call it isSessionValid.
On your FirstViewController.m override the method viewDidAppear as follows:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if([self isSessionValid]==NO){
[self performSegueWithIdentifier:@"showLogin" sender:self];
}
}
Then if the user logged in successfully, just dismiss or pop-out the LoginViewController to show your tabs.
Works 100%!
Hope it helps!
This answer from askubuntu is what worked for me. Seems simpler than other options an less error-prone, since it uses package libgtest-dev
to get the sources and builds from there: https://askubuntu.com/questions/145887/why-no-library-files-installed-for-google-test?answertab=votes#tab-top
Please refer to that answer, but just as a shortcut I provide the steps here as well:
sudo apt-get install -y libgtest-dev
sudo apt-get install -y cmake
cd /usr/src/gtest
sudo cmake .
sudo make
sudo mv libg* /usr/lib/
After that, I could build my project which depends on gtest
with no issues.
Or you can put in the CSS,
<style>
div#img {
background-image: url(“file.png");
color:yellow (this part doesn't matter;
height:100%;
width:100%;
}
</style>
I have recently written a tool for showing console logs in a movable/resizable "window" (actually a div). It provides similar functionality to Firebug's console but you can see it over your page on a tablet. Tablet/Smartphone/Phablet Debug Console
Please see the example below
public partial class Form1 : Form
{
[ThreadStatic()]
static Microsoft.Office.Interop.Word.Application wordObj = null;
public Form1()
{
InitializeComponent();
}
public bool OpenDoc(string documentName)
{
bool bSuccss = false;
System.Threading.Thread newThread;
int iRetryCount;
int iWait;
int pid = 0;
int iMaxRetry = 3;
try
{
iRetryCount = 1;
TRY_OPEN_DOCUMENT:
iWait = 0;
newThread = new Thread(() => OpenDocument(documentName, pid));
newThread.Start();
WAIT_FOR_WORD:
Thread.Sleep(1000);
iWait = iWait + 1;
if (iWait < 60) //1 minute wait
goto WAIT_FOR_WORD;
else
{
iRetryCount = iRetryCount + 1;
newThread.Abort();
//'-----------------------------------------
//'killing unresponsive word instance
if ((wordObj != null))
{
try
{
Process.GetProcessById(pid).Kill();
Marshal.ReleaseComObject(wordObj);
wordObj = null;
}
catch (Exception ex)
{
}
}
//'----------------------------------------
if (iMaxRetry >= iRetryCount)
goto TRY_OPEN_DOCUMENT;
else
goto WORD_SUCCESS;
}
}
catch (Exception ex)
{
bSuccss = false;
}
WORD_SUCCESS:
return bSuccss;
}
private bool OpenDocument(string docName, int pid)
{
bool bSuccess = false;
Microsoft.Office.Interop.Word.Application tWord;
DateTime sTime;
DateTime eTime;
try
{
tWord = new Microsoft.Office.Interop.Word.Application();
sTime = DateTime.Now;
wordObj = new Microsoft.Office.Interop.Word.Application();
eTime = DateTime.Now;
tWord.Quit(false);
Marshal.ReleaseComObject(tWord);
tWord = null;
wordObj.Visible = false;
pid = GETPID(sTime, eTime);
//now do stuff
wordObj.Documents.OpenNoRepairDialog(docName);
//other code
if (wordObj != null)
{
wordObj.Quit(false);
Marshal.ReleaseComObject(wordObj);
wordObj = null;
}
bSuccess = true;
}
catch
{ }
return bSuccess;
}
private int GETPID(System.DateTime startTime, System.DateTime endTime)
{
int pid = 0;
try
{
foreach (Process p in Process.GetProcessesByName("WINWORD"))
{
if (string.IsNullOrEmpty(string.Empty + p.MainWindowTitle) & p.HasExited == false && (p.StartTime.Ticks >= startTime.Ticks & p.StartTime.Ticks <= endTime.Ticks))
{
pid = p.Id;
break;
}
}
}
catch
{
}
return pid;
}
You can simply use the Glide API. It avoids all the boilerplate code and the task can be achieved in two lines of code. You refer this link https://blog.mindorks.com/downloading-and-showing-image-with-glide-library-in-android. Enjoy
I've set up a JSFiddle to test several different solutions to this problem. Based on the [vague] criteria of
1) Maximum flexibility
2) No weird behavior
The accepted answer here of
img { display: block; }
which is recommended by a lot of people (such as in this excellent article), actually ranks fourth.
1st, 2nd, and 3rd place are all a toss-up between these three solutions:
1) The solution given by @Dave Kok and @Hasan Gursoy:
img { vertical-align: top; } /* or bottom */
pros:
cons:
2) Setting font-size: 0;
on the parent element:
.parent {
font-size: 0;
vertical-align: top;
}
.parent > * {
font-size: 16px;
vertical-align: top;
}
Since this one [kind of] requires vertical-align: top
on the img
, this is basically an extension of the 1st solution.
pros:
cons:
3) Setting line-height: 0
on the parent element:
.parent {
line-height: 0;
vertical-align: top;
}
.parent > * {
line-height: 1.15;
vertical-align: top;
}
Similar to the 2nd solution in that, to make it fully flexible, it basically becomes an extension of the 1st.
pros:
cons:
So there you have it. I hope this helps some poor soul.
You can also try compressing (zipping) the file. It sometimes works for me if I can't get to php.ini for phpmyadmin. If zipping reduces the file size below the maximum file size, it just might work!
If you're not wanting to save changes set savechanges to false
Sub CloseBook2()
ActiveWorkbook.Close savechanges:=False
End Sub
for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used
ActiveWorkbook.Close False
You can use the jps
utility that is included in the JDK to find the process id of a Java process. The output will show you the name of the executable JAR file or the name of the main class.
Then use the Windows task manager to terminate the process. If you want to do it on the command line, use
TASKKILL /PID %PID%
You could use Role Strategy plugin for that purpose. It works like a charm, just setup some roles and assign them. Even on project-specific level.
make position absolute
for that div.
You could define something like this:
abstract class Father
{
//Do you need it public?
protected readonly int MyInt;
}
class Son : Father
{
public Son()
{
MyInt = 1;
}
}
By setting the value as readonly, it ensures that the value for that class remains unchanged for the lifetime of the object.
I suppose the next question is: why do you need it?
Very informative answer from @stej, but here is a short answer: Among other options, you have 3 simple options to format [System.DateTime] stored in a variable:
Pass the variable to the Get-Date cmdlet:
Get-Date -Format "HH:mm" $date
Use toString() method:
$date.ToString("HH:mm")
Use Composite formatting:
"{0:HH:mm}" -f $date
I don't have enough reputation points to comment on the recommendation to use *.csv >> ConcatenatedFile.csv
, but I can add a warning:
If you create ConcatenatedFile.csv
file in the same directory that you are using for concatenation it will be added to itself.
The part about not being able to use the Back button is a common misinterpretation. window.location.replace(URL) throws out the top ONE entry from the page history list, by overwriting it with the new entry, so the user can't easily go Back to that ONE particular webpage. The function does NOT wipe out the entire page history list, nor does it make the Back button completely non-functional.
(NO function nor combination of parameters that I know of can change or overwrite history list entries that you don't own absolutely for certain - browsers generally impelement this security limitation by simply not even defining any operation that might at all affect any entry other than the top one in the page history list. I shudder to think what sorts of dastardly things malware might do if such a function existed.)
If you really want to make the Back button non-functional (probably not "user friendly": think again if that's really what you want to do), "open" a brand new window. (You can "open" a popup that doesn't even have a "Back" button too ...but popups aren't very popular these days:-) If you want to keep your page showing no matter what the user does (again the "user friendliness" is questionable), set up a window.onunload handler that just reloads your page all over again clear from the very beginning every time.
Goal: no changes / installs necessary to the build agents
I have taken a hybrid approach to the NuGet approach by Lloyd here, which was based off of the committing binary dependencies solution by Andrik.
The reason why is I want to be able to add new build agents without having to pre-configure them with items such as this.
[solution]\packages\MSBuild.Microsoft.VisualStudio.Web.targets.nn.n.n.n\tools\VSToolsPath\
In Version 7, I did the following. This may not have been necessary, and based on the comments is definitely not needed now. Please see the comments below.
env.VSToolsPath
and set it to the VSToolsPath folder; I used ..\packages\MSBuild.Microsoft.VisualStudio.Web.targets.11.0.2.1\tools\VSToolsPath
This worked for me in FF 36, Chrome 41 and IE 11. Even if you cancel the print, and even if you closed the print dialog with the top-right "X".
var newWindow=window.open();
newWindow.document.open();
newWindow.document.write('<HTML><BODY>Hi!</BODY></HTML>'); //add your content
newWindow.document.close();
newWindow.print();
newWindow.onload = function(e){ newWindow.close(); }; //works in IE & FF but not chrome
//adding script to new document below makes it work in chrome
//but alone it sometimes failed in FF
//using both methods together works in all 3 browsers
var script = newWindow.document.createElement("script");
script.type = "text/javascript";
script.text = "window.close();";
newWindow.document.body.appendChild(script);
def findMaxSales(listoftuples):
newlist = []
tuple = ()
for item in listoftuples:
movie = item[0]
value = (item[1])
tuple = value, movie
newlist += [tuple]
newlist.sort()
highest = newlist[-1]
result = highest[1]
return result
movieList = [("Finding Dory", 486), ("Captain America: Civil
War", 408), ("Deadpool", 363), ("Zootopia", 341), ("Rogue One", 529), ("The Secret Life of Pets", 368), ("Batman v Superman", 330), ("Sing", 268), ("Suicide Squad", 325), ("The Jungle Book", 364)]
print(findMaxSales(movieList))
output --> Rogue One
Why don't you test all three and pick the one that the performs the best? This seems like a good candidate for Google Website Optimizer to test.
It may be that the type of users you have, or the type of site you are running may dictate that your solution should be different than the "norm".
Here is a version that uses dataType html, but this is far less explicit, because i am returning an empty string to indicate an error.
Ajax call:
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'html',
data: {
email : $('#email').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data == '') ? 'error' : 'success')
.html(data).show(500);
if (data == '') {
$('#message').html("Format your email correcly");
$('#demoForm').show(500);
}
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#demoForm').show(500);
}
});
post.php
<?php
sleep(1);
function processEmail($email) {
if (preg_match("#^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$#", $email)) {
// your logic here (ex: add into database)
return true;
}
return false;
}
if (processEmail($_POST['email'])) {
echo "<span>Your email is <strong>{$_POST['email']}</strong></span>";
}
You simply type vim
into the terminal to open it and start a new file.
You can pass a filename as an option and it will open that file, e.g. vim main.c
. You can open multiple files by passing multiple file arguments.
Vim has different modes, unlike most editors you have probably used. You begin in NORMAL
mode, which is where you will spend most of your time once you become familiar with vim.
To return to NORMAL
mode after changing to a different mode, press Esc. It's a good idea to map your Caps Lock key to Esc, as it's closer and nobody really uses the Caps Lock key.
The first mode to try is INSERT
mode, which is entered with a for append after cursor, or i for insert before cursor.
To enter VISUAL
mode, where you can select text, use v. There are many other variants of this mode, which you will discover as you learn more about vim.
To save your file, ensure you're in NORMAL
mode and then enter the command :w
. When you press :
, you will see your command appear in the bottom status bar. To save and exit, use :x
. To quit without saving, use :q
. If you had made a change you wanted to discard, use :q!
.
You can edit your ~/.vimrc
file to configure vim to your liking. It's best to look at a few first (here's mine) and then decide which options suits your style.
This is how mine looks:
To get the file explorer on the left, use NERDTree. For the status bar, use vim-airline. Finally, the color scheme is solarized.
You can use man vim
for some help inside the terminal. Alternatively, run vimtutor
which is a good hands-on starting point.
It's a good idea to print out a Vim Cheatsheet and keep it in front of you while you're learning vim.
Good luck!
it should be :
$_SERVER['REQUEST_URI'];
Take a look at : Get the full URL in PHP
If I understand correctly the documentation of Handler.post() method:
Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.
So examples provided by @alex2k8, even though are working correctly, are not the same.
In case, where Handler.post()
is used, no new threads are created. You just post Runnable
to the thread with Handler
to be executed by EDT.
After that, EDT only executes Runnable.run()
, nothing else.
Remember:
Runnable != Thread
.
add padding
to the CSS class of anchor tag. If required, add padding-top
, padding-bottom
,... individually according to the clickable area you want. It worked for me.