I think I found a simpler solution, only this uses a subclass of ViewPager instead of (its parent) ScrollView.
UPDATE 2013-07-16: I added an override for onTouchEvent
as well. It could possibly help with the issues mentioned in the comments, although YMMV.
public class UninterceptableViewPager extends ViewPager {
public UninterceptableViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
boolean ret = super.onInterceptTouchEvent(ev);
if (ret)
getParent().requestDisallowInterceptTouchEvent(true);
return ret;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
boolean ret = super.onTouchEvent(ev);
if (ret)
getParent().requestDisallowInterceptTouchEvent(true);
return ret;
}
}
This is similar to the technique used in android.widget.Gallery's onScroll(). It is further explained by the Google I/O 2013 presentation Writing Custom Views for Android.
Update 2013-12-10: A similar approach is also described in a post from Kirill Grouchnikov about the (then) Android Market app.
Here is a good tutorial with code. Let me know if it works for you! This is also a good tutorial.
EDIT
In This example, all you need to do is add this line:
gallery.setSelection(1);
after setting the adapter to gallery object, that is this line:
gallery.setAdapter(new ImageAdapter(this));
UPDATE1
Alright, I got your problem. This open source library is your solution. I also have used it for one of my projects. Hope this will solve your problem finally.
UPDATE2:
I would suggest you to go through this tutorial. You might get idea. I think I got your problem, you want the horizontal scrollview with snap. Try to search with that keyword on google or out here, you might get your solution.
if you want to write in column:
for x in np.nditer(a.T, order='C'):
file.write(str(x))
file.write("\n")
Here 'a' is the name of numpy array and 'file' is the variable to write in a file.
If you want to write in row:
writer= csv.writer(file, delimiter=',')
for x in np.nditer(a.T, order='C'):
row.append(str(x))
writer.writerow(row)
unique_ptr
's like that.I believe you're making a terrible mess - for those who will need to read your code, maintain it, and probably those who need to use it.
unique_ptr
constructor parameters if you have publicly-exposed unique_ptr
members.unique_ptr
s wrap raw pointers for ownership & lifetime management. They're great for localized use - not good, nor in fact intended, for interfacing. Wanna interface? Document your new class as ownership-taking, and let it get the raw resource; or perhaps, in the case of pointers, use owner<T*>
as suggested in the Core Guidelines.
Only if the purpose of your class is to hold unique_ptr
's, and have others use those unique_ptr
's as such - only then is it reasonable for your constructor or methods to take them.
unique_ptr
s internallyUsing unique_ptr
for list nodes is very much an implementation detail. Actually, even the fact that you're letting users of your list-like mechanism just use the bare list node directly - constructing it themselves and giving it to you - is not a good idea IMHO. I should not need to form a new list-node-which-is-also-a-list to add something to your list - I should just pass the payload - by value, by const lvalue ref and/or by rvalue ref. Then you deal with it. And for splicing lists - again, value, const lvalue and/or rvalue.
The most important thing to remember:
The only way to get a constant, variable (any result) from TenorFlow is the session.
Knowing this everything else is easy:
Both
tf.Session.run()
andtf.Tensor.eval()
get results from the session wheretf.Tensor.eval()
is a shortcut for callingtf.get_default_session().run(t)
I would also outline the method tf.Operation.run()
as in here:
After the graph has been launched in a session, an Operation can be executed by passing it to
tf.Session.run()
.op.run()
is a shortcut for callingtf.get_default_session().run(op)
.
There is an answer on the Zebra support website:
https://km.zebra.com/kb/index?page=content&id=SA301&cat=ZISV_PL_ZPL&actp=LIST
Simple.... use tapku library.... you can google that word and use it... its open source... enjoy..... no need of bugging with those codes....
There are detailed notes on this that helped me completely, located here.
Jonathon Reinhart has already answered with the key bit, to edit /etc/gitlab/gitlab.rb, alter the external_url and then run sudo gitlab-ctl reconfigure; sudo gitlab-ctl restart
However I needed to go a bit further and docs I linked above explained it. So what I ended up with looks like:
external_url 'https://gitlab.toilethumor.com'
nginx['ssl_certificate'] = "/www/ssl/star_toilethumor.com-chained.crt"
nginx['ssl_certificate_key'] = "/www/ssl/star_toilethumor.com.key"
nginx['proxy_set_headers'] = {
"X-Forwarded-Proto" => "http",
"CUSTOM_HEADER" => "VALUE"
}
Above, I've explicitly declared where my SSL goodies are on this server. And that's of course followed by
sudo gitlab-ctl reconfigure
sudo gitlab-ctl restart
Also, when you switch the omnibus package to https, the bundled nginx will only serve on port 443. Since all my stuff is reached via reverse proxy, this part was potentially significant.
As I went through this, I screwed something up and it helpful to find the actual nginx logs, this lead me there:
sudo gitlab-ctl tail nginx
var data = [
{"Id": 10004, "PageName": "club"},
{"Id": 10040, "PageName": "qaz"},
{"Id": 10059, "PageName": "jjjjjjj"}
];
$.each(data, function(i, item) {
alert(data[i].PageName);
});
$.each(data, function(i, item) {
alert(item.PageName);
});
these two options work well, unless you have something like:
var data.result = [
{"Id": 10004, "PageName": "club"},
{"Id": 10040, "PageName": "qaz"},
{"Id": 10059, "PageName": "jjjjjjj"}
];
$.each(data.result, function(i, item) {
alert(data.result[i].PageName);
});
EDIT:
try with this and describes what the result
$.get('/Cms/GetPages/123', function(data) {
alert(data);
});
FOR EDIT 3:
this corrects the problem, but not the idea to use "eval", you should see how are the response in '/Cms/GetPages/123'.
$.get('/Cms/GetPages/123', function(data) {
$.each(eval(data.replace(/[\r\n]/, "")), function(i, item) {
alert(item.PageName);
});
});
You only need the async
pipe:
<li *ngFor="let afd of afdeling | async">
{{afd.patientid}}
</li>
always use the async
pipe when dealing with Observables directly without explicitly unsubscribe.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="../Homepage-30-06-2016/Css.css" >
<title>Form</title>
<script type="text/javascript">
function isChar(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 47 && charCode < 58) {
document.getElementById("error").innerHTML = "*Please Enter Your Name Only";
document.getElementById("fullname").focus();
document.getElementById("fullname").style.borderColor = 'red';
return false;
}
else {
document.getElementById("error").innerHTML = "";
document.getElementById("fullname").style.borderColor = '';
return true;
}
}
</script>
</head>
<body>
<h1 style="margin-left:20px;"Registration Form>Registration Form</h1><hr/>
Name: <input id="fullname" type="text" placeholder="Full Name*"
name="fullname" onKeyPress="return isChar(event)" onChange="return isChar(event);"/><label id="error"></label><br /><br />
<button type="submit" id="submit" name="submit" onClick="return valid(event)" class="btn btn-link text-uppercase"> Submit now</button>
Take a look at this example: MDN Element.scrollHeight
I recommend that check out this example: stackoverflow.com/a/24815216... which implements a cross-browser handling for the scroll action.
You may use the following snippet:
//attaches the "scroll" event
$(window).scroll(function (e) {
var target = e.currentTarget,
scrollTop = target.scrollTop || window.pageYOffset,
scrollHeight = target.scrollHeight || document.body.scrollHeight;
if (scrollHeight - scrollTop === $(target).innerHeight()) {
console.log("? End of scroll");
}
});
Where do these characters occur? Do you see them if you examine the XML data in, say, notepad? Or do you see them when examining the XML data in the debugger. If it is the latter, they are only escape characters for the "
characters, and so part of the actual XML data.
jPDFImages is not free but a commercial library which converts PDF pages to images in JPEG, TIFF or PNG format. The output image size is customizable.
In order to avoid troubles compiling third party libraries that need boost installed in your system, run this:
sudo port install boost +universal
You could use replicate
or sapply
:
R> colMeans(replicate(10000, sample(100, size=815, replace=TRUE, prob=NULL))) R> sapply(seq_len(10000), function(...) mean(sample(100, size=815, replace=TRUE, prob=NULL)))
replicate
is a wrapper for the common use of sapply
for repeated evaluation of an expression (which will usually involve random number generation).
Yes, there is a better way: You can use the $parse service in your directive to evaluate an expression in the context of the parent scope while binding certain identifiers in the expression to values visible only inside your directive:
$parse(attributes.callback)(scope.$parent, { arg2: yourSecondArgument });
Add this line to the link function of the directive where you can access the directive's attributes.
Your callback attribute may then be set like callback = "callback(item.id, arg2)"
because arg2 is bound to yourSecondArgument by the $parse service inside the directive. Directives like ng-click
let you access the click event via the $event
identifier inside the expression passed to the directive by using exactly this mechanism.
Note that you do not have to make callback
a member of your isolated scope with this solution.
If you want to add a button with the title centered with multiple lines, set your Interface Builder's settings for the button:
[]
Do you mean something like this?
HTML
<button class="test"></button>
CSS
.test{
height:200px;
width:200px;
}
If you want to use inline CSS instead of an external stylesheet, see this:
<button style="height:200px;width:200px"></button>
There is indentation problem. The code below will work:
import textwrap
def sendMail(FROM,TO,SUBJECT,TEXT,SERVER):
import smtplib
"""this is some test documentation in the function"""
message = textwrap.dedent("""\
From: %s
To: %s
Subject: %s
%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT))
# Send the mail
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()
Sadly the other posters are correct that you're
...actually as corrected by kRON, you are ok with your IE7 and a strict doc, but most of us with IE6 requirements are reduced to JS or class references for this, but it is a CSS2 property, just one without sufficient support from IE^h^h browsers.
Out of completeness, the type selector is - similar to xpath - of the form [attribute=value]
but many interesting variants exist. It will be quite powerful when it's available, good thing to keep in your head for IE8.
Xml declaration is optional so your xml is well-formed without it. But it is recommended to use it so that wrong assumptions are not made by the parsers, specifically about the encoding used.
For anyone who like do things in XML, specially in case where you are using Navigation architecture component actions in order to navigate to dialogs
You can use:
<style name="DialogStyle" parent="ThemeOverlay.MaterialComponents.Dialog.Alert">
<!-- dialog_background is drawable shape with corner radius -->
<item name="android:background">@drawable/dialog_background</item>
<item name="android:windowBackground">@android:color/transparent</item>
</style>
As there's already an existing repository, running
git config --bool core.bare true
on the remote repository should suffice
From the core.bare documentation
If true (bare = true), the repository is assumed to be bare with no working directory associated. If this is the case a number of commands that require a working directory will be disabled, such as git-add or git-merge (but you will be able to push to it).
This setting is automatically guessed by git-clone or git-init when the repository is created. By default a repository that ends in "/.git" is assumed to be not bare (bare = false), while all other repositories are assumed to be bare (bare = true).
This is actually a fairly interesting question. It's not as simple as it looks at first. For reference, I'm going to be basing this off of the latest C11 language grammar defined in N1570
I guess the counter-intuitive part of the question is: if this is correct C:
if (a == 1) {
int b = 10;
}
then why is this not also correct C?
if (a == 1)
int b = 10;
I mean, a one-line conditional if
statement should be fine either with or without braces, right?
The answer lies in the grammar of the if
statement, as defined by the C standard. The relevant parts of the grammar I've quoted below. Succinctly: the int b = 10
line is a declaration, not a statement, and the grammar for the if
statement requires a statement after the conditional that it's testing. But if you enclose the declaration in braces, it becomes a statement and everything's well.
And just for the sake of answering the question completely -- this has nothing to do with scope. The b
variable that exists inside that scope will be inaccessible from outside of it, but the program is still syntactically correct. Strictly speaking, the compiler shouldn't throw an error on it. Of course, you should be building with -Wall -Werror
anyways ;-)
(6.7) declaration: declaration-speci?ers init-declarator-listopt ; static_assert-declaration (6.7) init-declarator-list: init-declarator init-declarator-list , init-declarator (6.7) init-declarator: declarator declarator = initializer (6.8) statement: labeled-statement compound-statement expression-statement selection-statement iteration-statement jump-statement (6.8.2) compound-statement: { block-item-listopt } (6.8.4) selection-statement: if ( expression ) statement if ( expression ) statement else statement switch ( expression ) statement
Is you want a plus (+) symbol in the body you have to encode it as 2B.
For example: Try this
We use ClosedXML in rather large systems.
Sympy, a python module for symbolic mathematics, has a built-in modular inverse function if you don't want to implement your own (or if you're using Sympy already):
from sympy import mod_inverse
mod_inverse(11, 35) # returns 16
mod_inverse(15, 35) # raises ValueError: 'inverse of 15 (mod 35) does not exist'
This doesn't seem to be documented on the Sympy website, but here's the docstring: Sympy mod_inverse docstring on Github
If double quotes does not work , try including the string within square brackets.
For eg:
SELECT "Business Name","Other Name" FROM your_Table
can be changed as
SELECT [Business Name],[Other Name] FROM your_Table
Complete answer:
1. Is there a function available in SQL?
Yes, the SQL 92 spec, Oct 97, pg. 171, section 6.16 specifies this functions:
CURRENT_TIME Time of day at moment of evaluation
CURRENT_DATE Date at moment of evaluation
CURRENT_TIMESTAMP Date & Time at moment of evaluation
2. It is implementation depended so each database has its own function for this?
Each database has its own implementations, but they have to implement the three function above if they comply with the SQL 92 specification (but depends on the version of the spec)
3. What is the function available in MySQL?
NOW() returns 2009-08-05 15:13:00
CURDATE() returns 2009-08-05
CURTIME() returns 15:13:00
Probably you use Microsoft SQL Server which support Common Table Expressions (CTE) (see http://msdn.microsoft.com/en-us/library/ms190766.aspx) which are very friendly for query optimization. So I suggest you my favor construction:
WITH GetNumberOfPlans(Id,NumberOfPlans) AS (
SELECT tableA.Id, COUNT(tableC.Id)
FROM tableC
RIGHT OUTER JOIN tableA ON tableC.tableAId = tableA.Id
GROUP BY tableA.Id
),GetUserInformation(Id,Name,Owner,ImageUrl,
CompanyImageUrl,NumberOfUsers) AS (
SELECT tableA.Id, tableA.Name, tableB.Username AS Owner, tableB.ImageUrl,
tableB.CompanyImageUrl,COUNT(tableD.UserId),p.NumberOfPlans
FROM tableA
INNER JOIN tableB ON tableB.Id = tableA.Owner
RIGHT OUTER JOIN tableD ON tableD.tableAId = tableA.Id
GROUP BY tableA.Name, tableB.Username, tableB.ImageUrl, tableB.CompanyImageUrl
)
SELECT u.Id,u.Name,u.Owner,u.ImageUrl,u.CompanyImageUrl
,u.NumberOfUsers,p.NumberOfPlans
FROM GetUserInformation AS u
INNER JOIN GetNumberOfPlans AS p ON p.Id=u.Id
After some experiences with CTE you will be find very easy to write code using CTE and you will be happy with the performance.
Another cause is accidentally putting the data=...
inside the aes(...)
instead of outside:
RIGHT:
ggplot(data=df[df$var7=='9-06',], aes(x=lifetime,y=rep_rate,group=mdcp,color=mdcp) ...)
WRONG:
ggplot(aes(data=df[df$var7=='9-06',],x=lifetime,y=rep_rate,group=mdcp,color=mdcp) ...)
In particular this can happen when you prototype your plot command with qplot()
, which doesn't use an explicit aes()
, then edit/copy-and-paste it into a ggplot()
qplot(data=..., x=...,y=..., ...)
ggplot(data=..., aes(x=...,y=...,...))
It's a pity ggplot's error message isn't Missing 'data' argument! instead of this cryptic nonsense, because that's what this message often means.
Reflection can help you.
var someObject;
var propertyName = "PropertyWhichValueYouWantToKnow";
var propertyName = someObject.GetType().GetProperty(propertyName).GetValue(someObject, null);
Spinner sp = (Spinner)findViewById(R.id.spinner);
sp.setSelection(pos);
here pos is integer (your array item position)
array is like below then pos = 0;
String str[] = new String{"Select Gender","male", "female" };
then in onItemSelected
@Override
public void onItemSelected(AdapterView<?> main, View view, int position,
long Id) {
if(position > 0){
// get spinner value
}else{
// show toast select gender
}
}
sed '/^abc$/,/^mno$/!d;//d' file
golfs two characters better than ppotong's {//!b};d
The empty forward slashes //
mean: "reuse the last regular expression used". and the command does the same as the more understandable:
sed '/^abc$/,/^mno$/!d;/^abc$/d;/^mno$/d' file
This seems to be POSIX:
If an RE is empty (that is, no pattern is specified) sed shall behave as if the last RE used in the last command applied (either as an address or as part of a substitute command) was specified.
You have multiple oddities happening. The first has been edited in your post, but it had to do with the order that the methods were being called.
.format
returns a string. String does not have a subtract
method.
The second issue is that you are subtracting the day, but not actually saving that as a variable.
Your code, then, should look like:
var startdate = moment();
startdate = startdate.subtract(1, "days");
startdate = startdate.format("DD-MM-YYYY");
However, you can chain this together; this would look like:
var startdate = moment().subtract(1, "days").format("DD-MM-YYYY");
The difference is that we're setting startdate to the changes that you're doing on startdate, because moment is destructive.
I'd make both the input
and label
elements display: block
, and then split the name label & input, and the email label & input into div's
and float them next to each other.
input, label {_x000D_
display:block;_x000D_
}
_x000D_
<form name="message" method="post">_x000D_
<section>_x000D_
_x000D_
<div style="float:left;margin-right:20px;">_x000D_
<label for="name">Name</label>_x000D_
<input id="name" type="text" value="" name="name">_x000D_
</div>_x000D_
_x000D_
<div style="float:left;">_x000D_
<label for="email">Email</label>_x000D_
<input id="email" type="text" value="" name="email">_x000D_
</div>_x000D_
_x000D_
<br style="clear:both;" />_x000D_
_x000D_
</section>_x000D_
_x000D_
<section>_x000D_
_x000D_
<label for="subject">Subject</label>_x000D_
<input id="subject" type="text" value="" name="subject">_x000D_
<label for="message">Message</label>_x000D_
<input id="message" type="text" value="" name="message">_x000D_
_x000D_
</section>_x000D_
</form>
_x000D_
In a real-time scenario, the difference between the Spring IOC Core container (BeanFactory) and Advanced J2EE container (ApplicationContext) are as follows.
BeanFactory will create objects for the beans (i.e., for POJO classes) mentioned in the spring.xml file (<bean></bean>
) only when you call the .getBean() method, but whereas ApplicationContext creates the objects for all the beans (<bean></bean>
if its scope is not explicitly mentioned as "Prototype") configured in the spring.xml while loading the spring.xml file itself.
BeanFactory: (Lazy container because it creates the objects for the beans only when you explicitly call from the user/main class)
/*
* Using core Container - Lazy container - Because it creates the bean objects On-Demand
*/
//creating a resource
Resource r = (Resource) new ClassPathResource("com.spring.resources/spring.xml");
//creating BeanFactory
BeanFactory factory=new XmlBeanFactory(r);
//Getting the bean for the POJO class "HelloWorld.java"
HelloWorld worldObj1 = (HelloWorld) factory.getBean("test");
ApplicationContext: (Eager container because of creating the objects of all singleton beans while loading the spring.xml file itself)
ApplicationContext context = new ClassPathXmlApplicationContext("com/ioc/constructorDI/resources/spring.xml");
Technically, using ApplicationContext is recommended because in real-time applications, the bean objects will be created while the application is getting started in the server itself. This reduces the response time for the user request as the objects are already available to respond.
Just try this :
ArrayList<SomeClass> arrayList;
public SomeConstructor(List<SomeClass> listData) {
arrayList.addAll(listData);
}
ALTER TABLE myTable ALTER COLUMN myColumn {DataType} NULL
where {DataType}
is the current data type of that column (For example int
or varchar(10)
)
Another example. When building a complex map of maps, the computeIfAbsent() method is a replacement for map's get() method. Through chaining of computeIfAbsent() calls together, missing containers are constructed on-the-fly by provided lambda expressions:
// Stores regional movie ratings
Map<String, Map<Integer, Set<String>>> regionalMovieRatings = new TreeMap<>();
// This will throw NullPointerException!
regionalMovieRatings.get("New York").get(5).add("Boyhood");
// This will work
regionalMovieRatings
.computeIfAbsent("New York", region -> new TreeMap<>())
.computeIfAbsent(5, rating -> new TreeSet<>())
.add("Boyhood");
using json.loads
will turn your data into a python dictionary.
Dictionaries values are accessed using ['key']
resp_str = {
"name" : "ns1:timeSeriesResponseType",
"declaredType" : "org.cuahsi.waterml.TimeSeriesResponseType",
"scope" : "javax.xml.bind.JAXBElement$GlobalScope",
"value" : {
"queryInfo" : {
"creationTime" : 1349724919000,
"queryURL" : "http://waterservices.usgs.gov/nwis/iv/",
"criteria" : {
"locationParam" : "[ALL:103232434]",
"variableParam" : "[00060, 00065]"
},
"note" : [ {
"value" : "[ALL:103232434]",
"title" : "filter:sites"
}, {
"value" : "[mode=LATEST, modifiedSince=null]",
"title" : "filter:timeRange"
}, {
"value" : "sdas01",
"title" : "server"
} ]
}
},
"nil" : false,
"globalScope" : true,
"typeSubstituted" : false
}
would translate into a python diction
resp_dict = json.loads(resp_str)
resp_dict['name'] # "ns1:timeSeriesResponseType"
resp_dict['value']['queryInfo']['creationTime'] # 1349724919000
These are mostly equivalent, but import *
has some restrictions that import ... = require
doesn't.
import * as
creates an identifier that is a module object, emphasis on object. According to the ES6 spec, this object is never callable or new
able - it only has properties. If you're trying to import a function or class, you should use
import express = require('express');
or (depending on your module loader)
import express from 'express';
Attempting to use import * as express
and then invoking express()
is always illegal according to the ES6 spec. In some runtime+transpilation environments this might happen to work anyway, but it might break at any point in the future without warning, which will make you sad.
Just generate ID and check whether it is already present or not in your list of generated IDs.
If you also need to support iOS 6, you'll have to conditionally move it down. That is, in iOS 7 you should just move it down 20 points (either through frame
manipulation or using auto-layout), and in iOS 6 you leave it alone. I don't believe you can do this in IB, so you'll have to do it in code.
EDIT
You can actually do this in IB, by using the iOS6/iOS7 deltas. Set your position in iOS 7, then for iOS 6 set the delta Y to -20points. See this SO question for more information.
Maintain a list of nodes you can travel to, sorted by the distance from your start node. In the beginning only your start node will be in the list.
While you haven't reached your destination: Visit the node closest to the start node, this will be the first node in your sorted list. When you visit a node, add all its neighboring nodes to your list except the ones you have already visited. Repeat!
If you installed mysql through brew then we can use command to uninstall mysql.
$ brew uninstall mysql
Uninstalling /usr/local/Cellar/mysql/5.6.19...
This worked for me.
You can leverage the java_home
helper binary on OS X
for what you're looking for.
To list all versions of installed JDK:
$ /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
1.8.0_51, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home
1.7.0_79, x86_64: "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/Home
To request the JAVA_HOME path of a specific JDK version, you can do:
$ /usr/libexec/java_home -v 1.7
/Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/Home
$ /usr/libexec/java_home -v 1.8
/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home
You could take advantage of the above commands in your script like this:
REQUESTED_JAVA_VERSION="1.7"
if POSSIBLE_JAVA_HOME="$(/usr/libexec/java_home -v $REQUESTED_JAVA_VERSION 2>/dev/null)"; then
# Do this if you want to export JAVA_HOME
export JAVA_HOME="$POSSIBLE_JAVA_HOME"
echo "Java SDK is installed"
else
echo "Did not find any installed JDK for version $REQUESTED_JAVA_VERSION"
fi
You might be able to do if-else and check for multiple different versions of java as well.
If you prefer XML output, java_home also has a -X option to output in XML.
$ /usr/libexec/java_home --help
Usage: java_home [options...]
Returns the path to a Java home directory from the current user's settings.
Options:
[-v/--version <version>] Filter Java versions in the "JVMVersion" form 1.X(+ or *).
[-a/--arch <architecture>] Filter JVMs matching architecture (i386, x86_64, etc).
[-d/--datamodel <datamodel>] Filter JVMs capable of -d32 or -d64
[-t/--task <task>] Use the JVM list for a specific task (Applets, WebStart, BundledApp, JNI, or CommandLine)
[-F/--failfast] Fail when filters return no JVMs, do not continue with default.
[ --exec <command> ...] Execute the $JAVA_HOME/bin/<command> with the remaining arguments.
[-R/--request] Request installation of a Java Runtime if not installed.
[-X/--xml] Print full JVM list and additional data as XML plist.
[-V/--verbose] Print full JVM list with architectures.
[-h/--help] This usage information.
It is specifically mentioned in the documentation as part of Entity SQL. Are you getting an error message?
// LIKE and ESCAPE
// If an AdventureWorksEntities.Product contained a Name
// with the value 'Down_Tube', the following query would find that
// value.
Select value P.Name FROM AdventureWorksEntities.Product
as P where P.Name LIKE 'DownA_%' ESCAPE 'A'
// LIKE
Select value P.Name FROM AdventureWorksEntities.Product
as P where P.Name like 'BB%'
I think zeroclipboard is great. this version work with latest Flash 11: http://www.itjungles.com/javascript/javascript-easy-cross-browser-copy-to-clipboard-solution.
In regards to multiple arrays in an object. For instance, you want to record modules for different courses
var course = {
InfoTech:["Information Systems","Internet Programming","Software Eng"],
BusComm:["Commercial Law","Accounting","Financial Mng"],
Tourism:["Travel Destination","Travel Services","Customer Mng"]
};
console.log(course.Tourism[1]);
console.log(course.BusComm);
console.log(course.InfoTech);
will the height attribute stretch the image beyond its native resolution? If I have a image with a height of say 420 pixels, I can't get css to stretch the image beyond the native resolution to fill the height of the viewport.
I am getting pretty close results with:
.rightdiv img {
max-width: 25vw;
min-height: 100vh;
}
the 100vh is getting pretty close, with just a few pixels left over at the bottom for some reason.
There's no difference between list implementations in both of your examples. There's however a difference in a way you can further use variable myList in your code.
When you define your list as:
List myList = new ArrayList();
you can only call methods and reference members that are defined in the List interface. If you define it as:
ArrayList myList = new ArrayList();
you'll be able to invoke ArrayList-specific methods and use ArrayList-specific members in addition to those whose definitions are inherited from List.
Nevertheless, when you call a method of a List interface in the first example, which was implemented in ArrayList, the method from ArrayList will be called (because the List interface doesn't implement any methods).
That's called polymorphism. You can read up on it.
For Location runtime Permission
ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d("yes","yes");
} else {
Log.d("yes","no");
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
Console.Writeline()
shows up in the debug output (Debug => Windows => Output).
You can use:
var queryString = url.Substring(url.IndexOf('?')).Split('#')[0]
System.Web.HttpUtility.ParseQueryString(queryString)
A programmatic way can be to:
Note:
My answer is basically the same as @pi-k. In my case my program worked locally but failed to build on QA servers. (I suspect devops had older versions of the package blocked and my version must have been too out-of-date) I just decided to upgrade everything
$ pip install pip-review
$ pip-review --local --interactive
In C++ the std::string class implements the comparison operators, so you can perform the comparison using ==
just as you would expect:
if (string == "add") { ... }
When used properly, operator overloading is an excellent C++ feature.
Isn't this the same:
if ((checkbox.checked || columnname != A2) &&
columnname != a && columnname != b && columnname != c)
{
"statement 1"
}
David Brabant's answer led me to what I needed, with this addition:
x.Stuffs | where { $_.Name -eq "Darts" } | Select -ExpandProperty Type
Or, if you know the width of the two "side" images and don't want to deal with floats:
<div class="container">
<div class="left-panel"><img src="myleftimage" /></div>
<div class="center-panel">Content goes here...</div>
<div class="right-panel"><img src="myrightimage" /></div>
</div>
CSS:
.container {
position:relative;
padding-left:50px;
padding-right:50px;
}
.container .left-panel {
width: 50px;
position:absolute;
left:0px;
top:0px;
}
.container .right-panel {
width: 50px;
position:absolute;
right:0px;
top:0px;
}
.container .center-panel {
background: url('mymiddleimage');
}
Notes:
Position:relative on the parent div is used to make absolutely positioned children position themselves relative to that node.
Tip: update_attribute
is being deprecated in Rails 4 via Commit a7f4b0a1. It removes update_attribute
in favor of update_column
.
The answer which suggests something like taskkill /f /im java.exe
will probably work, but if you want to kill only one java process instead of all, I can suggest doing it with the help of window titles. Expample:
start "MyProgram" "C:/Program Files/Java/jre1.8.0_201/bin/java.exe" -jar MyProgram.jar
taskkill /F /FI "WINDOWTITLE eq MyProgram" /T
A simple example, where a change on a dropdown list triggers an ajax form-submit to reload a datagrid:
<div id="pnlSearch">
<% using (Ajax.BeginForm("UserSearch", "Home", new AjaxOptions { UpdateTargetId = "pnlSearchResults" }, new { id="UserSearchForm" }))
{ %>
UserType: <%: Html.DropDownList("FilterUserType", Model.UserTypes, "--", new { onchange = "$('#UserSearchForm').trigger('submit');" })%>
<% } %>
</div>
The trigger('onsubmit') is the key thing: it calls the onsubmit function that MVC has grafted onto the form.
NB. The UserSearchResults controller returns a PartialView that renders a table using the supplied Model
<div id="pnlSearchResults">
<% Html.RenderPartial("UserSearchResults", Model); %>
</div>
You can center a box both vertically and horizontally, using the following technique :
display: table;
display: table-cell;
vertical-align: middle;
text-align: center;
display: inline-block;
If you use this technique, just add your table (along with any other content you want to go with it) to the content box.
body {_x000D_
margin : 0;_x000D_
}_x000D_
_x000D_
.outer-container {_x000D_
position : absolute;_x000D_
display: table;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
background: #ccc;_x000D_
}_x000D_
_x000D_
.inner-container {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.centered-content {_x000D_
display: inline-block;_x000D_
background: #fff;_x000D_
padding : 20px;_x000D_
border : 1px solid #000;_x000D_
}
_x000D_
<div class="outer-container">_x000D_
<div class="inner-container">_x000D_
<div class="centered-content">_x000D_
<em>Data :</em>_x000D_
<table>_x000D_
<tr>_x000D_
<th>Name</th>_x000D_
<th>Age</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Tom</td>_x000D_
<td>15</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Anne</td>_x000D_
<td>15</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Gina</td>_x000D_
<td>34</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
See also this Fiddle!
You can use this function to get the absolute value:
+(NSNumber *)absoluteValue:(NSNumber *)input {
return [NSNumber numberWithDouble:fabs([input doubleValue])];
}
You can use jQuery's Live Query plugin. And write code as follows:
$('#contentDiv:visible').livequery(function() {
alert("do something");
});
Then everytime the contentDiv is visible, "do something" will be alerted!
f'{float(f"{i:.1g}"):g}'
# Or with Python <3.6,
'{:g}'.format(float('{:.1g}'.format(i)))
This solution is different from all of the others because:
For an arbitrary number n
of significant figures, you can use:
print('{:g}'.format(float('{:.{p}g}'.format(i, p=n))))
Test:
a = [1234, 0.12, 0.012, 0.062, 6253, 1999, -3.14, 0., -48.01, 0.75]
b = ['{:g}'.format(float('{:.1g}'.format(i))) for i in a]
# b == ['1000', '0.1', '0.01', '0.06', '6000', '2000', '-3', '0', '-50', '0.8']
Note: with this solution, it is not possible to adapt the number of significant figures dynamically from the input because there is no standard way to distinguish numbers with different numbers of trailing zeros (3.14 == 3.1400
). If you need to do so, then non-standard functions like the ones provided in the to-precision package are needed.
![image.png](attachment:image.png)
The image is actually embedded in the ipynb Notebook and you don't need to mess around with separate files. This is unfortunately not working with Jupyter-Lab (v 1.1.4) yet.
Edit: Works in JupyterLab Version 1.2.6
Another "Up Tick" for AR..., but if you don't have to use interop I would avoid it altogether. This product is actually quite interesting: http://www.clearoffice.com/ and it provides a very intuitive, fully managed, api for manipulation excel files and seems to be free. (at least for the time being) SpreadSheetGear is also excellent but pricey.
my two cents.
This problem can happen when you deploy your web application to a server, so you must check if you already installed MVC3.
Check if the folder C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 3
exists.
If it doesn't exist, you need to install it from http://www.microsoft.com/en-us/download/details.aspx?id=1491
If you wont to install you can add all DLLs locally in bin folder and add references to them this work fine if you host on server don't deploy ASP.NET Web Pages or MVC3.
All the consumers per topic
(Replace --zookeeper
with --bootstrap-server
to get groups stored by newer Kafka clients)
Get all consumers-per-topic as a table of topic
tabconsumer
:
for t in `kafka-consumer-groups.sh --zookeeper <HOST>:2181 --list 2>/dev/null`; do
echo $t | xargs -I {} sh -c "kafka-consumer-groups.sh --zookeeper <HOST>:2181 --describe --group {} 2>/dev/null | grep ^{} | awk '{print \$2\"\t\"\$1}' "
done > topic-consumer.txt
Make this pairs unique:
cat topic-consumer.txt | sort -u > topic-consumer-u.txt
Get the desired one:
less topic-consumer-u.txt | grep -i <TOPIC>
In languages like Python, I would usually use a dictionary as it involves less overhead than creating a new class.
However, if I find myself constantly returning the same set of variables, then that probably involves a new class that I'll factor out.
Will the username and password be automatically SSL encrypted? Is the same true for GETs and POSTs
Yes, yes yes.
The entire communication (save for the DNS lookup if the IP for the hostname isn't already cached) is encrypted when SSL is in use.
This is an example of how to set time in a div(only_time) using javascript.
function date_time() {
var date = new Date();
var am_pm = "AM";
var hour = date.getHours();
if(hour>=12){
am_pm = "PM";
}
if (hour == 0) {
hour = 12;
}
if(hour>12){
hour = hour - 12;
}
if(hour<10){
hour = "0"+hour;
}
var minute = date.getMinutes();
if (minute<10){
minute = "0"+minute;
}
var sec = date.getSeconds();
if(sec<10){
sec = "0"+sec;
}
document.getElementById("time").innerHTML = hour+":"+minute+":"+sec+" "+am_pm;
}
setInterval(date_time,500);
<per>
<div class="date" id="time"></div>
</per>
Here's my setup: I am on Ubuntu 9.10.
Now, Here's what I did.
Create an xml file "myapp.xml" (i guess it must have the same name as the name of the folder in step 2) inside /etc/tomcat6/Catalina/localhost with the following contents.
< Context path="/myapp" docBase="/usr/share/tomcat6-myapp/myapp" />
This xml is called the 'Deployment Descriptor' which Tomcat reads and automatically deploys your app named "myapp".
Now go to http://localhost:8080/myapp in your browser - the index.html gets picked up by tomcat and is shown.
I hope this helps!
Use the DISTINCT operator in MySQL:
SELECT DISTINCT(Date) AS Date FROM buy ORDER BY Date DESC;
Since keys are what dictionaries use to lookup values, you can't really change them. The closest thing you can do is to save the value associated with the old key, delete it, then add a new entry with the replacement key and the saved value. Several of the other answers illustrate different ways this can be accomplished.
I've been frustrated by this problem as well. Find/Replace can be helpful though, because if you don't put anything in the "replace" field it will replace with an -actual- NULL. So the steps would be something along the lines of:
1: Place some unique string in your formula in place of the NULL output (i like to use a password-like string)
2: Run your formula
3: Open Find/Replace, and fill in the unique string as the search value. Leave "replace with" blank
4: Replace All
Obviously, this has limitations. It only works when the context allows you to do a find/replace, so for more dynamic formulas this won't help much. But, I figured I'd put it up here anyway.
Solution is :-
This basically forces your PC to restart because by default it does not restart after a kernel panic.
I've been struggling with this problem trying to create a simple App for SharePoint using Provider Hosted.
After going through the applicationhost.config, in the section, basicAuthentication was set to false. I changed it to true to get past the 401.2 in my scenario. There are plenty of other links of how to find the applicationhost.config for IIS Express.
It is not stuck, it will take some time normally 5-7 mins , it also depends upon internet connection, so wait for some time. It will take time only for first launch.
Update: Check the latest log file in your C:\Users\<User>\.gradle\daemon\x.y
folder to see what it's downloading.
I wrote a directive which lets you limit the areas where a click has effect. It could be used for certain scenarios like this one, so instead of having to deal with the click on a case by case basis you can just say "clicks won't come out of this element".
You would use it like this:
<table>
<tr ng-repeat="user in users" ng-click="showUser(user)">
<td>{{user.firstname}}</td>
<td>{{user.lastname}}</td>
<td isolate-click>
<button class="btn" ng-click="deleteUser(user.id, $index);">
Delete
</button>
</td>
</tr>
</table>
Keep in mind that this would prevent all clicks on the last cell, not just the button. If that's not what you want you may want to wrap the button like this:
<span isolate-click>
<button class="btn" ng-click="deleteUser(user.id, $index);">
Delete
</button>
</span>
Here is the directive's code:
angular.module('awesome', []).directive('isolateClick', function() {
return {
link: function(scope, elem) {
elem.on('click', function(e){
e.stopPropagation();
});
}
};
});
As of Python 3.6 you can use the secrets
module, which is preferable to the random
module for cryptography or security uses.
To print a random element from a list:
import secrets
foo = ['a', 'b', 'c', 'd', 'e']
print(secrets.choice(foo))
To print a random index:
print(secrets.randbelow(len(foo)))
For details, see PEP 506.
If you can't know the progress you should not fake it by abusing a progress bar, instead just display some sort of busy icon like en.wikipedia.org/wiki/Throbber#Spinning_wheel Show it when starting the task and hide it when it's finished. That would make for a more "honest" GUI.
I think you can try this for calling in from a class
System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/");
*----------------Sorry I oversight, for static function already answered the question by adrift*
System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");
Update
I got exception while using System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");
Ex details : System.ArgumentException: The relative virtual path 'SignatureImages' is not allowed here. at System.Web.VirtualPath.FailIfRelativePath()
Solution (tested in static webmethod)
System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/");
Worked
If i have understood correct then it is one line of code .It worked for me .
Collections.reverse(yourList);
var host = req.headers['host'];
The headers are stored in a JavaScript object, with the header strings as object keys.
Likewise, the user-agent header could be obtained with
var userAgent = req.headers['user-agent'];
You can use:
UPDATE Station AS st1, StationOld AS st2
SET st1.already_used = 1
WHERE st1.code = st2.code
Can be read, "For all s such that s does not equal s[start]"
Why not do string suppression with triple quotes:
>>> s = """my string with "some" double quotes"""
>>> print s
my string with "some" double quotes
getText is a member of the your Activity so it must be called when "this" exists. Your static variable is initialized when your class is loaded before your Activity is created.
Since you want the variable to be initialized from a Resource string then it cannot be static. If you want it to be static you can initialize it with the String value.
Go to My computer -> right click -> system properties -> environmental variables -> Path -> add you jdk/bin to this path
C:\Program Files\Java\jdk1.8.0_211\bin
*if this not work then
In cmd set the path by using the below command
set PATH=C:\Program Files\Java\jdk1.8.0_211\bin
now the path is set now you can use the keytool
First parse the created_at field as Carbon object.
$createdAt = Carbon::parse($item['created_at']);
Then you can use
$suborder['payment_date'] = $createdAt->format('M d Y');
package customExceptions;
public class MyException extends Exception{
public MyException(String exc)
{
super(exc);
}
public String getMessage()
{
return super.getMessage();
}
}
import customExceptions.MyException;
public class UseCustomException {
MyException newExc=new MyException("This is a custom exception");
public UseCustomException() throws MyException
{
System.out.println("Hello Back Again with custom exception");
throw newExc;
}
public static void main(String args[])
{
try
{
UseCustomException use=new UseCustomException();
}
catch(MyException myEx)
{
System.out.println("This is my custom exception:" + myEx.getMessage());
}
}
}
try this working fine
jQuery("body").load(window.location.href);
From the working copy:
svn rm branches/features
svn commit -m "delete stale feature branch"
Here is my code-
var datePicker = angular.module('appointmentApp', []);
datePicker.directive('datepicker', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
$(element).datepicker({
dateFormat: 'dd-mm-yy',
onSelect: function (date) {
scope.appoitmentScheduleDate = date;
scope.$apply();
}
});
}
};
});
The accepted answer to this question is awesome and should remain the accepted answer. However I ran into an issue with the code where the read stream was not always being ended/closed. Part of the solution was to send autoClose: true
along with start:start, end:end
in the second createReadStream
arg.
The other part of the solution was to limit the max chunksize
being sent in the response. The other answer set end
like so:
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
...which has the effect of sending the rest of the file from the requested start position through its last byte, no matter how many bytes that may be. However the client browser has the option to only read a portion of that stream, and will, if it doesn't need all of the bytes yet. This will cause the stream read to get blocked until the browser decides it's time to get more data (for example a user action like seek/scrub, or just by playing the stream).
I needed this stream to be closed because I was displaying the <video>
element on a page that allowed the user to delete the video file. However the file was not being removed from the filesystem until the client (or server) closed the connection, because that is the only way the stream was getting ended/closed.
My solution was just to set a maxChunk
configuration variable, set it to 1MB, and never pipe a read a stream of more than 1MB at a time to the response.
// same code as accepted answer
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;
// poor hack to send smaller chunks to the browser
var maxChunk = 1024 * 1024; // 1MB at a time
if (chunksize > maxChunk) {
end = start + maxChunk - 1;
chunksize = (end - start) + 1;
}
This has the effect of making sure that the read stream is ended/closed after each request, and not kept alive by the browser.
I also wrote a separate StackOverflow question and answer covering this issue.
Yes. You just have to use the RAISE_APPLICATION_ERROR
function. If you also want to name your exception, you'll need to use the EXCEPTION_INIT
pragma in order to associate the error number to the named exception. Something like
SQL> ed
Wrote file afiedt.buf
1 declare
2 ex_custom EXCEPTION;
3 PRAGMA EXCEPTION_INIT( ex_custom, -20001 );
4 begin
5 raise_application_error( -20001, 'This is a custom error' );
6 exception
7 when ex_custom
8 then
9 dbms_output.put_line( sqlerrm );
10* end;
SQL> /
ORA-20001: This is a custom error
PL/SQL procedure successfully completed.
Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.
You can use User Accounts by pressing Window
+R
, typing netplwiz
and pressing OK as described here.
Write the function inline, and the interpreter is smart enough to know you're writing a function. Do it like this, and it assumes it's just a string (which it technically is).
There are many options how to write a regex pattern for that
^(?:(?!0)\d{1,2}|100)$
^(?:[1-9]\d?|100)$
^(?!0)(?=100$|..$|.$)\d+$
You have install nodeJs on your system in order to execute npm
commands. Once npm
is properly working you can visit bower.io
. There you will find complete documentation on this topic. You will find a command $ npm install bower
. this will install bower on your machine. After installing bower you can install Bootstrap easily.
Try this instead:
=SUM(IF(MONTH($A$2:$A$6)=1,$B$2:$B$6,0))
It's an array formula, so you will need to enter it with the Control-Shift-Enter key combination.
Here's how the formula works.
{1, 1, 1, 2, 2}
.{1, 1, 1, 2, 2}= 1
produces the array {TRUE, TRUE, TRUE, FALSE, FALSE}
, which comprises the condition for the IF statement.{430, 96, 400..
for the values of the sum ranges where the month value equals 1 and ..0,0}
where the month value does not equal 1.{430, 96, 400, 0, 0}
is then summed to get the answer you are looking for.This is essentially equivalent to what the SUMIF and SUMIFs functions do. However, neither of those functions support the kind of calculation you tried to include in the conditional.
It's also possible to drop the IF completely. Since TRUE and FALSE can also be treated as 1 and 0, this formula--=SUM((MONTH($A$2:$A$6)=1)*$B$2:$B$6)
--also works.
Heads up: This does not work in Google Spreadsheets
The difference is that in the first example, the program will block in the first line. The next line (console.log
) will have to wait.
In the second example, the console.log
will be executed WHILE the query is being processed. That is, the query will be processed in the background, while your program is doing other things, and once the query data is ready, you will do whatever you want with it.
So, in a nutshell: The first example will block, while the second won't.
The output of the following two examples:
// Example 1 - Synchronous (blocks)
var result = database.query("SELECT * FROM hugetable");
console.log("Query finished");
console.log("Next line");
// Example 2 - Asynchronous (doesn't block)
database.query("SELECT * FROM hugetable", function(result) {
console.log("Query finished");
});
console.log("Next line");
Would be:
Query finished
Next line
Next line
Query finished
Note
While Node itself is single threaded, there are some task that can run in parallel. For example, File System operations occur in a different process.
That's why Node can do async operations: one thread is doing file system operations, while the main Node thread keeps executing your javascript code. In an event-driven server like Node, the file system thread notifies the main Node thread of certain events such as completion, failure, or progress, along with any data associated with that event (such as the result of a database query or an error message) and the main Node thread decides what to do with that data.
You can read more about this here: How the single threaded non blocking IO model works in Node.js
You can divide seconds by 60 to get the minutes
import time
seconds = time.time()
minutes = seconds / 60
print(minutes)
When you divide it by 60 again, you will get the hours
How about the H2 console application?
1) Add the following line to /etc/security/limits.conf
webuser hard nofile 64000
then login as webuser
su - webuser
2) Edit following two files for webuser
append .bashrc and .bash_profile file by running
echo "ulimit -n 64000" >> .bashrc ; echo "ulimit -n 64000" >> .bash_profile
3) Log out, then log back in and verify that the changes have been made correctly:
$ ulimit -a | grep open
open files (-n) 64000
Thats it and them boom, boom boom.
Take a look at the $_GET and $_REQUEST superglobals. Something like the following would work for your example:
$start = $_GET['start'];
$limit = $_GET['limit'];
EDIT
According to this post in the laravel forums, you need to use Input::get()
, e.g.,
$start = Input::get('start');
$limit = Input::get('limit');
See also: http://laravel.com/docs/input#input
I was unable to get Pavel's answer working as in when posting to a Web.Api application.
The issue appears to be with the deleting of the headers.
headersGetter();
delete headers['Content-Type'];
In order to ensure the browsers was allowed to default the Content-Type along with the boundary parameter, I needed to set the Content-Type to undefined. Using Pavel's example the boundary was never being set resulting in a 400 HTTP exception.
The key was to remove the code deleting the headers shown above and to set the headers content type to null manually. Thus allowing the browser to set the properties.
headers: {'Content-Type': undefined}
Here is a full example.
$scope.Submit = form => {
$http({
method: 'POST',
url: 'api/FileTest',
headers: {'Content-Type': undefined},
data: {
FullName: $scope.FullName,
Email: $scope.Email,
File1: $scope.file
},
transformRequest: function (data, headersGetter) {
var formData = new FormData();
angular.forEach(data, function (value, key) {
formData.append(key, value);
});
return formData;
}
})
.success(function (data) {
})
.error(function (data, status) {
});
return false;
}
Works particularly great for Google Earth Studio images:
ffmpeg -framerate 24 -i Project%03d.png Project.mp4
You can try this
click Help>Install New Software on the menu bar
I found my issue was an improper
if (leaf = NULL) {...}
where it should have been
if (leaf == NULL){...}
Check those compiler warnings!
This is a case for banker's rounding, aka 'round half-even'. It is supported by BigDecimal. Its purpose is to ensure that rounding balances out, i.e. doesn't favour either the bank orthe customer.
I solved my background image issue using this code.
import React from 'react';
import { StyleSheet, Text, View,Alert,ImageBackground } from 'react-native';
import { TextInput,Button,IconButton,Colors,Avatar } from 'react-native-paper';
class SignInScreen extends React.Component {
state = {
UsernameOrEmail : '',
Password : '',
}
render() {
return (
<ImageBackground source={require('../assets/icons/background3.jpg')} style {styles.backgroundImage}>
<Text>React Native App</Text>
</ImageBackground>
);
}
}
export default SignInScreen;
const styles = StyleSheet.create({
backgroundImage: {
flex: 1,
resizeMode: 'cover', // or 'stretch'
}
});
If your merge was not too complicated another option would be to:
After that you are left with only the changes from the stash you dropped too early.
Try this.
class User < ActiveRecord::Base
validate do |user|
user.errors.add_to_base("Country can't be blank") if user.country_iso.blank?
end
end
I found this here.
Update for Rails 3 to 6:
validate do |user|
user.errors.add(:base, "Country can't be blank") if user.country_iso.blank?
end
Here is another way to do it. What you do is define a human_attribute_name method on the model class. The method is passed the column name as a string and returns the string to use in validation messages.
class User < ActiveRecord::Base
HUMANIZED_ATTRIBUTES = {
:email => "E-mail address"
}
def self.human_attribute_name(attr)
HUMANIZED_ATTRIBUTES[attr.to_sym] || super
end
end
The above code is from here
eldNew <- eld[-14,]
See ?"["
for a start ...
For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.
(emphasis added)
edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?
edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame
...
Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame
This is a simple copy, just like you would do with memcpy()
(indeed, some compilers actually produce a call to memcpy()
for that code). There is no "string" in C, only pointers to a bunch a chars. If your source structure contains such a pointer, then the pointer gets copied, not the chars themselves.
Here's a quick jQuery plugin to map the built in browser functionality nicely:
$.fn.ensureVisible = function () { $(this).each(function () { $(this)[0].scrollIntoView(); }); };
...
$('.my-elements').ensureVisible();
You can override setMenuVisibility like this:
@Override
public void setMenuVisibility(final boolean visible) {
if (visible) {
//Do your stuff here
}
super.setMenuVisibility(visible);
}
volatile
[About] => synchronized
synchronized
block in Java is a monitor in multithreading. synchronized
block with the same object/class can be executed by only single thread, all others are waiting. It can help with race condition
situation when several threads try to update the same variable.
Java 5
extended synchronized
by supporting happens-before
[About]
An unlock (synchronized block or method exit) of a monitor happens-before every subsequent lock (synchronized block or method entry) of that same monitor.
The next step is java.util.concurrent
You need to add a directive
, like this:
Javascript:
app.directive('myEnter', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if(event.which === 13) {
scope.$apply(function (){
scope.$eval(attrs.myEnter);
});
event.preventDefault();
}
});
};
});
HTML:
<div ng-app="" ng-controller="MainCtrl">
<input type="text" my-enter="doSomething()">
</div>
I had the same issue after I started using Xcode 6.1 and changed my launcher images. I had all images in an Asset Catalog. I would get only a black screen instead of the expected static image. After trying so many things, I realised the problem was that the Asset Catalog had the Project 'Target Membership' ticked-off in its FileInspector view. Ticking it to ON did the magic and the image started to appear on App launch.
If you are using styled-components
, you could do something like this:
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import styled from 'styled-components';
const StyledLink = styled(Link)`
text-decoration: none;
&:focus, &:hover, &:visited, &:link, &:active {
text-decoration: none;
}
`;
export default (props) => <StyledLink {...props} />;
You can also combine es6 and stateless functions to get a much cleaner result:
import Dashboard from './Dashboard';
import Comments from './Comments';
let dashboardWrapper = () => <Dashboard {...props} />,
commentsWrapper = () => <Comments {...props} />,
index = () => <div>
<header>Some header</header>
<RouteHandler />
{this.props.children}
</div>;
routes = {
component: index,
path: '/',
childRoutes: [
{
path: 'comments',
component: dashboardWrapper
}, {
path: 'dashboard',
component: commentsWrapper
}
]
}
You could make it into a module and expose your inner function by returning it in an Object.
function outer() {
function inner() {
console.log("hi");
}
return {
inner: inner
};
}
var foo = outer();
foo.inner();
The best regex, i've found is: /(^|\s)((https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)/gi
For ios swift : (^|\\s)((https?:\\/\\/)?[\\w-]+(\\.[\\w-]+)+\\.?(:\\d+)?(\\/\\S*)?)
Found here
Try:
String text= br.readLine();
while (text != null)
{
System.out.println(text);
text=br.readLine();
}
in.close();
I was doing this sort of thing for mission critical code. Like every fraction of a second counts because I need to process 180k entries in an unnoticeable amount of time. So I skipped the regex and split altogether and allowed for inline processing of each element (though adding them to an ArrayList<String>
would be fine). If you want to do this exact thing but need it to be something like 20x faster...
void parseGroups(String text) {
int last = 0;
int state = 0;
for (int i = 0, s = text.length(); i < s; i++) {
switch (text.charAt(i)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (state == 2) {
processElement(text.substring(last, i));
last = i;
}
state = 1;
break;
default:
if (state == 1) {
processElement(text.substring(last, i));
last = i;
}
state = 2;
break;
}
}
processElement(text.substring(last));
}
i got the same problem and i notice that my security config has diferent TAGS like the @Xenolion answer says
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">localhost</domain>
</domain-config>
</network-security-config>
so i change the TAGS "domain-config" for "base-config" and works, like this:
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">localhost</domain>
</base-config>
</network-security-config>
$this->load->helper('security');
$h=mysql_real_escape_string(strip_image_tags($comment));
If user inputs
<img src="#">
In the database table just insert character this #
Works for me
df.index
Index
object. list(df.index)
df.index['Row 2':'Row 5']
This might help you.
Java:
JSONArray arr = new JSONArray(result);
JSONObject jObj = arr.getJSONObject(0);
String date = jObj.getString("NeededString");
Kotlin:
val jsonArray = JSONArray(result)
val jsonObject: JSONObject = jsonArray.getJSONObject(0)
val date= jsonObject.get("NeededString")
Running:
npm install
from inside your app directory (i.e. where package.json is located) will install the dependencies for your app, rather than install it as a module, as described here. These will be placed in ./node_modules relative to your package.json file (it's actually slightly more complex than this, so check the npm docs here).
You are free to move the node_modules dir to the parent dir of your app if you want, because node's 'require' mechanism understands this. However, if you want to update your app's dependencies with install/update, npm will not see the relocated 'node_modules' and will instead create a new dir, again relative to package.json.
To prevent this, just create a symlink to the relocated node_modules from your app dir:
ln -s ../node_modules node_modules
StringBuilder sb = new StringBuilder(name);
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
return sb.toString();
I'm failing to see the problem here. The code looks good to me.
The only thing I can think of is that the try/catch blocks are redundant -- Color is a struct and R, G, and B are bytes, so c can't be null and c.R.ToString()
, c.G.ToString()
, and c.B.ToString()
can't actually fail (the only way I can see them failing is with a NullReferenceException
, and none of them can actually be null).
You could clean the whole thing up using the following:
private static String HexConverter(System.Drawing.Color c)
{
return "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
}
private static String RGBConverter(System.Drawing.Color c)
{
return "RGB(" + c.R.ToString() + "," + c.G.ToString() + "," + c.B.ToString() + ")";
}
Android will not let you do this for security concerns. An evil developer could very easily steal user-entered login information.
Instead, you have to catch the text being displayed in the webview before it is displayed. If you don't want to set up a response handler (as per the other answers), I found this fix with some googling:
URL url = new URL("https://stackoverflow.com/questions/1381617");
URLConnection con = url.openConnection();
Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
Matcher m = p.matcher(con.getContentType());
/* If Content-Type doesn't match this pre-conception, choose default and
* hope for the best. */
String charset = m.matches() ? m.group(1) : "ISO-8859-1";
Reader r = new InputStreamReader(con.getInputStream(), charset);
StringBuilder buf = new StringBuilder();
while (true) {
int ch = r.read();
if (ch < 0)
break;
buf.append((char) ch);
}
String str = buf.toString();
This is a lot of code, and you should be able to copy/paster it, and at the end of it str
will contain the same html drawn in the webview. This answer is from Simplest way to correctly load html from web page into a string in Java and it should work on Android as well. I have not tested this and did not write it myself, but it might help you out.
Also, the URL this is pulling is hardcoded, so you'll have to change that.
Yes, there's a command git commit --amend
which is used to "fix" last commit.
In your case it would be called as:
git add the_left_out_file
git commit --amend --no-edit
The --no-edit flag allow to make amendment to commit without changing commit message.
EDIT: Warning You should never amend public commits, that you already pushed to public repository, because what amend does is actually removing from history last commit and creating new commit with combined changes from that commit and new added when amending.
Both styles, with a touch of tweaking, would work.
The first method uses a Javascript Constructor, which like most things has pros and cons.
// By convention, constructors start with an upper case letter
function MakePerson(name,age) {
// The magic variable 'this' is set by the Javascript engine and points to a newly created object that is ours.
this.name = name;
this.age = age;
this.occupation = "Hobo";
}
var jeremy = new MakePerson("Jeremy", 800);
On the other hand, your other method is called the 'Revealing Closure Pattern' if I recall correctly.
function makePerson(name2, age2) {
var name = name2;
var age = age2;
return {
name: name,
age: age
};
}
I use them sometimes as a syntax hack for Map instantiation:
Map map = new HashMap() {{
put("key", "value");
}};
vs
Map map = new HashMap();
map.put("key", "value");
It saves some redundancy when doing a lot of put statements. However, I have also run into problems doing this when the outer class needs to be serialized via remoting.
DOS Print 32 bit value stored in EAX with hexadecimal output (for 80386+)
(on 64 bit OS use DOSBOX)
.code
mov ax,@DATA ; get the address of the data segment
mov ds,ax ; store the address in the data segment register
;-----------------------
mov eax,0FFFFFFFFh ; 32 bit value (0 - FFFFFFFF) for example
;-----------------------
; convert the value in EAX to hexadecimal ASCIIs
;-----------------------
mov di,OFFSET ASCII ; get the offset address
mov cl,8 ; number of ASCII
P1: rol eax,4 ; 1 Nibble (start with highest byte)
mov bl,al
and bl,0Fh ; only low-Nibble
add bl,30h ; convert to ASCII
cmp bl,39h ; above 9?
jna short P2
add bl,7 ; "A" to "F"
P2: mov [di],bl ; store ASCII in buffer
inc di ; increase target address
dec cl ; decrease loop counter
jnz P1 ; jump if cl is not equal 0 (zeroflag is not set)
;-----------------------
; Print string
;-----------------------
mov dx,OFFSET ASCII ; DOS 1+ WRITE STRING TO STANDARD OUTPUT
mov ah,9 ; DS:DX->'$'-terminated string
int 21h ; maybe redirected under DOS 2+ for output to file
; (using pipe character">") or output to printer
; terminate program...
.data
ASCII DB "00000000",0Dh,0Ah,"$" ; buffer for ASCII string
Alternative string output directly to the videobuffer without using software interupts:
;-----------------------
; Print string
;-----------------------
mov ax,0B800h ; segment address of textmode video buffer
mov es,ax ; store address in extra segment register
mov si,OFFSET ASCII ; get the offset address of the string
; using a fixed target address for example (screen page 0)
; Position`on screen = (Line_number*80*2) + (Row_number*2)
mov di,(10*80*2)+(10*2)
mov cl,8 ; number of ASCII
cld ; clear direction flag
P3: lodsb ; get the ASCII from the address in DS:SI + increase si
stosb ; write ASCII directly to the screen using ES:DI + increase di
inc di ; step over attribut byte
dec cl ; decrease counter
jnz P3 ; repeat (print only 8 ASCII, not used bytes are: 0Dh,0Ah,"$")
; Hint: this directly output to the screen do not touch or move the cursor
; but feel free to modify..
if you are using django use forloop.counter
instead of loop.counter
<ul>
{% for user in userlist %}
<li>
{{ user }} {{forloop.counter}}
</li>
{% if forloop.counter == 1 %}
This is the First user
{% endif %}
{% endfor %}
</ul>
An anonymous class is extending or implementing while creating its object For example :
Interface in = new InterFace()
{
..............
}
Here anonymous class is implementing Interface.
Class cl = new Class(){
.................
}
here anonymous Class is extending a abstract Class.
In Matplotlib lexicon, i think you want a hexbin plot.
If you're not familiar with this type of plot, it's just a bivariate histogram in which the xy-plane is tessellated by a regular grid of hexagons.
So from a histogram, you can just count the number of points falling in each hexagon, discretiize the plotting region as a set of windows, assign each point to one of these windows; finally, map the windows onto a color array, and you've got a hexbin diagram.
Though less commonly used than e.g., circles, or squares, that hexagons are a better choice for the geometry of the binning container is intuitive:
hexagons have nearest-neighbor symmetry (e.g., square bins don't, e.g., the distance from a point on a square's border to a point inside that square is not everywhere equal) and
hexagon is the highest n-polygon that gives regular plane tessellation (i.e., you can safely re-model your kitchen floor with hexagonal-shaped tiles because you won't have any void space between the tiles when you are finished--not true for all other higher-n, n >= 7, polygons).
(Matplotlib uses the term hexbin plot; so do (AFAIK) all of the plotting libraries for R; still i don't know if this is the generally accepted term for plots of this type, though i suspect it's likely given that hexbin is short for hexagonal binning, which is describes the essential step in preparing the data for display.)
from matplotlib import pyplot as PLT
from matplotlib import cm as CM
from matplotlib import mlab as ML
import numpy as NP
n = 1e5
x = y = NP.linspace(-5, 5, 100)
X, Y = NP.meshgrid(x, y)
Z1 = ML.bivariate_normal(X, Y, 2, 2, 0, 0)
Z2 = ML.bivariate_normal(X, Y, 4, 1, 1, 1)
ZD = Z2 - Z1
x = X.ravel()
y = Y.ravel()
z = ZD.ravel()
gridsize=30
PLT.subplot(111)
# if 'bins=None', then color of each hexagon corresponds directly to its count
# 'C' is optional--it maps values to x-y coordinates; if 'C' is None (default) then
# the result is a pure 2D histogram
PLT.hexbin(x, y, C=z, gridsize=gridsize, cmap=CM.jet, bins=None)
PLT.axis([x.min(), x.max(), y.min(), y.max()])
cb = PLT.colorbar()
cb.set_label('mean value')
PLT.show()
The default value of enum is the enummember equal to 0 or the first element(if value is not specified)
... But i have faced critical problems using enum in my projects and overcome by doing something below ... How ever my need was related to class level ...
class CDDtype
{
public int Id { get; set; }
public DDType DDType { get; set; }
public CDDtype()
{
DDType = DDType.None;
}
}
[DefaultValue(None)]
public enum DDType
{
None = -1,
ON = 0,
FC = 1,
NC = 2,
CC = 3
}
and get expected result
CDDtype d1= new CDDtype();
CDDtype d2 = new CDDtype { Id = 50 };
Console.Write(d1.DDType);//None
Console.Write(d2.DDType);//None
Now what if value is coming from DB .... Ok in this scenario... pass value in below function and it will convertthe value to enum ...below function handled various scenario and it's generic... and believe me it is very fast ..... :)
public static T ToEnum<T>(this object value)
{
//Checking value is null or DBNull
if (!value.IsNull())
{
return (T)Enum.Parse(typeof(T), value.ToStringX());
}
//Returanable object
object ValueToReturn = null;
//First checking whether any 'DefaultValueAttribute' is present or not
var DefaultAtt = (from a in typeof(T).CustomAttributes
where a.AttributeType == typeof(DefaultValueAttribute)
select a).FirstOrNull();
//If DefaultAttributeValue is present
if ((!DefaultAtt.IsNull()) && (DefaultAtt.ConstructorArguments.Count == 1))
{
ValueToReturn = DefaultAtt.ConstructorArguments[0].Value;
}
//If still no value found
if (ValueToReturn.IsNull())
{
//Trying to get the very first property of that enum
Array Values = Enum.GetValues(typeof(T));
//getting very first member of this enum
if (Values.Length > 0)
{
ValueToReturn = Values.GetValue(0);
}
}
//If any result found
if (!ValueToReturn.IsNull())
{
return (T)Enum.Parse(typeof(T), ValueToReturn.ToStringX());
}
return default(T);
}
You just forgot the quotes. Change your code according to this:
<button type="button" onClick = "document.getElementById('chartdiv').style.height = '200px'">Click Me!</button>
should work.
You need to fill the value for Website with Facebook Login with the value http://localhost/OfferDrive/
to allow Facebook to authenticate that the requests from JavaScript SDK are coming from right place
I use this little function for VBA.
Public Function Pause(NumberOfSeconds As Variant)
On Error GoTo Error_GoTo
Dim PauseTime As Variant
Dim Start As Variant
Dim Elapsed As Variant
PauseTime = NumberOfSeconds
Start = Timer
Elapsed = 0
Do While Timer < Start + PauseTime
Elapsed = Elapsed + 1
If Timer = 0 Then
' Crossing midnight
PauseTime = PauseTime - Elapsed
Start = 0
Elapsed = 0
End If
DoEvents
Loop
Exit_GoTo:
On Error GoTo 0
Exit Function
Error_GoTo:
Debug.Print Err.Number, Err.Description, Erl
GoTo Exit_GoTo
End Function
#include <iostream>
using namespace std ;
typedef int (*Type)[3][3] ;
Type Demo_function( Type ); //prototype
int main (){
cout << "\t\t!!!!!Passing and returning 2D array from function!!!!!\n"
int array[3][3] ;
Type recieve , ptr = &array;
recieve = Demo_function( ptr ) ;
for ( int i = 0 ; i < 3 ; i ++ ){
for ( int j = 0 ; j < 3 ; j ++ ){
cout << (*recieve)[i][j] << " " ;
}
cout << endl ;
}
return 0 ;
}
Type Demo_function( Type array ){/*function definition */
cout << "Enter values : \n" ;
for (int i =0 ; i < 3 ; i ++)
for ( int j = 0 ; j < 3 ; j ++ )
cin >> (*array)[i][j] ;
return array ;
}
I think that this happens because you are running it on source mode with the dot
. myscript.sh
You should run that in a subshell:
/full/path/to/script/myscript.sh
'source' http://ss64.com/bash/source.html
Use --build-arg
with each argument.
If you are passing two argument then add --build-arg
with each argument like:
docker build \
-t essearch/ess-elasticsearch:1.7.6 \
--build-arg number_of_shards=5 \
--build-arg number_of_replicas=2 \
--no-cache .
Another possible problem (which I ran into):
Be sure that the ProjectInstaller
class is public
. To be honest, I am not sure how exactly I did it, but I added event handlers to ProjectInstaller.Designer.cs
, like:
this.serviceProcessInstaller1.BeforeInstall += new System.Configuration.Install.InstallEventHandler(this.serviceProcessInstaller1_BeforeInstall);
I guess during the automatical process of creating the handler function in ProjectInstaller.cs
it changed the class definition from
public class ProjectInstaller : System.Configuration.Install.Installer
to
partial class ProjectInstaller : System.Configuration.Install.Installer
replacing the public
keyword with partial
. So, in order to fix it it must be
public partial class ProjectInstaller : System.Configuration.Install.Installer
I use Visual Studio 2013 Community edition.
Another option to avoid nesting two different environments (like multicols
and enumerate
).
The environment called tasks
from the package with the same name seems to me very easy to customize thanks to a variety of options (pdf guide here).
This code:
\documentclass{article}
\usepackage{tasks}
%\settasks{style=itemize}
\begin{document}
Text text text text text text text text text text text text
text text text text text text text text text text text text
text text text text text text text text text text text text.
\begin{tasks}(2)
\task[*] a
\task[*] b
\task[*] c
\task[*] d
\task[*] e
\task[*] f
\end{tasks}
Text text text text text text text text text text text text
text text text text text text text text text text text text
text text text text text text text text text text text text.
\end{document}
produces this output
The package tasks
was updated in August 2020 and it was originally created specifically for horizontally columned lists (see the screenshot just above here), the motivations behind this are resumed in the guide. If such arrangement of the items/tasks is acceptable, then this may be a good choice since it keeps - IMHO - the code tidy and flexible.
@Rynant 's solution worked for me. I had a couple of additional requirements though:
Here's what I got working (finally):
[PS script code]
& runner.bat bat_to_run.bat logfile.txt
[runner.bat]
@echo OFF
REM This script can be executed from within a powershell script so that the bat file
REM passed as %1 will not cause execution to halt if PAUSE is encountered.
REM If {logfile} is included, bat file output will be appended to logfile.
REM
REM Usage:
REM runner.bat [path of bat script to execute] {logfile}
if not [%2] == [] GOTO APPEND_OUTPUT
@echo | call %1
GOTO EXIT
:APPEND_OUTPUT
@echo | call %1 1> %2 2>&1
:EXIT
What about one of these?
object.methods.sort
Class.methods.sort
The font-min-size
and font-max-size
CSS properties were removed from the CSS Fonts Module Level 4 specification (and never implemented in browsers AFAIK). And the CSS Working Group replaced the CSS examples with font-size: clamp(...)
which doesn't have the greatest browser support yet so we'll have to wait for browsers to support it. See example in https://developer.mozilla.org/en-US/docs/Web/CSS/clamp#Examples.
One way to see the contents would be:
for my_bucket_object in my_bucket.objects.all():
print(my_bucket_object)
The previous answers have lost the first frame. And it will be nice to store the images in a folder.
# create a folder to store extracted images
import os
folder = 'test'
os.mkdir(folder)
# use opencv to do the job
import cv2
print(cv2.__version__) # my version is 3.1.0
vidcap = cv2.VideoCapture('test_video.mp4')
count = 0
while True:
success,image = vidcap.read()
if not success:
break
cv2.imwrite(os.path.join(folder,"frame{:d}.jpg".format(count)), image) # save frame as JPEG file
count += 1
print("{} images are extacted in {}.".format(count,folder))
By the way, you can check the frame rate by VLC. Go to windows -> media information -> codec details
mcilist = (from mci in mcilist select mci).Distinct().ToList();
Typing q
starts macro recording, and the recording stops when the user hits q
again.
As Joey Adams mentioned, to disable recording, add the following line to .vimrc
in your home directory:
map q <Nop>
If you want to get it aligned to the right after the text looses focus you can try to use the direction modifier. This will show the right part of the text after loosing focus. e.g. useful if you want to show the file name in a large path.
input.rightAligned {_x000D_
direction:ltr;_x000D_
overflow:hidden;_x000D_
}_x000D_
input.rightAligned:not(:focus) {_x000D_
direction:rtl;_x000D_
text-align: left;_x000D_
unicode-bidi: plaintext;_x000D_
text-overflow: ellipsis;_x000D_
}
_x000D_
<form>_x000D_
<input type="text" class="rightAligned" name="name" value="">_x000D_
</form>
_x000D_
The not selector is currently well supported : Browser support
Javacript uses short-circuit evaluation for logical operators ||
and &&
. However, it's different to other languages in that it returns the result of the last value that halted the execution, instead of a true
, or false
value.
The following values are considered falsy in JavaScript.
""
(empty string)Ignoring the operator precedence rules, and keeping things simple, the following examples show which value halted the evaluation, and gets returned as a result.
false || null || "" || 0 || NaN || "Hello" || undefined // "Hello"
The first 5 values upto NaN
are falsy so they are all evaluated from left to right, until it meets the first truthy value - "Hello"
which makes the entire expression true, so anything further up will not be evaluated, and "Hello"
gets returned as a result of the expression. Similarly, in this case:
1 && [] && {} && true && "World" && null && 2010 // null
The first 5 values are all truthy and get evaluated until it meets the first falsy value (null
) which makes the expression false, so 2010
isn't evaluated anymore, and null
gets returned as a result of the expression.
The example you've given is making use of this property of JavaScript to perform an assignment. It can be used anywhere where you need to get the first truthy or falsy value among a set of values. This code below will assign the value "Hello"
to b
as it makes it easier to assign a default value, instead of doing if-else checks.
var a = false;
var b = a || "Hello";
You could call the below example an exploitation of this feature, and I believe it makes code harder to read.
var messages = 0;
var newMessagesText = "You have " + messages + " messages.";
var noNewMessagesText = "Sorry, you have no new messages.";
alert((messages && newMessagesText) || noNewMessagesText);
Inside the alert, we check if messages
is falsy, and if yes, then evaluate and return noNewMessagesText
, otherwise evaluate and return newMessagesText
. Since it's falsy in this example, we halt at noNewMessagesText and alert "Sorry, you have no new messages."
.
The closest thing I've seen would be to set border-spacing: 0 30px;
to the container div. However, this just leaves me with space on the upper edge of the table, which defeats the purpose, since you wanted margin-bottom.
Application program interface (API) is a set of routines, protocols, and tools for building software applications. An API specifies how software components should interact and APIs are used when programming graphical user interface (GUI) components. A good API makes it easier to develop a program by providing all the building blocks. A programmer then puts the blocks together.
$(document).ready(function(){_x000D_
(function (document) {_x000D_
var input = document.getElementById("files"),_x000D_
output = document.getElementById("result"),_x000D_
fileData; // We need fileData to be visible to getBuffer._x000D_
_x000D_
// Eventhandler for file input. _x000D_
function openfile(evt) {_x000D_
var files = input.files;_x000D_
// Pass the file to the blob, not the input[0]._x000D_
fileData = new Blob([files[0]]);_x000D_
// Pass getBuffer to promise._x000D_
var promise = new Promise(getBuffer);_x000D_
// Wait for promise to be resolved, or log error._x000D_
promise.then(function(data) {_x000D_
// Here you can pass the bytes to another function._x000D_
output.innerHTML = data.toString();_x000D_
console.log(data);_x000D_
}).catch(function(err) {_x000D_
console.log('Error: ',err);_x000D_
});_x000D_
}_x000D_
_x000D_
/* _x000D_
Create a function which will be passed to the promise_x000D_
and resolve it when FileReader has finished loading the file._x000D_
*/_x000D_
function getBuffer(resolve) {_x000D_
var reader = new FileReader();_x000D_
reader.readAsArrayBuffer(fileData);_x000D_
reader.onload = function() {_x000D_
var arrayBuffer = reader.result_x000D_
var bytes = new Uint8Array(arrayBuffer);_x000D_
resolve(bytes);_x000D_
}_x000D_
}_x000D_
_x000D_
// Eventlistener for file input._x000D_
input.addEventListener('change', openfile, false);_x000D_
}(document));_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<input type="file" id="files"/>_x000D_
<div id="result"></div>_x000D_
</body>_x000D_
</html>
_x000D_
So here i understand you're trying to break out of the outer if code block
if some_condition:
...
if condition_a:
# do something
# and then exit the outer if block
...
if condition_b:
# do something
# and then exit the outer if block
# more code here
One way out of this is that you can test for for a false condition in the outer if block, which will then implicitly exit out of the code block, you then use an else block to nest the other ifs to do something
if test_for_false:
# Exit the code(which is the outer if code)
else:
if condition_a:
# Do something
if condition_b:
# Do something
Get path from URI Use below class for android all version. access any type of File.
package com.satya.filemangerdemo.common;
import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.text.TextUtils;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;
public class FileUtils {
private static Uri contentUri = null;
/**
* Get a file path from a Uri. This will get the the path for Storage Access
* Framework Documents, as well as the _data field for the MediaStore and
* other file-based ContentProviders.<br>
* <br>
* Callers should check whether the path is local before assuming it
* represents a local file.
*
* @param context The context.
* @param uri The Uri to query.
*/
@SuppressLint("NewApi")
public static String getPath(final Context context, final Uri uri) {
// check here to KITKAT or new version
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
String selection = null;
String[] selectionArgs = null;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
String fullPath = getPathFromExtSD(split);
if (fullPath != "") {
return fullPath;
} else {
return null;
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
final String id;
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, new String[]{MediaStore.MediaColumns.DISPLAY_NAME}, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
String fileName = cursor.getString(0);
String path = Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName;
if (!TextUtils.isEmpty(path)) {
return path;
}
}
} finally {
if (cursor != null)
cursor.close();
}
id = DocumentsContract.getDocumentId(uri);
if (!TextUtils.isEmpty(id)) {
if (id.startsWith("raw:")) {
return id.replaceFirst("raw:", "");
}
String[] contentUriPrefixesToTry = new String[]{
"content://downloads/public_downloads",
"content://downloads/my_downloads"
};
for (String contentUriPrefix : contentUriPrefixesToTry) {
try {
final Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
/* final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));*/
return getDataColumn(context, contentUri, null, null);
} catch (NumberFormatException e) {
//In Android 8 and Android P the id is not a number
return uri.getPath().replaceFirst("^/document/raw:", "").replaceFirst("^raw:", "");
}
}
}
} else {
final String id = DocumentsContract.getDocumentId(uri);
final boolean isOreo = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O;
if (id.startsWith("raw:")) {
return id.replaceFirst("raw:", "");
}
try {
contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
} catch (NumberFormatException e) {
e.printStackTrace();
}
if (contentUri != null) {
return getDataColumn(context, contentUri, null, null);
}
}
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
selection = "_id=?";
selectionArgs = new String[]{split[1]};
return getDataColumn(context, contentUri, selection,
selectionArgs);
} else if (isGoogleDriveUri(uri)) {
return getDriveFilePath(uri, context);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
if (isGooglePhotosUri(uri)) {
return uri.getLastPathSegment();
}
if (isGoogleDriveUri(uri)) {
return getDriveFilePath(uri, context);
}
if( Build.VERSION.SDK_INT == Build.VERSION_CODES.N)
{
// return getFilePathFromURI(context,uri);
return getMediaFilePathForN(uri, context);
// return getRealPathFromURI(context,uri);
}else
{
return getDataColumn(context, uri, null, null);
}
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Check if a file exists on device
*
* @param filePath The absolute file path
*/
private static boolean fileExists(String filePath) {
File file = new File(filePath);
return file.exists();
}
/**
* Get full file path from external storage
*
* @param pathData The storage type and the relative path
*/
private static String getPathFromExtSD(String[] pathData) {
final String type = pathData[0];
final String relativePath = "/" + pathData[1];
String fullPath = "";
// on my Sony devices (4.4.4 & 5.1.1), `type` is a dynamic string
// something like "71F8-2C0A", some kind of unique id per storage
// don't know any API that can get the root path of that storage based on its id.
//
// so no "primary" type, but let the check here for other devices
if ("primary".equalsIgnoreCase(type)) {
fullPath = Environment.getExternalStorageDirectory() + relativePath;
if (fileExists(fullPath)) {
return fullPath;
}
}
// Environment.isExternalStorageRemovable() is `true` for external and internal storage
// so we cannot relay on it.
//
// instead, for each possible path, check if file exists
// we'll start with secondary storage as this could be our (physically) removable sd card
fullPath = System.getenv("SECONDARY_STORAGE") + relativePath;
if (fileExists(fullPath)) {
return fullPath;
}
fullPath = System.getenv("EXTERNAL_STORAGE") + relativePath;
if (fileExists(fullPath)) {
return fullPath;
}
return fullPath;
}
private static String getDriveFilePath(Uri uri, Context context) {
Uri returnUri = uri;
Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
/*
* Get the column indexes of the data in the Cursor,
* * move to the first row in the Cursor, get the data,
* * and display it.
* */
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
String name = (returnCursor.getString(nameIndex));
String size = (Long.toString(returnCursor.getLong(sizeIndex)));
File file = new File(context.getCacheDir(), name);
try {
InputStream inputStream = context.getContentResolver().openInputStream(uri);
FileOutputStream outputStream = new FileOutputStream(file);
int read = 0;
int maxBufferSize = 1 * 1024 * 1024;
int bytesAvailable = inputStream.available();
//int bufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
final byte[] buffers = new byte[bufferSize];
while ((read = inputStream.read(buffers)) != -1) {
outputStream.write(buffers, 0, read);
}
Log.e("File Size", "Size " + file.length());
inputStream.close();
outputStream.close();
Log.e("File Path", "Path " + file.getPath());
Log.e("File Size", "Size " + file.length());
} catch (Exception e) {
Log.e("Exception", e.getMessage());
}
return file.getPath();
}
private static String getMediaFilePathForN(Uri uri, Context context) {
Uri returnUri = uri;
Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
/*
* Get the column indexes of the data in the Cursor,
* * move to the first row in the Cursor, get the data,
* * and display it.
* */
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
String name = (returnCursor.getString(nameIndex));
String size = (Long.toString(returnCursor.getLong(sizeIndex)));
File file = new File(context.getFilesDir(), name);
try {
InputStream inputStream = context.getContentResolver().openInputStream(uri);
FileOutputStream outputStream = new FileOutputStream(file);
int read = 0;
int maxBufferSize = 1 * 1024 * 1024;
int bytesAvailable = inputStream.available();
//int bufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
final byte[] buffers = new byte[bufferSize];
while ((read = inputStream.read(buffers)) != -1) {
outputStream.write(buffers, 0, read);
}
Log.e("File Size", "Size " + file.length());
inputStream.close();
outputStream.close();
Log.e("File Path", "Path " + file.getPath());
Log.e("File Size", "Size " + file.length());
} catch (Exception e) {
Log.e("Exception", e.getMessage());
}
return file.getPath();
}
private static String getDataColumn(Context context, Uri uri,
String selection, String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection,
selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri - The Uri to check.
* @return - Whether the Uri authority is ExternalStorageProvider.
*/
private static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri - The Uri to check.
* @return - Whether the Uri authority is DownloadsProvider.
*/
private static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri - The Uri to check.
* @return - Whether the Uri authority is MediaProvider.
*/
private static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* @param uri - The Uri to check.
* @return - Whether the Uri authority is Google Photos.
*/
private static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is Google Drive.
*/
private static boolean isGoogleDriveUri(Uri uri) {
return "com.google.android.apps.docs.storage".equals(uri.getAuthority()) || "com.google.android.apps.docs.storage.legacy".equals(uri.getAuthority());
}
}
For the absolute coordinates of any jquery element I wrote this function, it probably doesnt work for all css position types but maybe its a good start for someone ..
function AbsoluteCoordinates($element) {
var sTop = $(window).scrollTop();
var sLeft = $(window).scrollLeft();
var w = $element.width();
var h = $element.height();
var offset = $element.offset();
var $p = $element;
while(typeof $p == 'object') {
var pOffset = $p.parent().offset();
if(typeof pOffset == 'undefined') break;
offset.left = offset.left + (pOffset.left);
offset.top = offset.top + (pOffset.top);
$p = $p.parent();
}
var pos = {
left: offset.left + sLeft,
right: offset.left + w + sLeft,
top: offset.top + sTop,
bottom: offset.top + h + sTop,
}
pos.tl = { x: pos.left, y: pos.top };
pos.tr = { x: pos.right, y: pos.top };
pos.bl = { x: pos.left, y: pos.bottom };
pos.br = { x: pos.right, y: pos.bottom };
//console.log( 'left: ' + pos.left + ' - right: ' + pos.right +' - top: ' + pos.top +' - bottom: ' + pos.bottom );
return pos;
}
Use: INT(11)
.
MySQL indexes will be able to parse through an int list fastest.
Use: BINARY(x)
, or BLOB(x)
.
You can store security tokens, etc., as hex directly in BINARY(x) or BLOB(x). To retrieve from binary
-type, use SELECT HEX(field)...
or SELECT ... WHERE field = UNHEX("ABCD....")
.
Use: DATETIME
, DATE
, or TIME
.
Always use DATETIME
if you need to store both date and time (instead of a pair of fields), as a DATETIME
indexing is more amenable to date-comparisons in MySQL.
Use: BIT(1)
(MySQL 8-only.) Otherwise, use BOOLEAN(1)
.
BOOLEAN
is actually just an alias of TINYINT(1)
, which actually stores 0 to 255 (not exactly a true/false, is it?).
Use: INT(11)
.
VARCHAR or other types of fields won't work with the SUM()
, etc., functions.
Use: TEXT.
Max limit is 65,535.
Use: MEDIUMTEXT.
Max limit is 16,777,215.
Use: LONGTEXT.
Max limit is 4,294,967,295.
Use : VARCHAR(255)
.
UTF-8 characters can take up three characters per visible character, and some cultures do not distinguish firstname and lastname. Additionally, cultures may have disagreements about which name is first and which name is last. You should name these fields Person.GivenName
and Person.FamilyName
.
Use : VARCHAR(256)
.
The definition of an e-mail path is set in RFC821 in 1982. The maximum limit of an e-mail was set by RFC2821 in 2001, and these limits were kept unchanged by RFC5321 in 2008. (See the section: 4.5.3.1. Size Limits and Minimums.) RFC3696, published 2004, mistakenly cites the email address limit as 320
characters, but this was an "info-only" RFC that explicitly "defines no standards" according to its intro, so disregard it.
Use: VARCHAR(255)
.
You never know when the phone number will be in the form of "1800...", or "1-800", or "1-(800)", or if it will end with "ext. 42", or "ask for susan".
Use: VARCHAR(10)
.
You'll get data like 12345
or 12345-6789
. Use validation to cleanse this input.
Use: VARCHAR(2000)
.
Official standards support URL's much longer than this, but few modern browsers support URL's over 2,000 characters. See this SO answer: What is the maximum length of a URL in different browsers?
Use: DECIMAL(11,2)
.
It goes up to 11.
You should use ()
to group your boolean vector to remove ambiguity.
df = df[(df['closing_price'] >= 99) & (df['closing_price'] <= 101)]
Revisiting this question a few years later, UglifyJS, seems to be the best option as of now.
As stated below, it runs on the NodeJS platform, but can be easily modified to run on any JavaScript engine.
--- Old answer below---
Google released Closure Compiler which seems to be generating the smallest files so far as seen here and here
Previous to that the various options were as follow
Basically Packer does a better job at initial compression , but if you are going to gzip the files before sending on the wire (which you should be doing) YUI Compressor gets the smallest final size.
The tests were done on jQuery code btw.
@daniel james mentions in the comment compressorrater which shows Packer leading the chart in best compression, so I guess ymmv
I couldn't find an off-the-shelf module that added this function, so I wrote one:
In Access, go to the Database Tools ribbon, in the Macro area click into Visual Basic. In the top left Project area, right click the name of your file and select Insert -> Module. In the module paste this:
Public Function Substring_Index(strWord As String, strDelim As String, intCount As Integer) As String
Substring_Index = delims
start = 0
test = ""
For i = 1 To intCount
oldstart = start + 1
start = InStr(oldstart, strWord, strDelim)
Substring_Index = Mid(strWord, oldstart, start - oldstart)
Next i
End Function
Save the module as module1 (the default). You can now use statements like:
SELECT Substring_Index([fieldname],",",2) FROM table
it's the same as think the next:
"starting with i = 0, while i is less than 8, and adding one to i at the end of the parenthesis, do the instructions between brackets"
It's also the same as:
while( i < 8 )
{
// instrucctions like:
Console.WriteLine(i);
i++;
}
the For sentences is a basis of coding, and it's as useful as necessary its understanding.
It's the way to repeat n-times the same instrucction, or browse ( or do something with each element) an array
To remove the default focus, use the following in your default .css file :
:focus {outline:none;}
You can then control the focus border color either individually by element, or in the default .css:
:focus {outline:none;border:1px solid red}
Obviously replace red
with your chosen hex code.
You could also leave the border untouched and control the background color (or image) to highlight the field:
:focus {outline:none;background-color:red}
:-)
If you use mongoose, you can just use(assuming you're using subdocuments and population):
Profile.findById profileId
.select 'friends'
.exec (err, profile) ->
if err or not profile
handleError err, profile, res
else
Status.find { profile: { $in: profile.friends } }, (err, statuses) ->
if err
handleErr err, statuses, res
else
res.json createJSON statuses
It retrieves Statuses
which belong to one of Profile
(profileId
) friends. Friends is array of references to other Profiles
. Profile
schema with friends
defined:
schema = new mongoose.Schema
# ...
friends: [
type: mongoose.Schema.Types.ObjectId
ref: 'Profile'
unique: true
index: true
]
Apple provides a macro to help provide better code compatibility, including Swift. Using the macro looks like this.
typedef NS_ENUM(NSInteger, PlayerStateType) {
PlayerStateOff,
PlayerStatePlaying,
PlayerStatePaused
};
http://rusanu.com/2006/01/30/how-long-should-i-expect-alter-databse-set-enable_broker-to-run/
alter database [<dbname>] set enable_broker with rollback immediate;
A lot of people come to this page with the goal of finding the webpack config and files in order to add their own configuration to them. Another way to achieve this without running npm run eject
is to use react-app-rewired. This allows you to overwrite your webpack config file without ejecting.
A practical example using a jQuery example might be
var today = new Date();
$('#'+[today.getMonth()+1, today.getDate(), today.getFullYear()].join("_")).whatever();
I do that in a calendar tool that I am using, this way on the page load, I can do certain things with today's date.
Found this great table at http://wiki.python.org/moin/MovingToPythonFromOtherLanguages
Python indexes and slices for a six-element list.
Indexes enumerate the elements, slices enumerate the spaces between the elements.
Index from rear: -6 -5 -4 -3 -2 -1 a=[0,1,2,3,4,5] a[1:]==[1,2,3,4,5]
Index from front: 0 1 2 3 4 5 len(a)==6 a[:5]==[0,1,2,3,4]
+---+---+---+---+---+---+ a[0]==0 a[:-2]==[0,1,2,3]
| a | b | c | d | e | f | a[5]==5 a[1:2]==[1]
+---+---+---+---+---+---+ a[-1]==5 a[1:-1]==[1,2,3,4]
Slice from front: : 1 2 3 4 5 : a[-2]==4
Slice from rear: : -5 -4 -3 -2 -1 :
b=a[:]
b==[0,1,2,3,4,5] (shallow copy of a)
Using an empty string is perfectly fine and actually much safer than simply using $_SERVER['PHP_SELF']
.
When using $_SERVER['PHP_SELF']
it is very easy to inject malicious data by simply appending /<script>...
after the whatever.php
part of the URL so you should not use this method and stop using any PHP tutorial that suggests it.
This example selects a new Range
of Cells
defined by the current cell to a cell 5 to the right.
Note that .Offset
takes arguments of Offset(row, columns)
and can be quite useful.
Sub testForStackOverflow()
Range(ActiveCell, ActiveCell.Offset(0, 5)).Copy
End Sub
This will match up to the first occurrence only in each string and will ignore subsequent occurrences.
/^([^;]*);*/
My problem was, that the SDK Tools updated it to the latest version, in my case it was 1.0.0-alpha9, but in my gradle dependency was set to
compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha8' So, you can change your gradle build file to
compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha9' Or you check "Show package details" in the SDK Tools Editor and install your needed version. See screenshow below. Image of SDK Tools
CURRENT_DATE
and CURRENT_TIMESTAMP
return the current date and time in the session time zone.
SYSDATE
and SYSTIMESTAMP
return the system date and time - that is, of the system on which the database resides.
If your client session isn't in the same timezone as the server the database is on (or says it isn't anyway, via your NLS settings), mixing the SYS*
and CURRENT_*
functions will return different values. They are all correct, they just represent different things. It looks like your server is (or thinks it is) in a +4:00 timezone, while your client session is in a +4:30 timezone.
You might also see small differences in the time if the clocks aren't synchronised, which doesn't seem to be an issue here.
Using the latest 7.x Tomcat (currently 7.0.69) solved the problem for me.
We did also try a workaround in a old eclipse bug, maybe that did it's part to solve the problem, too?
https://bugs.eclipse.org/bugs/show_bug.cgi?id=67414
Workaround:
Yes it is, and you can also use it like this
<button>Click here to<br/> start playing</button>
if you want to make the break yourself.
There is a pure JavaSript way that is not depended on any stacks:
const blobToBase64 = blob => {
const reader = new FileReader();
reader.readAsDataURL(blob);
return new Promise(resolve => {
reader.onloadend = () => {
resolve(reader.result);
};
});
};
For using this helper function you should set a callback, example:
blobToBase64(blobData).then(res => {
// do what you wanna do
console.log(res); // res is base64 now
});
I write this helper function for my problem on React Native project, I wanted to download an image and then store it as a cached image:
fetch(imageAddressAsStringValue)
.then(res => res.blob())
.then(blobToBase64)
.then(finalResult => {
storeOnMyLocalDatabase(finalResult);
});
On a Galaxy S7 and Windows 10 laptop, all I had to do whilst connected to the computer was change the USB connection mode to "Audio Source" (Phone Settings > Developer Options > USB Configuration).
This then immediately came up with the on-device prompt to allow the RSA key fingerprint. Then the dev tools on computer recognised my device.
Why this works I do not know, however it is by far the simplest of solutions, and without the need for installing unnecessary software.
I have also had some luck changing it to "MTP (Media Transfer Protocol)" mode too, but only on occasion.
Edit:
The MTP option no longer works for me.
In addition to Audio Source, setting the connection mode to MIDI also works. It is alot easier to change the connection mode by accessing it straight from the device's notification bar - Tap the "Transferring media files via USB" or the equivalent notification.
Using MIDI is probably the easiest of the two since it doesn't require going into several setting screens to access it.
As Sotirios Delimanolis already pointed out in the comments, there are two options:
ResponseEntity
with error messageChange your method like this:
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity getUser(@RequestHeader(value="Access-key") String accessKey,
@RequestHeader(value="Secret-key") String secretKey) {
try {
// see note 1
return ResponseEntity
.status(HttpStatus.CREATED)
.body(this.userService.chkCredentials(accessKey, secretKey, timestamp));
}
catch(ChekingCredentialsFailedException e) {
e.printStackTrace(); // see note 2
return ResponseEntity
.status(HttpStatus.FORBIDDEN)
.body("Error Message");
}
}
Note 1: You don't have to use the ResponseEntity
builder but I find it helps with keeping the code readable. It also helps remembering, which data a response for a specific HTTP status code should include. For example, a response with the status code 201 should contain a link to the newly created resource in the Location
header (see Status Code Definitions). This is why Spring offers the convenient build method ResponseEntity.created(URI)
.
Note 2: Don't use printStackTrace()
, use a logger instead.
@ExceptionHandler
Remove the try-catch block from your method and let it throw the exception. Then create another method in a class annotated with @ControllerAdvice
like this:
@ControllerAdvice
public class ExceptionHandlerAdvice {
@ExceptionHandler(ChekingCredentialsFailedException.class)
public ResponseEntity handleException(ChekingCredentialsFailedException e) {
// log exception
return ResponseEntity
.status(HttpStatus.FORBIDDEN)
.body("Error Message");
}
}
Note that methods which are annotated with @ExceptionHandler
are allowed to have very flexible signatures. See the Javadoc for details.
I got this message after removing two files from the SRC library, and when I brought them back I kept seeing this error message.
My solution was: Restart Eclipse. Since then I haven't seen this message again :-)
I tried
kill -9 $(ps -A -ostat,ppid | grep -e '[zZ]'| awk '{ print $2 }')
and it works for me.
CSVReader reader = new CSVReader(new FileReader(
"myfile.csv"));
try {
List<String[]> myEntries = reader.readAll();
for (String[] s : myEntries) {
for(String ss : s) {
System.out.print(", " + ss);
}
}
} catch (IOException e) {
e.printStackTrace();
}
If you set your executable dir dependencies in ProjectProperties>Debugging>Environment, the paths are stored in '.user' files.
Suppose I set this string in above-mentioned field: "PATH=C:\xyz\bin" This is how it will get stored in '.user' file:
<LocalDebuggerEnvironment>PATH=C:\xyz\bin$(LocalDebuggerEnvironment)</LocalDebuggerEnvironment>
This helped us a lot while working in OpenCV. We could use different versions of OpenCV for different projects. Another advantage is, it was very easy to set up our projects on a new machine. We just had to copy corresponding dependency dirs. So for some projects, I prefer to add the '.user' to source control.
Even though, it is entirely dependent on projects. You can take a call based on your needs.
You have to just check whether your WAMP server is online or not.
To put your WAMP server online, follow these steps.
And you are DONE...
you can use "Line1<br>Line2"
You can use readonly
attribute, if you want your input only to be read. And you can use disabled
attribute, if you want input to be shown, but totally disabled (even processing languages like PHP wont be able to read those).
Use the CREATE TABLE SELECT syntax.
http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html
CREATE TABLE new_tbl SELECT * FROM orig_tbl;