df = pd.DataFrame({'A':['a', 'b', 'c'], 'B':[54, 67, 89]}, index=[100, 200, 300])
df
A B
100 a 54
200 b 67
300 c 89
In [19]:
df.loc[100]
Out[19]:
A a
B 54
Name: 100, dtype: object
In [20]:
df.iloc[0]
Out[20]:
A a
B 54
Name: 100, dtype: object
In [24]:
df2 = df.set_index([df.index,'A'])
df2
Out[24]:
B
A
100 a 54
200 b 67
300 c 89
In [25]:
df2.ix[100, 'a']
Out[25]:
B 54
Name: (100, a), dtype: int64
use document.activeElement.blur();
example at http://jsfiddle.net/vGGdV/5/ that shows the currently focused element as well.
Keep a note though that calling blur()
on the body element in IE will make the IE lose focus
Yes it is possible depending on what css you have, you simply just declare the same thing with a different background like this
ul li {
background: none !important;
}
ul li{
background: blue !important;
}
But you have to make sure the declaration comes after the first one seeing as it is cascading.
You can also create a style tag in jQuery like this
$('head').append('<style> #an-element li { background: inherit !important;} </style>');
You cannot see any changes because it's not inheriting any background but it is overwriting the background: none;
I had the same error message. For me changing pooling=False
to ;pooling=true;Max Pool Size=200
in the connection string fixed the problem.
I searched for some good themes across internet and found nothing. So I ported selected controls of GTK Hybrid theme. It's MIT licensed and you can find it here:
https://github.com/stil/candyshop
It's not enterprise grade style and probably has some flaws, but I use it in my personal projects.
Simply this works!
// Set the array pointer to the last key
end($array);
// Store the last key
$lastkey = key($array);
foreach($array as $key => $element) {
....do array stuff
if ($lastkey === key($array))
echo 'THE LAST ELEMENT! '.$array[$lastkey];
}
Thank you @billynoah for your sorting out the end issue.
Well, for starters, you might not wanna overuse echo, because (as is the problem in your case) you can very easily make mistakes on quotation marks.
This would fix your problem:
echo "<a href=\"http://www.whatever.com/$param\">Click Here</a>";
but you should really do this
<?php
$param = "test";
?>
<a href="http://www.whatever.com/<?php echo $param; ?>">Click Here</a>
For Logging your request and response you need an interceptor and also for setting the header you need an interceptor, Here's the solution for adding both the interceptor at once using retrofit 2.1
public OkHttpClient getHeader(final String authorizationValue ) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okClient = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.addNetworkInterceptor(
new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request request = null;
if (authorizationValue != null) {
Log.d("--Authorization-- ", authorizationValue);
Request original = chain.request();
// Request customization: add request headers
Request.Builder requestBuilder = original.newBuilder()
.addHeader("Authorization", authorizationValue);
request = requestBuilder.build();
}
return chain.proceed(request);
}
})
.build();
return okClient;
}
Now in your retrofit object add this header in the client
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.client(getHeader(authorizationValue))
.addConverterFactory(GsonConverterFactory.create())
.build();
As you are aware, everything passed as email message has to be textualized.
<img />
tag is sufficient (the url of the image must be linked to a Source ID).A Typical email example will look like this:
From: foo1atbar.net
To: foo2atbar.net
Subject: A simple example
Mime-Version: 1.0
Content-Type: multipart/related; boundary="boundary-example"; type="text/html"
--boundary-example
Content-Type: text/html; charset="US-ASCII"
... text of the HTML document, which might contain a URI
referencing a resource in another body part, for example
through a statement such as:
<IMG SRC="cid:foo4atfoo1atbar.net" ALT="IETF logo">
--boundary-example
Content-Location: CID:somethingatelse ; this header is disregarded
Content-ID: <foo4atfoo1atbar.net>
Content-Type: IMAGE/GIF
Content-Transfer-Encoding: BASE64
R0lGODlhGAGgAPEAAP/////ZRaCgoAAAACH+PUNv
cHlyaWdodCAoQykgMTk5LiBVbmF1dGhvcml6ZWQgZHV
wbGljYXRpb24gcHJvaGliaXRlZC4A etc...
--boundary-example--
As you can see, the Content-ID: <foo4atfoo1atbar.net>
ID is matched to the <IMG>
at SRC="cid:foo4atfoo1atbar.net"
. That way, the client browser will render your image as a content and not as an attachement.
Hope this helps.
This is the modern browser way, without 3rd party libraries. Works on all the latest browsers.
app.directive('myDirective', function (httpPostFactory) {
return {
restrict: 'A',
scope: true,
link: function (scope, element, attr) {
element.bind('change', function () {
var formData = new FormData();
formData.append('file', element[0].files[0]);
httpPostFactory('upload_image.php', formData, function (callback) {
// recieve image name to use in a ng-src
console.log(callback);
});
});
}
};
});
app.factory('httpPostFactory', function ($http) {
return function (file, data, callback) {
$http({
url: file,
method: "POST",
data: data,
headers: {'Content-Type': undefined}
}).success(function (response) {
callback(response);
});
};
});
HTML:
<input data-my-Directive type="file" name="file">
PHP:
if (isset($_FILES['file']) && $_FILES['file']['error'] == 0) {
// uploads image in the folder images
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = substr(md5(time()), 0, 10) . '.' . end($temp);
move_uploaded_file($_FILES['file']['tmp_name'], 'images/' . $newfilename);
// give callback to your angular code with the image src name
echo json_encode($newfilename);
}
js fiddle (only front-end) https://jsfiddle.net/vince123/8d18tsey/31/
I have try a lot with different approaches. And finally, I improve one of the methods. First you need to create a separate collection and save there all events. Second you need to create a new lambda to be triggered by time. This lambda will Count events in event collection and clear event documents. Code details in article. https://medium.com/@ihor.malaniuk/how-to-count-documents-in-google-cloud-firestore-b0e65863aeca
The legend titles can be labeled by specific aesthetic.
This can be achieved using the guides()
or labs()
functions from ggplot2
(more here and here). It allows you to add guide/legend properties using the aesthetic mapping.
Here's an example using the mtcars
data set and labs()
:
ggplot(mtcars, aes(x=mpg, y=disp, size=hp, col=as.factor(cyl), shape=as.factor(gear))) +
geom_point() +
labs(x="miles per gallon", y="displacement", size="horsepower",
col="# of cylinders", shape="# of gears")
Answering the OP's question using guides()
:
# transforming the data from wide to long
require(reshape2)
dfm <- melt(df, id="TY")
# creating a scatterplot
ggplot(data = dfm, aes(x=TY, y=value, color=variable)) +
geom_point(size=5) +
labs(title="Temperatures\n", x="TY [°C]", y="Txxx") +
scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
theme_bw() +
guides(color=guide_legend("my title")) # add guide properties by aesthetic
Yes you just need to install the other version of python, and define the location of your other version of python in your command like :
virtualenv /home/payroll/Documents/env -p /usr/bin/python3
Here is an example of sending back a pdf.
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
header('Content-Transfer-Encoding: binary');
readfile($filename);
@Swish I didn't find application/force-download content type to do anything different (tested in IE and Firefox). Is there a reason for not sending back the actual MIME type?
Also in the PHP manual Hayley Watson posted:
If you wish to force a file to be downloaded and saved, instead of being rendered, remember that there is no such MIME type as "application/force-download". The correct type to use in this situation is "application/octet-stream", and using anything else is merely relying on the fact that clients are supposed to ignore unrecognised MIME types and use "application/octet-stream" instead (reference: Sections 4.1.4 and 4.5.1 of RFC 2046).
Also according IANA there is no registered application/force-download type.
“Android target: not installed”
Please install Android target / API level: "android-25".
You need to create an Android Virtual Device (API level: "android-25" or latest) or need to add android real device.
Also you can import the project in Android Studio and run.
You can check here:
https://cordova.apache.org/docs/en/latest/guide/platforms/android/index.html
#pragma mark
directives show up in Xcode in the menus for direct access to methods. They have no impact on the program at all.
For example, using it with Xcode 4 will make those items appear directly in the Jump Bar.
There is a special pragma mark -
which creates a line.
Note the guidelines for performing work on a UI thread, collected on my blog:
There are two techniques you should use:
1) Use ConfigureAwait(false)
when you can.
E.g., await MyAsync().ConfigureAwait(false);
instead of await MyAsync();
.
ConfigureAwait(false)
tells the await
that you do not need to resume on the current context (in this case, "on the current context" means "on the UI thread"). However, for the rest of that async
method (after the ConfigureAwait
), you cannot do anything that assumes you're in the current context (e.g., update UI elements).
For more information, see my MSDN article Best Practices in Asynchronous Programming.
2) Use Task.Run
to call CPU-bound methods.
You should use Task.Run
, but not within any code you want to be reusable (i.e., library code). So you use Task.Run
to call the method, not as part of the implementation of the method.
So purely CPU-bound work would look like this:
// Documentation: This method is CPU-bound.
void DoWork();
Which you would call using Task.Run
:
await Task.Run(() => DoWork());
Methods that are a mixture of CPU-bound and I/O-bound should have an Async
signature with documentation pointing out their CPU-bound nature:
// Documentation: This method is CPU-bound.
Task DoWorkAsync();
Which you would also call using Task.Run
(since it is partially CPU-bound):
await Task.Run(() => DoWorkAsync());
String runtimeVersion = System.getProperty("java.runtime.version");
should return you a string along the lines of:
1.5.0_01-b08
That's the version of Java that Eclipse is using to run your code which is not necessarily the same version that's being used to run Eclipse itself.
This phpMyAdmin query is returning those rows, that are NOT null or empty or just whitespaces:
SELECT * FROM `table_name` WHERE NOT ((`column_name` IS NULL) OR (TRIM(`column_name`) LIKE ''))
if you want to select rows that are null/empty/just whitespaces just remove NOT.
not only --install
,
also need --dbpath
and --logpath
and after reboot OS you need to delete "mongod.lock" manually
This is a BAD way to do it! I'm only leaving this answer in case it solves other weird problems. These better methods are the probably partly the result of newer data.table versions... so it's worth while to document this hard way. Plus, this is a nice syntax example for eval
substitute
syntax.
library(data.table)
dt <- data.table(ID = c(rep("A", 5), rep("B",5)),
fac1 = c(1:5, 1:5),
fac2 = c(1:5, 1:5) * 2,
val1 = rnorm(10),
val2 = rnorm(10))
names_factors = c('fac1', 'fac2')
names_values = c('val1', 'val2')
for (col in names_factors){
e = substitute(X := as.factor(X), list(X = as.symbol(col)))
dt[ , eval(e)]
}
for (col in names_values){
e = substitute(X := as.numeric(X), list(X = as.symbol(col)))
dt[ , eval(e)]
}
str(dt)
which gives you
Classes ‘data.table’ and 'data.frame': 10 obs. of 5 variables:
$ ID : chr "A" "A" "A" "A" ...
$ fac1: Factor w/ 5 levels "1","2","3","4",..: 1 2 3 4 5 1 2 3 4 5
$ fac2: Factor w/ 5 levels "2","4","6","8",..: 1 2 3 4 5 1 2 3 4 5
$ val1: num 0.0459 2.0113 0.5186 -0.8348 -0.2185 ...
$ val2: num -0.0688 0.6544 0.267 -0.1322 -0.4893 ...
- attr(*, ".internal.selfref")=<externalptr>
Quite simple with the latest version of Visual Studio Code, if you have installed the official Python extension for Visual Studio Code:
Shift + Command + P
Type: Python: Select Interpreter
Choose your virtual environment.
For Database first Aproach:
We can still set it in a constructor, by override the ContextName.Context.tt T4 Template this way:
<#=Accessibility.ForType(container)#> partial class <#=code.Escape(container)#> : DbContext
{
public <#=code.Escape(container)#>()
: base("name=<#=container.Name#>")
{
Database.CommandTimeout = 180;
<#
if (!loader.IsLazyLoadingEnabled(container))
{
#>
this.Configuration.LazyLoadingEnabled = false;
<#
}
Database.CommandTimeout = 180;
is the acutaly change.
The generated output is this:
public ContextName() : base("name=ContextName")
{
Database.CommandTimeout = 180;
}
If you change your Database Model, this template stays, but the actualy class will be updated.
Can you parse /etc/passwd?
e.g.:
cat /etc/passwd | awk -F: '{printf "User %s Home %s\n", $1, $6}'
I got this error today whilst trying to initiate a slide effect on a div. Thanks to the answer from 'I Hate Lazy' above (which I've upvoted), I went looking for a custom jQuery UI script, and you can in fact build your own file directly on the jQuery ui website http://jqueryui.com/download/. All you have to do is mark the effect(s) that you're looking for and then download.
I was looking for the slide effect. So I first unchecked all the checkboxes, then clicked on the 'slide effect' checkbox and the page automatically then checks those other components necessary to make the slide effect work. Very simple.
easeOutBounce is an easing effect, for which you'll need to check the 'Effects Core' checkbox.
I think the easiest way to return a row with the maximum value is by getting its index. argmax()
can be used to return the index of the row with the largest value.
index = df.Value.argmax()
Now the index could be used to get the features for that particular row:
df.iloc[df.Value.argmax(), 0:2]
What you missed is " "
in postcode because it is a varchar
.
There are two ways of inserting.
When you created a table Table created.
and you add a row just after creating it, you can use the following method.
INSERT INTO table_name
VALUES (value1,value2,value3,...);
1 row created.
You've added so many tables, or it is saved and you are reopening it, you need to mention the table's column name too or else it will display the same error.
ERROR at line 2:
ORA-00984: column not allowed here
INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);
1 row created.
C++17 inline
variables
This awesome C++17 feature allow us to:
constexpr
: How to declare constexpr extern?main.cpp
#include <cassert>
#include "notmain.hpp"
int main() {
// Both files see the same memory address.
assert(¬main_i == notmain_func());
assert(notmain_i == 42);
}
notmain.hpp
#ifndef NOTMAIN_HPP
#define NOTMAIN_HPP
inline constexpr int notmain_i = 42;
const int* notmain_func();
#endif
notmain.cpp
#include "notmain.hpp"
const int* notmain_func() {
return ¬main_i;
}
Compile and run:
g++ -c -o notmain.o -std=c++17 -Wall -Wextra -pedantic notmain.cpp
g++ -c -o main.o -std=c++17 -Wall -Wextra -pedantic main.cpp
g++ -o main -std=c++17 -Wall -Wextra -pedantic main.o notmain.o
./main
See also: How do inline variables work?
C++ standard on inline variables
The C++ standard guarantees that the addresses will be the same. C++17 N4659 standard draft 10.1.6 "The inline specifier":
6 An inline function or variable with external linkage shall have the same address in all translation units.
cppreference https://en.cppreference.com/w/cpp/language/inline explains that if static
is not given, then it has external linkage.
Inline variable implementation
We can observe how it is implemented with:
nm main.o notmain.o
which contains:
main.o:
U _GLOBAL_OFFSET_TABLE_
U _Z12notmain_funcv
0000000000000028 r _ZZ4mainE19__PRETTY_FUNCTION__
U __assert_fail
0000000000000000 T main
0000000000000000 u notmain_i
notmain.o:
0000000000000000 T _Z12notmain_funcv
0000000000000000 u notmain_i
and man nm
says about u
:
"u" The symbol is a unique global symbol. This is a GNU extension to the standard set of ELF symbol bindings. For such a symbol the dynamic linker will make sure that in the entire process there is just one symbol with this name and type in use.
so we see that there is a dedicated ELF extension for this.
C++17 standard draft on "global" const
implies static
This is the quote for what was mentioned at: https://stackoverflow.com/a/12043198/895245
C++17 n4659 standard draft 6.5 "Program and linkage":
3 A name having namespace scope (6.3.6) has internal linkage if it is the name of
- (3.1) — a variable, function or function template that is explicitly declared static; or,
- (3.2) — a non-inline variable of non-volatile const-qualified type that is neither explicitly declared extern nor previously declared to have external linkage; or
- (3.3) — a data member of an anonymous union.
"namespace" scope is what we colloquially often refer to as "global".
Annex C (informative) Compatibility, C.1.2 Clause 6: "basic concepts" gives the rationale why this was changed from C:
6.5 [also 10.1.7]
Change: A name of file scope that is explicitly declared const, and not explicitly declared extern, has internal linkage, while in C it would have external linkage.
Rationale: Because const objects may be used as values during translation in C++, this feature urges programmers to provide an explicit initializer for each const object. This feature allows the user to put const objects in source files that are included in more than one translation unit.
Effect on original feature: Change to semantics of well-defined feature.
Difficulty of converting: Semantic transformation.
How widely used: Seldom.
See also: Why does const imply internal linkage in C++, when it doesn't in C?
Tested in GCC 7.4.0, Ubuntu 18.04.
Open app.config on client side and add maxBufferSize and maxReceivedMessageSize attributes if it is not available
Original
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="Service1Soap"/>
</basicHttpBinding>
</bindings>
After Edit/Update
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="Service1Soap" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"/>
</basicHttpBinding>
</bindings>
As of Python 3.5 you can simply do:
from pathlib import Path
Path(__file__).stem
See more here: https://docs.python.org/3.5/library/pathlib.html#pathlib.PurePath.stem
For example, I have a file under my user directory named test.py
with this inside:
from pathlib import Path
print(Path(__file__).stem)
print(__file__)
running this outputs:
>>> python3.6 test.py
test
test.py
Try this one: https://github.com/tantau-horia/jquery-SuperCookie
Quick Usage:
create - create cookie
check - check existance
verify - verify cookie value if JSON
check_index - verify if index exists in JSON
read_values - read cookie value as string
read_JSON - read cookie value as JSON object
read_value - read value of index stored in JSON object
replace_value - replace value from a specified index stored in JSON object
remove_value - remove value and index stored in JSON object
Just use:
$.super_cookie().create("name_of_the_cookie",name_field_1:"value1",name_field_2:"value2"});
$.super_cookie().read_json("name_of_the_cookie");
This is my nginx config file and iosocket code. Server(express) is listening on port 9191. It works well: nginx config file:
server {
listen 443 ssl;
server_name localhost;
root /usr/share/nginx/html/rdist;
location /user/ {
proxy_pass http://localhost:9191;
}
location /api/ {
proxy_pass http://localhost:9191;
}
location /auth/ {
proxy_pass http://localhost:9191;
}
location / {
index index.html index.htm;
if (!-e $request_filename){
rewrite ^(.*)$ /index.html break;
}
}
location /socket.io/ {
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_pass http://localhost:9191/socket.io/;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
ssl_certificate /etc/nginx/conf.d/sslcert/xxx.pem;
ssl_certificate_key /etc/nginx/conf.d/sslcert/xxx.key;
}
Server:
const server = require('http').Server(app)
const io = require('socket.io')(server)
io.on('connection', (socket) => {
handleUserConnect(socket)
socket.on("disconnect", () => {
handleUserDisConnect(socket)
});
})
server.listen(9191, function () {
console.log('Server listening on port 9191')
})
Client(react):
const socket = io.connect('', { secure: true, query: `userId=${this.props.user._id}` })
socket.on('notifications', data => {
console.log('Get messages from back end:', data)
this.props.mergeNotifications(data)
})
This worked for me:
for div in mydivs:
try:
clazz = div["class"]
except KeyError:
clazz = ""
if (clazz == "stylelistrow"):
print div
Yes, just format your strings in the standard String.format()
way.
See the method Context.getString(int, Object...)
and the Android or Java Formatter
documentation.
In your case, the string definition would be:
<string name="timeFormat">%1$d minutes ago</string>
If I've understood this right, bootstrap provides a CSS class for just this case. Add 'pull-right' to the menu 'ul':
<ul class="dropdown-menu pull-right">
..and the end result is that the menu options appear right-aligned, in line with the button they drop down from.
select FOUND_ROWS();
will return no. of records selected by select query.
You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.
Pick an encoding and stick with it:
f.write(printinfo.encode('utf8') + '\n')
or use io.open()
to create a file object that'll encode for you as you write to the file:
import io
f = io.open(filename, 'w', encoding='utf8')
You may want to read:
Pragmatic Unicode by Ned Batchelder
The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) by Joel Spolsky
before continuing.
You can return json in PHP this way:
header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;
URL url = new URL(yourUrl, "/api/v1/status.xml");
According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:
URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");
Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html
This SQL request works for me :
ALTER TABLE users
CHANGE COLUMN `id` `id` INT(11) NOT NULL AUTO_INCREMENT ;
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
Be carefull that the page does not contain any empty component which has "required" attribute as "true" before your selectOneMenu component running.
If you use a component such as
<p:inputText label="Nm:" id="id_name" value="#{ myHelper.name}" required="true"/>
then,
<p:selectOneMenu .....></p:selectOneMenu>
and forget to fill the required component, ajax listener of selectoneMenu cannot be executed.
This is because the inline style display:block
is overwriting your CSS. You'll need to either remove this inline style or use:
#tfl {
display: none !important;
}
This overrides inline styles. Note that using !important
is generally not recommended unless it's a last resort.
The text 'dasda' will never not be within a tag, right? Semantically and to be valid HTML it as to be, just add the clear class to that:
You can try
WebElement navigationPageButton = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("navigationPageButton")));
navigationPageButton.click();
It's not immediately obvious from the documentation why the following does not work:
<span style={font-size: 1.7} class="glyphicon glyphicon-remove-sign"></span>
But when doing it entirely inline:
"em"
class
is className
The correct way looks like this:
<span style={{fontSize: 1.7 + "em"}} className="glyphicon glyphicon-remove-sign"></span>
cursor.execute(sql,array)
Only takes two arguments.
It will iterate the "array"-object and match ? in the sql-string.
(with sanity checks to avoid sql-injection)
You can use the count method in hbase to count the number of rows. But yes, counting rows of a large table can be slow.count 'tablename' [interval]
Return value is the number of rows.
This operation may take a LONG time (Run ‘$HADOOP_HOME/bin/hadoop jar hbase.jar rowcount’ to run a counting mapreduce job). Current count is shown every 1000 rows by default. Count interval may be optionally specified. Scan caching is enabled on count scans by default. Default cache size is 10 rows. If your rows are small in size, you may want to increase this parameter.
Examples:
hbase> count 't1'
hbase> count 't1', INTERVAL => 100000
hbase> count 't1', CACHE => 1000
hbase> count 't1', INTERVAL => 10, CACHE => 1000
The same commands also can be run on a table reference. Suppose you had a reference to table 't1', the corresponding commands would be:
hbase> t.count
hbase> t.count INTERVAL => 100000
hbase> t.count CACHE => 1000
hbase> t.count INTERVAL => 10, CACHE => 1000
Intent i = new Intent(this,Here is your first activity.Class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
both HTML5 and Google Gears add local storage capabilities, mainly by an embedded SQLite API.
For Bootstrap 3, this variation on the answers above makes the mobile slideUp()
animation smoother; the answers above have choppy animation because Bootstrap removes the .open
class from the toggle's parent immediately, so this code restores the class until the slideUp()
animation is finished.
// Add animations to topnav dropdowns
// based on https://stackoverflow.com/a/19339162
// and https://stackoverflow.com/a/52231970
$('.dropdown')
.on('show.bs.dropdown', function() {
$(this).find('.dropdown-menu').first().stop(true, true).slideDown(300);
})
.on('hide.bs.dropdown', function() {
$(this).find('.dropdown-menu').first().stop(true, false).slideUp(300, function() {
$(this).parent().removeClass('open');
});
})
.on('hidden.bs.dropdown', function() {
$(this).addClass('open');
});
Key differences:
hide.bs.dropdown
event handler I'm using .stop()
's default value (false
) for its second argument (jumpToEnd
)hidden.bs.dropdown
event handler restores the .open
class to the dropdown toggle's parent, and it does this pretty much immediately after the class has been first removed. Meanwhile the slideUp()
animation is still running, and just like in the answers above, its "the-animation-is-completed" callback is responsible for finally removing the .open
class from its parent.Java is a compiled programming language, but rather than compile straight to executable machine code, it compiles to an intermediate binary form called JVM byte code. The byte code is then compiled and/or interpreted to run the program.
One has pretty much control on which information from the traceback to be displayed/logged when catching exceptions.
The code
with open("not_existing_file.txt", 'r') as text:
pass
would produce the following traceback:
Traceback (most recent call last):
File "exception_checks.py", line 19, in <module>
with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
As others already mentioned, you can catch the whole traceback by using the traceback module:
import traceback
try:
with open("not_existing_file.txt", 'r') as text:
pass
except Exception as exception:
traceback.print_exc()
This will produce the following output:
Traceback (most recent call last):
File "exception_checks.py", line 19, in <module>
with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
You can achieve the same by using logging:
try:
with open("not_existing_file.txt", 'r') as text:
pass
except Exception as exception:
logger.error(exception, exc_info=True)
Output:
__main__: 2020-05-27 12:10:47-ERROR- [Errno 2] No such file or directory: 'not_existing_file.txt'
Traceback (most recent call last):
File "exception_checks.py", line 27, in <module>
with open("not_existing_file.txt", 'r') as text:
FileNotFoundError: [Errno 2] No such file or directory: 'not_existing_file.txt'
You might not be interested in the whole traceback, but only in the most important information, such as Exception name and Exception message, use:
try:
with open("not_existing_file.txt", 'r') as text:
pass
except Exception as exception:
print("Exception: {}".format(type(exception).__name__))
print("Exception message: {}".format(exception))
Output:
Exception: FileNotFoundError
Exception message: [Errno 2] No such file or directory: 'not_existing_file.txt'
Turns out it is possible to enter a host name directly into the playbook, so running the playbook with hosts: imac-2.local
will work fine. But it's kind of clunky.
A better solution might be defining the playbook's hosts using a variable, then passing in a specific host address via --extra-vars
:
# file: user.yml (playbook)
---
- hosts: '{{ target }}'
user: ...
Running the playbook:
ansible-playbook user.yml --extra-vars "target=imac-2.local"
If {{ target }}
isn't defined, the playbook does nothing. A group from the hosts file can also be passed through if need be. Overall, this seems like a much safer way to construct a potentially destructive playbook.
Playbook targeting a single host:
$ ansible-playbook user.yml --extra-vars "target=imac-2.local" --list-hosts
playbook: user.yml
play #1 (imac-2.local): host count=1
imac-2.local
Playbook with a group of hosts:
$ ansible-playbook user.yml --extra-vars "target=office" --list-hosts
playbook: user.yml
play #1 (office): host count=3
imac-1.local
imac-2.local
imac-3.local
Forgetting to define hosts is safe!
$ ansible-playbook user.yml --list-hosts
playbook: user.yml
play #1 ({{target}}): host count=0
Go to php.exe located folder.
C:\wamp\bin\php\php5.5.12\
open cmd there, and execute below command.
php -r "readfile('https://getcomposer.org/installer');" | php
composer.phar
will be downloaded in same folder.
Create folder named composer
in C://
drive (or anywhere you wish, for upcoming steps, remember the path).
move composer.phar
file to C://composer
folder.
Create composer.bat
file in same folder with contents below
@ECHO OFF
php "%~dp0composer.phar" %*
create file named composer
without any extensions.
running command type NUL > composer
in CMD will help to get it done quickly,
Open that file and place below contents inside it.
#!/bin/sh
dir=$(d=$(dirname "$0"); cd "$d" && pwd)
# see if we are running in cygwin by checking for cygpath program
if command -v 'cygpath' >/dev/null 2>&1; then
# cygwin paths start with /cygdrive/ which will break windows PHP,
# so we need to translate the dir path to windows format. However
# we could be using cygwin PHP which does not require this, so we
# test if the path to PHP starts with /cygdrive/ rather than /usr/bin.
if [[ $(which php) == /cygdrive/* ]]; then
dir=$(cygpath -m $dir);
fi
fi
dir=$(echo $dir | sed 's/ /\ /g')
php "${dir}/composer.phar" $*
Save.
Now set path
, So we can access composer from cmd.
Show Desktop.
Right Click My Computer shortcut in the desktop.
Click Properties.
You should see a section of control Panel - Control Panel\System and Security\System.
Click Advanced System Settings on the Left menu.
Click Environment Variables towards the bottom of the window.
Select PATH in the user variables list.
Append your PHP Path (C:\composer) to your PATH variable, separated from the already existing string by a semi colon.
Click OK
Restart your machine.
Or, restart explorer
only using below command in CMD.
taskkill /f /IM explorer.exe
start explorer.exe
exit
Original Article with screenshots here : http://aslamise.blogspot.com/2015/07/installing-composer-manually-in-windows-7-using-cmd.html
So let's say after getMasterData servlet will response.sendRedirect to to test.jsp.
In test.jsp
Create a javascript
<script type="text/javascript">
function alertName(){
alert("Form has been submitted");
}
</script>
and than at the bottom
<script type="text/javascript"> window.onload = alertName; </script>
Note:im not sure how to type the code in stackoverflow!. Edit: I just learned how to
Edit 2: TO the question:This works perfectly. Another question. How would I get rid of the initial alert when I first start up the JSP? "Form has been submitted" is present the second I execute. It shows up after the load is done to which is perfect.
To do that i would highly recommendation to use session!
So what you want to do is in your servlet:
session.setAttribute("getAlert", "Yes");//Just initialize a random variable.
response.sendRedirect(test.jsp);
than in the test.jsp
<%
session.setMaxInactiveInterval(2);
%>
<script type="text/javascript">
var Msg ='<%=session.getAttribute("getAlert")%>';
if (Msg != "null") {
function alertName(){
alert("Form has been submitted");
}
}
</script>
and than at the bottom
<script type="text/javascript"> window.onload = alertName; </script>
So everytime you submit that form a session will be pass on! If session is not null the function will run!
I just ran into this problem today. It turned out that a bug on the server (null pointer exception) was causing it to fail in creating a response, yet it still generated an HTTP status code of 200. Because of the 200 status code, Chrome expected a valid response. The first thing that Chrome did was to look for the 'Access-Control-Allow-Origin' header, which it did not find. Chrome then cancelled the request, and Angular gave me an error. The bug during processing the POST request is the reason why the OPTIONS would succeed, but the POST would fail.
In short, if you see this error, it may be that your server didn't return any headers at all in response to the POST request.
Instead of
null,
use CustomerDTO customers =
new CustomerDTO()`;
CustomerDTO customer = null;
private static List<Author> getAllAuthors() {
initConnection();
List<Author> authors = new ArrayList<Author>();
Author author = new Author();
try {
stmt = (Statement) conn.createStatement();
String str = "SELECT * FROM author";
rs = (ResultSet) stmt.executeQuery(str);
while (rs.next()) {
int id = rs.getInt("nAuthorId");
String name = rs.getString("cAuthorName");
author.setnAuthorId(id);
author.setcAuthorName(name);
authors.add(author);
System.out.println(author.getnAuthorId() + " - " + author.getcAuthorName());
}
rs.close();
closeConnection();
} catch (Exception e) {
System.out.println(e);
}
return authors;
}
I wrote how to write LaTeX in Jupyter Notebook in this article.
You need to enclose them in dollar($) signs.
$P(A)=\frac{n(A)}{n(U)}$
$$P(A)=\frac{n(A)}{n(U)}$$
Use \limits
for \lim
, \sum
and \int
to add limits to the top and the bottom of each sign.
Use a backslash to escape LaTeX special words such as Math symbols, Latin words, text, etc.
Try this one.
$$\overline{x}=\frac{\sum \limits _{i=1} ^k f_i x_i}{n} \text{, where } n=\sum \limits _{i=1} ^k f_i $$
$$
\begin{align}
\text{Probability density function:}\\
\begin{cases}
\frac{1}{b-a}&\text{for $x\in[a,b]$}\\
0&\text{otherwise}\\
\end{cases}
\\
\text{Cumulative distribution function:}\\
\begin{cases}
0&\text{for $x<a$}\\
\frac{x-a}{b-a}&\text{for $x\in[a,b)$}\\
1&\text{for $x\ge b$}\\
\end{cases}
\end{align}
$$
The above code will create this.
If you want to know how to add numbering to equations and align equations, please read this article for details.
Yes a correct sign()
function should be at least in the math module - as it is in numpy. Because one frequently needs it for math oriented code.
But math.copysign()
is also useful independently.
cmp()
and obj.__cmp__()
... have generally high importance independently. Not just for math oriented code. Consider comparing/sorting tuples, date objects, ...
The dev arguments at http://bugs.python.org/issue1640 regarding the omission of math.sign()
are odd, because:
-NaN
sign(nan) == nan
without worry (like exp(nan)
)sign(-0.0) == sign(0.0) == 0
without worrysign(-inf) == -1
without worry-- as it is in numpy
This is not possible. Linux permissions and windows permissions do not translate. They are machine specific. It would be a security hole to allow permissions to be set on files before they even arrive on the target system.
The easiest way (Worked for me) is to do the following:
anaconda search -t conda xgboost
You will get a list of install-able features like this:
for example if you want to install the first one on the list mndrake/xgboost (FOR WINDOWS-64bits):
conda install -c mndrake xgboost
If you're in a Unix system you can choose any other package with "linux-64" on the right.
Without searching in conda list of channels, you can install it using (source: https://anaconda.org/anaconda/py-xgboost) :
conda install -c anaconda py-xgboost
The problem is that you are passing a nullable type to a non-nullable type.
You can do any of the following solution:
A. Declare your dt
as nullable
DateTime? dt = dateTime;
B. Use Value
property of the the DateTime? datetime
DateTime dt = datetime.Value;
C. Cast it
DateTime dt = (DateTime) datetime;
Everything is cool, man. The 'u' is a good thing, it indicates that the string is of type Unicode in python 2.x.
http://docs.python.org/2/howto/unicode.html#the-unicode-type
Object to array
$array = (array) $players_Obj;
$object = new StdClass;
$object->foo = 1;
$object->bar = 2;
var_dump( (array) $object );
Output:
array(2) {
'foo' => int(1)
'bar' => int(2)
}
I'd like to make some changes: In C, you can use the built in qsort command:
int compare( const void* a, const void* b)
{
int int_a = * ( (int*) a );
int int_b = * ( (int*) b );
// an easy expression for comparing
return (int_a > int_b) - (int_a < int_b);
}
qsort( a, 6, sizeof(int), compare )
If you just want to kill any/all java processes, then all you need is;
killall java
If, however, you want to kill the wskInterface process in particular, then you're most of the way there, you just need to strip out the process id;
PID=`ps -ef | grep wskInterface | awk '{ print $2 }'`
kill -9 $PID
Should do it, there is probably an easier way though...
I believe java gleans this from the environment variables in which it was launched, so you'll need to make sure your LANG and LC_* environment variables are set appropriately.
The locale manpage has full info on said environment variables.
I found two plugins for that. One loads the values from a file and the other lets you configure the values in the job configuration screen.
Envfile Plugin — This plugin enables you to set environment variables via a file. The file's format must be the standard Java property file format.
EnvInject Plugin — This plugin makes it possible to add environment variables and execute a setup script in order to set up an environment for the Job.
Your return function is in line of def function(main function), you must give one tab to it. And Use
%%debug
instead of
%debug
to debug the whole cell not only line. Hope, maybe this will help you.
My users are allowed to upload CSV files and text/csv
and application/csv
did not appear by now. These are the ones identified through finfo():
text/plain
text/x-csv
And these are the ones transmitted through the browser:
text/plain
application/vnd.ms-excel
text/x-csv
The following types did not appear, but could:
application/csv
application/x-csv
text/csv
text/comma-separated-values
text/x-comma-separated-values
text/tab-separated-values
In the accepted answer, for Laravel 4 the headers array is constructed incorrectly. Use:
$headers = array(
'Content-Type' => 'application/pdf',
);
For a way to easily add hosts you trust at runtime without throwing out all checks, try the code here: http://code.google.com/p/self-signed-cert-trust-manager/.
In Django, a one-to-many relationship is called ForeignKey. It only works in one direction, however, so rather than having a number
attribute of class Dude
you will need
class Dude(models.Model):
...
class PhoneNumber(models.Model):
dude = models.ForeignKey(Dude)
Many models can have a ForeignKey
to one other model, so it would be valid to have a second attribute of PhoneNumber
such that
class Business(models.Model):
...
class Dude(models.Model):
...
class PhoneNumber(models.Model):
dude = models.ForeignKey(Dude)
business = models.ForeignKey(Business)
You can access the PhoneNumber
s for a Dude
object d
with d.phonenumber_set.objects.all()
, and then do similarly for a Business
object.
While I respect the answer from qkrijger explaining how you can work around this issue I think there is a lot more we can learn about what's going on here ...
To actually answer your question of "why" ... I think it would for helpful for you to understand how the docker stop
command works and that all processes should be shutdown cleanly to prevent problems when you try to restart them (file corruption etc).
Problem: What if docker did start SSH from it's command and started RabbitMQ from your Docker file? "The docker stop command attempts to stop a running container first by sending a SIGTERM signal to the root process (PID 1) in the container." Which process is docker tracking as PID 1 that will get the SIGTERM? Will it be SSH or Rabbit?? "According to the Unix process model, the init process -- PID 1 -- inherits all orphaned child processes and must reap them. Most Docker containers do not have an init process that does this correctly, and as a result their containers become filled with zombie processes over time."
Answer: Docker simply takes that last CMD as the one that will get launched as the root process with PID 1 and get the SIGTERM from docker stop
.
Suggested solution: You should use (or create) a base image specifically made for running more than one service, such as phusion/baseimage
It should be important to note that tini exists exactly for this reason, and as of Docker 1.13 and up, tini is officially part of Docker, which tells us that running more than one process in Docker IS VALID .. so even if someone claims to be more skilled regarding Docker, and insists that you absurd for thinking of doing this, know that you are not. There are perfectly valid situations for doing so.
Good to know:
Not directly, no. But you could use a site, such as colorschemedesigner.com, that will give you your base color and then give you the hex and rgb codes for different ranges of your base color.
Once I find my color schemes for my site, I put the hex codes for the colors and name them inside a comment section at the top of my stylesheet.
Some other color scheme generators include:
This post has inspired me to try the jQuery ui menu.
<ul id="nav">
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
<li><a href="#">Item 3</a>
<ul>
<li><a href="#">Item 3-1</a>
<ul>
<li><a href="#">Item 3-11</a></li>
<li><a href="#">Item 3-12</a></li>
<li><a href="#">Item 3-13</a></li>
</ul>
</li>
<li><a href="#">Item 3-2</a></li>
<li><a href="#">Item 3-3</a></li>
<li><a href="#">Item 3-4</a></li>
<li><a href="#">Item 3-5</a></li>
</ul>
</li>
<li><a href="#">Item 4</a></li>
<li><a href="#">Item 5</a></li>
</ul>
.ui-menu {
overflow: hidden;
}
.ui-menu .ui-menu {
overflow: visible !important;
}
.ui-menu > li {
float: left;
display: block;
width: auto !important;
}
.ui-menu ul li {
display:block;
float:none;
}
.ui-menu ul li ul {
left:120px !important;
width:100%;
}
.ui-menu ul li ul li {
width:auto;
}
.ui-menu ul li ul li a {
float:left;
}
.ui-menu > li {
margin: 5px 5px !important;
padding: 0 0 !important;
}
.ui-menu > li > a {
float: left;
display: block;
clear: both;
overflow: hidden;
}
.ui-menu .ui-menu-icon {
margin-top: 0.3em !important;
}
.ui-menu .ui-menu .ui-menu li {
float: left;
display: block;
}
$( "#nav" ).menu({position: {at: "left bottom"}});
<ul id="nav">
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
<li><a href="#">Item 3</a>
<ul>
<li><a href="#">Item 3-1</a>
<ul>
<li><a href="#">Item 3-11</a></li>
<li><a href="#">Item 3-12</a></li>
<li><a href="#">Item 3-13</a></li>
</ul>
</li>
<li><a href="#">Item 3-2</a></li>
<li><a href="#">Item 3-3</a></li>
<li><a href="#">Item 3-4</a></li>
<li><a href="#">Item 3-5</a></li>
</ul>
</li>
<li><a href="#">Item 4</a></li>
<li><a href="#">Item 5</a></li>
</ul>
.ui-menu { list-style:none; padding: 2px; margin: 0; display:block; outline: none; }
.ui-menu .ui-menu { margin-top: -3px; position: absolute; }
.ui-menu .ui-menu-item {
display: inline-block;
float: left;
margin: 0;
padding: 0;
width: auto;
}
.ui-menu .ui-menu-divider { margin: 5px -2px 5px -2px; height: 0; font-size: 0; line-height: 0; border-width: 1px 0 0 0; }
.ui-menu .ui-menu-item a { text-decoration: none; display: block; padding: 2px .4em; line-height: 1.5; zoom: 1; font-weight: normal; }
.ui-menu .ui-menu-item a.ui-state-focus,
.ui-menu .ui-menu-item a.ui-state-active { font-weight: normal; margin: -1px; }
.ui-menu .ui-state-disabled { font-weight: normal; margin: .4em 0 .2em; line-height: 1.5; }
.ui-menu .ui-state-disabled a { cursor: default; }
.ui-menu:after {
content: ".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
$( "#nav" ).menu({position: {at: "left bottom"}});
To make the dump to a source code control system that little bit faster, you can see which objects have changed since last time by using the version information in sysobjects.
Setup: Create a table in each database you want to check incrementally to hold the version information from the last time you checked it (empty on the first run). Clear this table if you want to re-scan your whole data structure.
IF ISNULL(OBJECT_ID('last_run_sysversions'), 0) <> 0 DROP TABLE last_run_sysversions
CREATE TABLE last_run_sysversions (
name varchar(128),
id int, base_schema_ver int,
schema_ver int,
type char(2)
)
Normal running mode: You can take the results from this sql, and generate sql scripts for just the ones you're interested in, and put them into a source control of your choice.
IF ISNULL(OBJECT_ID('tempdb.dbo.#tmp'), 0) <> 0 DROP TABLE #tmp
CREATE TABLE #tmp (
name varchar(128),
id int, base_schema_ver int,
schema_ver int,
type char(2)
)
SET NOCOUNT ON
-- Insert the values from the end of the last run into #tmp
INSERT #tmp (name, id, base_schema_ver, schema_ver, type)
SELECT name, id, base_schema_ver, schema_ver, type FROM last_run_sysversions
DELETE last_run_sysversions
INSERT last_run_sysversions (name, id, base_schema_ver, schema_ver, type)
SELECT name, id, base_schema_ver, schema_ver, type FROM sysobjects
-- This next bit lists all differences to scripts.
SET NOCOUNT OFF
--Renamed.
SELECT 'renamed' AS ChangeType, t.name, o.name AS extra_info, 1 AS Priority
FROM sysobjects o INNER JOIN #tmp t ON o.id = t.id
WHERE o.name <> t.name /*COLLATE*/
AND o.type IN ('TR', 'P' ,'U' ,'V')
UNION
--Changed (using alter)
SELECT 'changed' AS ChangeType, o.name /*COLLATE*/,
'altered' AS extra_info, 2 AS Priority
FROM sysobjects o INNER JOIN #tmp t ON o.id = t.id
WHERE (
o.base_schema_ver <> t.base_schema_ver
OR o.schema_ver <> t.schema_ver
)
AND o.type IN ('TR', 'P' ,'U' ,'V')
AND o.name NOT IN ( SELECT oi.name
FROM sysobjects oi INNER JOIN #tmp ti ON oi.id = ti.id
WHERE oi.name <> ti.name /*COLLATE*/
AND oi.type IN ('TR', 'P' ,'U' ,'V'))
UNION
--Changed (actually dropped and recreated [but not renamed])
SELECT 'changed' AS ChangeType, t.name, 'dropped' AS extra_info, 2 AS Priority
FROM #tmp t
WHERE t.name IN ( SELECT ti.name /*COLLATE*/ FROM #tmp ti
WHERE NOT EXISTS (SELECT * FROM sysobjects oi
WHERE oi.id = ti.id))
AND t.name IN ( SELECT oi.name /*COLLATE*/ FROM sysobjects oi
WHERE NOT EXISTS (SELECT * FROM #tmp ti
WHERE oi.id = ti.id)
AND oi.type IN ('TR', 'P' ,'U' ,'V'))
UNION
--Deleted
SELECT 'deleted' AS ChangeType, t.name, '' AS extra_info, 0 AS Priority
FROM #tmp t
WHERE NOT EXISTS (SELECT * FROM sysobjects o
WHERE o.id = t.id)
AND t.name NOT IN ( SELECT oi.name /*COLLATE*/ FROM sysobjects oi
WHERE NOT EXISTS (SELECT * FROM #tmp ti
WHERE oi.id = ti.id)
AND oi.type IN ('TR', 'P' ,'U' ,'V'))
UNION
--Added
SELECT 'added' AS ChangeType, o.name /*COLLATE*/, '' AS extra_info, 4 AS Priority
FROM sysobjects o
WHERE NOT EXISTS (SELECT * FROM #tmp t
WHERE o.id = t.id)
AND o.type IN ('TR', 'P' ,'U' ,'V')
AND o.name NOT IN ( SELECT ti.name /*COLLATE*/ FROM #tmp ti
WHERE NOT EXISTS (SELECT * FROM sysobjects oi
WHERE oi.id = ti.id))
ORDER BY Priority ASC
Note: If you use a non-standard collation in any of your databases, you will need to replace /* COLLATE */
with your database collation. i.e. COLLATE Latin1_General_CI_AI
If you want to check syntax error for any nginx files, you can use the -c option.
[root@server ~]# sudo nginx -t -c /etc/nginx/my-server.conf
nginx: the configuration file /etc/nginx/my-server.conf syntax is ok
nginx: configuration file /etc/nginx/my-server.conf test is successful
[root@server ~]#
this is a bit late.. but i have seen this problem occurs when you want to insert or delete one line from/to DB but u put/pull more than one line or more than one value ,
E.g:
you want to delete one line from DB with a specific value such as id of an item but you've queried a list of ids then you will encounter the same exception message.
regards.
In Apache 2.4, the authorization configuration syntax has changed, and the Order
, Deny
or Allow
directives should no longer be used.
The new way to do this would be:
<VirtualHost *:8080>
<Location />
Require ip 192.168.1.0
</Location>
...
</VirtualHost>
Further examples using the new syntax can be found in the Apache documentation: Upgrading to 2.4 from 2.2
The importance of locales is that your environment/os can provide formatting functionality for all installed locales even if you don't know about them when you write your application. My Windows 7 system has 211 locales installed (listed below), so you wouldn't likely write any custom code or translation specific to this many locales.
The most important thing for various versions of English is in formatting numbers and dates. Other differences are significant to the extent that you want and able to cater to specific variations.
af-ZA
am-ET
ar-AE
ar-BH
ar-DZ
ar-EG
ar-IQ
ar-JO
ar-KW
ar-LB
ar-LY
ar-MA
arn-CL
ar-OM
ar-QA
ar-SA
ar-SY
ar-TN
ar-YE
as-IN
az-Cyrl-AZ
az-Latn-AZ
ba-RU
be-BY
bg-BG
bn-BD
bn-IN
bo-CN
br-FR
bs-Cyrl-BA
bs-Latn-BA
ca-ES
co-FR
cs-CZ
cy-GB
da-DK
de-AT
de-CH
de-DE
de-LI
de-LU
dsb-DE
dv-MV
el-GR
en-029
en-AU
en-BZ
en-CA
en-GB
en-IE
en-IN
en-JM
en-MY
en-NZ
en-PH
en-SG
en-TT
en-US
en-ZA
en-ZW
es-AR
es-BO
es-CL
es-CO
es-CR
es-DO
es-EC
es-ES
es-GT
es-HN
es-MX
es-NI
es-PA
es-PE
es-PR
es-PY
es-SV
es-US
es-UY
es-VE
et-EE
eu-ES
fa-IR
fi-FI
fil-PH
fo-FO
fr-BE
fr-CA
fr-CH
fr-FR
fr-LU
fr-MC
fy-NL
ga-IE
gd-GB
gl-ES
gsw-FR
gu-IN
ha-Latn-NG
he-IL
hi-IN
hr-BA
hr-HR
hsb-DE
hu-HU
hy-AM
id-ID
ig-NG
ii-CN
is-IS
it-CH
it-IT
iu-Cans-CA
iu-Latn-CA
ja-JP
ka-GE
kk-KZ
kl-GL
km-KH
kn-IN
kok-IN
ko-KR
ky-KG
lb-LU
lo-LA
lt-LT
lv-LV
mi-NZ
mk-MK
ml-IN
mn-MN
mn-Mong-CN
moh-CA
mr-IN
ms-BN
ms-MY
mt-MT
nb-NO
ne-NP
nl-BE
nl-NL
nn-NO
nso-ZA
oc-FR
or-IN
pa-IN
pl-PL
prs-AF
ps-AF
pt-BR
pt-PT
qut-GT
quz-BO
quz-EC
quz-PE
rm-CH
ro-RO
ru-RU
rw-RW
sah-RU
sa-IN
se-FI
se-NO
se-SE
si-LK
sk-SK
sl-SI
sma-NO
sma-SE
smj-NO
smj-SE
smn-FI
sms-FI
sq-AL
sr-Cyrl-BA
sr-Cyrl-CS
sr-Cyrl-ME
sr-Cyrl-RS
sr-Latn-BA
sr-Latn-CS
sr-Latn-ME
sr-Latn-RS
sv-FI
sv-SE
sw-KE
syr-SY
ta-IN
te-IN
tg-Cyrl-TJ
th-TH
tk-TM
tn-ZA
tr-TR
tt-RU
tzm-Latn-DZ
ug-CN
uk-UA
ur-PK
uz-Cyrl-UZ
uz-Latn-UZ
vi-VN
wo-SN
xh-ZA
yo-NG
zh-CN
zh-HK
zh-MO
zh-SG
zh-TW
zu-ZA
From git stash --help
Recovering stashes that were cleared/dropped erroneously
If you mistakenly drop or clear stashes, they cannot be recovered through the normal safety mechanisms. However, you can try the
following incantation to get a list of stashes that are still in your repository, but not reachable any more:
git fsck --unreachable |
grep commit | cut -d\ -f3 |
xargs git log --merges --no-walk --grep=WIP
This helped me better than the accepted answer with the same scenario.
Contributed by Stephane CHAZELAS on c.u.s. Assuming POSIX shell:
prg=$0
if [ ! -e "$prg" ]; then
case $prg in
(*/*) exit 1;;
(*) prg=$(command -v -- "$prg") || exit;;
esac
fi
dir=$(
cd -P -- "$(dirname -- "$prg")" && pwd -P
) || exit
prg=$dir/$(basename -- "$prg") || exit
printf '%s\n' "$prg"
I do not know much about Java but URL query arguments should be separated by "&", not "?"
http://tools.ietf.org/html/rfc3986 is good place for reference using "sub-delim" as keyword. http://en.wikipedia.org/wiki/Query_string is another good source.
Instead of using this
as the accepted answer suggests, use $parent
instead. So in your partial1.html
you'll have:
<form ng-submit="$parent.addLine()">
<input type="text" ng-model="$parent.lineText" size="30" placeholder="Type your message here">
</form>
If you want to learn more about the scope in ng-include
or other directives, check this out: https://github.com/angular/angular.js/wiki/Understanding-Scopes#ng-include
return car.GetType().GetProperty(propertyName).GetValue(car, null);
It might be cleaner to take out your inline click handler and do it like this:
$(document).ready(function() {
$('#button-id').click(function() {
foo($('#formValueId').val());
});
});
Like that
var purchCount = (from purchase in myBlaContext.purchases select purchase).Count();
or even easier
var purchCount = myBlaContext.purchases.Count()
for _ in range(5):
try:
# replace this with something that may fail
raise ValueError("foo")
# replace Exception with a more specific exception
except Exception as e:
err = e
continue
# no exception, continue remainder of code
else:
break
# did not break the for loop, therefore all attempts
# raised an exception
else:
raise err
My version is similar to several of the above, but doesn't use a separate while
loop, and re-raises the latest exception if all retries fail. Could explicitly set err = None
at the top, but not strictly necessary as it should only execute the final else
block if there was an error and therefore err
is set.
You can also try this, after injecting $window service.
$window.location.reload();
And for my fellow Europeans, try using this:
timestamp=$(date +%d-%m-%Y_%H-%M-%S)
will give a format of the format: "15-02-2020_19-21-58"
You call the variable and get the string representation like this
$timestamp
If you want to use enhanced loop, you can convert the string to charArray
for (char ch : exampleString.toCharArray()) {
System.out.println(ch);
}
In Java, according to the JSSE Reference Guide, there is no default for the keystore
, the default for the truststore
is "jssecacerts, if it exists. Otherwise, cacerts".
A few applications use ~/.keystore
as a default keystore, but this is not without problems (mainly because you might not want all the application run by the user to use that trust store).
I'd suggest using application-specific values that you bundle with your application instead, it would tend to be more applicable in general.
**The best is to use try except block to get rid of EOF **
try:
width = input()
height = input()
def rectanglePerimeter(width, height):
return ((width + height)*2)
print(rectanglePerimeter(width, height))
except EOFError as e:
print(end="")
According to the release-notes, Java 11 removed the Java EE modules:
java.xml.bind (JAXB) - REMOVED
See JEP 320 for more info.
You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.3</version>
<scope>runtime</scope>
</dependency>
Use latest release of Eclipse Implementation of JAXB 3.0.0:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>3.0.0</version>
<scope>runtime</scope>
</dependency>
Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*
, so update import statements:
javax.xml.bind -> jakarta.xml.bind
It's safe to just delete the source directory and compiled package file. Find the source directory under $GOPATH/src
and the package file under $GOPATH/pkg/<architecture>
, for example: $GOPATH/pkg/windows_amd64
.
the best way to calculate the equation is simplified. That is, find the maximum divisor between two numbers and divide:
ex.
1920:1080 maximum common divisor 120 = 16:9
1024:768 maximum common divisor 256 = 4:3
1280:768 maximum common divisor 256 = 5:3
may happen also some approaches
Declare @month as char(2)
Declare @date as char(2)
Declare @year as char(4)
declare @time as char(8)
declare @customdate as varchar(20)
set @month = MONTH(GetDate());
set @date = Day(GetDate());
set @year = year(GetDate());
set @customdate= @month+'/'+@date+'/'+@year+' '+ CONVERT(varchar(8), GETDATE(),108);
print(@customdate)
select replace(wm_concat(new),',','-') exp_res from (select distinct initcap(substr(name,decode(level,1,1,instr(name,'-',1,level-1)+1),decode(level,(length(name)-length(replace(name,'-','')))+1,9999,instr(name,'-',1,level)-1-decode(level,1,0,instr(name,'-',1,level-1))))) new from table;
connect by level<= (select (length(name)-length(replace(name,'-','')))+1 from table));
I know this is quite an old question -
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Let's say, you want to extract the first 2 rows and first 3 columns
A_NEW = A[0:2, 0:3]
A_NEW = [[1, 2, 3],
[4, 5, 6]]
Understanding the syntax
A_NEW = A[start_index_row : stop_index_row,
start_index_column : stop_index_column)]
If one wants row 2 and column 2 and 3
A_NEW = A[1:2, 1:3]
Reference the numpy indexing and slicing article - Indexing & Slicing
You might no need to having export, just add this line in catalina.sh :
CATALINA_OPTS="-Xms512M -Xmx1024M"
Let the method return a object from a common baseclass or interface.
public class TV:IMediaPlayer
{
void Play(){};
}
public class Radio:IMediaPlayer
{
void Play(){};
}
public interface IMediaPlayer
{
void Play():
}
public class Test
{
public void Main()
{
IMediaPlayer player = GetMediaPlayer();
player.Play();
}
private IMediaPlayer GetMediaPlayer()
{
if(...)
return new TV();
else
return new Radio();
}
}
Try this one-
<script>
(function($){
$(document).on('contextmenu', 'img', function() {
return false;
})
})(jQuery);
</script>
additionally for accepted answer you can use UseSubmitBehavior="false" MSDN
You can use .replaceWith()
$(function() {_x000D_
_x000D_
$(".region").click(function(e) {_x000D_
e.preventDefault();_x000D_
var content = $(this).html();_x000D_
$('#map').replaceWith('<div class="region">' + content + '</div>');_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="map">_x000D_
<div class="region"><a href="link1">region1</a></div>_x000D_
<div class="region"><a href="link2">region2</a></div>_x000D_
<div class="region"><a href="link3">region3</a></div>_x000D_
</div>
_x000D_
I just had to solve a similar problem where I added a Sequence number (so that items as grouped by a parent ID, have a Sequence that I can order by (and presumably the user can change the sequence number to change the ordering).
In my case, it's insurance for a Patient, and the user gets to set the order they are assigned, so just going by the primary key isn't useful for long-term, but is useful for setting a default.
The problem with all the other solutions is that certain aggregate functions aren't allowed outside of a SELECT
This SELECT gets you the new Sequence number:
select PatientID,
PatientInsuranceID,
Sequence,
Row_Number() over(partition by PatientID order by PatientInsuranceID) as RowNum
from PatientInsurance
order by PatientID, PatientInsuranceID
This update command, would be simple, but isn't allowed:
update PatientInsurance
set Sequence = Row_Number() over(partition by PatientID order by PatientInsuranceID)
The solution that worked (I just did it), and is similar to eKek0's solution:
UPDATE PatientInsurance
SET PatientInsurance.Sequence = q.RowNum
FROM (select PatientInsuranceID,
Row_Number() over(partition by PatientID order by PatientInsuranceID) as RowNum
from PatientInsurance
) as q
WHERE PatientInsurance.PatientInsuranceID=q.PatientInsuranceID
this lets me select the ID I need to match things up to, and the value I need to set for that ID. Other solutions would have been fine IF I wasn't using Row_Number() which won't work outside of a SELECT.
Given that this is a 1 time operation, it's coding is still simple, and run-speed is fast enough for 4000+ rows
You're better off using table-layout: fixed
Auto is the default value and with large tables can cause a bit of client side lag as the browser iterates through it to check all the sizes fit.
Fixed is far better and renders quicker to the page. The structure of the table is dependent on the tables overall width and the width of each of the columns.
Here it is applied to the original example: JSFIDDLE, You'll note that the remaining columns are crushed and overlapping their content. We can fix that with some more CSS (all I've had to do is add a class to the first TR):
table {
width: 100%;
table-layout: fixed;
}
.header-row > td {
width: 100px;
}
td.rhead {
width: 300px
}
Seen in action here: JSFIDDLE
Something like
script > /dev/null 2>&1
This will prevent standard output and error output, redirecting them both to /dev/null
.
Change visible="false"
to style="visibility:hidden"
on your tags..
or better use a class to show/hide the labels..
.hidden{
visibility:hidden;
}
then on your labels add class="hidden"
and with your script remove the class
document.getElementById("endTimeLabel").className = 'hidden'; // to hide
and
document.getElementById("endTimeLabel").className = ''; // to show
For t2/m3/c3/c4/r3/i2/d2 instances:
m1 small, medium, and large instances tend to perform higher than expected. c1.medium is another freak, at 800 MBit/s.
I gathered this by combing dozens of sources doing benchmarks (primarily using iPerf & TCP connections). Credit to CloudHarmony & flux7 in particular for many of the benchmarks (note that those two links go to google searches showing the numerous individual benchmarks).
The large instance size has the most variation reported:
Burstable (T2) instances appear to exhibit burstable networking performance too:
The CloudHarmony iperf benchmarks show initial transfers start at 1 GBit/s and then gradually drop to the sustained levels above after a few minutes. PDF links to reports below:
t2.small (PDF)
Note that these are within the same region - if you're transferring across regions, real performance may be much slower. Even for the larger instances, I'm seeing numbers of a few hundred MBit/s.
Just a little addition to psycho brm´s answer (his version doesn't work in IE<=8). This code is cross-browser compatible:
function explode (s, separator, limit)
{
var arr = s.split(separator);
if (limit) {
arr.push(arr.splice(limit-1, (arr.length-(limit-1))).join(separator));
}
return arr;
}
Sometimes even autocomplete=off
won't prevent filling in credentials into wrong fields.
A workaround is to disable browser autofill using readonly-mode and set writable on focus:
<input type="password" readonly onfocus="this.removeAttribute('readonly');"/>
The focus
event occurs at mouse clicks and tabbing through fields.
Update:
Mobile Safari sets cursor in the field, but does not show virtual keyboard. This new workaround works like before, but handles virtual keyboard:
<input id="email" readonly type="email" onfocus="if (this.hasAttribute('readonly')) {
this.removeAttribute('readonly');
// fix for mobile safari to show virtual keyboard
this.blur(); this.focus(); }" />
Live Demo https://jsfiddle.net/danielsuess/n0scguv6/
// UpdateEnd
Explanation: Browser auto fills credentials to wrong text field?
filling the inputs incorrectly, for example filling the phone input with an email address
Sometimes I notice this strange behavior on Chrome and Safari, when there are password fields in the same form. I guess, the browser looks for a password field to insert your saved credentials. Then it autofills username into the nearest textlike-input field , that appears prior the password field in DOM (just guessing due to observation). As the browser is the last instance and you can not control it,
This readonly-fix above worked for me.
As far as you're concerned once you've "pulled out" the contents with something like .html() it's just a string. You can test that with
<html>
<head>
<title>runthis</title>
<script type="text/javascript" language="javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready( function() {
var x = $("#foo").html();
alert( typeof(x) );
});
</script>
</head>
<body>
<div id="foo"><table><tr><td>x</td></tr></table><span>xyz</span></div>
</body>
</html>
The alert text is string. As long as you don't pass it to a parser there's no magic about it, it's a string like any other string.
There's nothing that hinders you from using .post() to send this string back to the server.
edit: Don't pass a string as the parameter data to .post() but an object, like
var data = {
id: currid,
html: div_html
};
$.post("http://...", data, ...);
jquery will handle the encoding of the parameters.
If you (for whatever reason) want to keep your string you have to encode the values with something like escape().
var data = 'id='+ escape(currid) +'&html='+ escape(div_html);
Some Google services do not like to be used to much. Quite recently my account was locked because of script, which was sending two e-mails per second to the same user. Google considered it as a spam. So using sleep here is also justified to prevent such situations.
There is also:
try:
del mydict[key]
except KeyError:
pass
This only does 1 lookup instead of 2. However, except
clauses are expensive, so if you end up hitting the except clause frequently, this will probably be less efficient than what you already have.
Using a dictionary for unique names without a name list:
class MyClass:
def __init__(self, name):
self.name = name
self.pretty_print_name()
def pretty_print_name(self):
print("This object's name is {}.".format(self.name))
my_objects = {}
for i in range(1,11):
name = 'obj_{}'.format(i)
my_objects[name] = my_objects.get(name, MyClass(name = name))
Output:
"This object's name is obj_1."
"This object's name is obj_2."
"This object's name is obj_3."
"This object's name is obj_4."
"This object's name is obj_5."
"This object's name is obj_6."
"This object's name is obj_7."
"This object's name is obj_8."
"This object's name is obj_9."
"This object's name is obj_10."
You're not adding a new instance of the class to the list. Try this:
lstemail.Add(new EmailData { FirstName="John", LastName="Smith", Location="Los Angeles" });`
List
is a generic class. When you specify a List<EmailData>
, the Add
method is expecting an object that's of type EmailData
. The example above, expressed in more verbose syntax, would be:
EmailData data = new EmailData();
data.FirstName="John";
data.LastName="Smith;
data.Location = "Los Angeles";
lstemail.Add(data);
Events are pretty easy in C#, but the MSDN docs in my opinion make them pretty confusing. Normally, most documentation you see discusses making a class inherit from the EventArgs
base class and there's a reason for that. However, it's not the simplest way to make events, and for someone wanting something quick and easy, and in a time crunch, using the Action
type is your ticket.
1. Create your event on your class right after your class
declaration.
public event Action<string,string,string,string>MyEvent;
2. Create your event handler class method in your class.
private void MyEventHandler(string s1,string s2,string s3,string s4)
{
Console.WriteLine("{0} {1} {2} {3}",s1,s2,s3,s4);
}
3. Now when your class is invoked, tell it to connect the event to your new event handler. The reason the +=
operator is used is because you are appending your particular event handler to the event. You can actually do this with multiple separate event handlers, and when an event is raised, each event handler will operate in the sequence in which you added them.
class Example
{
public Example() // I'm a C# style class constructor
{
MyEvent += new Action<string,string,string,string>(MyEventHandler);
}
}
4. Now, when you're ready, trigger (aka raise) the event somewhere in your class code like so:
MyEvent("wow","this","is","cool");
The end result when you run this is that the console will emit "wow this is cool". And if you changed "cool" with a date or a sequence, and ran this event trigger multiple times, you'd see the result come out in a FIFO sequence like events should normally operate.
In this example, I passed 4 strings. But you could change those to any kind of acceptable type, or used more or less types, or even remove the <...>
out and pass nothing to your event handler.
And, again, if you had multiple custom event handlers, and subscribed them all to your event with the +=
operator, then your event trigger would have called them all in sequence.
But what if you want to identify the caller to this event in your event handler? This is useful if you want an event handler that reacts with conditions based on who's raised/triggered the event. There are a few ways to do this. Below are examples that are shown in order by how fast they operate:
Option 1. (Fastest) If you already know it, then pass the name as a literal string to the event handler when you trigger it.
Option 2. (Somewhat Fast) Add this into your class and call it from the calling method, and then pass that string to the event handler when you trigger it:
private static string GetCaller([System.Runtime.CompilerServices.CallerMemberName] string s = null) => s;
Option 3. (Least Fast But Still Fast) In your event handler when you trigger it, get the calling method name string with this:
string callingMethod = new System.Diagnostics.StackTrace().GetFrame(1).GetMethod().ReflectedType.Name.Split('<', '>')[1];
You may have a scenario where your custom event has multiple event handlers, but you want to remove one special one out of the list of event handlers. To do so, use the -=
operator like so:
MyEvent -= MyEventHandler;
A word of minor caution with this, however. If you do this and that event no longer has any event handlers, and you trigger that event again, it will throw an exception. (Exceptions, of course, you can trap with try/catch blocks.)
Okay, let's say you're through with events and you don't want to process any more. Just set it to null like so:
MyEvent = null;
The same caution for Unsubscribing events is here, as well. If your custom event handler no longer has any events, and you trigger it again, your program will throw an exception.
Try something like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
Write-Host $_.Exception.ToString()
}
The exception is in the $_
variable. You might explore $_
like this:
try {
$w = New-Object net.WebClient
$d = $w.downloadString('http://foo')
}
catch [Net.WebException] {
$_ | fl * -Force
}
I think it will give you all the info you need.
My rule: if there is some data that is not displayed, try to use -force
.
Alternatively, create a figure()
object using the figsize
argument and then use add_subplot
to add your subplots. E.g.
import matplotlib.pyplot as plt
import numpy as np
f = plt.figure(figsize=(10,3))
ax = f.add_subplot(121)
ax2 = f.add_subplot(122)
x = np.linspace(0,4,1000)
ax.plot(x, np.sin(x))
ax2.plot(x, np.cos(x), 'r:')
Benefits of this method are that the syntax is closer to calls of subplot()
instead of subplots()
. E.g. subplots doesn't seem to support using a GridSpec
for controlling the spacing of the subplots, but both subplot()
and add_subplot()
do.
One right way:
Here are the high-level differences:
Here's an example program that will send myfile.mp3 by streaming it from disk (that is, it doesn't read the whole file into memory before sending the file). The server listens on port 2000.
[Update] As mentioned by @Aftershock in the comments, util.pump
is gone and was replaced with a method on the Stream prototype called pipe
; the code below reflects this.
var http = require('http'),
fileSystem = require('fs'),
path = require('path');
http.createServer(function(request, response) {
var filePath = path.join(__dirname, 'myfile.mp3');
var stat = fileSystem.statSync(filePath);
response.writeHead(200, {
'Content-Type': 'audio/mpeg',
'Content-Length': stat.size
});
var readStream = fileSystem.createReadStream(filePath);
// We replaced all the event handlers with a simple call to readStream.pipe()
readStream.pipe(response);
})
.listen(2000);
Taken from http://elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/
And for all input and select:
$("input[required], select[required]").attr("oninvalid", "this.setCustomValidity('Required!')");
$("input[required], select[required]").attr("oninput", "setCustomValidity('')");
AngularJS provides the $http
service that does exactly what you want: Sending AJAX requests to web services and receiving data from them, using JSON (which is perfectly for talking to REST services).
To give an example (taken from the AngularJS documentation and slightly adapted):
$http({ method: 'GET', url: '/foo' }).
success(function (data, status, headers, config) {
// ...
}).
error(function (data, status, headers, config) {
// ...
});
Please note that there is also another service in AngularJS, the $resource
service which provides access to REST services in a more high-level fashion (example again taken from AngularJS documentation):
var Users = $resource('/user/:userId', { userId: '@id' });
var user = Users.get({ userId: 123 }, function () {
user.abc = true;
user.$save();
});
Moreover, there are also third-party solutions, such as Restangular. See its documentation on how to use it. Basically, it's way more declarative and abstracts more of the details away from you.
Try this. The scope of local variables defined by "template" directive.
<table>
<template ngFor let-group="$implicit" [ngForOf]="groups">
<tr>
<td>
<h2>{{group.name}}</h2>
</td>
</tr>
<tr *ngFor="let item of group.items">
<td>{{item}}</td>
</tr>
</template>
</table>
Not sure if this applies, but the fix for me was to commit something locally after git init. Then I pushed to remote using --set-upstream ...
This will also give external links an absolute path without having to use php.ini
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.your_external_website.com");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
$result = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"'>]+)#",'$1http://www.your_external_website.com/$2$3', $result);
echo $result
?>
With AWK you can do, I find it faster than sort
./yourscript.ksh | awk '!a[$0]++'
More methods in java 8:
EnumSet
with forEach
EnumSet.allOf(Direction.class).forEach(...);
Arrays.asList
with forEach
Arrays.asList(Direction.values()).forEach(...);
When you have everything #included, an unresolved external symbol is often a missing * or & in the declaration or definition of a function.
Html.TextBoxFor(model => model.Control.PeriodType,
new { @class="text-box single-line"})
you can use like this ; same output with Html.EditorFor
,and you can add your html attributes
Gives totals and percentages for process using swap
smem -t -p
Source : https://www.cyberciti.biz/faq/linux-which-process-is-using-swap/
Cellpadding
is the amount of space between the outer edges of the
table cell and the content of the cell.
Cellspacing
is the amount of space in between the individual table cells.
More Details *Link 1*
Or Using promises:
const AWS = require('aws-sdk');
AWS.config.update({
accessKeyId: 'accessKeyId',
secretAccessKey: 'secretAccessKey',
region: 'region'
});
let params = {
Bucket: "yourBucketName",
Key: 'someUniqueKey',
Body: 'someFile'
};
try {
let uploadPromise = await new AWS.S3().putObject(params).promise();
console.log("Successfully uploaded data to bucket");
} catch (e) {
console.log("Error uploading data: ", e);
}
First cast your Edit text like this:
TextView tekst = (TextView) findViewById(R.id.editText1);
tekst.setText(text);
And after that close the DB not befor this line...
myDataBaseHelper.close();
Consider using the Restlet framework, which has great semantics for this sort of thing. It's powerful and flexible.
The code could be as simple as:
Client client = new Client(Protocol.HTTP);
Response response = client.get(url);
if (response.getStatus().isError()) {
// uh oh!
}
the simplest way, type in normal mode *
I also have these mappings to enable and disable
"highligh search enabled by default
set hlsearch
"now you can toggle it
nnoremap <S-F11> <ESC>:set hls! hls?<cr>
inoremap <S-F11> <C-o>:set hls! hls?<cr>
vnoremap <S-F11> <ESC>:set hls! hls?<cr> <bar> gv
Select word by clickin on it
set mouse=a "Enables mouse click
nnoremap <silent> <2-LeftMouse> :let @/='\V\<'.escape(expand('<cword>'), '\').'\>'<cr>:set hls<cr>
Bonus: CountWordFunction
fun! CountWordFunction()
try
let l:win_view = winsaveview()
let l:old_query = getreg('/')
let var = expand("<cword>")
exec "%s/" . var . "//gn"
finally
call winrestview(l:win_view)
call setreg('/', l:old_query)
endtry
endfun
" Bellow we set a command "CountWord" and a mapping to count word
" change as you like it
command! -nargs=0 CountWord :call CountWordFunction()
nnoremap <f3> :CountWord<CR>
Selecting word with mouse and counting occurrences at once: OBS: Notice that in this version we have "CountWord" command at the end
nnoremap <silent> <2-LeftMouse> :let @/='\V\<'.escape(expand('<cword>'), '\').'\>'<cr>:set hls<cr>:CountWord<cr>
If you don't know when data will be added to #data
, you could set an interval to update the element's scrollTop to its scrollHeight every couple of seconds. If you are controlling when data is added, just call the internal of the following function after the data has been added.
window.setInterval(function() {
var elem = document.getElementById('data');
elem.scrollTop = elem.scrollHeight;
}, 5000);
The previous answers were accurate, but perhaps too terse. I will try to add some examples.
First of all, the word "proxy" describes someone or something acting on behalf of someone else.
In the computer realm, we are talking about one server acting on the behalf of another computer.
For the purposes of accessibility, I will limit my discussion to web proxies - however, the idea of a proxy is not limited to websites.
Most discussion of web proxies refers to the type of proxy known as a "forward proxy."
The proxy event, in this case, is that the "forward proxy" retrieves data from another web site on behalf of the original requestee.
For an example, I will list three computers connected to the internet.
Normally, one would connect directly from X --> Z.
However, in some scenarios, it is better for Y --> Z
on behalf of X
,
which chains as follows: X --> Y --> Z
.
Here is a (very) partial list of uses of a forward proxy server:
1) X is unable to access Z directly because
a) Someone with administrative authority over X
's internet connection has decided to block all access to site Z
.
Examples:
The Storm Worm virus is spreading by tricking people into visiting familypostcards2008.com
, so the system administrator has blocked access to the site to prevent users from inadvertently infecting themselves.
Employees at a large company have been wasting too much time on facebook.com
, so management wants access blocked during business hours.
A local elementary school disallows internet access to the playboy.com
website.
A government is unable to control the publishing of news, so it controls access to news instead, by blocking sites such as wikipedia.org
. See TOR or FreeNet.
b) The administrator of Z
has blocked X
.
Examples:
The administrator of Z has noticed hacking attempts coming from X, so the administrator has decided to block X's IP address (and/or netrange).
Z is a forum website. X
is spamming the forum. Z blocks X.
For this example, I will list three computers connected to the internet.
Normally, one would connect directly from X --> Z.
However, in some scenarios, it is better for the administrator of Z
to restrict or disallow direct access and force visitors to go through Y first.
So, as before, we have data being retrieved by Y --> Z
on behalf of X
, which chains as follows: X --> Y --> Z
.
What is different this time compared to a "forward proxy," is that this time the user X
does not know he is accessing Z
, because the user X
only sees he is communicating with Y
.
The server Z
is invisible to clients and only the reverse proxy Y
is visible externally. A reverse proxy requires no (proxy) configuration on the client side.
The client X
thinks he is only communicating with Y
(X --> Y
), but the reality is that Y
forwarding all communication (X --> Y --> Z
again).
In the above scenarios, Z
has the ability to choose Y
.
myUIImageview.image = UIImage (named:"myImage.png")
Use subDays()
method:
$users = Users::where('status_id', 'active')
->where( 'created_at', '>', Carbon::now()->subDays(30))
->get();
Why use deflate instead of gzip for text files served by Apache?
The simple answer is don't.
RFC 2616 defines deflate as:
deflate The "zlib" format defined in RFC 1950 in combination with the "deflate" compression mechanism described in RFC 1951
The zlib format is defined in RFC 1950 as :
0 1
+---+---+
|CMF|FLG| (more-->)
+---+---+
0 1 2 3
+---+---+---+---+
| DICTID | (more-->)
+---+---+---+---+
+=====================+---+---+---+---+
|...compressed data...| ADLER32 |
+=====================+---+---+---+---+
So, a few headers and an ADLER32 checksum
RFC 2616 defines gzip as:
gzip An encoding format produced by the file compression program "gzip" (GNU zip) as described in RFC 1952 [25]. This format is a Lempel-Ziv coding (LZ77) with a 32 bit CRC.
RFC 1952 defines the compressed data as:
The format presently uses the DEFLATE method of compression but can be easily extended to use other compression methods.
CRC-32 is slower than ADLER32
Compared to a cyclic redundancy check of the same length, it trades reliability for speed (preferring the latter).
So ... we have 2 compression mechanisms that use the same algorithm for compression, but a different algorithm for headers and checksum.
Now, the underlying TCP packets are already pretty reliable, so the issue here is not Adler 32 vs CRC-32 that GZIP uses.
Turns out many browsers over the years implemented an incorrect deflate algorithm. Instead of expecting the zlib header in RFC 1950 they simply expected the compressed payload. Similarly various web servers made the same mistake.
So, over the years browsers started implementing a fuzzy logic deflate implementation, they try for zlib header and adler checksum, if that fails they try for payload.
The result of having complex logic like that is that it is often broken. Verve Studio have a user contributed test section that show how bad the situation is.
For example: deflate works in Safari 4.0 but is broken in Safari 5.1, it also always has issues on IE.
So, best thing to do is avoid deflate altogether, the minor speed boost (due to adler 32) is not worth the risk of broken payloads.
Try this:
net use * /delete /y
The /y
key makes it select Yes in prompt silently
If after calling "csrutil disabled" still your command does not work, try with "sudo" in terminal, for example:
sudo mv geckodriver /usr/local/bin
And it should work.
The standard SQL way is to use like:
where @stringVar like '%thisstring%'
That is in a query statement. You can also do this in TSQL:
if @stringVar like '%thisstring%'
It is possible to do with CSS only by selecting active and focus pseudo element of the button.
button:active{
background:olive;
}
button:focus{
background:olive;
}
See codepen: http://codepen.io/fennefoss/pen/Bpqdqx
You could also write a simple jQuery click function which changes the background color.
HTML:
<button class="js-click">Click me!</button>
CSS:
button {
background: none;
}
JavaScript:
$( ".js-click" ).click(function() {
$( ".js-click" ).css('background', 'green');
});
Check out this codepen: http://codepen.io/fennefoss/pen/pRxrVG
If it's a 1 time import, the Import/Export utility in SSMS will probably work the easiest and fastest. SSIS also seems to work better for importing large data sets than a straight INSERT.
BULK INSERT or BCP can also be used to import large record sets.
Another option would be to temporarily remove all indexes and constraints on the table you're importing into and add them back once the import process completes. A straight INSERT that previously failed might work in those cases.
If you're dealing with timeouts or locking/blocking issues when going directly from one database to another, you might consider going from one db into TEMPDB and then going from TEMPDB into the other database as it minimizes the effects of locking and blocking processes on either side. TempDB won't block or lock the source and it won't hold up the destination.
Those are a few options to try.
-Eric Isaacs
In my case over time I had saved a bunch of versions of myfile as myfile_bak, myfile_old, myfile_2010, backups/myfile etc. I wanted to put myfile's history in git using their modification dates. So rename the oldest to myfile, git add myfile
, then git commit --date=(modification date from ls -l) myfile
, rename next oldest to myfile, another git commit with --date, repeat...
To automate this somewhat, you can use shell-foo to get the modification time of the file. I started with ls -l
and cut
, but stat(1) is more direct
git commit --date="`stat -c %y myfile`" myfile
There are three ways
1) This runs the GUI editor for the user environment variables. It does exactly what the OP wanted to do and does not prompt for administrative credentials.
rundll32.exe sysdm.cpl,EditEnvironmentVariables
(bonus: This works on Windows Vista to Windows 10 for desktops and Windows Server 2008 through Server 2016. It does not work on Windows NT, 2000, XP, and 2003. However, on the older systems you can use sysdm.cpl without the ",EditEnvironmentVariables" parameter and then navigate to the Advanced tab and then Environment Variables button.)
2) Use the SETX command from the command prompt. This is like the set command but updates the environment that's stored in the registry. Unfortunately, SETX is not as easy to use as the built in SET command. There's no way to list the variables for example. Thus it's impossible to do something such as appending a folder to the user's PATH variable. While SET will display the variables you don't know which ones are user vs. system variables and the PATH that's shown is a combination of both.
3) Use regedit and navigate to HKEY_CURRENT_USER\Environment
Keep in mind that changes to the user's environment does not immediately propagate to all processes currently running for that user. You can see this in a command prompt where your changes will not be visible if you use SET. For example
rem Add a user environment variable named stackoverflow that's set to "test"
setx stackoverflow test
set st
This should show all variables whose names start with the letters "st". If there are none then it displays "Environment variable st not defined
".
Exit the command prompt and start another. Try set st
again
and you'll see
stackoverflow=test
To delete the stackoverflow variable use
setx stackoverflow ""
It will respond with "SUCCESS: Specified value was saved.
" which looks strange given you want to delete the variable. However, if you start a new command prompt then set st
will show that there are no variables starting with the letters "st"
(correction - I discovered that setx stackoverflow ""
did not delete the variable. It's in the registry as an empty string. The SET
command though interprets it as though there is no variable. if not defined stackoverflow echo Not defined
says it's not defined.)
Try like this
Pass Camera Intent like below
Intent intent = new Intent(this);
startActivityForResult(intent, REQ_CAMERA_IMAGE);
And after capturing image Write an OnActivityResult
as below
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
knop.setVisibility(Button.VISIBLE);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), photo);
// CALL THIS METHOD TO GET THE ACTUAL PATH
File finalFile = new File(getRealPathFromURI(tempUri));
System.out.println(mImageCaptureUri);
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
String path = "";
if (getContentResolver() != null) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
path = cursor.getString(idx);
cursor.close();
}
}
return path;
}
And check log
Edit:
Lots of people are asking how to not get a thumbnail. You need to add this code instead for the getImageUri
method:
public Uri getImageUri(Context inContext, Bitmap inImage) {
Bitmap OutImage = Bitmap.createScaledBitmap(inImage, 1000, 1000,true);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), OutImage, "Title", null);
return Uri.parse(path);
}
The other method Compresses the file. You can adjust the size by changing the number 1000,1000
This is not a direct answer, but very useful if you don't have access to how java starts: you can set the environment variable JAVA_TOOLS_OPTIONS
to -Dfile.encoding="UTF-8"
and every time the jvm starts it will pick up that option.
CREATE OR REPLACE PACKAGE BODY TEST AS
FUNCTION GET_UPS(
TIMESPAN_IN IN VARCHAR2 DEFAULT 'MONTLHY',
STARTING_DATE_IN DATE,
ENDING_DATE_IN DATE
)RETURN MEASURE_TABLE IS
T MEASURE_TABLE;
BEGIN
**SELECT MEASURE_RECORD(L4_ID , L6_ID ,L8_ID ,YEAR ,
PERIOD,VALUE ) BULK COLLECT INTO T
FROM ...**
;
RETURN T;
END GET_UPS;
END TEST;
Although the linq answer is interesting, it's also quite heavy-weight. My approach is somewhat different:
var DataGrouper = (function() {
var has = function(obj, target) {
return _.any(obj, function(value) {
return _.isEqual(value, target);
});
};
var keys = function(data, names) {
return _.reduce(data, function(memo, item) {
var key = _.pick(item, names);
if (!has(memo, key)) {
memo.push(key);
}
return memo;
}, []);
};
var group = function(data, names) {
var stems = keys(data, names);
return _.map(stems, function(stem) {
return {
key: stem,
vals:_.map(_.where(data, stem), function(item) {
return _.omit(item, names);
})
};
});
};
group.register = function(name, converter) {
return group[name] = function(data, names) {
return _.map(group(data, names), converter);
};
};
return group;
}());
DataGrouper.register("sum", function(item) {
return _.extend({}, item.key, {Value: _.reduce(item.vals, function(memo, node) {
return memo + Number(node.Value);
}, 0)});
});
You can see it in action on JSBin.
I didn't see anything in Underscore that does what has
does, although I might be missing it. It's much the same as _.contains
, but uses _.isEqual
rather than ===
for comparisons. Other than that, the rest of this is problem-specific, although with an attempt to be generic.
Now DataGrouper.sum(data, ["Phase"])
returns
[
{Phase: "Phase 1", Value: 50},
{Phase: "Phase 2", Value: 130}
]
And DataGrouper.sum(data, ["Phase", "Step"])
returns
[
{Phase: "Phase 1", Step: "Step 1", Value: 15},
{Phase: "Phase 1", Step: "Step 2", Value: 35},
{Phase: "Phase 2", Step: "Step 1", Value: 55},
{Phase: "Phase 2", Step: "Step 2", Value: 75}
]
But sum
is only one potential function here. You can register others as you like:
DataGrouper.register("max", function(item) {
return _.extend({}, item.key, {Max: _.reduce(item.vals, function(memo, node) {
return Math.max(memo, Number(node.Value));
}, Number.NEGATIVE_INFINITY)});
});
and now DataGrouper.max(data, ["Phase", "Step"])
will return
[
{Phase: "Phase 1", Step: "Step 1", Max: 10},
{Phase: "Phase 1", Step: "Step 2", Max: 20},
{Phase: "Phase 2", Step: "Step 1", Max: 30},
{Phase: "Phase 2", Step: "Step 2", Max: 40}
]
or if you registered this:
DataGrouper.register("tasks", function(item) {
return _.extend({}, item.key, {Tasks: _.map(item.vals, function(item) {
return item.Task + " (" + item.Value + ")";
}).join(", ")});
});
then calling DataGrouper.tasks(data, ["Phase", "Step"])
will get you
[
{Phase: "Phase 1", Step: "Step 1", Tasks: "Task 1 (5), Task 2 (10)"},
{Phase: "Phase 1", Step: "Step 2", Tasks: "Task 1 (15), Task 2 (20)"},
{Phase: "Phase 2", Step: "Step 1", Tasks: "Task 1 (25), Task 2 (30)"},
{Phase: "Phase 2", Step: "Step 2", Tasks: "Task 1 (35), Task 2 (40)"}
]
DataGrouper
itself is a function. You can call it with your data and a list of the properties you want to group by. It returns an array whose elements are object with two properties: key
is the collection of grouped properties, vals
is an array of objects containing the remaining properties not in the key. For example, DataGrouper(data, ["Phase", "Step"])
will yield:
[
{
"key": {Phase: "Phase 1", Step: "Step 1"},
"vals": [
{Task: "Task 1", Value: "5"},
{Task: "Task 2", Value: "10"}
]
},
{
"key": {Phase: "Phase 1", Step: "Step 2"},
"vals": [
{Task: "Task 1", Value: "15"},
{Task: "Task 2", Value: "20"}
]
},
{
"key": {Phase: "Phase 2", Step: "Step 1"},
"vals": [
{Task: "Task 1", Value: "25"},
{Task: "Task 2", Value: "30"}
]
},
{
"key": {Phase: "Phase 2", Step: "Step 2"},
"vals": [
{Task: "Task 1", Value: "35"},
{Task: "Task 2", Value: "40"}
]
}
]
DataGrouper.register
accepts a function and creates a new function which accepts the initial data and the properties to group by. This new function then takes the output format as above and runs your function against each of them in turn, returning a new array. The function that's generated is stored as a property of DataGrouper
according to a name you supply and also returned if you just want a local reference.
Well that's a lot of explanation. The code is reasonably straightforward, I hope!
I guess this could help, adding this before any tag of javascript:
try{
console
}catch(e){
console={}; console.log = function(){};
}
Since variable names in the BASH shell cannot contain a dot or space it is better to use an associative array in BASH like this:
#!/bin/bash
# declare an associative array
declare -A arr
# read file line by line and populate the array. Field separator is "="
while IFS='=' read -r k v; do
arr["$k"]="$v"
done < app.properties
Testing:
Use declare -p to show the result:
> declare -p arr
declare -A arr='([db.uat.passwd]="secret" [db.uat.user]="saple user" )'
GOOGLE SOLUTION - not a hack, like previous solutions. Use ProcessLifecycleOwner
Kotlin:
class ArchLifecycleApp : Application(), LifecycleObserver {
override fun onCreate() {
super.onCreate()
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onAppBackgrounded() {
//App in background
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onAppForegrounded() {
// App in foreground
}
}
Java:
public class ArchLifecycleApp extends Application implements LifecycleObserver {
@Override
public void onCreate() {
super.onCreate();
ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onAppBackgrounded() {
//App in background
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onAppForegrounded() {
// App in foreground
}
}
in app.gradle
dependencies {
...
implementation "android.arch.lifecycle:extensions:1.1.0"
//New Android X dependency is this -
implementation "androidx.lifecycle:lifecycle-extensions:2.0.0"
}
allprojects {
repositories {
...
google()
jcenter()
maven { url 'https://maven.google.com' }
}
}
You can read more about Lifecycle related architecture components here - https://developer.android.com/topic/libraries/architecture/lifecycle
You can install python with homebrew:
brew install python
Make sure that OSX uses the correct path:
which python
Then you can use the pip tool to install pandas:
pip install pandas
Make sure that all dependencies are installed. I followed this tutorial: http://penandpants.com/2013/04/04/install-scientific-python-on-mac-os-x/
Works fine on my machine.
echo "This is the main body of the mail" | mail -s "Subject of the Email" [email protected] -- -f [email protected] -F "Elvis Presley"
or
echo "This is the main body of the mail" | mail -s "Subject of the Email" [email protected] -aFrom:"Elvis Presley<[email protected]>"
Yes.
Map.Entry
can be used as a Pair
.
Unfortunately it does not help with Java 8 streams as the problem is that even though lambdas can take multiple arguments, the Java language only allows for returning a single value (object or primitive type). This implies that whenever you have a stream you end up with being passed a single object from the previous operation. This is a lack in the Java language, because if multiple return values was supported AND streams supported them we could have much nicer non-trivial tasks done by streams.
Until then, there is only little use.
EDIT 2018-02-12: While working on a project I wrote a helper class which helps handling the special case of having an identifier earlier in the stream you need at a later time but the stream part in between does not know about it. Until I get around to release it on its own it is available at IdValue.java with a unit test at IdValueTest.java
In the OpenGL ES 2.0/3.0 you can also combining OGL View and Android's UI-elements:
public class GameActivity extends AppCompatActivity {
private SurfaceView surfaceView;
@Override
protected void onCreate(Bundle state) {
setContentView(R.layout.activity_gl);
surfaceView = findViewById(R.id.oglView);
surfaceView.init(this.getApplicationContext());
...
}
}
public class SurfaceView extends GLSurfaceView {
private SceneRenderer renderer;
public SurfaceView(Context context) {
super(context);
}
public SurfaceView(Context context, AttributeSet attributes) {
super(context, attributes);
}
public void init(Context context) {
renderer = new SceneRenderer(context);
setRenderer(renderer);
...
}
}
Create layout activity_gl.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
tools:context=".activities.GameActivity">
<com.app.SurfaceView
android:id="@+id/oglView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<TextView ... />
<TextView ... />
<TextView ... />
</androidx.constraintlayout.widget.ConstraintLayout>
To update elements from the render thread, can use Handler/Looper.
Floating Point Exception happens because of an unexpected infinity or NaN. You can track that using gdb, which allows you to see what is going on inside your C program while it runs. For more details: https://www.cs.swarthmore.edu/~newhall/unixhelp/howto_gdb.php
In a nutshell, these commands might be useful...
gcc -g myprog.c
gdb a.out
gdb core a.out
ddd a.out
Yes, sort of.
You can explicitly size a container using units relative to font-size:
In addition you can use a few CSS properties such as overflow:hidden;
white-space:nowrap;
text-overflow:ellipsis;
to help limit the number as well.
The -maxdepth
option should be before the -name
option, like below.,
find . -maxdepth 1 -name "string" -print
here is generic swipe left detector for any view in kotlin using databinding
@BindingAdapter("onSwipeLeft")
fun View.setOnSwipeLeft(runnable: Runnable) {
setOnTouchListener(object : View.OnTouchListener {
var x0 = 0F; var y0 = 0F; var t0 = 0L
val defaultClickDuration = 200
override fun onTouch(v: View?, motionEvent: MotionEvent?): Boolean {
motionEvent?.let { event ->
when(event.action) {
MotionEvent.ACTION_DOWN -> {
x0 = event.x; y0 = event.y; t0 = System.currentTimeMillis()
}
MotionEvent.ACTION_UP -> {
val x1 = event.x; val y1 = event.y; val t1 = System.currentTimeMillis()
if (x0 == x1 && y0 == y1 && (t1 - t0) < defaultClickDuration) {
performClick()
return false
}
if (x0 > x1) { runnable.run() }
}
else -> {}
}
}
return true
}
})
}
and then to use it in your layout:
app:onSwipeLeft="@{() -> viewModel.swipeLeftHandler()}"
I think you can adapt the function to substract the two timestamps:
return EXTRACT(MINUTE FROM
TO_TIMESTAMP(to_char(p_date1,'DD-MON-YYYY HH:MI:SS'),'DD-MON-YYYY HH24:MI:SS')
-
TO_TIMESTAMP(to_char(p_date2,'DD-MON-YYYY HH:MI:SS'),'DD-MON-YYYY HH24:MI:SS')
);
I think you could simplify it by just using CAST(p_date as TIMESTAMP)
.
return EXTRACT(MINUTE FROM cast(p_date1 as TIMESTAMP) - cast(p_date2 as TIMESTAMP));
Remember dates and timestamps are big ugly numbers inside Oracle, not what we see in the screen; we don't need to tell him how to read them. Also remember timestamps can have a timezone defined; not in this case.
According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.
This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.
select num_rows from all_tables where table_name = 'MY_TABLE'
This query counts the current number of rows in MY_TABLE
select count(*) from my_table
By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.
In the documentation there's an asterisk by the column name, which leads to this note:
Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.
This means that unless you have gathered statistics on the table then this column will not have any data.
Statistics gathered in 11g+ with the default estimate_percent
, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent
less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.
If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.
Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.
For Mac Users
I am using Mac and I was facing the same problem while I was trying to push a project from Android Studio. The reason for that is another user had previously logged into GitHub and his credentials were saved in Keychain Access.
The solution is to delete all the information store in keychain for that process
Use RGB values combined with opacity to get the transparency that you wish.
For instance,
<div style=" background: rgb(255, 0, 0) ; opacity: 0.2;"> </div>
<div style=" background: rgb(255, 0, 0) ; opacity: 0.4;"> </div>
<div style=" background: rgb(255, 0, 0) ; opacity: 0.6;"> </div>
<div style=" background: rgb(255, 0, 0) ; opacity: 0.8;"> </div>
<div style=" background: rgb(255, 0, 0) ; opacity: 1;"> </div>
Similarly, with actual values without opacity, will give the below.
<div style=" background: rgb(243, 191, 189) ; "> </div>
<div style=" background: rgb(246, 143, 142) ; "> </div>
<div style=" background: rgb(249, 95 , 94) ; "> </div>
<div style=" background: rgb(252, 47, 47) ; "> </div>
<div style=" background: rgb(255, 0, 0) ; "> </div>
You can have a look at this WORKING EXAMPLE.
Now, if we specifically target your issue, here is the WORKING DEMO SPECIFIC TO YOUR ISSUE.
The HTML
<div class="social">
<img src="http://www.google.co.in/images/srpr/logo4w.png" border="0" />
</div>
The CSS:
social img{
opacity:0.5;
}
.social img:hover {
opacity:1;
background-color:black;
cursor:pointer;
background: rgb(255, 0, 0) ; opacity: 0.5;
}
Hope this helps Now.
First we'll create a basic CSV
[dumb@one pts]$ cat > file
a,b,c,d,e,f,g,h,i,k
1,2,3,4,5,6,7,8,9,10
a,b,c,d,e,f,g,h,i,k
1,2,3,4,5,6,7,8,9,10
Then we get the 1st column
[dumb@one pts]$ awk -F , '{print $1}' file
a
1
a
1
You can't do that from the initialization list,
Have a look at this:
http://www.cprogramming.com/tutorial/initialization-lists-c++.html
:)
Read the existing answers first, this is just an addendum.
Notice that you can raise exceptions with or without arguments.
Example:
raise SystemExit
exits the program but you might want to know what happened.So you can use this.
raise SystemExit("program exited")
this will print "program exited" to stderr before closing the program.
First off, it might not be good to just go by recall alone. You can simply achieve a recall of 100% by classifying everything as the positive class. I usually suggest using AUC for selecting parameters, and then finding a threshold for the operating point (say a given precision level) that you are interested in.
For how class_weight
works: It penalizes mistakes in samples of class[i]
with class_weight[i]
instead of 1. So higher class-weight means you want to put more emphasis on a class. From what you say it seems class 0 is 19 times more frequent than class 1. So you should increase the class_weight
of class 1 relative to class 0, say {0:.1, 1:.9}.
If the class_weight
doesn't sum to 1, it will basically change the regularization parameter.
For how class_weight="auto"
works, you can have a look at this discussion.
In the dev version you can use class_weight="balanced"
, which is easier to understand: it basically means replicating the smaller class until you have as many samples as in the larger one, but in an implicit way.
instead of this line -
int hours = stoi(hours0);
write this -
int hours = atoi(hours0.c_str());
Reference : int atoi(const char *str)
I would recommend using a Double not a double as your type then you check against null.
SELECT Customers.*
FROM Customers
WHERE NOT EXISTS (
SELECT *
FROM SUBSCRIBERS AS s
JOIN s.Cust_ID = Customers.Customer_ID)
When using “NOT IN”, the query performs nested full table scans, whereas for “NOT EXISTS”, the query can use an index within the sub-query.
Do this for a temporary fix
git push -u https://username:[email protected]/username/repo_name.git master
and
/or
are for control flow.
Ruby will not allow this as valid syntax:
false || raise "Error"
However this is valid:
false or raise "Error"
You can make the first work, with ()
but using or
is the correct method.
false || (raise "Error")
$(document).ready(function() {
$("#raaagh").click(function() {
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data) {
console.log(data);
$.ajax({
url:'ajax.php',
data: data,
dataType:'json',
success:function(data1) {
var y1=data1;
console.log(data1);
}
});
}
});
});
});
Use like this, first make a ajax call to get data, then your php function will return u the result which u wil get in data and pass that data to the new ajax call
semeTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
context.getResources().getDimension(R.dimen.text_size_in_dp))
If you're just searching for a string rather than a more complicated regular expression, you can use indexOf()
- but remember to lowercase both strings first because indexOf()
is case sensitive:
var string="Stackoverflow is the BEST";
var searchstring="best";
// lowercase both strings
var lcString=string.toLowerCase();
var lcSearchString=searchstring.toLowerCase();
var result = lcString.indexOf(lcSearchString)>=0;
alert(result);
Or in a single line:
var result = string.toLowerCase().indexOf(searchstring.toLowerCase())>=0;
Just press windows button and type %APPDATA% and type enter.
Above is the location where you can find \npm\node_modules folder. This is where global modules sit in your system.
Instead of switching autocommit off manually at restore time you can already dump your MySQL data in a way that includes all necessary statements right into your SQL file.
The command line parameter for mysqldump is --no-autocommit
. You might also consider to add --opt
which sets a combination of other parameters to speed up restore operations.
Here is an example for a complete mysqldump command line as I use it, containing --no-autocommit
and --opt
:
mysqldump -hlocalhost -uMyUser -p'MyPassword' --no-autocommit --opt --default-character-set=utf8 --quote-names MyDbName > dump.sql
For details of these parameters see the reference of mysqldump
If you don't know what backend is , you can read this: https://matplotlib.org/tutorials/introductory/usage.html#backends
Some people use matplotlib interactively from the python shell and have plotting windows pop up when they type commands. Some people run Jupyter notebooks and draw inline plots for quick data analysis. Others embed matplotlib into graphical user interfaces like wxpython or pygtk to build rich applications. Some people use matplotlib in batch scripts to generate postscript images from numerical simulations, and still others run web application servers to dynamically serve up graphs. To support all of these use cases, matplotlib can target different outputs, and each of these capabilities is called a backend; the "frontend" is the user facing code, i.e., the plotting code, whereas the "backend" does all the hard work behind-the-scenes to make the figure.
So when you type %matplotlib inline , it activates the inline backend. As discussed in the previous posts :
With this backend, the output of plotting commands is displayed inline within frontends like the Jupyter notebook, directly below the code cell that produced it. The resulting plots will then also be stored in the notebook document.
You can install pip
(or any other package) with easy_install
almost as described in the first answer. However you will need a HTTPS
proxy, too. The full sequence of commands is:
set http_proxy=http://proxy.myproxy.com
set https_proxy=http://proxy.myproxy.com
easy_install pip
You might also want to add a port to the proxy, such as http{s}_proxy=http://proxy.myproxy.com:8080
You can use this one also (sets a special listener to be called when an action is performed on the EditText), it works both for DONE and RETURN:
max.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {
Log.i(TAG,"Enter pressed");
}
return false;
}
});
This will not only change the max_retries but also enable a backoff strategy which makes requests to all http:// addresses sleep for a period of time before retrying (to a total of 5 times):
import requests
from urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
s = requests.Session()
retries = Retry(total=5,
backoff_factor=0.1,
status_forcelist=[ 500, 502, 503, 504 ])
s.mount('http://', HTTPAdapter(max_retries=retries))
s.get('http://httpstat.us/500')
As per documentation for Retry
: if the backoff_factor is 0.1, then sleep() will sleep for [0.1s, 0.2s, 0.4s, ...] between retries. It will also force a retry if the status code returned is 500, 502, 503 or 504.
Various other options to Retry
allow for more granular control:
MaxRetryError
, or to return a response with a response code in the 3xx range.NB: raise_on_status is relatively new, and has not made it into a release of urllib3 or requests yet. The raise_on_status keyword argument appears to have made it into the standard library at most in python version 3.6.
To make requests retry on specific HTTP status codes, use status_forcelist. For example, status_forcelist=[503] will retry on status code 503 (service unavailable).
By default, the retry only fires for these conditions:
TimeoutError
HTTPException
raised (from http.client in Python 3 else httplib).
This seems to be low-level HTTP exceptions, like URL or protocol not
formed correctly.SocketError
ProtocolError
Notice that these are all exceptions that prevent a regular HTTP response from being received. If any regular response is generated, no retry is done. Without using the status_forcelist, even a response with status 500 will not be retried.
To make it behave in a manner which is more intuitive for working with a remote API or web server, I would use the above code snippet, which forces retries on statuses 500, 502, 503 and 504, all of which are not uncommon on the web and (possibly) recoverable given a big enough backoff period.
EDITED: Import Retry
class directly from urllib3.
According to the MSDN documentation here, The basename argument specifies "The root name of the resource file without its extension but including any fully qualified namespace name. For example, the root name for the resource file named "MyApplication.MyResource.en-US.resources" is "MyApplication.MyResource"."
The ResourceManager will automatically try to retrieve the values for the current UI culture. If you want to use a specific language, you'll need to set the current UI culture to the language you wish to use.
I added the file Under Build Phase in Targets and the issue got resolved. For the steps to add the file, see my answer at:
I would personally use a complete editing package such as:
Then I would install "MikTeX" as the compiling package, which allows you to generate a PDF from your document, using the pdfLaTeX
compiler.
These are the different variables you have access to and their values, depending on the IIS configuration.
Scenario 1: Anonymous Authentication in IIS with impersonation off.
HttpContext.Current.Request.LogonUserIdentity.Name SERVER1\IUSR_SERVER1
HttpContext.Current.Request.IsAuthenticated False
HttpContext.Current.User.Identity.Name –
System.Environment.UserName ASPNET
Security.Principal.WindowsIdentity.GetCurrent().Name SERVER1\ASPNET
Scenario 2: Windows Authentication in IIS, impersonation off.
HttpContext.Current.Request.LogonUserIdentity.Name MYDOMAIN\USER1
HttpContext.Current.Request.IsAuthenticated True
HttpContext.Current.User.Identity.Name MYDOMAIN\USER1
System.Environment.UserName ASPNET
Security.Principal.WindowsIdentity.GetCurrent().Name SERVER1\ASPNET
Scenario 3: Anonymous Authentication in IIS, impersonation on
HttpContext.Current.Request.LogonUserIdentity.Name SERVER1\IUSR_SERVER1
HttpContext.Current.Request.IsAuthenticated False
HttpContext.Current.User.Identity.Name –
System.Environment.UserName IUSR_SERVER1
Security.Principal.WindowsIdentity.GetCurrent().Name SERVER1\IUSR_SERVER1
Scenario 4: Windows Authentication in IIS, impersonation on
HttpContext.Current.Request.LogonUserIdentity.Name MYDOMAIN\USER1
HttpContext.Current.Request.IsAuthenticated True
HttpContext.Current.User.Identity.Name MYDOMAIN\USER1
System.Environment.UserName USER1
Security.Principal.WindowsIdentity.GetCurrent().Name MYDOMAIN\USER1
Legend
SERVER1\ASPNET
: Identity of the running process on server.
SERVER1\IUSR_SERVER1
: Anonymous guest user defined in IIS.
MYDOMAIN\USER1
: The user of the remote client.
textarea {
border: 0;
overflow: auto; }
less CSS ^ you can't align the text to the bottom unfortunately.
@dsimcha wrote: Counting sort: When you are sorting integers with a limited range
I would change that to:
Counting sort: When you sort positive integers (0 - Integer.MAX_VALUE-2 due to the pigeonhole).
You can always get the max and min values as an efficiency heuristic in linear time as well.
Also you need at least n extra space for the intermediate array and it is stable obviously.
/**
* Some VMs reserve some header words in an array.
* Attempts to allocate larger arrays may result in
* OutOfMemoryError: Requested array size exceeds VM limit
*/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
(even though it actually will allow to MAX_VALUE-2) see: Do Java arrays have a maximum size?
Also I would explain that radix sort complexity is O(wn) for n keys which are integers of word size w. Sometimes w is presented as a constant, which would make radix sort better (for sufficiently large n) than the best comparison-based sorting algorithms, which all perform O(n log n) comparisons to sort n keys. However, in general w cannot be considered a constant: if all n keys are distinct, then w has to be at least log n for a random-access machine to be able to store them in memory, which gives at best a time complexity O(n log n). (from wikipedia)