I found this question by the title. If anyone else is looking for the answer on how to just get the domain name, use the following environment variable.
System.Environment.UserDomainName
I'm aware that the author to the question mentions this, but I missed it at the first glance and thought someone else might do the same.
What the description of the question then ask for is the fully qualified domain name (FQDN).
It sounds like some of your styles are being reset.
By default in most browsers, ul
s and ol
s have margin
and padding
added to them.
You can override this (and many do) by adding a line to your css like so
ul, ol { //THERE MAY BE OTHER ELEMENTS IN THE LIST
margin:0;
padding:0;
}
In this case, you would remove the element from this list or add a margin
/padding
back, like so
ul{
margin:1em;
}
Microsoft Windows accepts any memory request from processes if it could be done.
There is no limit for the memory that can be provided to a process, except the Virtual Memory Size.
Virtual Memory Size is 4GB in 32bit systems for any processes, no matter how many applications you are running. Any processes can allocate up to 4GB memory in 32bit systems.
In practice, Windows automatically allocates some parts of allocated memory from RAM or page-file depending on processes requests and paging file mechanism.
But another limit is the size of paging file. If you have a small paging-file, you cannot allocated large memories. You could increase the size of paging file according to Microsoft to have more memory space.
Assuming this is what the HTML looks like
<div class="form-group required">
<label class="col-md-2 control-label">E-mail</label>
<div class="col-md-4"><input class="form-control" id="id_email" name="email" placeholder="E-mail" required="required" title="" type="email" /></div>
</div>
To display an asterisk on the right of the label:
.form-group.required .control-label:after {
color: #d00;
content: "*";
position: absolute;
margin-left: 8px;
top:7px;
}
Or to the left of the label:
.form-group.required .control-label:before{
color: red;
content: "*";
position: absolute;
margin-left: -15px;
}
To make a nice big red asterisks you can add these lines:
font-family: 'Glyphicons Halflings';
font-weight: normal;
font-size: 14px;
Or if you are using Font Awesome add these lines (and change the content line):
font-family: 'FontAwesome';
font-weight: normal;
font-size: 14px;
content: "\f069";
You can't solve it. Simply answer1.sum()==0
, and you can't perform a division by zero.
This happens because answer1
is the exponential of 2 very large, negative numbers, so that the result is rounded to zero.
nan
is returned in this case because of the division by zero.
Now to solve your problem you could:
scipy/numpy
function that does exactly what you want! Check out @Warren Weckesser answer.Here I explain how to do some math manipulation that helps on this problem. We have that for the numerator:
exp(-x)+exp(-y) = exp(log(exp(-x)+exp(-y)))
= exp(log(exp(-x)*[1+exp(-y+x)]))
= exp(log(exp(-x) + log(1+exp(-y+x)))
= exp(-x + log(1+exp(-y+x)))
where above x=3* 1089
and y=3* 1093
. Now, the argument of this exponential is
-x + log(1+exp(-y+x)) = -x + 6.1441934777474324e-06
For the denominator you could proceed similarly but obtain that log(1+exp(-z+k))
is already rounded to 0
, so that the argument of the exponential function at the denominator is simply rounded to -z=-3000
. You then have that your result is
exp(-x + log(1+exp(-y+x)))/exp(-z) = exp(-x+z+log(1+exp(-y+x))
= exp(-266.99999385580668)
which is already extremely close to the result that you would get if you were to keep only the 2 leading terms (i.e. the first number 1089
in the numerator and the first number 1000
at the denominator):
exp(3*(1089-1000))=exp(-267)
For the sake of it, let's see how close we are from the solution of Wolfram alpha (link):
Log[(exp[-3*1089]+exp[-3*1093])/([exp[-3*1000]+exp[-3*4443])] -> -266.999993855806522267194565420933791813296828742310997510523
The difference between this number and the exponent above is +1.7053025658242404e-13
, so the approximation we made at the denominator was fine.
The final result is
'exp(-266.99999385580668) = 1.1050349147204485e-116
From wolfram alpha is (link)
1.105034914720621496.. × 10^-116 # Wolfram alpha.
and again, it is safe to use numpy here too.
If it helps someone you can just use css property
text-decoration-color: red;
If you want to replace the nulls with something you can do this:
def fix_nulls(s):
for line in s:
yield line.replace('\0', ' ')
r = csv.reader(fix_nulls(open(...)))
Alternatively you could use
declare @d datetimeselect
@d = '2008-12-1 14:30:12'
where tstamp
BETWEEN dateadd(dd, datediff(dd, 0, @d)+0, 0)
AND dateadd(dd, datediff(dd, 0, @d)+1, 0)
Unfortunately, C++ does not allow you to directly get a callable object referring to an object and one of its member functions. &Foo::doSomething
gives you a "pointer to member function" which refers to the member function but not the associated object.
There are two ways around this, one is to use std::bind
to bind the "pointer to member function" to the this
pointer. The other is to use a lambda that captures the this
pointer and calls the member function.
std::function<void(void)> f = std::bind(&Foo::doSomething, this);
std::function<void(void)> g = [this](){doSomething();};
I would prefer the latter.
With g++ at least binding a member function to this will result in an object three-pointers in size, assigning this to an std::function
will result in dynamic memory allocation.
On the other hand, a lambda that captures this
is only one pointer in size, assigning it to an std::function
will not result in dynamic memory allocation with g++.
While I have not verified this with other compilers, I suspect similar results will be found there.
Slightly alternative solution to @jpp's but outputting a YearMonth
string:
df['YearMonth'] = pd.to_datetime(df['Date']).apply(lambda x: '{year}-{month}'.format(year=x.year, month=x.month))
res = df.groupby('YearMonth')['Values'].sum()
For your literal example you'd want to use the adjacent selector (+).
h4 + p {color:red}//any <p> that is immediately preceded by an <h4>
<h4>Some text</h4>
<p>I'm red</p>
<p>I'm not</p>
However, if you wanted to select all successive paragraphs, you'd need to use the general sibling selector (~).
h4 ~ p {color:red}//any <p> that has the same parent as, and comes after an <h4>
<h4>Some text</h4>
<p>I'm red</p>
<p>I am too</p>
So if you wanna dismiss your Viewcontroller use this. This code is written in button action to dismiss VC
@IBAction func cancel(sender: AnyObject) {
dismiss(animated: true, completion: nil)
}
instead of using
ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(this).parentNode);
try using
ReactDOM.unmountComponentAtNode(document.getElementById('root'));
You should be aware that [^a-zA-Z]
will replace characters not being itself in the character range A-Z/a-z. That means special characters like é
, ß
etc. or cyrillic characters and such will be removed.
If the replacement of these characters is not wanted use pre-defined character classes instead:
str.replaceAll("[^\\p{IsAlphabetic}\\p{IsDigit}]", "");
PS: \p{Alnum}
does not achieve this effect, it acts the same as [A-Za-z0-9]
.
Now the command is
heroku pg:reset DATABASE_URL --confirm your_app_name
this way you can specify which app's db you want to reset. Then you can run
heroku run rake db:migrate
heroku run rake db:seed
or direct for both above commands
heroku run rake db:setup
And now final step to restart your app
heroku restart
This will replace all ?
with '
:
UPDATE dbo.authors
SET city = replace(city, '?', '''')
WHERE city LIKE '%?%'
If you need to update more than one column, you can either change city
each time you execute to a different column name, or list the columns like so:
UPDATE dbo.authors
SET city = replace(city, '?', '''')
,columnA = replace(columnA, '?', '''')
WHERE city LIKE '%?%'
OR columnA LIKE '%?%'
To add to the above: If interrupt is not working, you can restart the kernel.
Go to the kernel dropdown >> restart >> restart and clear output. This usually does the trick. If this still doesn't work, kill the kernel in the terminal (or task manager) and then restart.
Interrupt doesn't work well for all processes. I especially have this problem using the R kernel.
It sounds like your database dump includes the information for creating the database. So don't give the MySQL command line a database name. It will create the new database and switch to it to do the import.
I always use:
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
The join()
call prepends the current working directory, but the documentation says that if some path is absolute, all other paths left of it are dropped. Therefore, getcwd()
is dropped when dirname(__file__)
returns an absolute path.
Also, the realpath
call resolves symbolic links if any are found. This avoids troubles when deploying with setuptools on Linux systems (scripts are symlinked to /usr/bin/
-- at least on Debian).
You may the use the following to open up files in the same folder:
f = open(os.path.join(__location__, 'bundled-resource.jpg'))
# ...
I use this to bundle resources with several Django application on both Windows and Linux and it works like a charm!
We do it that way: First add this script.
<script type="text/javascript">
function populateIframe(id,path)
{
var ifrm = document.getElementById(id);
ifrm.src = "download.php?path="+path;
}
</script>
Place this where you want the download button(here we use just a link):
<iframe id="frame1" style="display:none"></iframe>
<a href="javascript:populateIframe('frame1','<?php echo $path; ?>')">download</a>
The file 'download.php' (needs to be put on your server) simply contains:
<?php
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$_GET['path']);
readfile($_GET['path']);
?>
So when you click the link, the hidden iframe then gets/opens the sourcefile 'download.php'. With the path as get parameter. We think this is the best solution!
It should be noted that the PHP part of this solution is a simple demonstration and potentially very, very insecure. It allows the user to download any file, not just a pre-defined set. That means they could download parts of the source code of the site itself, possibly containing API credentials etc.
In order to find out what's wrong you can use gradle's signingReport
command.
On mac:
./gradlew signingReport
On Windows:
gradlew signingReport
Many people set their cookie path to /. That will cause every favicon request to send a copy of the sites cookies, at least in chrome. Addressing your favicon to your cookieless domain should correct this.
<link rel="icon" href="https://cookieless.MySite.com/favicon.ico" type="image/x-icon" />
Depending on how much traffic you get, this may be the most practical reason for adding the link.
Info on setting up a cookieless domain:
If you target a non-rooted device and/or have services in you APK that you don't want to stop as well, the other solutions won't work.
To solve this problem, I've resorted to a broadcast message receiver I've added to my activity in order to stop it.
public class TestActivity extends Activity {
private static final String STOP_COMMAND = "com.example.TestActivity.STOP";
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
TestActivity.this.finish();
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//other stuff...
registerReceiver(broadcastReceiver, new IntentFilter(STOP_COMMAND));
}
}
That way, you can issue this adb command to stop your activity:
adb shell am broadcast -a com.example.TestActivity.STOP
Max has the best solution for when you always want to start both projects, but you can also right click a project and choose menu Debug ? Start New Instance.
This is an option when you only occasionally need to start the second project or when you need to delay the start of the second project (maybe the server needs to get up and running before the client tries to connect, or something).
Raw arrays aren't resizable in C++.
You should be using something like a Vector class which does allow resizing..
std::vector
allows you to resize it as well as allowing dynamic resizing when you add elements (often making the manual resizing unnecessary for adding).
If the image is part of the layout it might be "View.VISIBLE" but that doesn't mean it's within the confines of the visible screen. If that's what you're after; this will work:
Rect scrollBounds = new Rect();
scrollView.getHitRect(scrollBounds);
if (imageView.getLocalVisibleRect(scrollBounds)) {
// imageView is within the visible window
} else {
// imageView is not within the visible window
}
it worked for me adding type="module"
to the script import
ing my mjs:
<script type="module">
import * as module from 'https://rawgit.com/abernier/7ce9df53ac9ec00419634ca3f9e3f772/raw/eec68248454e1343e111f464e666afd722a65fe2/mymod.mjs'
console.log(module.default()) // Prints: Hi from the default export!
</script>
See demo: https://codepen.io/abernier/pen/wExQaa
.Net framework of the referencing dll should be same as the .Net framework version of the Project in which dll is referred
After generation of woff files, you have to define font-family, which can be used later in all your css styles. Below is the code to define font families (for normal, bold, bold-italic, italic) typefaces. It is assumed, that there are 4 *.woff files (for mentioned typefaces), placed in fonts
subdirectory.
In CSS code:
@font-face {
font-family: "myfont";
src: url("fonts/awesome-font.woff") format('woff');
}
@font-face {
font-family: "myfont";
src: url("fonts/awesome-font-bold.woff") format('woff');
font-weight: bold;
}
@font-face {
font-family: "myfont";
src: url("fonts/awesome-font-boldoblique.woff") format('woff');
font-weight: bold;
font-style: italic;
}
@font-face {
font-family: "myfont";
src: url("fonts/awesome-font-oblique.woff") format('woff');
font-style: italic;
}
After having that definitions, you can just write, for example,
In HTML code:
<div class="mydiv">
<b>this will be written with awesome-font-bold.woff</b>
<br/>
<b><i>this will be written with awesome-font-boldoblique.woff</i></b>
<br/>
<i>this will be written with awesome-font-oblique.woff</i>
<br/>
this will be written with awesome-font.woff
</div>
In CSS code:
.mydiv {
font-family: myfont
}
The good tool for generation woff files, which can be included in CSS stylesheets is located here. Not all woff files work correctly under latest Firefox versions, and this generator produces 'correct' fonts.
This is the most foolproof way to get your rails app working with postgres in the development environment in Ubuntu 13.10.
1) Create rails app with postgres YAML and 'pg' gem in the Gemfile:
$ rails new my_application -d postgresql
2) Give it some CRUD functionality. If you're just seeing if postgres works, create a scaffold:
$ rails g scaffold cats name:string age:integer colour:string
3) As of rails 4.0.1
the -d postgresql
option generates a YAML that doesn't include a host parameter. I found I needed this. Edit the development section and create the following parameters:
encoding: UTF-8
host: localhost
database: my_application_development
username: thisismynewusername
password: thisismynewpassword
Note the database
parameter is for a database that doesn't exit yet, and the username
and password
are credentials for a role that doesn't exist either. We'll create those later on!
This is how config/database.yml
should look (no shame in copypasting :D ):
development:
adapter: postgresql
pool: 5
# these are our new parameters
encoding: UTF-8
database: my_application_development
host: localhost
username: thisismynewusername
password: thisismynewpassword
test:
# this won't work
adapter: postgresql
encoding: unicode
database: my_application_test
pool: 5
username: my_application
password:
production:
# this won't work
adapter: postgresql
encoding: unicode
database: my_application_production
pool: 5
username: my_application
password:
4) Start the postgres shell with this command:
$ psql
4a) You may get this error if your current user (as in your computer user) doesn't have a corresponding administration postgres role.
psql: FATAL: role "your_username" does not exist
Now I've only installed postgres once, so I may be wrong here, but I think postgres automatically creates an administration role with the same credentials as the user you installed postgres as.
4b) So this means you need to change to the user that installed postgres to use the psql command and start the shell:
$ sudo su postgres
And then run
$ psql
5) You'll know you're in the postgres shell because your terminal will look like this:
$ psql
psql (9.1.10)
Type "help" for help.
postgres=#
6) Using the postgresql syntax, let's create the user we specified in config/database.yml
's development section:
postgres=# CREATE ROLE thisismynewusername WITH LOGIN PASSWORD 'thisismynewpassword';
Now, there's some subtleties here so let's go over them.
You should see this in your terminal:
postgres=#
CREATE ROLE
postgres=#
That means, "ROLE CREATED", but postgres' alerts seem to adopt the same imperative conventions of git hub.
7) Now, still in the postgres shell, we need to create the database with the name we set in the YAML. Make the user we created in step 6 its owner:
postgres=# CREATE DATABASE my_application_development OWNER thisismynewusername;
You'll know if you were successful because you'll get the output:
CREATE DATABASE
8) Quit the postgres shell:
\q
9) Now the moment of truth:
$ RAILS_ENV=development rake db:migrate
If you get this:
== CreateCats: migrating =================================================
-- create_table(:cats)
-> 0.0028s
== CreateCats: migrated (0.0028s) ========================================
Congratulations, postgres is working perfectly with your app.
9a) On my local machine, I kept getting a permission error. I can't remember it exactly, but it was an error along the lines of
Can't access the files. Change permissions to 666.
Though I'd advise thinking very carefully about recursively setting write privaledges on a production machine, locally, I gave my whole app read write privileges like this:
9b) Climb up one directory level:
$ cd ..
9c) Set the permissions of the my_application directory and all its contents to 666:
$ chmod -R 0666 my_application
9d) And run the migration again:
$ RAILS_ENV=development rake db:migrate
== CreateCats: migrating =================================================
-- create_table(:cats)
-> 0.0028s
== CreateCats: migrated (0.0028s) ========================================
Some tips and tricks if you muck up
Try these before restarting all of these steps:
The mynewusername user doesn't have privileges to CRUD to the my_app_development
database? Drop the database and create it again with mynewusername as the owner:
1) Start the postgres shell:
$ psql
2) Drop the my_app_development
database. Be careful! Drop means utterly delete!
postgres=# DROP DATABASE my_app_development;
3) Recreate another my_app_development
and make mynewusername the owner:
postgres=# CREATE DATABASE my_application_development OWNER mynewusername;
4) Quit the shell:
postgres=# \q
The mynewusername
user can't log into the database? Think you wrote the wrong password in the YAML and can't quite remember the password you entered using the postgres shell? Simply alter the role with the YAML password:
1) Open up your YAML, and copy the password to your clipboard:
development:
adapter: postgresql
pool: 5
# these are our new parameters
encoding: UTF-8
database: my_application_development
host: localhost
username: thisismynewusername
password: musthavebeenverydrunkwheniwrotethis
2) Start the postgres shell:
$ psql
3) Update mynewusername
's password. Paste in the password, and remember to put single quotes around it:
postgres=# ALTER ROLE mynewusername PASSWORD `musthavebeenverydrunkwheniwrotethis`;
4) Quit the shell:
postgres=# \q
Trying to connect to localhost via a database viewer such as Dbeaver, and don't know what your postgres user's password is? Change it like this:
1) Run passwd
as a superuser:
$ sudo passwd postgres
2) Enter your accounts password for sudo
(nothing to do with postgres):
[sudo] password for starkers: myaccountpassword
3) Create the postgres account's new passwod:
Enter new UNIX password: databasesarefun
Retype new UNIX password: databasesarefun
passwd: password updated successfully
Getting this error message?:
Run `$ bin/rake db:create db:migrate` to create your database
$ rake db:create db:migrate
PG::InsufficientPrivilege: ERROR: permission denied to create database
4) You need to give your user the ability to create databases. From the psql shell:
ALTER ROLE thisismynewusername WITH CREATEDB
Use g++
g++ -o hi hi.cpp
g++ is for C++, gcc is for C although with the -libstdc++ you can compile c++ most people don't do this.
I suggest storing the numbers in a varchar without formatting. Then you can just reformat the numbers on the client side appropriately. Some cultures prefer to have phone numbers written differently; in France, they write phone numbers like 01-22-33-44-55.
You might also consider storing another field for the country that the phone number is for, because this can be difficult to figure out based on the number you are looking at. The UK uses 11 digit long numbers, some African countries use 7 digit long numbers.
That said, I used to work for a UK phone company, and we stored phone numbers in our database based on if they were UK or international. So, a UK phone number would be 02081234123 and an international one would be 001800300300.
Ok, I fixed it:
When I changed manifest to target 1.5 version, million errors appeared and only one wasn't related to inexistance of R class - in manifest file attributes "targetSdkVersion" and "maxSdkVersion" did not exist in sdk 1.5
Because of this R class was not able to generate.
in one line
> samp.with.rownames <- data.frame(samp[,-1], row.names=samp[,1])
given that you're a newbie, I'd say don't try to do this yet. it's definitely possible, but will needlessly complicate your Makefile. stick to the simple ways until you're more comfortable with make.
that said, one way to build in a directory different from the source directory is VPATH; i prefer pattern rules
This works for me:
<c:forEach var="i" begin="1970" end="2000">
<option value="${2000-(i-1970)}">${2000-(i-1970)}
</option>
</c:forEach>
hey I understand this is an old thread but I have a query in regards to apachebenchmarking. how do you collect the metrics from apache benchmarking. P.S: I have to do it via telegraf and put it to influxdb . any suggestions/advice/help would be appreciated. Thanks a ton.
Try this:
List<Double> list = Arrays.asList(1.38, 2.56, 4.3);
which returns a fixed size list.
If you need an expandable list, pass this result to the ArrayList
constructor:
List<Double> list = new ArrayList<>(Arrays.asList(1.38, 2.56, 4.3));
Not to belabor the point but be sure to add the following to
under File >> Preferences >> Settings
"javascript.implicitProjectConfig.experimentalDecorators": true
this fixed the issue for me, and i tried quite a few suggestions i found here and other places.
I Faced same problem but it work for.I executed the Pod Install Command Before 3 Hour ago after that its updated what i want. You just need to Keep tracking the "Activity Monitor" You can see their "git remote https" or "Git" in disk tab. It will download around 330 Mb then it shows 1 GB and After some minutes it will starts installing. No need to Execute extra command.
Note : during downloading your MAC need to in continuously Active mode.If your system goes in sleep mode then CPU stop the process and you will get a error Like Add manually.
For testing only two values, I'd personally do this:
if x ~= 0 and x ~= 1 then
print( "X must be equal to 1 or 0" )
return
end
If you need to test against more than two values, I'd stuff your choices in a table acting like a set, like so:
choices = {[0]=true, [1]=true, [3]=true, [5]=true, [7]=true, [11]=true}
if not choices[x] then
print("x must be in the first six prime numbers")
return
end
$.each( { name: "John", lang: "JS" }, function(i, n){
alert( "Name: " + i + ", Value: " + n );
});
If you are plotting time series graph and if you have used mtplotlib for drawing graphs then use median method to smooth-en the graph
smotDeriv = timeseries.rolling(window=20, min_periods=5, center=True).median()
where timeseries
is your set of data passed you can alter windowsize
for more smoothining.
Quick tip - if you use a PyCharm, go to Edit Configurations
=> Configurations
and enable FLASK_DEBUG
checkbox, restart the Run
.
You can't access your fieldname
as a global variable. Use document.getElementById:
function updateInput(ish){
document.getElementById("fieldname").value = ish;
}
and
onchange="updateInput(this.value)"
In Rails 3.2.18, :decimal turns into :integer when using SQLServer, but it works fine in SQLite. Switching to :float solved this issue for us.
The lesson learned is "always use homogeneous development and deployment databases!"
All you need is to give the AnchorPane
an ID, and then you can get the Stage
from that.
@FXML private AnchorPane ap;
Stage stage = (Stage) ap.getScene().getWindow();
From here, you can add in the Listener
that you need.
Edit: As stated by EarthMind below, it doesn't have to be the AnchorPane
element; it can be any element that you've defined.
When I open Python (command line)
the first thing it tells me is the version.
The main()
method is the entry point for a Java application. run()
is typically used for new threads or tasks.
Where have you been writing a run()
method, what kind of application are you writing (e.g. Swing, AWT, console etc) and what's your development environment?
It might be better to use communicate
:
from subprocess import Popen, PIPE, STDOUT
p = Popen(['myapp'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
stdout_data = p.communicate(input='data_to_write')[0]
"Better", because of this warning:
Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.
Tk is available for Ruby. Some nice examples (in Ruby, Perl and Tcl) can be found at http://www.tkdocs.com/
var postData = "text";
$.ajax({
type: "post",
url: "url",
data: postData,
contentType: "application/x-www-form-urlencoded",
success: function(responseData, textStatus, jqXHR) {
alert("data saved")
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
})
This gets routes registered directly on the app (via app.VERB) and routes that are registered as router middleware (via app.use). Express 4.11.0
//////////////
app.get("/foo", function(req,res){
res.send('foo');
});
//////////////
var router = express.Router();
router.get("/bar", function(req,res,next){
res.send('bar');
});
app.use("/",router);
//////////////
var route, routes = [];
app._router.stack.forEach(function(middleware){
if(middleware.route){ // routes registered directly on the app
routes.push(middleware.route);
} else if(middleware.name === 'router'){ // router middleware
middleware.handle.stack.forEach(function(handler){
route = handler.route;
route && routes.push(route);
});
}
});
// routes:
// {path: "/foo", methods: {get: true}}
// {path: "/bar", methods: {get: true}}
[I mentioned this in response to the selected answer, but it was suggested to make it more prominent as an answer of its own]
It should be noted that
ENV PATH="/opt/gtk/bin:${PATH}"
may not be the same as
ENV PATH="/opt/gtk/bin:$PATH"
The former, with curly brackets, might provide you with the host's PATH. The documentation doesn't suggest this would be the case, but I have observed that it is. This is simple to check just do RUN echo $PATH
and compare it to RUN echo ${PATH}
And if you need to calculate the MD5 to see whether it matches the MD5 of an Azure blob, then this SO question and answer might be helpful: MD5 hash of blob uploaded on Azure doesnt match with same file on local machine
You can also use HeapWalker from the Netbeans Profiler or the Visual VM stand-alone tool. Visual VM is a good alternative to JHAT as it is stand alone, but is much easier to use than JHAT.
You need Java 6+ to fully use Visual VM.
Use below methods.
/// <summary>
/// Returns replacement value if expression is null
/// </summary>
/// <param name="expression"></param>
/// <param name="replacement"></param>
/// <returns></returns>
public static long? IsNull(long? expression, long? replacement)
{
if (expression.HasValue)
return expression;
else
return replacement;
}
/// <summary>
/// Returns replacement value if expression is null
/// </summary>
/// <param name="expression"></param>
/// <param name="replacement"></param>
/// <returns></returns>
public static string IsNull(string expression, string replacement)
{
if (string.IsNullOrWhiteSpace(expression))
return replacement;
else
return expression;
}
try this one
npm cache clean --force
after that run
npm cache verify
As we all know that IPv4 address for
localhost
is127.0.0.1
(loopback address).
Actually, any IPv4 address in 127.0.0.0/8
is a loopback address.
In IPv6, the direct analog of the loopback range is ::1/128
. So ::1
(long form 0:0:0:0:0:0:0:1
) is the one and only IPv6 loopback address.
While the hostname localhost
will normally resolve to 127.0.0.1
or ::1
, I have seen cases where someone has bound it to an IP address that is not a loopback address. This is a bit crazy ... but sometimes people do it.
I say "this is crazy" because you are liable to break applications assumptions by doing this; e.g. an application may attempt to do a reverse lookup on the loopback IP and not get the expected result. In the worst case, an application may end up sending sensitive traffic over an insecure network by accident ... though you probably need to make other mistakes as well to "achieve" that.
Blocking 0.0.0.0
makes no sense. In IPv4 it is never routed. The equivalent in IPv6 is the ::
address (long form 0:0:0:0:0:0:0:0
) ... which is also never routed.
The 0.0.0.0
and ::
addresses are reserved to mean "any address". So, for example a program that is providing a web service may bind to 0.0.0.0
port 80 to accept HTTP connections via any of the host's IPv4 addresses. These addresses are not valid as a source or destination address for an IP packet.
Finally, some comments were asking about ::/128
versus ::/0
versus ::
.
What is this difference?
Strictly speaking, the first two are CIDR notation not IPv6 addresses. They are actually specifying a range of IP addresses. A CIDR consists of a IP address and an additional number that specifies the number of bits in a netmask. The two together specify a range of addresses; i.e. the set of addresses formed by ignoring the bits masked out of the given address.
So:
::
means just the IPv6 address 0:0:0:0:0:0:0:0
::/128
means 0:0:0:0:0:0:0:0
with a netmask consisting of 128 bits. This gives a network range with exactly one address in it.::/0
means 0:0:0:0:0:0:0:0
with a netmask consisting of 0 bits. This gives a network range with 2128 addresses in it.; i.e. it is the entire IPv6 address space!For more information, read the Wikipedia pages on IPv4 & IPv6 addresses, and CIDR notation:
I had to deal with this same issue and was able to solve it without stopping any of my running containers. This is a solution up-to-date as of February 2016, using Docker 1.9.1. Anyway, this answer is a detailed version of @ricardo-branco's answer, but in more depth for new users.
In my scenario, I wanted to temporarily connect to MySQL running in a container, and since other application containers are linked to it, stopping, reconfiguring, and re-running the database container was a non-starter.
Since I'd like to access the MySQL database externally (from Sequel Pro via SSH tunneling), I'm going to use port 33306
on the host machine. (Not 3306
, just in case there is an outer MySQL instance running.)
About an hour of tweaking iptables proved fruitless, even though:
Step by step, here's what I did:
mkdir db-expose-33306
cd db-expose-33306
vim Dockerfile
Edit dockerfile
, placing this inside:
# Exposes port 3306 on linked "db" container, to be accessible at host:33306
FROM ubuntu:latest # (Recommended to use the same base as the DB container)
RUN apt-get update && \
apt-get -y install socat && \
apt-get clean
USER nobody
EXPOSE 33306
CMD socat -dddd TCP-LISTEN:33306,reuseaddr,fork TCP:db:3306
Then build the image:
docker build -t your-namespace/db-expose-33306 .
Then run it, linking to your running container. (Use -d
instead of -rm
to keep it in the background until explicitly stopped and removed. I only want it running temporarily in this case.)
docker run -it --rm --name=db-33306 --link the_live_db_container:db -p 33306:33306 your-namespace/db-expose-33306
For those who want to add noise to a multi-dimensional dataset loaded within a pandas dataframe or even a numpy ndarray, here's an example:
import pandas as pd
# create a sample dataset with dimension (2,2)
# in your case you need to replace this with
# clean_signal = pd.read_csv("your_data.csv")
clean_signal = pd.DataFrame([[1,2],[3,4]], columns=list('AB'), dtype=float)
print(clean_signal)
"""
print output:
A B
0 1.0 2.0
1 3.0 4.0
"""
import numpy as np
mu, sigma = 0, 0.1
# creating a noise with the same dimension as the dataset (2,2)
noise = np.random.normal(mu, sigma, [2,2])
print(noise)
"""
print output:
array([[-0.11114313, 0.25927152],
[ 0.06701506, -0.09364186]])
"""
signal = clean_signal + noise
print(signal)
"""
print output:
A B
0 0.888857 2.259272
1 3.067015 3.906358
"""
Accessing colors from a non-activity class can be difficult. One of the alternatives that I found was using enum
. enum
offers a lot of flexibility.
public enum Colors
{
COLOR0(0x26, 0x32, 0x38), // R, G, B
COLOR1(0xD8, 0x1B, 0x60),
COLOR2(0xFF, 0xFF, 0x72),
COLOR3(0x64, 0xDD, 0x17);
private final int R;
private final int G;
private final int B;
Colors(final int R, final int G, final int B)
{
this.R = R;
this.G = G;
this.B = B;
}
public int getColor()
{
return (R & 0xff) << 16 | (G & 0xff) << 8 | (B & 0xff);
}
public int getR()
{
return R;
}
public int getG()
{
return G;
}
public int getB()
{
return B;
}
}
Facebook has a strict policy on sharing only the content which a profile makes public to the end user.. Still what you want is possible if the user has actually left the email id open to public domain.. A wild try u can do is send batch requests for the maximum possible batch size to ids..."http://graph.facebook.com/ .. and parse the result to check if email exists and if it does then it matches to the one you want.. you don't need any access_token for the public information ..
in case you want email id of a FB user only possible way is that they authorize ur app and then you can use the access_token thus generated for the required task.
You can see all steps to connect MySQL database from Java application here. For other database, you just need to change the driver in first step only. Please make sure that you provide right path to database and correct username and password.
Visit http://apekshit.com/t/51/Steps-to-connect-Database-using-JAVA
Here ViewData and ViewBag both are used pass data from Controller to View.
1. ViewData
-- ViewData is dictionary object that is derived from ViewDataDictonary class.
-- Data only allow for one request, ViewData values get cleared when page redirecting occurs.
-- ViewData value must be typed cate before use.
Example: In Controller
public ActionResult PassingDatatoViewWithViewData()
{
ViewData["Message"] = "This message shown in view with the ViewData";
return View();
}
In View
@ViewData["Message"];
-- With ViewData is a pair like Key and Value, Message is Key and in inverted comma value is Value.
-- Data is simple so we can not use typecasting here if data is complex then using type casting.
public ActionResult PassingDatatoViewWithViewData()
{
var type= new List<string>
{
"MVC",
"MVP",
"MVVC"
};
ViewData["types"] = type;
return View();
}
-- In View data can be extracted as
<ul>
@foreach (var items in (List<string>)ViewData["types"])
{
<li>@items</li>
}
</ul>
2. ViewBag
--ViewBag uses the dynamic feature.ViewBag wrapper around the ViewData.
-- In ViewBag type casting is required.
-- Same as ViewData, if redirection occurs value becomes null.
Example:
public ActionResult PassingDatatoViewWithViewBag()
{
ViewData.Message = "This message shown in view with the ViewBag";
return View();
}
In View
@ViewBag.vbMessage
--For Complex type use ViewBag
public ActionResult PassingDatatoViewWithViewBag()
{
var type= new List<string>
{
"MVC",
"MVP",
"MVVC"
};
ViewBag.types = type;
return View();
}
-- In View data can be extracted as
<ul>
@foreach (var items in ViewBag.types)
{
<li>@items</li>
}
</ul>
-- the main difference is that ViewBag not required typecasting but ViewData is required typecasting.
By default, all one-to-many
and many-to-many
associations are fetched lazily upon being accessed for the first time.
In your use case, you could overcome this issue by wrapping all DAO operations into one logical transaction:
transactionTemplate.execute(new TransactionCallback<Void>() {
@Override
public Void doInTransaction(TransactionStatus transactionStatus) {
int startingCount = sfdao.count();
sfdao.create( sf );
SecurityFiling sf2 = sfdao.read( sf.getId() );
sfdao.delete( sf );
int endingCount = sfdao.count();
assertTrue( startingCount == endingCount );
assertTrue( sf.getId().longValue() == sf2.getId().longValue() );
assertTrue( sf.getSfSubmissionType().equals( sf2.getSfSubmissionType() ) );
assertTrue( sf.getSfTransactionNumber().equals( sf2.getSfTransactionNumber() ) );
return null;
}
});
Another option is to fetch all LAZY associations upon loading your entity, so that:
SecurityFiling sf2 = sfdao.read( sf.getId() );
should fetch the LAZY submissionType
too:
select sf
from SecurityFiling sf
left join fetch.sf.submissionType
This way, you eagerly fetch all lazy properties and you can access them after the Session gets closed too.
You can fetch as many [one|many]-to-one
associations and one "[one|many]-to-many" List associations (because of running a Cartesian Product).
To initialize multiple "[one|many]-to-many", you should use Hibernate.initialize(collection), right after loading your root entity.
This proc correctly prints out VARCHAR(MAX)
parameter considering wrapping:
CREATE PROCEDURE [dbo].[Print]
@sql varchar(max)
AS
BEGIN
declare
@n int,
@i int = 0,
@s int = 0, -- substring start posotion
@l int; -- substring length
set @n = ceiling(len(@sql) / 8000.0);
while @i < @n
begin
set @l = 8000 - charindex(char(13), reverse(substring(@sql, @s, 8000)));
print substring(@sql, @s, @l);
set @i = @i + 1;
set @s = @s + @l + 2; -- accumulation + CR/LF
end
return 0
END
The most likely cause is an error in mysql_query()
. Have you checked to make sure it worked? Output the value of $result
and mysql_error()
. You may have misspelled something, selected the wrong database, have a permissions issue, etc. So:
$id = (int)$_GET['id']; // this also sanitizes it
$sql = "SELECT * FROM student WHERE idno = $id";
$result = mysql_query($sql);
if (!$result) {
die("Error running $sql: " . mysql_error());
}
Sanitizing $_GET['id']
is really important. You can use mysql_real_escape_string()
but casting it to an int
is sufficient for integers. Basically you want to avoid SQL injection.
Try this for WPF
StreamResourceInfo sri = Application.GetResourceStream(new Uri("pack://application:,,,/WpfGifImage001;Component/Images/Progess_Green.gif"));
picBox1.Image = System.Drawing.Image.FromStream(sri.Stream);
Open the hosts file located at : **C:\windows\system32\drivers\etc**.
Add the following at end of this file :
YourServerIP YourDNS
Example:
198.168.1.1 maps.google.com
I had faced the same issue, because the jar library was copied by other Linux user(root), and the logged in user(process) did not have sufficient privilege to read the jar file content.
Depending on your needs, you want to use their section feeds, their search feeds
http://news.google.com/news?q=apple&output=rss
or Bing News Search.
Sometimes the column you are looking for may be part of the name of many other things that you are not interested in.
For example I was recently looking for a column called "BQR", which also forms part of many other columns such as "BQR_OWNER", "PROP_BQR", etc.
So I would like to have the checkbox that word processors have to indicate "Whole words only".
Unfortunately LIKE has no such functionality, but REGEXP_LIKE can help.
SELECT *
FROM user_source
WHERE regexp_like(text, '(\s|\.|,|^)bqr(\s|,|$)');
This is the regular expression to find this column and exclude the other columns with "BQR" as part of the name:
(\s|\.|,|^)bqr(\s|,|$)
The regular expression matches white-space (\s), or (|) period (.), or (|) comma (,), or (|) start-of-line (^), followed by "bqr", followed by white-space, comma or end-of-line ($).
If you happen to have ImageMagick installed, then you can use 'identify'. For example, you can call it like this:
path = "//folder/image.jpg"
dim = subprocess.Popen(["identify","-format","\"%w,%h\"",path], stdout=subprocess.PIPE).communicate()[0]
(width, height) = [ int(x) for x in re.sub('[\t\r\n"]', '', dim).split(',') ]
You can do it easily by Assertion using Selenium Testng framework.
Steps:
1.Create Firefox browser session
2.Initialize expected title name.
3.Navigate to "www.google.com" [As per you requirement, you can change] and wait for some time (15 seconds) to load the page completely.
4.Get the actual title name using "driver.getTitle()" and store it in String variable.
5.Apply the Assertion like below, Assert.assertTrue(actualGooglePageTitlte.equalsIgnoreCase(expectedGooglePageTitle ),"Page title name not matched or Problem in loading grid");
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.myapplication.Utilty;
public class PageTitleVerification
{
private static WebDriver driver = new FirefoxDriver();
@Test
public void test01_GooglePageTitleVerify()
{
driver.navigate().to("https://www.google.com/");
String expectedGooglePageTitle = "Google";
Utility.waitForElementInDOM(driver, "Google Search", 15);
//Get page title
String actualGooglePageTitlte=driver.getTitle();
System.out.println("Google page title" + actualGooglePageTitlte);
//Verify expected page title and actual page title is same
Assert.assertTrue(actualGooglePageTitlte.equalsIgnoreCase(expectedGooglePageTitle
),"Page title not matched or Problem in loading url page");
}
}
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Utility {
/*Wait for an element to be present in DOM before specified time (in seconds ) has
elapsed */
public static void waitForElementInDOM(WebDriver driver,String elementIdentifier,
long timeOutInSeconds)
{
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds );
try
{
//this will wait for element to be visible for 15 seconds
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath
(elementIdentifier)));
}
catch(NoSuchElementException e)
{
e.printStackTrace();
}
}
}
You could try save the query results as excel, change the file extension to .txt. Open using excel (open with...) then use text to columns (formatting as text). Not sure if this will work for this situation, but works well for other formatting issues that excel auto-strips off.
Dude... exit()
function is defined under stdlib.h
So you need to add a preprocessor.
Put include stdlib.h
in the header section
Then use exit();
wherever you like but remember to put an interger number in the parenthesis of exit.
for example:
exit(0);
Try this:
=RIGHT(TRIM(A2),LEN(TRIM(A2))-FIND(" ",TRIM(A2)))
I was able to copy/paste the formula and it worked fine.
Here is a list of Excel text functions (which worked in May 2011, and but is subject to being broken the next time Microsoft changes their website). :-(
You can use a multiple-stage-nested IF() functions to handle middle names or initials, titles, etc. if you expect them. Excel formulas do not support looping, so there are some limits to what you can do.
The questions is perfectly valid and clear since Spinner and ComboBox (read it: Spinner where you can provide a custom value as well) are two different things.
I was looking for the same thing myself and I wasn't satisfied with the given answers. So I created my own thing. Perhaps some will find the following hints useful. I am not providing the full source code as I am using some legacy calls in my own project. It should be pretty clear anyway.
Here is the screenshot of the final thing:
The first thing was to create a view that will look the same as the spinner that hasn't been expanded yet. In the screenshot, on the top of the screen (out of focus) you can see the spinner and the custom view right bellow it. For that purpose I used LinearLayout (actually, I inherited from Linear Layout) with style="?android:attr/spinnerStyle"
. LinearLayout contains TextView with style="?android:attr/spinnerItemStyle"
. Complete XML snippet would be:
<com.example.comboboxtest.ComboBox
style="?android:attr/spinnerStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="@+id/textView"
style="?android:attr/spinnerItemStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:singleLine="true"
android:text="January"
android:textAlignment="inherit"
/>
</com.example.comboboxtest.ComboBox>
As, I mentioned earlier ComboBox inherits from LinearLayout. It also implements OnClickListener which creates a dialog with a custom view inflated from the XML file. Here is the inflated view:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:hint="Enter custom value ..." >
<requestFocus />
</EditText>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="OK"
/>
</LinearLayout>
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
There are two more listeners that you need to implement: onItemClick for the list and onClick for the button. Both of these set the selected value and dismiss the dialog.
For the list, you want it to look the same as expanded Spinner, you can do that providing the list adapter with the appropriate (Spinner) style like this:
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(
activity,
android.R.layout.simple_spinner_dropdown_item,
states
);
More or less, that should be it.
In ruby Fixnums are automatically converted to Bignums.
To find the highest possible Fixnum you could do something like this:
class Fixnum
N_BYTES = [42].pack('i').size
N_BITS = N_BYTES * 8
MAX = 2 ** (N_BITS - 2) - 1
MIN = -MAX - 1
end
p(Fixnum::MAX)
Shamelessly ripped from a ruby-talk discussion. Look there for more details.
public static void PrintFileToDefaultPrinter(string FilePath)
{
try
{
var file = File.ReadAllBytes(FilePath);
var printQueue = LocalPrintServer.GetDefaultPrintQueue();
using (var job = printQueue.AddJob())
using (var stream = job.JobStream)
{
stream.Write(file, 0, file.Length);
}
}
catch (Exception)
{
throw;
}
}
Came across this question, so here's a quick comparison. Compare these two different ways to extract one frame per minute from a video 38m07s long:
time ffmpeg -i input.mp4 -filter:v fps=fps=1/60 ffmpeg_%0d.bmp
1m36.029s
This takes long because ffmpeg parses the entire video file to get the desired frames.
time for i in {0..39} ; do ffmpeg -accurate_seek -ss `echo $i*60.0 | bc` -i input.mp4 -frames:v 1 period_down_$i.bmp ; done
0m4.689s
This is about 20 times faster. We use fast seeking to go to the desired time index and extract a frame, then call ffmpeg several times for every time index. Note that -accurate_seek
is the default
, and make sure you add -ss
before the input video -i
option.
Note that it's better to use -filter:v -fps=fps=...
instead of -r
as the latter may be inaccurate. Although the ticket is marked as fixed, I still did experience some issues, so better play it safe.
Also, you can use shelljs
plugin.
It's easy and it's cross-platform.
Install command:
npm install [-g] shelljs
What is shellJS
ShellJS is a portable (Windows/Linux/OS X) implementation of Unix shell commands on top of the Node.js API. You can use it to eliminate your shell script's dependency on Unix while still keeping its familiar and powerful commands. You can also install it globally so you can run it from outside Node projects - say goodbye to those gnarly Bash scripts!
An example of how it works:
var shell = require('shelljs');
if (!shell.which('git')) {
shell.echo('Sorry, this script requires git');
shell.exit(1);
}
// Copy files to release dir
shell.rm('-rf', 'out/Release');
shell.cp('-R', 'stuff/', 'out/Release');
// Replace macros in each .js file
shell.cd('lib');
shell.ls('*.js').forEach(function (file) {
shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file);
shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file);
});
shell.cd('..');
// Run external tool synchronously
if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
shell.echo('Error: Git commit failed');
shell.exit(1);
}
Also, you can use from the command line:
$ shx mkdir -p foo
$ shx touch foo/bar.txt
$ shx rm -rf foo
We can make use of removeIf which takes a predicate to write a utility method as:
// computes the difference without modifying the sets
public static <T> Set<T> differenceJava8(final Set<T> setOne, final Set<T> setTwo) {
Set<T> result = new HashSet<T>(setOne);
result.removeIf(setTwo::contains);
return result;
}
And in case we are still at some prior version then we can use removeAll as:
public static <T> Set<T> difference(final Set<T> setOne, final Set<T> setTwo) {
Set<T> result = new HashSet<T>(setOne);
result.removeAll(setTwo);
return result;
}
You could use CSS to do that, but it wouldn't be supported in IE8-. You can use some site like http://borderradius.com to come up with actual CSS you'd use, which would look something like this (again, depending on how many browsers you're trying to support):
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
I’ve been struggling with this for a while now. Dycey’s solution is correct in that specifying the src
multiple times outputs the same thing in your css file. However, this seems to break in OSX Firefox 23 (probably other versions too, but I don’t have time to test).
The cross-browser @font-face
solution from Font Squirrel looks like this:
@font-face {
font-family: 'fontname';
src: url('fontname.eot');
src: url('fontname.eot?#iefix') format('embedded-opentype'),
url('fontname.woff') format('woff'),
url('fontname.ttf') format('truetype'),
url('fontname.svg#fontname') format('svg');
font-weight: normal;
font-style: normal;
}
To produce the src
property with the comma-separated values, you need to write all of the values on one line, since line-breaks are not supported in Sass. To produce the above declaration, you would write the following Sass:
@font-face
font-family: 'fontname'
src: url('fontname.eot')
src: url('fontname.eot?#iefix') format('embedded-opentype'), url('fontname.woff') format('woff'), url('fontname.ttf') format('truetype'), url('fontname.svg#fontname') format('svg')
font-weight: normal
font-style: normal
I think it seems silly to write out the path a bunch of times, and I don’t like overly long lines in my code, so I worked around it by writing this mixin:
=font-face($family, $path, $svg, $weight: normal, $style: normal)
@font-face
font-family: $family
src: url('#{$path}.eot')
src: url('#{$path}.eot?#iefix') format('embedded-opentype'), url('#{$path}.woff') format('woff'), url('#{$path}.ttf') format('truetype'), url('#{$path}.svg##{$svg}') format('svg')
font-weight: $weight
font-style: $style
Usage: For example, I can use the previous mixin to setup up the Frutiger Light font like this:
+font-face('frutigerlight', '../fonts/frutilig-webfont', 'frutigerlight')
please try to do
make clean
(instead of make
), then
make
again.
Recently when working on a web app for a client, I noticed that any click events added to a non-anchor element didn't work on the iPad or iPhone. All desktop and other mobile devices worked fine - but as the Apple products are the most popular mobile devices, it was important to get it fixed.
Turns out that any non-anchor element assigned a click handler in jQuery must either have an onClick attribute (can be empty like below):
onClick=""
OR
The element css needs to have the following declaration:
cursor:pointer
Strange, but that's what it took to get things working again!
source:http://www.mitch-solutions.com/blog/17-ipad-jquery-live-click-events-not-working
To apply different classes when different expressions evaluate to true
:
<div ng-class="{class1 : expression1, class2 : expression2}">
Hello World!
</div>
To apply multiple classes when an expression holds true:
<!-- notice expression1 used twice -->
<div ng-class="{class1 : expression1, class2 : expression1}">
Hello World!
</div>
or quite simply:
<div ng-class="{'class1 class2' : expression1}">
Hello World!
</div>
Notice the single quotes surrounding css classes.
You should not rely on a hard coded build dir name in your script, so the line with ../Compile
must be changed.
It's because it should be up to user where to compile.
Instead of that use one of predefined variables:
http://www.cmake.org/Wiki/CMake_Useful_Variables
(look for CMAKE_BINARY_DIR
and CMAKE_CURRENT_BINARY_DIR
)
For me its now :
docker restart $(docker ps -a -q)
As mentioned in the error, the official manual and the comments:
Replace
public function TSStatus($host, $queryPort)
with
public function __construct($host, $queryPort)
sudo make uninstall
did the trick for me using the Ruby 2.4 tar from the official downloads page.
Why not simply use bin log files? If the replication is set on the Mysql server, and binlog file format is set to ROW, then all the changes could be captured.
A good python library called noplay can be used. More info here.
Both Query is used for round down the nearest integer in MySQL
Run dos2unix or similar utility on it to remove the carriage returns (^M).
This message indicates that your file has dos-style lineendings:
-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory
Utilities like dos2unix
will fix it:
dos2unix <backup.bash >improved-backup.sh
Or, if no such utility is installed, you can accomplish the same thing with translate:
tr -d "\015\032" <backup.bash >improved-backup.sh
As for how those characters got there in the first place, @MadPhysicist had some good comments.
When building separate apks for different densities, drawable folders for other densities get stripped. This will make the icons appear blurry in devices that use launcher icons of higher density. Since, mipmap folders do not get stripped, it’s always best to use them for including the launcher icons.
Usually, one should put a transaction at the service layer.
But as stated before, the atomicity of an operation is what tells us where an annotation is necessary. Thus, if you use frameworks like Hibernate, where a single "save/update/delete/...modification" operation on an object has the potential to modify several rows in several tables (because of the cascade through the object graph), of course there should also be transaction management on this specific DAO method.
This is my c++11 style solution. parameter 'base' is for base class of all sub-classes. creators, are std::function objects to create sub-class instances, might be a binding to your sub-class' static member function 'create(some args)'. This maybe not perfect but works for me. And it is kinda 'general' solution.
template <class base, class... params> class factory {
public:
factory() {}
factory(const factory &) = delete;
factory &operator=(const factory &) = delete;
auto create(const std::string name, params... args) {
auto key = your_hash_func(name.c_str(), name.size());
return std::move(create(key, args...));
}
auto create(key_t key, params... args) {
std::unique_ptr<base> obj{creators_[key](args...)};
return obj;
}
void register_creator(const std::string name,
std::function<base *(params...)> &&creator) {
auto key = your_hash_func(name.c_str(), name.size());
creators_[key] = std::move(creator);
}
protected:
std::unordered_map<key_t, std::function<base *(params...)>> creators_;
};
An example on usage.
class base {
public:
base(int val) : val_(val) {}
virtual ~base() { std::cout << "base destroyed\n"; }
protected:
int val_ = 0;
};
class foo : public base {
public:
foo(int val) : base(val) { std::cout << "foo " << val << " \n"; }
static foo *create(int val) { return new foo(val); }
virtual ~foo() { std::cout << "foo destroyed\n"; }
};
class bar : public base {
public:
bar(int val) : base(val) { std::cout << "bar " << val << "\n"; }
static bar *create(int val) { return new bar(val); }
virtual ~bar() { std::cout << "bar destroyed\n"; }
};
int main() {
common::factory<base, int> factory;
auto foo_creator = std::bind(&foo::create, std::placeholders::_1);
auto bar_creator = std::bind(&bar::create, std::placeholders::_1);
factory.register_creator("foo", foo_creator);
factory.register_creator("bar", bar_creator);
{
auto foo_obj = std::move(factory.create("foo", 80));
foo_obj.reset();
}
{
auto bar_obj = std::move(factory.create("bar", 90));
bar_obj.reset();
}
}
This does it in text.
<p> The download will begin in <span id="countdowntimer">10 </span> Seconds</p>_x000D_
_x000D_
<script type="text/javascript">_x000D_
var timeleft = 10;_x000D_
var downloadTimer = setInterval(function(){_x000D_
timeleft--;_x000D_
document.getElementById("countdowntimer").textContent = timeleft;_x000D_
if(timeleft <= 0)_x000D_
clearInterval(downloadTimer);_x000D_
},1000);_x000D_
</script>
_x000D_
Uri.IsFile doesn't work with http urls. It only works for "file://". From MSDN : "The IsFile property is true when the Scheme property equals UriSchemeFile." So you can't depend on that.
Uri uri = new Uri(hreflink);
string filename = System.IO.Path.GetFileName(uri.LocalPath);
You can't do it directly, you should provide your own way to check this. Eg.
class MyClass {
Object attr1, attr2, attr3;
public boolean isValid() {
return attr1 != null && attr2 != null && attr3 != null;
}
}
Or make all fields final and initialize them in constructors so that you can be sure that everything is initialized.
func post() {
NotificationCenter.default.post(name: Notification.Name("SomeNotificationName"),
object: nil,
userInfo:["key0": "value", "key1": 1234])
}
func addObservers() {
NotificationCenter.default.addObserver(self,
selector: #selector(someMethod),
name: Notification.Name("SomeNotificationName"),
object: nil)
}
@objc func someMethod(_ notification: Notification) {
let info0 = notification.userInfo?["key0"]
let info1 = notification.userInfo?["key1"]
}
Replace Notification.Name("SomeNotificationName")
with .someNotificationName
:
extension Notification.Name {
static let someNotificationName = Notification.Name("SomeNotificationName")
}
Replace "key0"
and "key1"
with Notification.Key.key0
and Notification.Key.key1
:
extension Notification {
enum Key: String {
case key0
case key1
}
}
Why should I definitely do this ? To avoid costly typo errors, enjoy renaming, enjoy find usage etc...
Straight from the horse's mouth:
If you prefer to have dict-like view of the attributes, you can use the standard Python idiom,
vars()
:>>> parser = argparse.ArgumentParser() >>> parser.add_argument('--foo') >>> args = parser.parse_args(['--foo', 'BAR']) >>> vars(args) {'foo': 'BAR'}
— The Python Standard Library, 16.4.4.6. The Namespace object
all the solutions given doesnt work.. dont concentrate only on the retrieving part. luk at the inserting of the image. i did the same mistake. I tuk an image from hard disk and saved it to database. The problem lies in the insert command. luk at my fault code..:
public bool convertImage()
{
try
{
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
photo = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo, 0, photo.Length);
return true;
}
catch
{
MessageBox.Show("image can not be converted");
return false;
}
}
public void insertImage()
{
// SqlConnection con = new SqlConnection();
try
{
cs.Close();
cs.Open();
da.UpdateCommand = new SqlCommand("UPDATE All_students SET disco = " +photo+" WHERE Reg_no = '" + Convert.ToString(textBox1.Text)+ "'", cs);
da.UpdateCommand.ExecuteNonQuery();
cs.Close();
cs.Open();
int i = da.UpdateCommand.ExecuteNonQuery();
if (i > 0)
{
MessageBox.Show("Successfully Inserted...");
}
}
catch
{
MessageBox.Show("Error in Connection");
}
cs.Close();
}
The above code shows succesfully inserted... but actualy its saving the image in the form of wrong datatype.. whereas the datatype must bt "image".. so i improved the code..
public bool convertImage()
{
try
{
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
photo = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo, 0, photo.Length);
return true;
}
catch
{
MessageBox.Show("image can not be converted");
return false;
}
}
public void insertImage()
{
// SqlConnection con = new SqlConnection();
try
{
cs.Close();
cs.Open();
//THIS WHERE THE CODE MUST BE CHANGED>>>>>>>>>>>>>>
da.UpdateCommand = new SqlCommand("UPDATE All_students SET disco = @img WHERE Reg_no = '" + Convert.ToString(textBox1.Text)+ "'", cs);
da.UpdateCommand.Parameters.Add("@img", SqlDbType.Image);//CHANGED TO IMAGE DATATYPE...
da.UpdateCommand.Parameters["@img"].Value = photo;
da.UpdateCommand.ExecuteNonQuery();
cs.Close();
cs.Open();
int i = da.UpdateCommand.ExecuteNonQuery();
if (i > 0)
{
MessageBox.Show("Successfully Inserted...");
}
}
catch
{
MessageBox.Show("Error in Connection");
}
cs.Close();
}
100% gurantee that there will be no PARAMETER NOT VALID error in retrieving....SOLVED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
It seems that your date column is not of type datetime but varchar. You have to convert it to datetime when sorting:
select date
from tbemp
order by convert(datetime, date, 103) ASC
style 103 = dd/MM/yyyy (
msdn
)
It's all in the tutorial how to do that:
ContentValues args = new ContentValues();
args.put(columnName, newValue);
db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null);
Use ContentValues
to set the updated columns and than the update()
method in which you have to specifiy, the table and a criteria to only update the rows you want to update.
here is the trick http://neworganizing.com/content/blog/tip-prepopulate-mailto-links-with-subject-body-text
<a href="mailto:[email protected]?subject=Your+tip+on+mailto+links&body=Thanks+for+this+tip">tell a friend</a>
See this example: http://jsfiddle.net/89C54/
for (i = 0; i < myArray.length; i++) {
if (myArray[i].hello === 'stevie') {
alert('position: ' + i);
return;
}
}
It starts to count with zero.
From my notes:
Which parses like this:
q=latN+lonW+(label) location of teardrop
t=k keyhole (satelite map)
t=h hybrid
ll=lat,-lon center of map
spn=w.w,h.h span of map, degrees
iwloc has something to do with the info window. hl is obviously language.
See also: http://www.seomoz.org/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters
Try these to clarify the issue of right alignment in float point printing
printf(" 4|%4.1lf\n", 8.9);
printf("04|%04.1lf\n", 8.9);
the output is
4| 8.9
04|08.9
Alternatively if you want to grab the private and public keys from a PuTTY formated key file you can use puttygen
on *nix systems. For most apt-based systems puttygen
is part of the putty-tools
package.
Outputting a private key from a PuTTY formated keyfile:
$ puttygen keyfile.pem -O private-openssh -o avdev.pvk
For the public key:
$ puttygen keyfile.pem -L
One advantage your current approach does have is that it will raise an error if multiple rows are returned by the predicate. To reproduce that you can use.
SELECT @currentTerm = currentterm,
@termID = termid,
@endDate = enddate
FROM table1
WHERE iscurrent = 1
IF( @@ROWCOUNT <> 1 )
BEGIN
RAISERROR ('Unexpected number of matching rows',
16,
1)
RETURN
END
I came across this error while working on a programming project in c++,
This should take care of the errors
An example would be nice - here's a trivial one
for %I in (*.*) do @echo %~xI
it lists only the EXTENSIONS of each file in current folder
for more useful variable combinations (also listed in previous response) from the CMD prompt execute: HELP FOR
which contains this snippet
The modifiers can be combined to get compound results:
%~dpI - expands %I to a drive letter and path only
%~nxI - expands %I to a file name and extension only
%~fsI - expands %I to a full path name with short names only
%~dp$PATH:I - searches the directories listed in the PATH
environment variable for %I and expands to the
drive letter and path of the first one found.
%~ftzaI - expands %I to a DIR like output line
Java is a platform. It consists of two products - the software development kit, and the runtime environment.
When Java was first released, it was apparently just called Java. If you were a developer, you also knew the version, which was a normal "1.0" and later a "1.1". The two products that were part of the platform were also given names:
Apparently the changes in version 1.2 so significant that they started calling the platform as Java 2.
The default "distribution" of the platform was given the moniker "standard" to contrast it with its siblings. So you had three platforms:
The JDK was officially renamed to "Java 2 Software Development Kit".
When version 1.5 came out, the suits decided that they needed to "rebrand" the product. So the Java platform got two versions - the product version "5" and the developer version "1.5" (Yes, the rule is explicitly mentioned -- "drop the '1.'). However, the "2" was retained in the name. So now the platform is officially called "Java 2 Platform Standard Edition 5.0 (J2SE 5.0)".
When version 1.6 come out, someone realized that having two numbers in the name was weird. So they decide to completely drop the 2 (and the ".0" suffix), and we end up with the "Java Platform, Standard Edition 6 (Java SE 6)" containing the "Java SE Development Kit 6 (JDK 6)" and the "Java SE Runtime Environment 6 (JRE 6)".
Version 1.7 did not do anything stupid. If I had to guess, the next big change would be dropping the "SE", so that the cycle completes and the JDK again gets to be called the "Java Development Kit".
For simplicity, a bunch of trademark signs were omitted. So assume Java™, JDK™ and JRE™.
SO seems to have trouble rendering nested lists.
Just drop the "1." from versions printed by javac -version
and java -version
and you're good to go.
I have the same today on Win7.x64, this solve it.
Right Click MyComputer > Manage > Local Users and Groups > Groups > Administrators double click > your name should be there, if not press add...
As several of my friend has posted there are many free leak detectors for C++. All of that will cause overhead when running your code, approximatly 20% slower. I preffer Visual Leak Detector for Visual C++ 2008/2010/2012 , you can download the source code from - enter link description here .
Might be late to answer - if you don't want to modify your current code a lot and still be able to have similar validation code all over your project, you may try this one too - https://github.com/vishalvisd/react-validator.
EDIT: Updated for jQuery 1.8
Since jQuery 1.8 browser specific transformations will be added automatically. jsFiddle Demo
var rotation = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({'transform' : 'rotate('+ degrees +'deg)'});
return $(this);
};
$('.rotate').click(function() {
rotation += 5;
$(this).rotate(rotation);
});
EDIT: Added code to make it a jQuery function.
For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.
var rotation = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
'-moz-transform' : 'rotate('+ degrees +'deg)',
'-ms-transform' : 'rotate('+ degrees +'deg)',
'transform' : 'rotate('+ degrees +'deg)'});
return $(this);
};
$('.rotate').click(function() {
rotation += 5;
$(this).rotate(rotation);
});
EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.
Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.
Here is a jsFiddle.
If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.
HTML
<div class="rotate">
<h1>Rotatey text</h1>
</div>
CSS
/* Totally for style */
.rotate {
background: #F02311;
color: #FFF;
width: 200px;
height: 200px;
text-align: center;
font: normal 1em Arial;
position: relative;
top: 50px;
left: 50px;
}
/* The real code */
.rotated {
-webkit-transform: rotate(45deg); /* Chrome, Safari 3.1+ */
-moz-transform: rotate(45deg); /* Firefox 3.5-15 */
-ms-transform: rotate(45deg); /* IE 9 */
-o-transform: rotate(45deg); /* Opera 10.50-12.00 */
transform: rotate(45deg); /* Firefox 16+, IE 10+, Opera 12.10+ */
}
jQuery
Make sure these are wrapped in $(document).ready
$('.rotate').click(function() {
$(this).toggleClass('rotated');
});
Custom intervals
var rotation = 0;
$('.rotate').click(function() {
rotation += 5;
$(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
'-moz-transform' : 'rotate('+ rotation +'deg)',
'-ms-transform' : 'rotate('+ rotation +'deg)',
'transform' : 'rotate('+ rotation +'deg)'});
});
The problem solved when I don't use any declaration like var, let or const
It looks like ReflectionClass
is a pretty productive option.
class MyClass {
public function test() {
// 'MyClass'
return (new \ReflectionClass($this))->getShortName();
}
}
Benchmark:
Method Name Iterations Average Time Ops/second
-------------- ------------ -------------- -------------
testExplode : [10,000 ] [0.0000020221710] [494,518.01547]
testSubstring : [10,000 ] [0.0000017177343] [582,162.19968]
testReflection: [10,000 ] [0.0000015984058] [625,623.34059]
If the version is 20150616132425
, then use:
rails db:migrate:down VERSION=20150616132425
In phpMyAdmin v.4.6.5.2 there's a checkbox option "The first line of the file contains the table column names...." :
While above approaches do not address the case for Mac OS X because Mac Os X does not support -readable
switch this is how you can avoid 'Permission denied' errors in your output. This might help someone.
find / -type f -name "your_pattern" 2>/dev/null
.
If you're using some other command with find
, for example, to find the size of files of certain pattern in a directory 2>/dev/null
would still work as shown below.
find . -type f -name "your_pattern" -exec du -ch {} + 2>/dev/null | grep total$
.
This will return the total size of the files of a given pattern. Note the 2>/dev/null
at the end of find command.
Enter the command
which python
//output:
/usr/bin/python
cd /usr/bin
ls -l
Here you can see something like this
lrwxrwxrwx 1 root root 9 Mar 7 17:04 python -> python2.7
your default python2.7 is soft linked to the text 'python'
So remove the softlink python
sudo rm -r python
then retry the above command
ls -l
you can see the softlink is removed
-rwxr-xr-x 1 root root 3670448 Nov 12 20:01 python2.7
Then create a new softlink for python3.6
ln -s /usr/bin/python3.6 python
Then try the command python
in terminal
//output:
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type help
, copyright
, credits
or license
for more information.
I apologise for replying to a super old question but after spending an hour wrestling with the above solutions I opted for simpler stuff.
<script src=".." one="1" two="2"></script>
Inside above script:
document.currentScript.getAttribute('one'); //1
document.currentScript.getAttribute('two'); //2
Much easier than jquery OR url parsing.
You might need the polyfil for doucment.currentScript from @Yared Rodriguez's answer for IE:
document.currentScript = document.currentScript || (function() {
var scripts = document.getElementsByTagName('script');
return scripts[scripts.length - 1];
})();
Check the Variables section in the Go template docs. A range may declare two variables, separated by a comma. The following should work:
{{ range $key, $value := . }}
<li><strong>{{ $key }}</strong>: {{ $value }}</li>
{{ end }}
What version of WPF are you using? I tried in both 3.5 and 4.0, and Fill="#FF000000" should work fine in a in the XAML. There is another syntax, however, if it doesn't. Here's a 3.5 XAML that I tested with two different ways. Better yet would be to use a resource.
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Rectangle Height="100" HorizontalAlignment="Left" Margin="100,12,0,0" Name="rectangle1" Stroke="Black" VerticalAlignment="Top" Width="200" Fill="#FF00AE00" />
<Rectangle Height="100" HorizontalAlignment="Left" Margin="100,132,0,0" Name="rectangle2" Stroke="Black" VerticalAlignment="Top" Width="200" >
<Rectangle.Fill>
<SolidColorBrush Color="#FF00AE00" />
</Rectangle.Fill>
</Rectangle>
</Grid>
It depends on the type of data you need access to. If you have some kind of data pool that needs to persist across Activity
s then Erich's answer is the way to go. If you just need to pass a few objects from one activity to another then you can have them implement Serializable
and pass them in the extras of the Intent
to start the new Activity
.
You can add a random (or datetime string) as query string to the url that points to your script. Like so:
<script type="text/javascript" src="test.js?q=123"></script>
Every time you refresh the page you need to make sure the value of 'q' is changed.
Starting with Spring Boot 1.4.0 you can use this in your test:
import org.springframework.boot.context.embedded.LocalServerPort;
@SpringBootTest(classes = {Application.class}, webEnvironment = WebEnvironment.RANDOM_PORT)
public class MyTest {
@LocalServerPort
int randomPort;
// ...
}
Although, this may not be advisable.
If you want to get customer details, even when the user doesn’t create an account, but only makes an order, you could just query it, directly from the database.
Although, there may be performance issues, querying directly. But this surely works 100%.
You can search by post_id
and meta_keys
.
global $wpdb; // Get the global $wpdb
$order_id = {Your Order Id}
$table = $wpdb->prefix . 'postmeta';
$sql = 'SELECT * FROM `'. $table . '` WHERE post_id = '. $order_id;
$result = $wpdb->get_results($sql);
foreach($result as $res) {
if( $res->meta_key == 'billing_phone'){
$phone = $res->meta_value; // get billing phone
}
if( $res->meta_key == 'billing_first_name'){
$firstname = $res->meta_value; // get billing first name
}
// You can get other values
// billing_last_name
// billing_email
// billing_country
// billing_address_1
// billing_address_2
// billing_postcode
// billing_state
// customer_ip_address
// customer_user_agent
// order_currency
// order_key
// order_total
// order_shipping_tax
// order_tax
// payment_method_title
// payment_method
// shipping_first_name
// shipping_last_name
// shipping_postcode
// shipping_state
// shipping_city
// shipping_address_1
// shipping_address_2
// shipping_company
// shipping_country
}
You can't do it with only Javascript. You'll need some server-side code (PHP, in your case) that serves as a proxy between the DB and the client-side code.
Here is my attempt to measure time difference in batch.
It respects the regional format of %TIME% without taking any assumptions on type of characters for time and decimal separators.
The code is commented but I will also describe it here.
It is flexible so it can also be used to normalize non-standard time values as well
The main function :timediff
:: timediff
:: Input and output format is the same format as %TIME%
:: If EndTime is less than StartTime then:
:: EndTime will be treated as a time in the next day
:: in that case, function measures time difference between a maximum distance of 24 hours minus 1 centisecond
:: time elements can have values greater than their standard maximum value ex: 12:247:853.5214
:: provided than the total represented time does not exceed 24*360000 centiseconds
:: otherwise the result will not be meaningful.
:: If EndTime is greater than or equals to StartTime then:
:: No formal limitation applies to the value of elements,
:: except that total represented time can not exceed 2147483647 centiseconds.
:timediff <outDiff> <inStartTime> <inEndTime>
(
setlocal EnableDelayedExpansion
set "Input=!%~2! !%~3!"
for /F "tokens=1,3 delims=0123456789 " %%A in ("!Input!") do set "time.delims=%%A%%B "
)
for /F "tokens=1-8 delims=%time.delims%" %%a in ("%Input%") do (
for %%A in ("@h1=%%a" "@m1=%%b" "@s1=%%c" "@c1=%%d" "@h2=%%e" "@m2=%%f" "@s2=%%g" "@c2=%%h") do (
for /F "tokens=1,2 delims==" %%A in ("%%~A") do (
for /F "tokens=* delims=0" %%B in ("%%B") do set "%%A=%%B"
)
)
set /a "@d=(@h2-@h1)*360000+(@m2-@m1)*6000+(@s2-@s1)*100+(@c2-@c1), @sign=(@d>>31)&1, @d+=(@sign*24*360000), @h=(@d/360000), @d%%=360000, @m=@d/6000, @d%%=6000, @s=@d/100, @c=@d%%100"
)
(
if %@h% LEQ 9 set "@h=0%@h%"
if %@m% LEQ 9 set "@m=0%@m%"
if %@s% LEQ 9 set "@s=0%@s%"
if %@c% LEQ 9 set "@c=0%@c%"
)
(
endlocal
set "%~1=%@h%%time.delims:~0,1%%@m%%time.delims:~0,1%%@s%%time.delims:~1,1%%@c%"
exit /b
)
Example:
@echo off
setlocal EnableExtensions
set "TIME="
set "Start=%TIME%"
REM Do some stuff here...
set "End=%TIME%"
call :timediff Elapsed Start End
echo Elapsed Time: %Elapsed%
pause
exit /b
:: put the :timediff function here
function prototype :timediff <outDiff> <inStartTime> <inEndTime>
Input and output format is the same format as %TIME%
It takes 3 parameters from left to right:
Param1: Name of the environment variable to save the result to.
Param2: Name of the environment variable to be passed to the function containing StartTime string
Param3: Name of the environment variable to be passed to the function containing EndTime string
If EndTime is less than StartTime then:
@echo off
setlocal EnableExtensions
set "start=23:57:33,12"
set "end=00:02:19,41"
call :timediff dif start end
echo Start Time: %start%
echo End Time: %end%
echo,
echo Difference: %dif%
echo,
pause
exit /b
:: put the :timediff function here
Start Time: 23:57:33,12 End Time: 00:02:19,41 Difference: 00:04:46,29
@echo off
setlocal EnableExtensions
set "start=00:00:00.00"
set "end=27:2457:433.85935"
call :timediff normalized start end
echo,
echo %end% is equivalent to %normalized%
echo,
pause
exit /b
:: put the :timediff function here
27:2457:433.85935 is equivalent to 68:18:32.35
@echo off
setlocal EnableExtensions
set "start=00:00:00.00"
set "end=00:00:00.2147483647"
call :timediff normalized start end
echo,
echo 2147483647 centiseconds equals to %normalized%
echo,
pause
exit /b
:: put the :timediff function here
2147483647 centiseconds equals to 5965:13:56.47
If you are using Eclipse Neon, try this:
1) Add the maven plugin in the properties section of the POM:
<properties>
<java.version>1.8</java.version>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>
2) Force update of project snapshot by right clicking on Project
Maven -> Update Project -> Select your Project -> Tick on the 'Force Update of Snapshots/Releases' option -> OK
This worked for me:
ul.dropdown-menu > li {
max-width: 144px;
}
in Chromium and Firefox.
Result Set
are actually contains multiple rows of data, and use a cursor to point out current position. So in your case, rs4.getString(1)
only get you the data in first column of first row. In order to change to next row, you need to call next()
a quick example
while (rs.next()) {
String sid = rs.getString(1);
String lid = rs.getString(2);
// Do whatever you want to do with these 2 values
}
there are many useful method in ResultSet
, you should take a look :)
Try This:
$(document).on('click', '#btnClick', function(){ _x000D_
alert("button is clicked");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id="btnClick">Click me</button>
_x000D_
Restart your Android device. Things started to work for me after I restarted the device.
In my case I need to clear just the view and restart the controller. I could get my intention with this snippet:
$ionicHistory.clearCache([$state.current.name]).then(function() {
$state.reload();
}
The cache still working and seems that just the view is cleared.
ionic --version
says 1.7.5.
Ubuntu:
sudo apt-get install imagemagick libmagickwand-dev libmagickcore-dev
gem install rmagick
CentOS:
yum remove ImageMagick
gem uninstall rmagick
yum install ImageMagick ImageMagick-devel ImageMagick-last-libs ImageMagick-c++ ImageMagick-c++-devel
gem install rmagick
MacOS:
download and install http://xquartz.macosforge.org/trac/wiki/X112.7.2
after:
brew uninstall imagemagick
brew link xz jpeg freetype
brew install imagemagick
brew link --overwrite imagemagick
gem install rmagick
place the value inside the items.then it will work,
new DropdownButton<String>(
items:_dropitems.map((String val){
return DropdownMenuItem<String>(
value: val,
child: new Text(val),
);
}).toList(),
hint:Text(_SelectdType),
onChanged:(String val){
_SelectdType= val;
setState(() {});
})
datetime.datetime.fromtimestamp()
is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp()
expects Unix timestamp, in seconds.
Do it like that:
>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)
and the result is:
>>> date
datetime.datetime(2012, 3, 16, 1, 0)
Does it answer your question?
EDIT: J.F. Sebastian correctly suggested to use true division by 1e3
(float 1000
). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int
when dividing (using /
operator) int
by int
(this is called floor division). By replacing the divisor 1000
(being an int
) with the 1e3
divisor (being representation of 1000
as float) or with float(1000)
(or 1000.
etc.), the division becomes true division. Python 2.x returns float
when dividing int
by float
, float
by int
, float
by float
etc. And when there is some fractional part in the timestamp passed to fromtimestamp()
method, this method's result also contains information about that fractional part (as the number of microseconds).
Since i stumbled on the post via google:
Try using npm ci
it will be much than an npm install
.
From the manual:
In short, the main differences between using npm install and npm ci are:
- The project must have an existing package-lock.json or npm-shrinkwrap.json.
- If dependencies in the package lock do not match those in package.json, npm ci will exit with an error, instead of updating the package lock.
- npm ci can only install entire projects at a time: individual dependencies cannot be added with this command.
- If a node_modules is already present, it will be automatically removed before npm ci begins its install.
- It will never write to package.json or any of the package-locks: installs are essentially frozen.
The best way to find out the REAL type of an object (including BOTH the native Object or DataType name (such as String, Date, Number, ..etc) AND the REAL type of an object (even custom ones); is by grabbing the name property of the object prototype's constructor:
Native Type Ex1:
var string1 = "Test";
console.log(string1.__proto__.constructor.name);
displays:
String
Ex2:
var array1 = [];
console.log(array1.__proto__.constructor.name);
displays:
Array
Custom Classes:
function CustomClass(){_x000D_
console.log("Custom Class Object Created!");_x000D_
}_x000D_
var custom1 = new CustomClass();_x000D_
_x000D_
console.log(custom1.__proto__.constructor.name);
_x000D_
displays:
CustomClass
Use jquery change event
Description: Bind an event handler to the "change" JavaScript event, or trigger that event on an element.
An example
$("input[type='text']").change( function() {
// your code
});
The advantage that .change
has over .keypress
, .focus
, .blur
is that .change
event will fire only when input has changed
Add a class to your CSS that defines you cannot select or highlight an element. I have an example:
<style>
.no_highlighting{
user-select: none;
}
.anchor_without_decoration:hover{
text-decoration-style: none;
}
</style>
<a href="#" class="anchor_without_decoration no_highlighting">Anchor text</a>
There are a number of "is methods" on strings. islower()
and isupper()
should meet your needs:
>>> 'hello'.islower()
True
>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']
Here's an example of how to use those methods to classify a list of strings:
>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']
I'm a full-blown Emacs fan-boy, but I knew VI long before I knew Emacs. That said, I make all of my people learn VI because it's always available, everywhere. Can't go wrong with either one of them.
The most simple and native way it's to use CURL directly.
This works for me :
<?php
$login = 'login';
$password = 'password';
$url = 'http://your.url';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$login:$password");
$result = curl_exec($ch);
curl_close($ch);
echo($result);
You can do the same in Razor or in the Controller, like so..
@{
//do this on the top most of your View, immediately after `using` statement
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=receipt.pdf");
}
Or in the Controller..
public ActionResult Receipt() {
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=receipt.pdf");
return View();
}
I tried this in Chrome and IE9, both is downloading the pdf file.
I probably should add I am using RazorPDF to generate my PDFs. Here is a blog about it: http://nyveldt.com/blog/post/Introducing-RazorPDF
The answer by @PeterWilkinson didn't work for me because a constructor for a "typed" object is customized to the name of that object. I had to work with typeof
function isJson(obj) {
var t = typeof obj;
return ['boolean', 'number', 'string', 'symbol', 'function'].indexOf(t) == -1;
}
I am not an expert on this, but I'll share my example with you. One guy suggested to create new eclipse preferences file or epf file using another clean install of eclipse. I made a file called clean.epf and compared it with RainbowDrops.epf (the one which messed up my highlighting and such). I noticed a huge difference between the two epf files. So, you might not want to use this method.
The whole windows --- preferences thing did not help. So, I just closed eclipse. Went to
My workspace directory/.metadata/.plugins/org.eclipse.core.runtime/.settings/
and deleted the file org.eclipse.ui.editors.prefs
and opened eclipse. It works.
BTW, keep a back up of your .settings folders just in case.
In case you want to see some difference between rainbow and clean epf -
Rainbow -
file_export_version=3.0
/instance/ccw.core/ccw.preferences.editor_color.FUNCTION=167,236,33
/instance/ccw.core/ccw.preferences.editor_color.FUNCTION.bold=false
/instance/ccw.core/ccw.preferences.editor_color.FUNCTION.enabled=true
/instance/ccw.core/ccw.preferences.editor_color.FUNCTION.italic=false
/instance/ccw.core/ccw.preferences.editor_color.GLOBAL_VAR=141,218,248
...more here
Clean (exporting all) -
/instance/org.eclipse.jdt.ui/tabWidthPropagated=true
/instance/org.eclipse.mylyn.monitor.ui/org.eclipse.mylyn.monitor.activity.tracking.enabled.checked=true
/instance/org.eclipse.mylyn.tasks.ui/org.eclipse.mylyn.tasks.ui.filters.nonmatching.encouraged=true
@org.eclipse.mylyn.monitor.ui=3.13.0.v20140702-2155
/instance/org.eclipse.jdt.ui/useQuickDiffPrefPage=true
...more here
Clean (exporting only java) -
file_export_version=3.0
/instance/org.eclipse.jdt.ui/org.eclipse.jdt.ui.formatterprofiles.version=12
@org.eclipse.jdt.ui=3.10.100.v20140905-1343
\!/=
...end of file
So, I am not sure if this is the best way to go.
You can view the java doc examples or the example of usage of Predicate here
Basically it is used to filter rows in the resultset based on any specific criteria that you may have and return true for those rows that are meeting your criteria:
// the age column to be between 7 and 10
AgeFilter filter = new AgeFilter(7, 10, 3);
// set the filter.
resultset.beforeFirst();
resultset.setFilter(filter);
Since you want to pivot multiple columns of data, I would first suggest unpivoting the result
, score
and grade
columns so you don't have multiple columns but you will have multiple rows.
Depending on your version of SQL Server you can use the UNPIVOT function or CROSS APPLY. The syntax to unpivot the data will be similar to:
select ratio, col, value
from GRAND_TOTALS
cross apply
(
select 'result', cast(result as varchar(10)) union all
select 'score', cast(score as varchar(10)) union all
select 'grade', grade
) c(col, value)
See SQL Fiddle with Demo. Once the data has been unpivoted, then you can apply the PIVOT function:
select ratio = col,
[current ratio], [gearing ratio], [performance ratio], total
from
(
select ratio, col, value
from GRAND_TOTALS
cross apply
(
select 'result', cast(result as varchar(10)) union all
select 'score', cast(score as varchar(10)) union all
select 'grade', grade
) c(col, value)
) d
pivot
(
max(value)
for ratio in ([current ratio], [gearing ratio], [performance ratio], total)
) piv;
See SQL Fiddle with Demo. This will give you the result:
| RATIO | CURRENT RATIO | GEARING RATIO | PERFORMANCE RATIO | TOTAL |
|--------|---------------|---------------|-------------------|-----------|
| grade | Good | Good | Satisfactory | Good |
| result | 1.29400 | 0.33840 | 0.04270 | (null) |
| score | 60.00000 | 70.00000 | 50.00000 | 180.00000 |
How about this, replacing @
with $
:
$("body").children().each(function () {
$(this).html( $(this).html().replace(/@/g,"$") );
});
Here's an update as of Nov 2014. I find that setting method='curl'
did the trick for me (while method='auto'
, does not).
For example:
# does not work
download.file(url='https://s3.amazonaws.com/tripdata/201307-citibike-tripdata.zip',
destfile='localfile.zip')
# does not work. this appears to be the default anyway
download.file(url='https://s3.amazonaws.com/tripdata/201307-citibike-tripdata.zip',
destfile='localfile.zip', method='auto')
# works!
download.file(url='https://s3.amazonaws.com/tripdata/201307-citibike-tripdata.zip',
destfile='localfile.zip', method='curl')
Something like:
import threading
thr = threading.Thread(target=foo, args=(), kwargs={})
thr.start() # Will run "foo"
....
thr.is_alive() # Will return whether foo is running currently
....
thr.join() # Will wait till "foo" is done
See the documentation at https://docs.python.org/library/threading.html for more details.
Use
python python_script.py filename
and in your Python script
import sys
print sys.argv[1]
What is the difference between NULL, ‘\0’ and 0
"null character (NUL)" is easiest to rule out. '\0'
is a character literal.
In C, it is implemented as int
, so, it's the same as 0, which is of INT_TYPE_SIZE
. In C++, character literal is implemented as char
, which is 1 byte. This is normally different from NULL
or 0
.
Next, NULL
is a pointer value that specifies that a variable does not point to any address space. Set aside the fact that it is usually implemented as zeros, it must be able to express the full address space of the architecture. Thus, on a 32-bit architecture NULL (likely) is 4-byte and on 64-bit architecture 8-byte. This is up to the implementation of C.
Finally, the literal 0
is of type int
, which is of size INT_TYPE_SIZE
. The default value of INT_TYPE_SIZE
could be different depending on architecture.
Apple wrote:
The 64-bit data model used by Mac OS X is known as "LP64". This is the common data model used by other 64-bit UNIX systems from Sun and SGI as well as 64-bit Linux. The LP64 data model defines the primitive types as follows:
- ints are 32-bit
- longs are 64-bit
- long-longs are also 64-bit
- pointers are 64-bit
Wikipedia 64-bit:
Microsoft's VC++ compiler uses the LLP64 model.
64-bit data models
Data model short int long long long pointers Sample operating systems
LLP64 16 32 32 64 64 Microsoft Win64 (X64/IA64)
LP64 16 32 64 64 64 Most Unix and Unix-like systems (Solaris, Linux, etc.)
ILP64 16 64 64 64 64 HAL
SILP64 64 64 64 64 64 ?
Edit: Added more on the character literal.
#include <stdio.h>
int main(void) {
printf("%d", sizeof('\0'));
return 0;
}
The above code returns 4 on gcc and 1 on g++.
Define this in your String.xml file and name the array what you want, such as "Weight"
<string-array name="Weight">
<item>Kg</item>
<item>Gram</item>
<item>Tons</item>
</string-array>
and this code in your layout.xml
<Spinner
android:id="@+id/fromspin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:entries="@array/Weight"
/>
In your java file, getActivity
is used in fragment; if you write that code in activity, then remove getActivity
.
a = (Spinner) findViewById(R.id.fromspin);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),
R.array.weight, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
a.setAdapter(adapter);
a.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (a.getSelectedItem().toString().trim().equals("Kilogram")) {
if (!b.getText().toString().isEmpty()) {
float value1 = Float.parseFloat(b.getText().toString());
float kg = value1;
c.setText(Float.toString(kg));
float gram = value1 * 1000;
d.setText(Float.toString(gram));
float carat = value1 * 5000;
e.setText(Float.toString(carat));
float ton = value1 / 908;
f.setText(Float.toString(ton));
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
});
// Inflate the layout for this fragment
return v;
}
In my opinion early return is fine if you are just returning void (or some useless return code you're never gonna check) and it might improve readability because you avoid nesting and at the same time you make explicit that your function is done.
If you are actually returning a returnValue - nesting is usually a better way to go cause you return your returnValue just in one place (at the end - duh), and it might make your code more maintainable in a whole lot of cases.
Yes there is a difference in the performance of both:
jQuery('#id').show()
is slower than jQuery('#id').css("display","block")
as in former case extra work is to be done for retrieving the initial state from the jquery cache as display is not a binary attribute it can be inline
,block
,none
,table
, etc.
similar is the case with hide()
method.
The technical limitations with using PUT and DELETE requests does not lie with PHP or Apache2; it is instead on the burden of the browser to sent those types of requests.
Simply putting <form action="" method="PUT"> will not work because there are no browsers that support that method (and they would simply default to GET, treating PUT the same as it would treat gibberish like FDSFGS). Sadly those HTTP verbs are limited to the realm of non-desktop application browsers (ie: web service consumers).
To delete multiple values try this one:
while (($key = array_search($del_val, $messages)) !== false)
{
unset($messages[$key]);
}
You could also change resolution of your bluestacks emulator. For example from 800x1280 to 1280x800
Here are instructions for how to change the screen resolution.
To change screen resolution in BlueStacks Android emulator you need to edit two registry items:
Run regedit.exe
Set new resolution (in decimal):
HKEY_LOCAL_MACHINE\SOFTWARE\BlueStacks\Guests\Android\FrameBuffer\0\Height
and
HKEY_LOCAL_MACHINE\SOFTWARE\BlueStacks\Guests\Android\FrameBuffer\0\Width
Kill all BlueStacks processes.
Restart BlueStacks
You can also run ->select('DISTINCT `field`', FALSE)
and the second parameter tells CI
not to escape the first argument.
With the second parameter as false
, the output would be SELECT DISTINCT `field`
instead of without the second parameter, SELECT `DISTINCT` `field`
works at Swift 5
do {
let documentDirectory = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileUrl = documentDirectory.appendingPathComponent("userInfo").appendingPathExtension("sqlite3")
if FileManager.default.fileExists(atPath: fileUrl.path) {
print("FILE AVAILABLE")
} else {
print("FILE NOT AVAILABLE")
}
} catch {
print(error)
}
where "userInfo"
- file's name, and "sqlite3"
- file's extension
Assign the response to a value and test the attributes of it. These should tell you something useful.
response = requests.post(url,params=data,headers=headers)
response.status_code
response.text
try using ";" to separate the commands if you are in verions two e.g.
command: "sleep 20; echo 'a'"
At a guess, AppEngine is using a 64-bit implementation of Python (-5768830964305142685 won't fit in 32 bits) and your implementation of Python is 32 bits. You can't rely on object hashes being meaningfully comparable between different implementations.
Many of these answers are simply wrong for the general case, others are unnecessarily complicated if they in fact even work. The jQuery .before
and .after
methods do most of what you want to do, but you need a 3rd element the way many swap algorithms work. It's pretty simple - make a temporary DOM element as a placeholder while you move things around. There is no need to look at parents or siblings, and certainly no need to clone...
$.fn.swapWith = function(that) {
var $this = this;
var $that = $(that);
// create temporary placeholder
var $temp = $("<div>");
// 3-step swap
$this.before($temp);
$that.before($this);
$temp.after($that).remove();
return $this;
}
1) put the temporary div temp
before this
2) move this
before that
3) move that
after temp
3b) remove temp
Then simply
$(selectorA).swapWith(selectorB);
Choose your poison - if you can't change the type of the property to be nullable then you're going to have to use a "magic" value to represent NULL. Guid.Empty
seems as good as any unless you have some specific reason for not wanting to use it. A second choice would be Guid.Parse("ffffffff-ffff-ffff-ffff-ffffffffffff")
but that's a lot uglier IMHO.
Well, this question is asked many times before, and the short typical answer is: It cannot be done by pure CSS. It's in the name: Cascading Style Sheets only supports styling in cascading direction, not up.
But in most circumstances where this effect is wished, like in the given example, there still is the possibility to use these cascading characteristics to reach the desired effect. Consider this pseudo markup:
<parent>
<sibling></sibling>
<child></child>
</parent>
The trick is to give the sibling the same size and position as the parent and to style the sibling instead of the parent. This will look like the parent is styled!
Now, how to style the sibling?
When the child is hovered, the parent is too, but the sibling is not. The same goes for the sibling. This concludes in three possible CSS selector paths for styling the sibling:
parent sibling { }
parent sibling:hover { }
parent:hover sibling { }
These different paths allow for some nice possibilities. For instance, unleashing this trick on the example in the question results in this fiddle:
div {position: relative}
div:hover {background: salmon}
div p:hover {background: white}
div p {padding-bottom: 26px}
div button {position: absolute; bottom: 0}
Obviously, in most cases this trick depends on the use of absolute positioning to give the sibling the same size as the parent, ánd still let the child appear within the parent.
Sometimes it is necessary to use a more qualified selector path in order to select a specific element, as shown in this fiddle which implements the trick multiple times in a tree menu. Quite nice really.
Just a few minutes ago i was facing the same problem. I got the problem that is after just placing your jQuery start the other jQuery scripting. After all it will work fine.
To answer the original question: yes, you can access the index value of a row in apply()
. It is available under the key name
and requires that you specify axis=1
(because the lambda processes the columns of a row and not the rows of a column).
Working example (pandas 0.23.4):
>>> import pandas as pd
>>> df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
>>> df.set_index('a', inplace=True)
>>> df
b c
a
1 2 3
4 5 6
>>> df['index_x10'] = df.apply(lambda row: 10*row.name, axis=1)
>>> df
b c index_x10
a
1 2 3 10
4 5 6 40
for VS2008 with feature pack update, shared_ptr can be found under namespace std::tr1.
std::tr1::shared_ptr<int> MyIntSmartPtr = new int;
of
if you had boost installation path (for example @ C:\Program Files\Boost\boost_1_40_0
) added to your IDE settings:
#include <boost/shared_ptr.hpp>
That will do the trick:
rails g migration add_user_to_tester user_id:integer:index
pattern - re
str.split(/re/g)
will return everything except the pattern.
Test here
I ran into the same issue and figured out the problem. When you initialize a repository there aren't actually any branches. When you start a project run git add .
and then git commit
and the master branch will be created.
Without checking anything in you have no master branch. In that case you need to follow the steps other people here have suggested.
puts "string".split('').map(&:ord).to_s
You need to start the SQL Server manually. Press
windows + R
type
sqlservermanager12.msc
right click ->Start
@pst gave a great answer, but I'd like to mention that in Ruby the ternary operator is written on one line to be syntactically correct, unlike Perl and C where we can write it on multiple lines:
(true) ? 1 : 0
Normally Ruby will raise an error if you attempt to split it across multiple lines, but you can use the \
line-continuation symbol at the end of a line and Ruby will be happy:
(true) \
? 1 \
: 0
This is a simple example, but it can be very useful when dealing with longer lines as it keeps the code nicely laid out.
It's also possible to use the ternary without the line-continuation characters by putting the operators last on the line, but I don't like or recommend it:
(true) ?
1 :
0
I think that leads to really hard to read code as the conditional test and/or results get longer.
I've read comments saying not to use the ternary operator because it's confusing, but that is a bad reason to not use something. By the same logic we shouldn't use regular expressions, range operators ('..
' and the seemingly unknown "flip-flop" variation). They're powerful when used correctly, so we should learn to use them correctly.
Why have you put brackets around
true
?
Consider the OP's example:
<% question = question.size > 20 ? question.question.slice(0, 20)+"..." : question.question %>
Wrapping the conditional test helps make it more readable because it visually separates the test:
<% question = (question.size > 20) ? question.question.slice(0, 20)+"..." : question.question %>
Of course, the whole example could be made a lot more readable by using some judicious additions of whitespace. This is untested but you'll get the idea:
<% question = (question.size > 20) ? question.question.slice(0, 20) + "..." \
: question.question
%>
Or, more written more idiomatically:
<% question = if (question.size > 20)
question.question.slice(0, 20) + "..."
else
question.question
end
%>
It'd be easy to argument that readability suffers badly from question.question
too.
This can be done with a CSS hack (see the other answers), but it can also be done very easily with JavaScript.
Set the div's width to (for example) 50%, use JavaScript to check its width, and then set the height accordingly. Here's a code example using jQuery:
$(function() {_x000D_
var div = $('#dynamicheight');_x000D_
var width = div.width();_x000D_
_x000D_
div.css('height', width);_x000D_
});
_x000D_
#dynamicheight_x000D_
{_x000D_
width: 50%;_x000D_
_x000D_
/* Just for looks: */_x000D_
background-color: cornflowerblue;_x000D_
margin: 25px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="dynamicheight"></div>
_x000D_
If you want the box to scale with the browser window on resize, move the code to a function and call it on the window resize event. Here's a demonstration of that too (view example full screen and resize browser window):
$(window).ready(updateHeight);_x000D_
$(window).resize(updateHeight);_x000D_
_x000D_
function updateHeight()_x000D_
{_x000D_
var div = $('#dynamicheight');_x000D_
var width = div.width();_x000D_
_x000D_
div.css('height', width);_x000D_
}
_x000D_
#dynamicheight_x000D_
{_x000D_
width: 50%;_x000D_
_x000D_
/* Just for looks: */_x000D_
background-color: cornflowerblue;_x000D_
margin: 25px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="dynamicheight"></div>
_x000D_
iOS 11
Setting a custom button using constraint:
let buttonWidth = CGFloat(30)
let buttonHeight = CGFloat(30)
let button = UIButton(type: .custom)
button.setImage(UIImage(named: "img name"), for: .normal)
button.addTarget(self, action: #selector(buttonTapped(sender:)), for: .touchUpInside)
button.widthAnchor.constraint(equalToConstant: buttonWidth).isActive = true
button.heightAnchor.constraint(equalToConstant: buttonHeight).isActive = true
self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: button)
Actually there is. There is a static method valueOf in the java.sql.Date
object which does exactly that. So we have
java.util.Date date = java.sql.Date.valueOf(localDate);
and that's it. No explicit setting of time zones because the local time zone is taken implicitly.
From docs:
The provided LocalDate is interpreted as the local date in the local time zone.
The java.sql.Date
subclasses java.util.Date
so the result is a java.util.Date
also.
And for the reverse operation there is a toLocalDate method in the java.sql.Date class. So we have:
LocalDate ld = new java.sql.Date(date.getTime()).toLocalDate();
It sounds indeed like video streaming more than image streaming, as someone suggested. JPEG/PNG compression isn't targeted for these types of speeds, so forget them.
Imagine having a recording codec on your system that can realtime record an incoming video stream (your screen). A bit like Fraps perhaps. Then imagine a video playback codec on the other side (the remote client). As HD recorders can do it (record live and even playback live from the same HD), so should you, in the end. The HD surely can't deliver images quicker than you can read your display, so that isn't the bottleneck. The bottleneck are the video codecs. You'll find the encoder much more of a problem than the decoder, as all decoders are mostly free.
I'm not saying it's simple; I myself have used DirectShow to encode a video file, and it's not realtime by far. But given the right codec I'm convinced it can work.
If you face this issue in Linux, one of the common reasons can be that the folder "anaconda3" or "anaconda2" has root ownership. This prevents other users from writing into the folder. This can be resolved by changing the ownership of the folder from root to "USER" by running the command:
sudo chown -R $USER:$USER anaconda3
or sudo chown -R $USER:$USER <path of anaconda 3/2 folder>
Note: How to figure out whether a folder has root ownership? -- There will be a lock symbol on the top right corner of the respective folder. Or right-click on the folder->properties and you will be able to see the owner details
The -R argument lets the $USER access all the folders and files within the folder anaconda3 or anaconda2 or any respective folder. It stands for "recursive".
import java.io.IOException;
import org.apache.log4j.Appender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
/**
* @author Kiran
*
*/
public class MyLogger {
public MyLogger() {
}
public static void main(String[] args) {
Logger logger = Logger.getLogger("MyLog");
Appender fh = null;
try {
fh = new FileAppender(new SimpleLayout(), "MyLogFile.log");
logger.addAppender(fh);
fh.setLayout(new SimpleLayout());
logger.info("My first log");
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
logger.info("Hi How r u?");
}
}
It's called a shebang, and tells the parent shell which interpreter should be used to execute the script.
#!/bin/sh <--------- bourne shell compatible script
#!/usr/bin/perl <-- perl script
#!/usr/bin/php <--- php script
#!/bin/false <------ do-nothing script, because false returns immediately anyways.
Most scripting languages tend to interpret a line starting with #
as comment and will ignore the following !/usr/bin/whatever
portion, which might otherwise cause a syntax error in the interpreted language.
In my case the problem was because of conflicting Jars.
Here is the full list of jars which is working absolutely fine for me.
antlr-2.7.7.jar
byte-buddy-1.8.12.jar
c3p0-0.9.5.2.jar
classmate-1.3.4.jar
dom4j-1.6.1.jar
geolatte-geom-1.3.0.jar
hibernate-c3p0-5.3.1.Final.jar
hibernate-commons-annotations-5.0.3.Final.jar
hibernate-core-5.3.1.Final.jar
hibernate-envers-5.3.1.Final.jar
hibernate-jpamodelgen-5.3.1.Final.jar
hibernate-osgi-5.3.1.Final.jar
hibernate-proxool-5.3.1.Final.jar
hibernate-spatial-5.3.1.Final.jar
jandex-2.0.3.Final.jar
javassist-3.22.0-GA.jar
javax.interceptor-api-1.2.jar
javax.persistence-api-2.2.jar
jboss-logging-3.3.2.Final.jar
jboss-transaction-api_1.2_spec-1.1.1.Final.jar
jts-core-1.14.0.jar
mchange-commons-java-0.2.11.jar
mysql-connector-java-5.1.21.jar
org.osgi.compendium-4.3.1.jar
org.osgi.core-4.3.1.jar
postgresql-42.2.2.jar
proxool-0.8.3.jar
slf4j-api-1.6.1.jar
.m2 directory on linux box usually would be $HOME/.m2
you could get the $HOME :
echo $HOME
or simply:
cd <enter>
to go to your home directory.
other information from maven site: http://maven.apache.org/download.html#Installation
In general, you use the #
syntax:
{{#a_boolean}}
I only show up if the boolean was true.
{{/a_boolean}}
The goal is to move as much logic as possible out of the template (which makes sense).
The problem is in this method:
public static byte[] encrypt(String toEncrypt) throws Exception{
This is the method signature which pretty much says:
In this case the method signature says that when invoked this method "could" potentially throw an exception of type "Exception".
....
concatURL = padString(concatURL, ' ', 16);
byte[] encrypted = encrypt(concatURL); <-- HERE!!!!!
String encryptedString = bytesToHex(encrypted);
content.removeAll();
......
So the compilers is saying: Either you surround that with a try/catch construct or you declare the method ( where is being used ) to throw "Exception" it self.
The real problem is the "encrypt" method definition. No method should ever return "Exception", because it is too generic and may hide some other kinds of exception better is to have an specific exception.
Try this:
public static byte[] encrypt(String toEncrypt) {
try{
String plaintext = toEncrypt;
String key = "01234567890abcde";
String iv = "fedcba9876543210";
SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE,keyspec,ivspec);
byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());
return encrypted;
} catch ( NoSuchAlgorithmException nsae ) {
// What can you do if the algorithm doesn't exists??
// this usually won't happen because you would test
// your code before shipping.
// So in this case is ok to transform to another kind
throw new IllegalStateException( nsae );
} catch ( NoSuchPaddingException nspe ) {
// What can you do when there is no such padding ( whatever that means ) ??
// I guess not much, in either case you won't be able to encrypt the given string
throw new IllegalStateException( nsae );
}
// line 109 won't say it needs a return anymore.
}
Basically in this particular case you should make sure the cryptography package is available in the system.
Java needs an extension for the cryptography package, so, the exceptions are declared as "checked" exceptions. For you to handle when they are not present.
In this small program you cannot do anything if the cryptography package is not available, so you check that at "development" time. If those exceptions are thrown when your program is running is because you did something wrong in "development" thus a RuntimeException subclass is more appropriate.
The last line don't need a return statement anymore, in the first version you were catching the exception and doing nothing with it, that's wrong.
try {
// risky code ...
} catch( Exception e ) {
// a bomb has just exploited
// you should NOT ignore it
}
// The code continues here, but what should it do???
If the code is to fail, it is better to Fail fast
Here are some related answers:
to use in onMenuItemClick(MenuItem item)
just do invalidateOptionsMenu();
item.setIcon(ContextCompat.getDrawable(this, R.drawable.ic_baseline_play_circle_outline_24px));
I've created an angular directive for xCharts which is a nice js chart library http://tenxer.github.io/xcharts/. You can install it using bower, quite easy: https://github.com/radu-cigmaian/ng-xCharts
Highcharts is also a solution, but it is not free for comercial use.
Try this, at the end of the each loop, ids array will contain all the hexcodes.
var ids = [];
$(document).ready(function($) {
var $div = $("<div id='hexCodes'></div>").appendTo(document.body), code;
$(".color_cell").each(function() {
code = $(this).attr('id');
ids.push(code);
$div.append(code + "<br />");
});
});
In addition to this, due to some recent website hacks we had to secure our sites more. In doing so, we discovered that file_get_contents failed to work, where curl still would work.
Not 100%, but I believe that this php.ini setting may have been blocking the file_get_contents request.
; Disable allow_url_fopen for security reasons
allow_url_fopen = 0
Either way, our code now works with curl.