Create two animation xml under res/anim folder
slide_down.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration="1000"
android:fromYDelta="0"
android:toYDelta="100%" />
</set>
slide_up.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration="1000"
android:fromYDelta="100%"
android:toYDelta="0" />
</set>
Load animation Like bellow Code and start animation when you want According to your Requirement
//Load animation
Animation slide_down = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.slide_down);
Animation slide_up = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.slide_up);
// Start animation
linear_layout.startAnimation(slide_down);
@Mark Rajcok gave a great solution for ion projects that include a range type input.
In any other case of non ion projects I will suggest this:
HTML:
<input type="text" name="points" #points maxlength="8" [(ngModel)]="range" (ngModelChange)="range=saverange($event, points)">
Component:
onChangeAchievement(eventStr: string, eRef): string {
//Do something (some manipulations) on input and than return it to be saved:
//In case you need to force of modifing the Element-Reference value on-focus of input:
var eventStrToReplace = eventStr.replace(/[^0-9,eE\.\+]+/g, "");
if (eventStr != eventStrToReplace) {
eRef.value = eventStrToReplace;
}
return this.getNumberOnChange(eventStr);
}
The idea here:
Letting the (ngModelChange)
method to do the Setter job:
(ngModelChange)="range=saverange($event, points)
Enabling direct access to the native Dom element using this call:
eRef.value = eventStrToReplace;
Depending what size you want your div
to be, you could utilize Bootstrap's built-in component thumbnail
class, along with (or without) the grid system to create borders around each of your div
items.
These examples on Bootstrap's website demonstrates the ease-of-use and lack of need for any special additional CSS
:
<div class="row">
<div class="col-xs-6 col-md-3">
<a href="#" class="thumbnail">
<img src="..." alt="...">
</a>
</div>
...
</div>
which produces the following div
grid items:
or add some additional content:
<div class="row">
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<img src="..." alt="...">
<div class="caption">
<h3>Thumbnail label</h3>
<p>...</p>
<p>
<a href="#" class="btn btn-primary" role="button">Button</a>
<a href="#" class="btn btn-default" role="button">Button</a>
</p>
</div>
</div>
</div>
</div>
which produces the following div
grid items:
This helped in my case:
options: {
responsive: true,
scales: {
yAxes: [{
display: true,
ticks: {
min:0,
max:100
}
}]
}
}
Let's try this way:
select
a.ip,
a.os,
a.hostname,
a.port,
a.protocol,
b.state
from a
left join b
on a.ip = b.ip
and a.port = b.port /*if you has to filter by columns from right table , then add this condition in ON clause*/
where a.somecolumn = somevalue /*if you have to filter by some column from left table, then add it to where condition*/
So, in where
clause you can filter result set by column from right table only on this way:
...
where b.somecolumn <> (=) null
You are missing a semicolon at the end of your 'struct' definition.
Also,
*sotrudnik
needs to be
sotrudnik*
For Sybase aka SQL Anywhere the following command outputs the structure of a table:
DESCRIBE 'TABLE_NAME';
I'm getting the same solution as @camino's comment on https://stackoverflow.com/a/19365454/10593190 and XavierStuvw's reply.
I got it to work (for installing ffmpeg) by simply reinstalling the whole thing from the beginning with all instances of $ ./configure
replaced by $ ./configure --enable-shared
(first make sure to delete all the folders and files including the .so files from the previous attempt).
Apparently this works because https://stackoverflow.com/a/13812368/10593190.
No.
You can use grouping selectors and/or multiple classes on a single element, or you can use a template language and process it with software to write your CSS.
See also my article on CSS inheritance.
To create sets you can use a varargs factory method instead of double-brace initialisation:
public static Set<T> setOf(T ... elements) {
return new HashSet<T>(Arrays.asList(elements));
}
The Google Collections library has lots of convenience methods like this, as well as loads of other useful functionality.
As for the idiom's obscurity, I encounter it and use it in production code all the time. I'd be more concerned about programmers who get confused by the idiom being allowed to write production code.
For anyone that wants to watch for a change to an object within an array of objects, this seemed to work for me (as the other solutions on this page didn't):
function MyController($scope) {
$scope.array = [
data1: {
name: 'name',
surname: 'surname'
},
data2: {
name: 'name',
surname: 'surname'
},
]
$scope.$watch(function() {
return $scope.data,
function(newVal, oldVal){
console.log(newVal, oldVal);
}, true);
Try this, It will help.
I have used this in my project.
SELECT
*
FROM
customer c
OUTER APPLY(SELECT top 1 * FROM purchase pi
WHERE pi.customer_id = c.Id order by pi.Id desc) AS [LastPurchasePrice]
I had the same issue. It's solved by adding following lines in .bashrc
:
export HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_HOME/lib/native
export HADOOP_OPTS="-Djava.library.path=$HADOOP_HOME/lib"
It has to do with the order in which bytes are stored in memory. The decimal number 5001
is 0x1389
in hexadecimal, so the bytes involved are 0x13
and 0x89
. Many devices store numbers in little-endian format, meaning that the least significant byte comes first. So in this particular example it means that in memory the number 5001
will be stored as
0x89 0x13
The htons()
function makes sure that numbers are stored in memory in network byte order, which is with the most significant byte first. It will therefore swap the bytes making up the number so that in memory the bytes will be stored in the order
0x13 0x89
On a little-endian machine, the number with the swapped bytes is 0x8913
in hexadecimal, which is 35091
in decimal notation. Note that if you were working on a big-endian machine, the htons()
function would not need to do any swapping since the number would already be stored in the right way in memory.
The underlying reason for all this swapping has to do with the network protocols in use, which require the transmitted packets to use network byte order.
Using the SysUtils.TStringHelper.Split function, introduced in Delphi XE3:
var
MyString: String;
Splitted: TArray<String>;
begin
MyString := 'word:doc,txt,docx';
Splitted := MyString.Split([':']);
end.
This will split a string with a given delimiter into an array of strings.
you can use the below css styles for all browsers except Firefox 30
select {
background: url(dropdown_arw.png) no-repeat right center;
appearance: none;
-moz-appearance: none;
-webkit-appearance: none;
width: 90px;
text-indent: 0.01px;
text-overflow: "";
}
demo page - http://kvijayanand.in/jquery-plugin/test.html
Updated
here is solution for Firefox 30. little trick for custom select elements in firefox :-moz-any() css pseudo class.
Before you run make oldconfig
, you need to copy a kernel configuration file from an older kernel into the root directory of the new kernel.
You can find a copy of the old kernel configuration file on a running system at /boot/config-3.11.0
. Alternatively, kernel source code has configs in linux-3.11.0/arch/x86/configs/{i386_defconfig / x86_64_defconfig}
If your kernel source is located at /usr/src/linux
:
cd /usr/src/linux
cp /boot/config-3.9.6-gentoo .config
make oldconfig
If you're only doing a few of them (and/or the array size is large), then you were on the right track with array_search:
$list = array('string1', 'string2', 'string3');
$k = array_search('string2', $list); //$k = 1;
If you want all (or a lot of them), a loop will prob do you better:
foreach ($list as $key => $value) {
echo $value . " in " . $key . ", ";
}
// Prints "string1 in 0, string2 in 1, string3 in 2, "
I found the solutions here when the Stream is created of list or array (and you know the size). But what if Stream is with unknown size? In this case try this variant:
public class WithIndex<T> {
private int index;
private T value;
WithIndex(int index, T value) {
this.index = index;
this.value = value;
}
public int index() {
return index;
}
public T value() {
return value;
}
@Override
public String toString() {
return value + "(" + index + ")";
}
public static <T> Function<T, WithIndex<T>> indexed() {
return new Function<T, WithIndex<T>>() {
int index = 0;
@Override
public WithIndex<T> apply(T t) {
return new WithIndex<>(index++, t);
}
};
}
}
Usage:
public static void main(String[] args) {
Stream<String> stream = Stream.of("a", "b", "c", "d", "e");
stream.map(WithIndex.indexed()).forEachOrdered(e -> {
System.out.println(e.index() + " -> " + e.value());
});
}
var result = from sc in enumerableOfSomeClass
join soc in enumerableOfSomeOtherClass
on sc.Property1 equals soc.Property2
select new { SomeClass = sc, SomeOtherClass = soc };
Would be equivalent to:
var result = enumerableOfSomeClass
.Join(enumerableOfSomeOtherClass,
sc => sc.Property1,
soc => soc.Property2,
(sc, soc) => new
{
SomeClass = sc,
SomeOtherClass = soc
});
As you can see, when it comes to joins, query syntax is usually much more readable than lambda syntax.
Although this question is related to string conversion, I stumbled upon this while wanting an easy way to write arrays to my log files. If you just want the info, and don't care about the exact cleanliness of a string you might consider:
json_encode($array)
POSIX 7 example
It is also worth checking the example from the standard: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/getopts.html
aflag=
bflag=
while getopts ab: name
do
case $name in
a) aflag=1;;
b) bflag=1
bval="$OPTARG";;
?) printf "Usage: %s: [-a] [-b value] args\n" $0
exit 2;;
esac
done
if [ ! -z "$aflag" ]; then
printf "Option -a specified\n"
fi
if [ ! -z "$bflag" ]; then
printf 'Option -b "%s" specified\n' "$bval"
fi
shift $(($OPTIND - 1))
printf "Remaining arguments are: %s\n" "$*"
And then we can try it out:
$ sh a.sh
Remaining arguments are:
$ sh a.sh -a
Option -a specified
Remaining arguments are:
$ sh a.sh -b
No arg for -b option
Usage: a.sh: [-a] [-b value] args
$ sh a.sh -b myval
Option -b "myval" specified
Remaining arguments are:
$ sh a.sh -a -b myval
Option -a specified
Option -b "myval" specified
Remaining arguments are:
$ sh a.sh remain
Remaining arguments are: remain
$ sh a.sh -- -a remain
Remaining arguments are: -a remain
Tested in Ubuntu 17.10, sh
is dash 0.5.8.
Note: There appears to be a fix implemented in JDK 10 that ensures the Custom Thread Pool uses the expected number of threads.
Parallel stream execution within a custom ForkJoinPool should obey the parallelism https://bugs.openjdk.java.net/browse/JDK-8190974
The answer to the question was already posted by the @latemail in the comments above. You can use regular expressions for the second and subsequent arguments of filter
like this:
dplyr::filter(df, !grepl("RTB",TrackingPixel))
Since you have not provided the original data, I will add a toy example using the mtcars
data set. Imagine you are only interested in cars produced by Mazda or Toyota.
mtcars$type <- rownames(mtcars)
dplyr::filter(mtcars, grepl('Toyota|Mazda', type))
mpg cyl disp hp drat wt qsec vs am gear carb type
1 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4
2 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 Mazda RX4 Wag
3 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 Toyota Corolla
4 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1 Toyota Corona
If you would like to do it the other way round, namely excluding Toyota and Mazda cars, the filter
command looks like this:
dplyr::filter(mtcars, !grepl('Toyota|Mazda', type))
If you have done this to make sure the user can't close the window:
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
Then you should change your pullThePlug()
method to be
public void pullThePlug() {
// this will make sure WindowListener.windowClosing() et al. will be called.
WindowEvent wev = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);
// this will hide and dispose the frame, so that the application quits by
// itself if there is nothing else around.
setVisible(false);
dispose();
// if you have other similar frames around, you should dispose them, too.
// finally, call this to really exit.
// i/o libraries such as WiiRemoteJ need this.
// also, this is what swing does for JFrame.EXIT_ON_CLOSE
System.exit(0);
}
I found this to be the only way that plays nice with the WindowListener
and JFrame.DO_NOTHING_ON_CLOSE
.
Yes, 1 byte does encode a character (inc spaces etc) from the ASCII set. However in data units assigned to character encoding it can and often requires in practice up to 4 bytes. This is because English is not the only character set. And even in English documents other languages and characters are often represented. The numbers of these are very many and there are very many other encoding sets, which you may have heard of e.g. BIG-5, UTF-8, UTF-32. Most computers now allow for these uses and ensure the least amount of garbled text (which usually means a missing encoding set.) 4 bytes is enough to cover these possible encodings. I byte per character does not allow for this and in use it is larger often 4 bytes per possible character for all encodings, not just ASCII. The final character may only need a byte to function or be represented on screen, but requires 4 bytes to be located in the rather vast global encoding "works".
For renaming existing file without using plugins you should use command
:Explore
This command allow you explore files in.directory, delete or rename them. than you should navigate to neccessary file in explorer than type R
command which will allow you to rename file name
Simply point the new repo by changing the GIT repo URL with this command:
git remote set-url origin [new repo URL]
Example: git remote set-url origin [email protected]:Batman/batmanRepoName.git
Now, pushing and pulling are linked to the new REPO.
Then push normally like so:
git push -u origin master
One way to do this without JS is to use the hover action to reveal a HTML element that is otherwise hidden, see this codepen:
http://codepen.io/c0un7z3r0/pen/LZWXEw
Note that the span that contains the tooltip content is relative to the parent li. The magic is here:
ul#list_of_thrones li > span{
display:none;
}
ul#list_of_thrones li:hover > span{
position: absolute;
display:block;
...
}
As you can see, the span is hidden unless the listitem is hovered over, thus revealing the span element, the span can contain as much html as you need. In the codepen attached I have also used a :after element for the arrow but that of course is entirely optional and has only been included in this example for cosmetic purposes.
I hope this helps, I felt compelled to post as all the other answers included JS solutions but the OP asked for a HTML/CSS only solution.
You can't modify the references in an enumerator whilst you enumerate over it; you must keep track of the ones to remove then remove them.
This is an example of the work around:
List<string> listbox = new List<string>();
List<object> toRemove = new List<object>();
foreach (string item in listbox)
{
string removelistitem = "OBJECT";
if (item.Contains(removelistitem))
{
toRemove.Add(item);
}
}
foreach (string item in toRemove)
{
listbox.Remove(item);
}
But if you're using c#3.5, you could say something like this.
listbox.Items = listbox.Items.Select(n => !n.Contains("OBJECT"));
(This is my third answer because I misunderstood what your code was doing in my original, and then made a small but crucial mistake in my second—hopefully three's a charm.
Edits: Since this seems to be a popular answer, I've made a few modifications to improve its implementation over the years—most not too major. This is so if folks use it as template, it will provide an even better basis.
As others have pointed out, your MemoryError
problem is most likely because you're attempting to read the entire contents of huge files into memory and then, on top of that, effectively doubling the amount of memory needed by creating a list of lists of the string values from each line.
Python's memory limits are determined by how much physical ram and virtual memory disk space your computer and operating system have available. Even if you don't use it all up and your program "works", using it may be impractical because it takes too long.
Anyway, the most obvious way to avoid that is to process each file a single line at a time, which means you have to do the processing incrementally.
To accomplish this, a list of running totals for each of the fields is kept. When that is finished, the average value of each field can be calculated by dividing the corresponding total value by the count of total lines read. Once that is done, these averages can be printed out and some written to one of the output files. I've also made a conscious effort to use very descriptive variable names to try to make it understandable.
try:
from itertools import izip_longest
except ImportError: # Python 3
from itertools import zip_longest as izip_longest
GROUP_SIZE = 4
input_file_names = ["A1_B1_100000.txt", "A2_B2_100000.txt", "A1_B2_100000.txt",
"A2_B1_100000.txt"]
file_write = open("average_generations.txt", 'w')
mutation_average = open("mutation_average", 'w') # left in, but nothing written
for file_name in input_file_names:
with open(file_name, 'r') as input_file:
print('processing file: {}'.format(file_name))
totals = []
for count, fields in enumerate((line.split('\t') for line in input_file), 1):
totals = [sum(values) for values in
izip_longest(totals, map(float, fields), fillvalue=0)]
averages = [total/count for total in totals]
for print_counter, average in enumerate(averages):
print(' {:9.4f}'.format(average))
if print_counter % GROUP_SIZE == 0:
file_write.write(str(average)+'\n')
file_write.write('\n')
file_write.close()
mutation_average.close()
You can use the npm modules jsdom and htmlparser to create and parse a DOM in Node.JS.
Other options include:
Out of all these options, I prefer using the Node.js option, because it uses the standard W3C DOM accessor methods and I can reuse code on both the client and server. I wish BeautifulSoup's methods were more similar to the W3C dom, and I think converting your HTML to XHTML to write XSLT is just plain sadistic.
You can use the bindParam
or bindValue
methods to help prepare your statement.
It makes things more clear on first sight instead of doing $check->execute(array(':name' => $name));
Especially if you are binding multiple values/variables.
Check the clear, easy to read example below:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname LIMIT 1");
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetch(PDO::FETCH_ASSOC);
$row_id = $check['id'];
// do something
}
If you are expecting multiple rows remove the LIMIT 1
and change the fetch method into fetchAll
:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname");// removed limit 1
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetchAll(PDO::FETCH_ASSOC);
//$check will now hold an array of returned rows.
//let's say we need the second result, i.e. index of 1
$row_id = $check[1]['id'];
// do something
}
For those using force directed graphs in D3 v4/v5, the size
method doesn't exist any more. Something like the following worked for me (based on this github issue):
simulation
.force("center", d3.forceCenter(width / 2, height / 2))
.force("x", d3.forceX(width / 2))
.force("y", d3.forceY(height / 2))
.alpha(0.1).restart();
I am not sure what the last line means. Does it mean, I read the file, create multiple Movie objects. Then make a vector of pointers where each element (pointer) points to one of those Movie objects?
I would guess this is what is intended. The intent is probably that you read the data for one movie, allocate an object with new
, fill the object in with the data, and then push the address of the data onto the vector
(probably not the best design, but most likely what's intended anyway).
Avoiding sudo
:
python <(curl https://bootstrap.pypa.io/get-pip.py) --user
echo 'export "PATH=$HOME/Library/Python/2.7/bin:$PATH"' >> ~/.bash_profile
From:
You are comparing two objects for equality. The snippet:
if (obj == this) { return true; }
is a quick test that can be read
"If the object I'm comparing myself to is me, return true"
. You usually see this happen in equals
methods so they can exit early and avoid other costly comparisons.
By adding the external jar into your build path just adds the jar to your package, but it will not be available during runtime.
In order for the jar to be available at runtime, you need to:
assets
folder If you want your button to call the routine you have written in filename.js you have to edit filename.js so that the code you want to run is the body of a function. For you can call a function, not a source file. (A source file has no entry point)
If the current content of your filename.js is:
alert('Hello world');
_x000D_
you have to change it to:
function functionName(){_x000D_
alert('Hello world');_x000D_
}
_x000D_
Then you have to load filename.js in the header of your html page by the line:
<head>_x000D_
<script type="text/javascript" src="Public/Scripts/filename.js"></script>_x000D_
</head>
_x000D_
so that you can call the function contained in filename.js by your button:
<button onclick="functionName()">Call the function</button>
_x000D_
I have made a little working example. A simple HTML page asks the user to input her name, and when she clicks the button, the function inside Public/Scripts/filename.js is called passing the inserted string as a parameter so that a popup says "Hello, <insertedName>!".
Here is the calling HTML page:
<html>_x000D_
_x000D_
<head>_x000D_
<script type="text/javascript" src="Public/Scripts/filename.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
What's your name? <input id="insertedName" />_x000D_
<button onclick="functionName(insertedName.value)">Say hello</button>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
And here is Public/Scripts/filename.js
function functionName( s ){_x000D_
alert('Hello, ' + s + '!');_x000D_
}
_x000D_
Yes, quite straight forward:
Private _name As String
Public Property Name() As String
Get
Return _name
End Get
Private Set(ByVal value As String)
_name = value
End Set
End Property
If you do not have access to the TestRunner
type information in the calling assembly (it sounds like you may not), you can call the method like this:
Assembly assembly = Assembly.LoadFile(@"C:\dyn.dll");
Type type = assembly.GetType("TestRunner");
var obj = Activator.CreateInstance(type);
// Alternately you could get the MethodInfo for the TestRunner.Run method
type.InvokeMember("Run",
BindingFlags.Default | BindingFlags.InvokeMethod,
null,
obj,
null);
If you have access to the IRunnable
interface type, you can cast your instance to that (rather than the TestRunner
type, which is implemented in the dynamically created or loaded assembly, right?):
Assembly assembly = Assembly.LoadFile(@"C:\dyn.dll");
Type type = assembly.GetType("TestRunner");
IRunnable runnable = Activator.CreateInstance(type) as IRunnable;
if (runnable == null) throw new Exception("broke");
runnable.Run();
Why don't you go for awk:
awk '/Start pattern/,/End pattern/' filename
Subtract datetime.timedelta(days=1)
Perhaps this is what you are looking for:
import os
os.chdir(default_path)
<ui:include>
Most basic way is <ui:include>
. The included content must be placed inside <ui:composition>
.
Kickoff example of the master page /page.xhtml
:
<!DOCTYPE html>
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<h:head>
<title>Include demo</title>
</h:head>
<h:body>
<h1>Master page</h1>
<p>Master page blah blah lorem ipsum</p>
<ui:include src="/WEB-INF/include.xhtml" />
</h:body>
</html>
The include page /WEB-INF/include.xhtml
(yes, this is the file in its entirety, any tags outside <ui:composition>
are unnecessary as they are ignored by Facelets anyway):
<ui:composition
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<h2>Include page</h2>
<p>Include page blah blah lorem ipsum</p>
</ui:composition>
This needs to be opened by /page.xhtml
. Do note that you don't need to repeat <html>
, <h:head>
and <h:body>
inside the include file as that would otherwise result in invalid HTML.
You can use a dynamic EL expression in <ui:include src>
. See also How to ajax-refresh dynamic include content by navigation menu? (JSF SPA).
<ui:define>
/<ui:insert>
A more advanced way of including is templating. This includes basically the other way round. The master template page should use <ui:insert>
to declare places to insert defined template content. The template client page which is using the master template page should use <ui:define>
to define the template content which is to be inserted.
Master template page /WEB-INF/template.xhtml
(as a design hint: the header, menu and footer can in turn even be <ui:include>
files):
<!DOCTYPE html>
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<h:head>
<title><ui:insert name="title">Default title</ui:insert></title>
</h:head>
<h:body>
<div id="header">Header</div>
<div id="menu">Menu</div>
<div id="content"><ui:insert name="content">Default content</ui:insert></div>
<div id="footer">Footer</div>
</h:body>
</html>
Template client page /page.xhtml
(note the template
attribute; also here, this is the file in its entirety):
<ui:composition template="/WEB-INF/template.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<ui:define name="title">
New page title here
</ui:define>
<ui:define name="content">
<h1>New content here</h1>
<p>Blah blah</p>
</ui:define>
</ui:composition>
This needs to be opened by /page.xhtml
. If there is no <ui:define>
, then the default content inside <ui:insert>
will be displayed instead, if any.
<ui:param>
You can pass parameters to <ui:include>
or <ui:composition template>
by <ui:param>
.
<ui:include ...>
<ui:param name="foo" value="#{bean.foo}" />
</ui:include>
<ui:composition template="...">
<ui:param name="foo" value="#{bean.foo}" />
...
</ui:composition >
Inside the include/template file, it'll be available as #{foo}
. In case you need to pass "many" parameters to <ui:include>
, then you'd better consider registering the include file as a tagfile, so that you can ultimately use it like so <my:tagname foo="#{bean.foo}">
. See also When to use <ui:include>, tag files, composite components and/or custom components?
You can even pass whole beans, methods and parameters via <ui:param>
. See also JSF 2: how to pass an action including an argument to be invoked to a Facelets sub view (using ui:include and ui:param)?
The files which aren't supposed to be publicly accessible by just entering/guessing its URL, need to be placed in /WEB-INF
folder, like as the include file and the template file in above example. See also Which XHTML files do I need to put in /WEB-INF and which not?
There doesn't need to be any markup (HTML code) outside <ui:composition>
and <ui:define>
. You can put any, but they will be ignored by Facelets. Putting markup in there is only useful for web designers. See also Is there a way to run a JSF page without building the whole project?
The HTML5 doctype is the recommended doctype these days, "in spite of" that it's a XHTML file. You should see XHTML as a language which allows you to produce HTML output using a XML based tool. See also Is it possible to use JSF+Facelets with HTML 4/5? and JavaServer Faces 2.2 and HTML5 support, why is XHTML still being used.
CSS/JS/image files can be included as dynamically relocatable/localized/versioned resources. See also How to reference CSS / JS / image resource in Facelets template?
You can put Facelets files in a reusable JAR file. See also Structure for multiple JSF projects with shared code.
For real world examples of advanced Facelets templating, check the src/main/webapp
folder of Java EE Kickoff App source code and OmniFaces showcase site source code.
You can find the answer on this other S.O. question:
MySQL - can I limit the maximum time allowed for a query to run?
a cron job that runs every second on your database server, connecting and doing something like this:
- SHOW PROCESSLIST
- Find all connections with a query time larger than your maximum desired time
- Run KILL [process id] for each of those processes
I could never get $viewContentLoaded
to work for me, and ng-init
should really only be used in an ng-repeat
(according to the documentation), and also calling a function directly in a controller can cause errors if the code relies on an element that hasn't been defined yet.
This is what I do and it works for me:
$scope.$on('$routeChangeSuccess', function () {
// do something
});
Unless you're using ui-router
. Then it's:
$scope.$on('$stateChangeSuccess', function () {
// do something
});
Replace the whitespace characters, and then convert it(using the intval function or by regular typecasting)
intval(str_replace(" ", "", $b))
I've to add the following in the settings.json file of vscode to remove the warning.
"javascript.implicitProjectConfig.experimentalDecorators": true
VSCode -> Preferences -> Settings
UPDATE
As Clepsyd pointed out, this setting had been deprecated. You need to use now
"js/ts.implicitProjectConfig.experimentalDecorators":true
You may try this example:
<form>_x000D_
<h1>Hello! I'm duke! What's you name?</h1>_x000D_
<input type="text" name="user">_x000D_
<br>_x000D_
<br>_x000D_
<input type="submit" value="submit"> _x000D_
<input type="reset">_x000D_
</form>_x000D_
<h1>Hello ${param.user}</h1> _x000D_
<!-- its Expression Language -->
_x000D_
For those who are looking for pure javascript solution
document.getElementById(location.hash.substring(1)).style.display = 'block'
Hope this saves you some time.
Why not create symlinks the other way around? Meaning instead of linking from the Git repository to the application directory, just link the other way around.
For example, let’s say I am setting up an application installed in ~/application
that needs a configuration file config.conf
:
config.conf
to my Git repository, for example, at ~/repos/application/config.conf
.~/application
by running ln -s ~/repos/application/config.conf
.This approach might not always work, but it worked well for me so far.
This means that Jupyter is still running the kernel. It is possible that you are running an infinite loop within the kernel and that is why it can't complete the execution.
Try manually stopping the kernel by pressing the stop button at the top. If that doesn't work, interrupt it and restart it by going to the "Kernel" menu. This should disconnect it.
Otherwise, I would recommend closing and reopening the notebook. The problem may also be with your code.
Whenever you're confused, I would suggest consulting the Javadoc as the first place for your clarification.
From the javadoc about System
, here's what the doc says:
public final class System
extends Object
The System class contains several useful class fields and methods. It cannot be instantiated.
Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.
Since:
JDK1.0
Regarding System.out
public static final PrintStream out
The "standard" output stream. This stream is already open and ready to accept output data. Typically this stream corresponds to display output or another output destination specified by the host environment or user.
For simple stand-alone Java applications, a typical way to write a line of output data is:
System.out.println(data)
inspired by @SteveLazaridis's answer, which would fail, here is a POSIX shell function - just copy and paste into a file named cpx
in yout $PATH
and make it executible (chmod a+x cpr
). [Source is now maintained in my GitLab.
#!/bin/sh
# usage: cpx [-n|--dry-run] "from_path" "to_path" "newline_separated_exclude_list"
# limitations: only excludes from "from_path", not it's subdirectories
cpx() {
# run in subshell to avoid collisions
(_CopyWithExclude "$@")
}
_CopyWithExclude() {
case "$1" in
-n|--dry-run) { DryRun='echo'; shift; } ;;
esac
from="$1"
to="$2"
exclude="$3"
$DryRun mkdir -p "$to"
if [ -z "$exclude" ]; then
cp "$from" "$to"
return
fi
ls -A1 "$from" \
| while IFS= read -r f; do
unset excluded
if [ -n "$exclude" ]; then
for x in $(printf "$exclude"); do
if [ "$f" = "$x" ]; then
excluded=1
break
fi
done
fi
f="${f#$from/}"
if [ -z "$excluded" ]; then
$DryRun cp -R "$f" "$to"
else
[ -n "$DryRun" ] && echo "skip '$f'"
fi
done
}
# Do not execute if being sourced
[ "${0#*cpx}" != "$0" ] && cpx "$@"
Example usage
EXCLUDE="
.git
my_secret_stuff
"
cpr "$HOME/my_stuff" "/media/usb" "$EXCLUDE"
We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.
Check your linker flags:
Target > Build Settings > Other Linker Flags
You should see -lApptentiveConnect
listed as a linker flag:
... -ObjC -lApptentiveConnect ...
You should also see our required Frameworks listed:
UIKit
-ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit
I'd recommend using http://shapecatcher.com/ to help search for unicode characters. It allows you to draw the shape you're after, and then lists the closest matches to that shape.
Pandas has a datetime round feature, but as with most things in Pandas it needs to be in Series format.
>>> ts = pd.Series(pd.date_range(Dt(2019,1,1,1,1),Dt(2019,1,1,1,4),periods=8))
>>> print(ts)
0 2019-01-01 01:01:00.000000000
1 2019-01-01 01:01:25.714285714
2 2019-01-01 01:01:51.428571428
3 2019-01-01 01:02:17.142857142
4 2019-01-01 01:02:42.857142857
5 2019-01-01 01:03:08.571428571
6 2019-01-01 01:03:34.285714285
7 2019-01-01 01:04:00.000000000
dtype: datetime64[ns]
>>> ts.dt.round('1min')
0 2019-01-01 01:01:00
1 2019-01-01 01:01:00
2 2019-01-01 01:02:00
3 2019-01-01 01:02:00
4 2019-01-01 01:03:00
5 2019-01-01 01:03:00
6 2019-01-01 01:04:00
7 2019-01-01 01:04:00
dtype: datetime64[ns]
Docs - Change the frequency string as needed.
Requests natively supports basic auth only with user-pass params, not with tokens.
You could, if you wanted, add the following class to have requests support token based basic authentication:
import requests
from base64 import b64encode
class BasicAuthToken(requests.auth.AuthBase):
def __init__(self, token):
self.token = token
def __call__(self, r):
authstr = 'Basic ' + b64encode(('token:' + self.token).encode('utf-8')).decode('utf-8')
r.headers['Authorization'] = authstr
return r
Then, to use it run the following request :
r = requests.get(url, auth=BasicAuthToken(api_token))
An alternative would be to formulate a custom header instead, just as was suggested by other users here.
Your stored procedure is designed to accept a single parameter, Arg1List. You can't pass 4 parameters to a procedure that only accepts one.
To make it work, the code that calls your procedure will need to concatenate your parameters into a single string of no more than 3000 characters and pass it in as a single parameter.
One thing that could have happened:
Hence, at compile time for the version X, the JVM will generate a first Serial ID (for version X) and it will do the same with the other version Y (another Serial ID).
When your program tries to de-serialize the data, it can't because the two classes do not have the same Serial ID and your program have no guarantee that the two Serialized objects correspond to the same class format.
Assuming you changed your constructor in the mean time and this should make sense to you.
when curl
is used to download a large file then CURLOPT_TIMEOUT
is the main option you have to set for.
CURLOPT_RETURNTRANSFER
has to be true in case you are getting file like pdf/csv/image etc.
You may find the further detail over here(correct url) Curl Doc
From that page:
curl_setopt($request, CURLOPT_TIMEOUT, 300); //set timeout to 5 mins
curl_setopt($request, CURLOPT_RETURNTRANSFER, true); // true to get the output as string otherwise false
You can also use the restore menu in MySQL Administrator. You just have to open the back-up file, and then click the restore button.
15841:error:140790E5:SSL routines:SSL23_WRITE:ssl handshake failure:s23_lib.c:188:
...
SSL handshake has read 0 bytes and written 121 bytes
This is a handshake failure. The other side closes the connection without sending any data ("read 0 bytes"). It might be, that the other side does not speak SSL at all. But I've seen similar errors on broken SSL implementation, which do not understand newer SSL version. Try if you get a SSL connection by adding -ssl3
to the command line of s_client.
With the directory
parameter:
impdp system/password@$ORACLE_SID schemas=USER_SCHEMA directory=MY_DIR \
dumpfile=mydumpfile.dmp logfile=impdpmydumpfile.log
The default directory is DATA_PUMP_DIR
, which is presumably set to /u01/app/oracle/admin/mydatabase/dpdump
on your system.
To use a different directory you (or your DBA) will have to create a new directory object in the database, which points to the Oracle-visible operating system directory you put the file into, and assign privileges to the user doing the import.
Here is a good tutorial with code. Let me know if it works for you! This is also a good tutorial.
EDIT
In This example, all you need to do is add this line:
gallery.setSelection(1);
after setting the adapter to gallery object, that is this line:
gallery.setAdapter(new ImageAdapter(this));
UPDATE1
Alright, I got your problem. This open source library is your solution. I also have used it for one of my projects. Hope this will solve your problem finally.
UPDATE2:
I would suggest you to go through this tutorial. You might get idea. I think I got your problem, you want the horizontal scrollview with snap. Try to search with that keyword on google or out here, you might get your solution.
do docker cp file.sql <CONTAINER NAME>:/file.sql
first
then docker exec -i <CONTAINER NAME> mysql -u user -p
then inside mysql container execute source \file.sql
You can vertically align a floated element in a way which works on IE 6+. It doesn't need full table markup either. This method isn't perfectly clean - includes wrappers and there are a few things to be aware of e.g. if you have too much text outspilling the container - but it's pretty good.
Short answer: You just need to apply display: table-cell
to an element inside the floated element (table cells don't float), and use a fallback with position: absolute
and top
for old IE.
Long answer: Here's a jsfiddle showing the basics. The important stuff summarized (with a conditional comment adding an .old-ie class):
.wrap {
float: left;
height: 100px; /* any fixed amount */
}
.wrap2 {
height: inherit;
}
.content {
display: table-cell;
height: inherit;
vertical-align: middle;
}
.old-ie .wrap{
position: relative;
}
.old-ie .wrap2 {
position: absolute;
top: 50%;
}
.old-ie .content {
position: relative;
top: -50%;
display: block;
}
Here's a jsfiddle that deliberately highlight the minor faults with this method. Note how:
overflow: auto;
don't seem to work)Those are pretty minor limitations, but worth being aware of.
It's pretty simple.
HTML:
<img id="theImage" src="yourImage.png">
<a id="showImage">Show image</a>
JavaScript:
document.getElementById("showImage").onclick = function() {
document.getElementById("theImage").style.visibility = "visible";
}
CSS:
#theImage { visibility: hidden; }
Call "setWarningMsg()" Method and pass the text that you want to show.
exm:- setWarningMsg("thank you for using java");
public static void setWarningMsg(String text){
Toolkit.getDefaultToolkit().beep();
JOptionPane optionPane = new JOptionPane(text,JOptionPane.WARNING_MESSAGE);
JDialog dialog = optionPane.createDialog("Warning!");
dialog.setAlwaysOnTop(true);
dialog.setVisible(true);
}
Or Just use
JOptionPane optionPane = new JOptionPane("thank you for using java",JOptionPane.WARNING_MESSAGE);
JDialog dialog = optionPane.createDialog("Warning!");
dialog.setAlwaysOnTop(true); // to show top of all other application
dialog.setVisible(true); // to visible the dialog
You can use JOptionPane. (WARNING_MESSAGE or INFORMATION_MESSAGE or ERROR_MESSAGE)
For file operations, Python uses the operating system's default buffering unless you configure it do otherwise. You can specify a buffer size, unbuffered, or line buffered.
For example, the open function takes a buffer size argument.
http://docs.python.org/library/functions.html#open
"The optional buffering argument specifies the file’s desired buffer size:"
code:
bufsize = 0
f = open('file.txt', 'w', buffering=bufsize)
With the plugin: jQuery Selection Box. You can do this:
var myOptions = {
"Value 1" : "Text 1",
"Value 2" : "Text 2",
"Value 3" : "Text 3"
}
$("#myselect2").addOption(myOptions, false);
It's work for me
SELECT CONCAT(column1, ' ' ,column2) AS newColumn;
A view uses a query to pull data from the underlying tables.
A materialized view is a table on disk that contains the result set of a query.
Materialized views are primarily used to increase application performance when it isn't feasible or desirable to use a standard view with indexes applied to it. Materialized views can be updated on a regular basis either through triggers or by using the ON COMMIT REFRESH
option. This does require a few extra permissions, but it's nothing complex. ON COMMIT REFRESH
has been in place since at least Oracle 10.
May I suggest a little simplification of @ashishduh's answer:
public class AlertDialogFragment extends DialogFragment {
public static final String ARG_TITLE = "AlertDialog.Title";
public static final String ARG_MESSAGE = "AlertDialog.Message";
public static void showAlert(String title, String message, Fragment targetFragment) {
DialogFragment dialog = new AlertDialogFragment();
Bundle args = new Bundle();
args.putString(ARG_TITLE, title);
args.putString(ARG_MESSAGE, message);
dialog.setArguments(args);
dialog.setTargetFragment(targetFragment, 0);
dialog.show(targetFragment.getFragmentManager(), "tag");
}
public AlertDialogFragment() {}
@NonNull
@Override
public AlertDialog onCreateDialog(Bundle savedInstanceState)
{
Bundle args = getArguments();
String title = args.getString(ARG_TITLE, "");
String message = args.getString(ARG_MESSAGE, "");
return new AlertDialog.Builder(getActivity())
.setTitle(title)
.setMessage(message)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, null);
}
})
.create();
}
It removes the need for the user (of the class) to be familiar with the internals of the component and makes usage really simple:
AlertDialogFragment.showAlert(title, message, this);
P.S. In my case I needed a simple alert dialog so that's what I created. You can apply the approach to a Yes/No or any other type you need.
I also had the same issue, I solved the problem by adding a ng-submit which sets the variable submitted to true.
<form name="form" ng-submit="submitted = true" novalidate>
<div>
<span ng-if="submitted && form.email.$error.email">invalid email address</span>
<span ng-if="submitted && form.email.$error.required">required</span>
<label>email</label>
<input type="email" name="email" ng-model="user.email" required>
</div>
<div>
<span ng-if="submitted && form.name.$error.required">required</span>
<label>name</label>
<input type="text" name="name" ng-model="user.name" required>
</div>
<button ng-click="form.$valid && save(user)">Save</button>
</form>
I like the idea of using $submitted, I think I've to upgrade Angular to 1.3 ;)
You don't need to insert
or wrap your extra-space with <span/>
. Just use HTML entity code for space -  
Insert regular space as HTML-entity
<form>
<div>Full name:</span> 
<span>{this.props.fullName}</span>
</form>
Abstraction is about identifying commonalities and reducing features that you have to work with at different levels of your code.
e.g. I may have a Vehicle
class. A Car
would derive from a Vehicle
, as would a Motorbike
. I can ask each Vehicle
for the number of wheels, passengers etc. and that info has been abstracted and identified as common from Cars
and Motorbikes
.
In my code I can often just deal with Vehicles
via common methods go()
, stop()
etc. When I add a new Vehicle type later (e.g. Scooter
) the majority of my code would remain oblivious to this fact, and the implementation of Scooter
alone worries about Scooter
particularities.
There is also a smaller one yet called "input-mini".
we can use target = blank to open in new tab
<a href="https://www.google.co.in/" target="blank">click Here </a>
Another option is to suppress the warning individually:
xmlns:tools="http://schemas.android.com/tools" (usually inserted automatically)
tools:ignore="contentDescription"
Example:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:ignore="contentDescription" >
<ImageView
android:layout_width="50dp"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:padding="5dp"
android:src="@drawable/icon" />
Adapted from this answer to a very similar question:
FORFILES /S /D -10 /C "cmd /c IF @isdir == TRUE rd /S /Q @path"
You should run this command from within your d:\study
folder. It will delete all subfolders which are older than 10 days.
The /S /Q
after the rd
makes it delete folders even if they are not empty, without prompting.
I suggest you put the above command into a .bat file, and save it as d:\study\cleanup.bat
.
Assuming you are using an auto-incrementing primary key, which is the normal way to do things, then you can access the key value of the last row you put into the database with:
$userID = mysqli_insert_id($link);
otherwise, you'll have to know more specifics about the row you are trying to find, such as email address. Without knowing your table structure, we can't be more specific.
Either way, to limit your SELECT
query, use a WHERE
statement like this:
(Generic Example)
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];
(Specific example) Or a more specific example:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE userID = 1"));
$userID = $getID['userID'];
Try this
--Generate number from 2 to 90
;with numcte as(
select 2 as rn
union all
select rn+1 from numcte where rn<90)
--Program that formats the number based on length
select case when LEN(rn) = 1 then '00'+CAST(rn as varchar(10)) else CAST(rn as varchar(10)) end number
from numcte
Partial Output:
number
002
003
004
005
006
007
008
009
10
11
12
13
14
15
16
17
18
19
20
Using %lf
will help you in solving this problem.
Use :
scanf("%lf",&doub)
The .NET Framework has an API to truncate a string like this:
Microsoft.VisualBasic.Strings.Left(string, int);
But in a C# app you'll probably prefer to roll your own than taking a dependency on Microsoft.VisualBasic.dll, whose main raison d'etre is backwards compatibility.
You can include a different jade file into your template, that to from a different directory
views/
layout.jade
static/
page.jade
To include the layout file from views dir to static/page.jade
page.jade
extends ../views/layout
These documents describe data dictionary views:
all_tables: http://docs.oracle.com/cd/B19306_01/server.102/b14237/statviews_4473.htm#REFRN26286
user_tables: http://docs.oracle.com/cd/B19306_01/server.102/b14237/statviews_2105.htm#i1592091
dba_tables: http://docs.oracle.com/cd/B19306_01/server.102/b14237/statviews_4155.htm#i1627762
You can run queries on these views to count what you need.
To add something more to @Anurag Thakre's answer:
Use this query which will give you the actual no of counts respect to the owners
SELECT COUNT(*),tablespace_name FROM USER_TABLES group by tablespace_name;
Or by table owners:
SELECT COUNT(*), owner FROM ALL_TABLES group by owner;
Tablespace itself does not identify an unique object owner. Multiple users can create objects in the same tablespace and a single user can create objects in various tablespaces. It is a common practice to separate tables and indexes into different tablespaces.
let's say on the command-line you have:
C:\> C:\Documents and Settings\fred\My Documents\Downloads\google-python-exercises
\google-python-exercises\hello.py John
to make it easier to read, let's just shorten this to:
C:\> hello.py John
argv
represents all the items that come along via the command-line input, but counting starts at zero (0) not one (1): in this case, "hello.py
" is element 0, "John
" is element 1
in other words, sys.argv[0] == 'hello.py'
and sys.argv[1] == 'John'
... but look, how many elements is this? 2, right! so even though the numbers are 0 and 1, there are 2 elements here.
len(sys.argv) >= 2
just checks whether you entered at least two elements. in this case, we entered exactly 2.
now let's translate your code into English:
define main() function:
if there are at least 2 elements on the cmd-line:
set 'name' to the second element located at index 1, e.g., John
otherwise there is only 1 element... the program name, e.g., hello.py:
set 'name' to "World" (since we did not get any useful user input)
display 'Hello' followed by whatever i assigned to 'name'
so what does this mean? it means that if you enter:
hello.py
", the code outputs "Hello World
" because you didn't give a namehello.py John
", the code outputs "Hello John
" because you didhello.py John Paul
", the code still outputs "Hello John
" because it does not save nor use sys.argv[2]
, which was "Paul
" -- can you see in this case that len(sys.argv) == 3
because there are 3 elements in the sys.argv
list?The full list is:
DB, DW, DD, DQ, DT, DDQ, and DO (used to declare initialized data in the output file.)
See: http://www.tortall.net/projects/yasm/manual/html/nasm-pseudop.html
They can be invoked in a wide range of ways: (Note: for Visual-Studio - use "h" instead of "0x" syntax - eg: not 0x55 but 55h instead):
db 0x55 ; just the byte 0x55
db 0x55,0x56,0x57 ; three bytes in succession
db 'a',0x55 ; character constants are OK
db 'hello',13,10,'$' ; so are string constants
dw 0x1234 ; 0x34 0x12
dw 'A' ; 0x41 0x00 (it's just a number)
dw 'AB' ; 0x41 0x42 (character constant)
dw 'ABC' ; 0x41 0x42 0x43 0x00 (string)
dd 0x12345678 ; 0x78 0x56 0x34 0x12
dq 0x1122334455667788 ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
ddq 0x112233445566778899aabbccddeeff00
; 0x00 0xff 0xee 0xdd 0xcc 0xbb 0xaa 0x99
; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
do 0x112233445566778899aabbccddeeff00 ; same as previous
dd 1.234567e20 ; floating-point constant
dq 1.234567e20 ; double-precision float
dt 1.234567e20 ; extended-precision float
DT does not accept numeric constants as operands, and DDQ does not accept float constants as operands. Any size larger than DD does not accept strings as operands.
Use the title
attribute while alt
is important for SEO stuff.
Use this:
document.getElementById(target).value = newVal.replace(/[^0-9.]/g, '');
Here is another idea that allow you to affect other elements without considering any specific selector and by only using the :hover
state of the main element.
For this, I will rely on the use of custom properties (CSS variables). As we can read in the specification:
Custom properties are ordinary properties, so they can be declared on any element, are resolved with the normal inheritance and cascade rules ...
The idea is to define custom properties within the main element and use them to style child elements and since these properties are inherited we simply need to change them within the main element on hover.
Here is an example:
#container {_x000D_
width: 200px;_x000D_
height: 30px;_x000D_
border: 1px solid var(--c);_x000D_
--c:red;_x000D_
}_x000D_
#container:hover {_x000D_
--c:blue;_x000D_
}_x000D_
#container > div {_x000D_
width: 30px;_x000D_
height: 100%;_x000D_
background-color: var(--c);_x000D_
}
_x000D_
<div id="container">_x000D_
<div>_x000D_
</div>_x000D_
</div>
_x000D_
Why this can be better than using specific selector combined with hover?
I can provide at least 2 reasons that make this method a good one to consider:
border
, linear-gradient
, background-color
, box-shadow
etc. This will avoid us reseting all these properties on hover.Here is a more complex example:
.container {_x000D_
--c:red;_x000D_
width:400px;_x000D_
display:flex;_x000D_
border:1px solid var(--c);_x000D_
justify-content:space-between;_x000D_
padding:5px;_x000D_
background:linear-gradient(var(--c),var(--c)) 0 50%/100% 3px no-repeat;_x000D_
}_x000D_
.box {_x000D_
width:30%;_x000D_
background:var(--c);_x000D_
box-shadow:0px 0px 5px var(--c);_x000D_
position:relative;_x000D_
}_x000D_
.box:before {_x000D_
content:"A";_x000D_
display:block;_x000D_
width:15px;_x000D_
margin:0 auto;_x000D_
height:100%;_x000D_
color:var(--c);_x000D_
background:#fff;_x000D_
}_x000D_
_x000D_
/*Hover*/_x000D_
.container:hover {_x000D_
--c:blue;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="box"></div>_x000D_
<div class="box"></div>_x000D_
</div>
_x000D_
As we can see above, we only need one CSS declaration in order to change many properties of different elements.
How do I invoke a maven task without leaving vi?
Maven is no different than any other shell command:
:!mvn
You can :set makeprg=mvn
if you already have a favourite key mapping for :make
.
Can I get code completion?
Yes, eclim is great, a bridge between vim's editing efficiency and Eclipse's Java language-specific awareness.
<C-n>
and <C-p>
are not-so-great, but amazingly helpful.
How's the syntax highlighting?
More than good enough for a regex-based highligher.
You may want to consider tools for other vim+java purposes, like code templates (snippetEmu—default snippets suck, but customizability shines), searching for usages and going to declarations (eclim, grep, ctags), generating getters and setters (java_getset, or eclim), automatic imports (eclim). You might also need a java shell for quick experiments (the BeanShell, a.k.a. bsh
).
If you're willing to go the way of the preprocessor abuse, Boost.Preprocessor
can help you.
#include <boost/preprocessor/seq/for_each.hpp>
#define CASE_case(ign, ign2, n) case n:
#define CASES(seq) \
BOOST_PP_SEQ_FOR_EACH(CASE_case, ~, seq)
CASES((1)(3)(15)(13))
Running this through gcc
with -E -P
to only run the preprocessor, the expansion of CASES
gives:
case 1: case 3: case 15: case 13:
Note that this probably wouldn't pass a code review (wouldn't where I work!) so I recommend it be constrained to personal use.
It should also be possible to create a CASE_RANGE(1,5)
macro to expand to
case 1: case 2: case 3: case 4: case 5:
for you as well.
I'd just like to add to Jon's example. To get a reference to your own assembly, you can use:
Assembly myAssembly = Assembly.GetExecutingAssembly();
System.Reflection
namespace.
If you want to examine an assembly that you have no reference to, you can use either of these:
Assembly assembly = Assembly.ReflectionOnlyLoad(fullAssemblyName);
Assembly assembly = Assembly.ReflectionOnlyLoadFrom(fileName);
If you intend to instantiate your type once you've found it:
Assembly assembly = Assembly.Load(fullAssemblyName);
Assembly assembly = Assembly.LoadFrom(fileName);
See the Assembly class documentation for more information.
Once you have the reference to the Assembly
object, you can use assembly.GetTypes()
like Jon already demonstrated.
public class Country
{
public string Name { get; set; }
public IList<City> Cities { get; set; }
public Country()
{
Cities = new List<City>();
}
}
public class City
{
public string Name { get; set; }
}
List<Country> Countries = new List<Country>
{
new Country
{
Name = "Germany",
Cities =
{
new City {Name = "Berlin"},
new City {Name = "Hamburg"}
}
},
new Country
{
Name = "England",
Cities =
{
new City {Name = "London"},
new City {Name = "Birmingham"}
}
}
};
bindingSource1.DataSource = Countries;
member_CountryComboBox.DataSource = bindingSource1.DataSource;
member_CountryComboBox.DisplayMember = "Name";
member_CountryCombo
Box.ValueMember = "Name";
This is the code I am using now.
In my case, I noticed this behavior when the box was out of memory (RAM) I went to Jenkins -> Manage Jenkins -> Manage Nodes and found an out of memory exception. I just freed up some memory on the machine and the jobs started to go into the executors.
You can continue chaining them like you've done.
results = results.Where (o => o.OrderStatus == OrderStatus.Open);
results = results.Where (o => o.InvoicePaid);
This represents an AND.
I got this error when I installed Skype. Because my site uses port 80 and Skype uses the same port also.
Please see this.
You could have searched just for whereIn
function in the core to see that. Here you are. This must answer all your questions
/**
* Add a "where in" clause to the query.
*
* @param string $column
* @param mixed $values
* @param string $boolean
* @param bool $not
* @return \Illuminate\Database\Query\Builder|static
*/
public function whereIn($column, $values, $boolean = 'and', $not = false)
{
$type = $not ? 'NotIn' : 'In';
// If the value of the where in clause is actually a Closure, we will assume that
// the developer is using a full sub-select for this "in" statement, and will
// execute those Closures, then we can re-construct the entire sub-selects.
if ($values instanceof Closure)
{
return $this->whereInSub($column, $values, $boolean, $not);
}
$this->wheres[] = compact('type', 'column', 'values', 'boolean');
$this->bindings = array_merge($this->bindings, $values);
return $this;
}
Look that it has a third boolean param. Good luck.
ValueErrors :In Python, a value is the information that is stored within a certain object. To encounter a ValueError in Python means that is a problem with the content of the object you tried to assign the value to.
in your case name,lastname and email 3 parameters are there but unpaidmembers only contain 2 of them.
name, lastname, email in unpaidMembers.items() so you should refer data or your code might be
lastname, email in unpaidMembers.items() or name, email in unpaidMembers.items()
First set path of python
https://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows
and run python
file
python filename.py
command line argument with python
python filename.py command-line argument
Maybe you can do something with
get-process -includeusername
Well I found nobody mentioned this trick.
Without redirection, you can still prevent the form confirmation when refresh.
By default, form code is like this:
<form method="post" action="test.php">
now, change it to
<form method="post" action="test.php?nonsense=1">
You will see the magic.
I guess its because browsers won't trigger the confirmation alert popup if it gets a GET method (query string) in the url.
You can try the following:
gitk --all
You can tell gitk
what to display using anything that git rev-list
understands, so if you just want a few branches, you can do:
gitk master origin/master origin/experiment
... or more exotic things like:
gitk --simplify-by-decoration --all
On linux: print('\007')
will make the system bell sound.
Use .height()
like this:
var result = $("#myDiv").height();
There's also .innerHeight()
and .outerHeight()
depending on exactly what you want.
You can test it here, play with the padding/margins/content to see how it changes around.
Add space between Data Source
con.ConnectionString = @"Data Source=.\SQLEXPRESS;
AttachDbFilename=c:\folder\SampleDatabase.mdf;
Integrated Security=True;
Connect Timeout=30;
User Instance=True";
UPDATE: 2017-12-16:
There are 2 simple ways to do this in Spring Boot 1.5.8.RELEASE, no need for XML.
First way: If you do not have any spacific URL pattern, you can use @Component like this: (Full code and details are here https://www.surasint.com/spring-boot-filter/)
@Component
public class ExampleFilter implements Filter{
...
}
Second way: If you want to use url patterns, you can use @WebFilter like this: (Full code and details are here https://www.surasint.com/spring-boot-filter-urlpattern/)
@WebFilter(urlPatterns = "/api/count")
public class ExampleFilter implements Filter{
...
}
But you also need to add @ServletComponentScan annotation in your @SpringBootApplication class:
@ServletComponentScan
@SpringBootApplication
public class MyApplication extends SpringBootServletInitializer {
...
}
Note that @Component is Spring's annotation, but @WebFilter is not. @WebFilter is Servlet 3 annotation.
Both ways, you just need basic Spring Boot dependency in pom.xml (no need for explicit tomcat embedded jasper)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
</parent>
<groupId>com.surasint.example</groupId>
<artifactId>spring-boot-04</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
WARNING: The first way, if the Controller in Spring Boot returns to a JSP file, the request will pass the filter twice.
While, in the second way, the request will pass the filter only once.
I prefer the second way because it is more similar to default behavior in Servlet specification (https://docs.oracle.com/cd/E19879-01/819-3669/6n5sg7b0b/index.html)
You can see more test log here https://www.surasint.com/spring-boot-webfilter-instead-of-component/
Strangely enough, the solution ended up being to change
volumes:
- ./postgres-data:/var/lib/postgresql
to
volumes:
- ./postgres-data:/var/lib/postgresql/data
You can do this as:
WITH abc AS( select
FROM ...)
, XYZ AS(select
From abc ....) /*This one uses "abc" multiple times*/
Select
From XYZ.... /*using abc, XYZ multiple times*/
In webkit you can try this out...
input[type="file"]::-webkit-file-upload-button{
/* style goes here */
}
If your VARCHAR
column contains empty strings (which are not the same as NULL
for PostgreSQL as you might recall) you will have to use something in the line of the following to set a default:
ALTER TABLE presales ALTER COLUMN code TYPE NUMERIC(10,0)
USING COALESCE(NULLIF(code, '')::NUMERIC, 0);
(found with the help of this answer)
Since you only care about the indexes, you don't need to map to tuples at all. Why not just write a filter that uses the looks up elements in your array?
int[] value = ...
IntStream.range(0, value.length)
.filter(i -> value[i] > 30) //or whatever filter you want
.forEach(i -> System.out.println(i));
The command is lowercase: touch filename
.
Keep in mind that touch
will only create a new file if it does not exist! Here's some docs for good measure: http://unixhelp.ed.ac.uk/CGI/man-cgi?touch
If you always want an empty file, one way to do so would be to use:
echo "" > filename
It will look like this
<head>
<script type="text/javascript">
var image1 = new Image()
image1.src = "images/pentagg.jpg"
var image2 = new Image()
image2.src = "images/promo.jpg"
</script>
</head>
<body>
<p><img src="images/pentagg.jpg" width="500" height="300" name="slide" /></p>
<script type="text/javascript">
var step=1;
function slideit()
{
document.images.slide.src = eval("image"+step+".src");
if(step<2)
step++;
else
step=1;
setTimeout("slideit()",2500);
}
slideit();
</script>
</body>
People are trying to create their own csv string, which fail on edge cases, e.g. special characters, surely this is a solved problem right?
papaparse - use for JSON to CSV encoding. Papa.unparse()
.
import Papa from "papaparse";
const downloadCSV = (args) => {
let filename = args.filename || 'export.csv';
let columns = args.columns || null;
let csv = Papa.unparse({ data: args.data, fields: columns})
if (csv == null) return;
var blob = new Blob([csv]);
if (window.navigator.msSaveOrOpenBlob) // IE hack; see http://msdn.microsoft.com/en-us/library/ie/hh779016.aspx
window.navigator.msSaveBlob(blob, args.filename);
else
{
var a = window.document.createElement("a");
a.href = window.URL.createObjectURL(blob, {type: "text/plain"});
a.download = filename;
document.body.appendChild(a);
a.click(); // IE: "Access is denied"; see: https://connect.microsoft.com/IE/feedback/details/797361/ie-10-treats-blob-url-as-cross-origin-and-denies-access
document.body.removeChild(a);
}
}
Example usage
downloadCSV({
filename: 'filename.csv',
data: [{'a': '1', 'b': 2'}],
columns: ['a','b']
});
https://github.com/mholt/PapaParse/issues/175 - See this comment for browser support discussion.
This should fix your problem:
$credentials = New-Object Management.Automation.PSCredential “[email protected]”, (“password” | ConvertTo-SecureString -AsPlainText -Force)
Then use the credential in your call to Send-MailMessage -From $From -To $To -Body $Body $Body -SmtpServer {$smtpServer URI} -Credential $credentials -Verbose -UseSsl
You can instantiate it after you implemented all the methods. Then the constructor will be called.
There is no portable way to get resolution of less than a second in standard C So best you can do is, use the POSIX function gettimeofday().
OK... I can resond..
Disclaimer: I just had an 18+ hour day (again).. I'm old and forgetfull.. I can't spell.. I have a short attention span so I better respond fast.. :-)
Question:
Is it possible to change the thread principal to an user with no account on the local machine?
Answer:
Yes, you can change a thread principal even if the credentials you are using are not defined locally or are outside the "forest".
I just ran into this problem when trying to connect to an SQL server with NTLM authentication from a service. This call uses the credentials associated with the process meaning that you need either a local account or a domain account to authenticate before you can impersonate. Blah, blah...
But...
Calling LogonUser(..) with the attribute of ????_NEW_CREDENTIALS will return a security token without trying to authenticate the credentials. Kewl.. Don't have to define the account within the "forest". Once you have the token you might have to call DuplicateToken() with the option to enable impersonation resulting in a new token. Now call SetThreadToken( NULL, token ); (It might be &token?).. A call to ImpersonateLoggedonUser( token ); might be required, but I don't think so. Look it up..
Do what you need to do..
Call RevertToSelf() if you called ImpersonateLoggedonUser() then SetThreadToken( NULL, NULL ); (I think... look it up), and then CloseHandle() on the created handles..
No promises but this worked for me... This is off the top of my head (like my hair) and I can't spell!!!
If you ended here googling, this is a simple configuration to prevent this error full the web server logs:
Apache virtualhost
Redirect 404 /apple-touch-icon-precomposed.png
<Location /apple-touch-icon-precomposed.png>
ErrorDocument 404 "apple-touch-icon-precomposed does not exist"
</Location>
Nginx server block:
location =/apple-touch-icon-precomposed.png {
log_not_found off;
access_log off;
}
PS: Is possible you want to add apple-touch-icon.png
and favicon.ico
too.
Just for all those people who say side effects are evil: a place where having two side effects in one condition is good would be reading two file objects in tandem.
While File1.Seek_Next_Row() And File2.Seek_Next_Row()
Str1 = File1.GetRow()
Str2 = File2.GetRow()
End While
Using the And
ensures that a row is consumed every time the condition is checked. Whereas AndAlso
might read the last line of File1
and leave File2
without a consumed line.
Of course the code above wouldn't work, but I use side effects like this all the time and wouldn't consider it "bad" or "evil" code as some would lead you to believe. It's easy to read and efficient.
CREATE FUNCTION dbo.ConvertUnixToDateTime(@Datetime BIGINT)
RETURNS DATETIME
AS
BEGIN
RETURN (SELECT DATEADD(second,@Datetime, CAST('1970-01-01' AS datetime)))
END;
GO
If your tags are sortable using the linux sort
command, use this:
git tag | sort -n | tail -1
eg. if git tag
returns:
v1.0.1
v1.0.2
v1.0.5
v1.0.4
git tag | sort -n | tail -1
will output:
v1.0.5
git tag | sort -n | tail -2 | head -1
will output:
v1.0.4
(because you asked for the second most recent tag)
to checkout the tag, first clone the repo, then type:
git checkout v1.0.4
..or whatever tag you need.
There is comma missing in your tuple.
insert the comma between the tuples as shown:
pack_size = (('1', '1'),('3', '3'),(b, b),(h, h),(d, d), (e, e),(r, r))
Do the same for all
You can set a bucket policy as detailed in this blog post:
http://ariejan.net/2010/12/24/public-readable-amazon-s3-bucket-policy/
As per @robbyt's suggestion, create a bucket policy with the following JSON:
{
"Version": "2008-10-17",
"Statement": [{
"Sid": "AllowPublicRead",
"Effect": "Allow",
"Principal": { "AWS": "*" },
"Action": ["s3:GetObject"],
"Resource": ["arn:aws:s3:::bucket/*" ]
}]
}
Important: replace bucket
in the Resource
line with the name of your bucket.
Why reinvent the wheel? Use Commons Collections:
CollectionUtils.intersection(java.util.Collection a, java.util.Collection b)
This code is working for me either paste from right click or direct copy paste
$('.textbox').on('paste input propertychange', function (e) {
$(this).val( $(this).val().replace(/[^0-9.]/g, '') );
})
When i paste Section 1: Labour Cost
it becomes 1
in text box.
To allow only float value i use this code
//only decimal
$('.textbox').keypress(function(e) {
if(e.which == 46 && $(this).val().indexOf('.') != -1) {
e.preventDefault();
}
if (e.which == 8 || e.which == 46) {
return true;
} else if ( e.which < 48 || e.which > 57) {
e.preventDefault();
}
});
subprocess.Popen
takes a cwd
argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'
), or use r'd:\test\local'
so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t
part will be translated to a tab.
So, your new line should look like:
subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')
To use your Python script path as cwd, import os
and define cwd using this:
os.path.dirname(os.path.realpath(__file__))
I have a simple bash script I created for this it just means running it on your file before use: https://github.com/antonosmond/subber
Basically just create your compose file using double curly braces to denote environment variables e.g:
app:
build: "{{APP_PATH}}"
ports:
- "{{APP_PORT_MAP}}"
Anything in double curly braces will be replaced with the environment variable of the same name so if I had the following environment variables set:
APP_PATH=~/my_app/build
APP_PORT_MAP=5000:5000
on running subber docker-compose.yml
the resulting file would look like:
app:
build: "~/my_app/build"
ports:
- "5000:5000"
Deploy your application in the IIS with the default port. Try to debug it using visual studio. It's a good practice. If you use visual studio, it will keep changing the port number most of the time. So better deploy the application in the IIS first and Open the same in visual studio and Debug it.
The problem is that your regex is a string, but html
is bytes:
>>> type(html)
<class 'bytes'>
Since python doesn't know how those bytes are encoded, it throws an exception when you try to use a string regex on them.
You can either decode
the bytes to a string:
html = html.decode('ISO-8859-1') # encoding may vary!
title = re.findall(pattern, html) # no more error
Or use a bytes regex:
regex = rb'<title>(,+?)</title>'
# ^
In this particular context, you can get the encoding from the response headers:
with urllib.request.urlopen(url) as response:
encoding = response.info().get_param('charset', 'utf8')
html = response.read().decode(encoding)
See the urlopen
documentation for more details.
Background location service. It will be restarted even after killing the app.
MainActivity.java
public class MainActivity extends AppCompatActivity {
AlarmManager alarmManager;
Button stop;
PendingIntent pendingIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (alarmManager == null) {
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceive.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 30000,
pendingIntent);
}
}
}
BookingTrackingService.java
public class BookingTrackingService extends Service implements LocationListener {
private static final String TAG = "BookingTrackingService";
private Context context;
boolean isGPSEnable = false;
boolean isNetworkEnable = false;
double latitude, longitude;
LocationManager locationManager;
Location location;
private Handler mHandler = new Handler();
private Timer mTimer = null;
long notify_interval = 30000;
public double track_lat = 0.0;
public double track_lng = 0.0;
public static String str_receiver = "servicetutorial.service.receiver";
Intent intent;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mTimer = new Timer();
mTimer.schedule(new TimerTaskToGetLocation(), 5, notify_interval);
intent = new Intent(str_receiver);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.context = this;
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.e(TAG, "onDestroy <<");
if (mTimer != null) {
mTimer.cancel();
}
}
private void trackLocation() {
Log.e(TAG, "trackLocation");
String TAG_TRACK_LOCATION = "trackLocation";
Map<String, String> params = new HashMap<>();
params.put("latitude", "" + track_lat);
params.put("longitude", "" + track_lng);
Log.e(TAG, "param_track_location >> " + params.toString());
stopSelf();
mTimer.cancel();
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
/******************************/
private void fn_getlocation() {
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnable && !isNetworkEnable) {
Log.e(TAG, "CAN'T GET LOCATION");
stopSelf();
} else {
if (isNetworkEnable) {
location = null;
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Log.e(TAG, "isNetworkEnable latitude" + location.getLatitude() + "\nlongitude" + location.getLongitude() + "");
latitude = location.getLatitude();
longitude = location.getLongitude();
track_lat = latitude;
track_lng = longitude;
// fn_update(location);
}
}
}
if (isGPSEnable) {
location = null;
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
Log.e(TAG, "isGPSEnable latitude" + location.getLatitude() + "\nlongitude" + location.getLongitude() + "");
latitude = location.getLatitude();
longitude = location.getLongitude();
track_lat = latitude;
track_lng = longitude;
// fn_update(location);
}
}
}
Log.e(TAG, "START SERVICE");
trackLocation();
}
}
private class TimerTaskToGetLocation extends TimerTask {
@Override
public void run() {
mHandler.post(new Runnable() {
@Override
public void run() {
fn_getlocation();
}
});
}
}
// private void fn_update(Location location) {
//
// intent.putExtra("latutide", location.getLatitude() + "");
// intent.putExtra("longitude", location.getLongitude() + "");
// sendBroadcast(intent);
// }
}
AlarmReceive.java (BroadcastReceiver)
public class AlarmReceive extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.e("Service_call_" , "You are in AlarmReceive class.");
Intent background = new Intent(context, BookingTrackingService.class);
// Intent background = new Intent(context, GoogleService.class);
Log.e("AlarmReceive ","testing called broadcast called");
context.startService(background);
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<service
android:name=".ServiceAndBroadcast.BookingTrackingService"
android:enabled="true" />
<receiver
android:name=".ServiceAndBroadcast.AlarmReceive"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Follow as in picture for removing that lint error and adding automatic fix by addin g--fix in package.json
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_query('SET character_set_results=utf8');
mysql_query('SET names=utf8');
mysql_query('SET character_set_client=utf8');
mysql_query('SET character_set_connection=utf8');
mysql_query('SET character_set_results=utf8');
mysql_query('SET collation_connection=utf8_general_ci');
mysql_select_db('onlinetest',$con);
$nith = "CREATE TABLE IF NOT EXISTS `TAMIL` (
`data` varchar(1000) character set utf8 collate utf8_bin default NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1";
if (!mysql_query($nith,$con))
{
die('Error: ' . mysql_error());
}
$nithi = "INSERT INTO `TAMIL` VALUES ('??????? ???????? ?????????')";
if (!mysql_query($nithi,$con))
{
die('Error: ' . mysql_error());
}
$result = mysql_query("SET NAMES utf8");//the main trick
$cmd = "select * from TAMIL";
$result = mysql_query($cmd);
while($myrow = mysql_fetch_row($result))
{
echo ($myrow[0]);
}
?>
</body>
</html>
If you need to use a port outside of the 44300-44399 range, here's a workaround:
This registers the IIS Express Development certificate with that port and is the easiest way I've found to get around the 44300-44399 range requirement.
When I run your code, I get the following output for example.
<usb.Device object at 0xef38c0>
Device: 001
idVendor: 7531 (0x1d6b)
idProduct: 1 (0x0001)
Manufacturer: 3
Serial: 1
Product: 2
Noteworthy are that a) I have usb.Device
objects whereas you have usb.legacy.Device
objects, and b) I have device filenames.
Each usb.Bus
has a dirname
field and each usb.Device
has the filename. As you can see, the filename is something like 001
, and so is the dirname. You can combine these to get the bus file. For dirname=001
and filname=001
, it should be something like /dev/bus/usb/001/001.
You should first, though figure out what this "usb.legacy" situation is. I'm running the latest version and I don't even have a legacy
sub-module.
Finally, you should use the idVendor
and idProduct
fields to uniquely identify the device when it's plugged in.
I added the start
and exit
which works. Without both it was not working
start C:/Anaconda3/Library/bin/pyrcc4.exe -py3 {path}/Resourses.qrc -{path}/Resourses_rc.py
exit
First you should use print_r($_FILES)
to debug, and see what it contains. :
your uploads.php
would look like:
//This is the directory where images will be saved
$target = "pics/";
$target = $target . basename( $_FILES['Filename']['name']);
//This gets all the other information from the form
$Filename=basename( $_FILES['Filename']['name']);
$Description=$_POST['Description'];
//Writes the Filename to the server
if(move_uploaded_file($_FILES['Filename']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['Filename']['name']). " has been uploaded, and your information has been added to the directory";
// Connects to your Database
mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("altabotanikk") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO picture (Filename,Description)
VALUES ('$Filename', '$Description')") ;
} else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
EDIT: Since this is old post, currently it is strongly recommended to use either mysqli or pdo instead mysql_ functions in php
//if i input 9 it should go to 8?
You still have to work with the elements of the array. You will count 8 elements when looping through the array, but they are still going to be array(0) - array(7).
You can do this by comparing each field using the NULL-safe equals operator <=>
and then negating the result using NOT
.
The complete trigger would become:
DROP TRIGGER IF EXISTS `my_trigger_name`;
DELIMITER $$
CREATE TRIGGER `my_trigger_name` AFTER UPDATE ON `my_table_name` FOR EACH ROW
BEGIN
/*Add any fields you want to compare here*/
IF !(OLD.a <=> NEW.a AND OLD.b <=> NEW.b) THEN
INSERT INTO `my_other_table` (
`a`,
`b`
) VALUES (
NEW.`a`,
NEW.`b`
);
END IF;
END;$$
DELIMITER ;
(Based on a different answer of mine.)
If I may give an answer to an old thread; You can use PC Decrapifier to select programs you want to uninstall. PC Decrapifier will uninstall them one by one for you so you don't have to click them all seperately.
This is very useful for removing all the 'junk' - like the SQL Database tools - Visual Studio leaves behind even when uninstalled.
Memoization is basically saving the results of past operations done with recursive algorithms in order to reduce the need to traverse the recursion tree if the same calculation is required at a later stage.
see http://scriptbucket.wordpress.com/2012/12/11/introduction-to-memoization/
Fibonacci Memoization example in Python:
fibcache = {}
def fib(num):
if num in fibcache:
return fibcache[num]
else:
fibcache[num] = num if num < 2 else fib(num-1) + fib(num-2)
return fibcache[num]
The simple answer is that arrays are ALWAYS passed by reference and the int arg[] simply lets the compiler know to expect an array
You need to put the format arguments into a tuple (add parentheses):
instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % (softname, procversion, int(percent), exe, description, company, procurl)
What you currently have is equivalent to the following:
intstr = ("'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname), procversion, int(percent), exe, description, company, procurl
Example:
>>> "%s %s" % 'hello', 'world'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s %s" % ('hello', 'world')
'hello world'
Your second question
How many columns can be used together as a primary key in a given table?
is implementation specific: it's defined in the actual DBMS being used.[1],[2],[3] You have to inspect the technical specification of the database system you use. Some are very detailed, some are not. Searching the web about such limitations can be hard because the terminology varies. The term composite primary key should be mandatory ;)
If you cannot find explicit information, try creating a test database to ensure you can expect stable (and specific) handling of the limit violations (which are to be expected). Be careful to get the right information about this: sometimes the limits are accumulated, and you'll see different results with different database layouts.
I just emptied my session data then it worked again. Here is where you find the button:
Simply move the declaration outside of the if block.
@{
string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
string imgsrc="";
if (currentstore == "www.mydomain.com")
{
<link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" />
imgsrc="/content/images/uploaded/store1_logo.jpg";
}
else
{
<link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" />
imgsrc="/content/images/uploaded/store2_logo.gif";
}
}
<a href="@Url.RouteUrl("HomePage")" class="logo"><img alt="" src="@imgsrc"></a>
You could make it a bit cleaner.
@{
string currentstore=HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
string imgsrc="/content/images/uploaded/store2_logo.gif";
if (currentstore == "www.mydomain.com")
{
<link href="/path/to/my/stylesheets/styles1-print.css" rel="stylesheet" type="text/css" />
imgsrc="/content/images/uploaded/store1_logo.jpg";
}
else
{
<link href="/path/to/my/stylesheets/styles2-print.css" rel="stylesheet" type="text/css" />
}
}
You need to put the text-align:center
on the containing div, not on the input itself.
To build on @Livven's answer, here are some useful combinations.
variable substitution, leading tab retained, overwrite file, echo to stdout
tee /path/to/file <<EOF
${variable}
EOF
no variable substitution, leading tab retained, overwrite file, echo to stdout
tee /path/to/file <<'EOF'
${variable}
EOF
variable substitution, leading tab removed, overwrite file, echo to stdout
tee /path/to/file <<-EOF
${variable}
EOF
variable substitution, leading tab retained, append to file, echo to stdout
tee -a /path/to/file <<EOF
${variable}
EOF
variable substitution, leading tab retained, overwrite file, no echo to stdout
tee /path/to/file <<EOF >/dev/null
${variable}
EOF
the above can be combined with sudo
as well
sudo -u USER tee /path/to/file <<EOF
${variable}
EOF
Also want to add that ad hoc query is vulnerable to SQL injection attacks. We should try to avoid using it and use parameterized SQLs instead (like PreparedStatement in Java).
Apparently, I needed to run OpenSSL as root in order for it to have permission to the seeding file.
plt.errorbar
can be used to plot x, y, error data (as opposed to the usual plt.plot
)
import matplotlib.pyplot as plt
import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = np.power(x, 2) # Effectively y = x**2
e = np.array([1.5, 2.6, 3.7, 4.6, 5.5])
plt.errorbar(x, y, e, linestyle='None', marker='^')
plt.show()
plt.errorbar
accepts the same arguments as plt.plot
with additional yerr
and xerr
which default to None (i.e. if you leave them blank it will act as plt.plot
).
It looks like you are trying to read an object from JSON that actually describes an array. Java objects are mapped to JSON objects with curly braces {}
but your JSON actually starts with square brackets []
designating an array.
What you actually have is a List<product>
To describe generic types, due to Java's type erasure, you must use a TypeReference
. Your deserialization could read: myProduct = objectMapper.readValue(productJson, new TypeReference<List<product>>() {});
A couple of other notes: your classes should always be PascalCased. Your main method can just be public static void main(String[] args) throws Exception
which saves you all the useless catch
blocks.
The Date
documentation states that :
The JavaScript date is based on a time value that is milliseconds since midnight January 1, 1970, UTC
Click on start button then on end button. It will show you the number of seconds between the 2 clicks.
The milliseconds diff is in variable timeDiff
. Play with it to find seconds/minutes/hours/ or what you need
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
startTime = new Date();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
endTime = new Date();_x000D_
var timeDiff = endTime - startTime; //in ms_x000D_
// strip the ms_x000D_
timeDiff /= 1000;_x000D_
_x000D_
// get seconds _x000D_
var seconds = Math.round(timeDiff);_x000D_
console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
_x000D_
<button onclick="end()">End</button>
_x000D_
OR another way of doing it for modern browser
Using performance.now()
which returns a value representing the time elapsed since the time origin. This value is a double with microseconds in the fractional.
The time origin is a standard time which is considered to be the beginning of the current document's lifetime.
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
startTime = performance.now();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
endTime = performance.now();_x000D_
var timeDiff = endTime - startTime; //in ms _x000D_
// strip the ms _x000D_
timeDiff /= 1000; _x000D_
_x000D_
// get seconds _x000D_
var seconds = Math.round(timeDiff);_x000D_
console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
<button onclick="end()">End</button>
_x000D_
Something like this (not tested, but should work)
Pass this as parameter in Html:
<input type="text" placeholder="some text" class="search" onkeydown="search(this)"/>
And alert the value of the parameter passed into the search function:
function search(e){
alert(e.value);
}
Declare @DatePeriod datetime
Set @DatePeriod = '2011-05-30'
Select ProductName,
IsNull([1],0) as 'Week 1',
IsNull([2],0) as 'Week 2',
IsNull([3],0) as 'Week 3',
IsNull([4],0) as 'Week 4',
IsNull([5], 0) as 'Week 5'
From
(
Select ProductName,
DATEDIFF(week, DATEADD(MONTH, DATEDIFF(MONTH, 0, '2011-05-30'), 0), '2011-05-30') +1 as [Weeks],
Sale as 'Sale'
From dbo.WeekReport
-- Only get rows where the date is the same as the DatePeriod
-- i.e DatePeriod is 30th May 2011 then only the weeks of May will be calculated
Where DatePart(Month, '2011-05-30')= DatePart(Month, @DatePeriod)
)p
Pivot (Sum(Sale) for Weeks in ([1],[2],[3],[4],[5])) as pv
OUTPUT LOOK LIKE THIS
a 0 0 0 0 20
b 0 0 0 0 4
c 0 0 0 0 3
You can use as below and also can use various color just assign
myLabel.textColor = UIColor.yourChoiceOfColor
Ex:
Swift
myLabel.textColor = UIColor.red
Objective-C
[myLabel setTextColor:[UIColor redColor]];
or you can click here to Choose the color,
https://www.ralfebert.de/ios-examples/uikit/swift-uicolor-picker/
Once you have the source trees, e.g.
diff -ENwbur repos1/ repos2/
Even better
diff -ENwbur repos1/ repos2/ | kompare -o -
and have a crack at it in a good gui tool :)
There are quite a few ways to work with dynamic arrays in PHP. Initialise an array:
$array = array();
Add to an array:
$array[] = "item"; // for your $arr1
$array[$key] = "item"; // for your $arr2
array_push($array, "item", "another item");
Remove from an array:
$item = array_pop($array);
$item = array_shift($array);
unset($array[$key]);
There are plenty more ways, these are just some examples.
I saw in the comments for Nico's answer that some people were running into issues with saving lists that had lists within them. I also ran into this problem with some of my work and was hoping that someone found a better answer than what I found however no one responded to their issue.
So: @ali, @FMKerckhof, and @Kerry the only way that I found to save a nested list is to use sink() like user6585653 suggested (I tried to up vote his answer but could not). It is not the best way to do it since you link the text file which means it can be easily over written or other results may be saved within that file if you do not cancel the sink. See below for the code.
sink("mylist.txt")
print(mylist)
sink()
Make sure to have the sink() at the end your code so that you cancel the sink.
Here are two functions that may help if your backup is corrupted, or you have a few partially corrupted backups as well (this may happen if you backup the corrupted objects).
Run both in the repo you're trying to recover.
Standard warning: only use if you're really desperate and you have backed up your (corrupted) repo. This might not resolve anything, but at least should highlight the level of corruption.
fsck_rm_corrupted() {
corrupted='a'
while [ "$corrupted" ]; do
corrupted=$( \
git fsck --full --no-dangling 2>&1 >/dev/null \
| grep 'stored in' \
| sed -r 's:.*(\.git/.*)\).*:\1:' \
)
echo "$corrupted"
rm -f "$corrupted"
done
}
if [ -z "$1" ] || [ ! -d "$1" ]; then
echo "'$1' is not a directory. Please provide the directory of the git repo"
exit 1
fi
pushd "$1" >/dev/null
fsck_rm_corrupted
popd >/dev/null
and
unpack_rm_corrupted() {
corrupted='a'
while [ "$corrupted" ]; do
corrupted=$( \
git unpack-objects -r < "$1" 2>&1 >/dev/null \
| grep 'stored in' \
| sed -r 's:.*(\.git/.*)\).*:\1:' \
)
echo "$corrupted"
rm -f "$corrupted"
done
}
if [ -z "$1" ] || [ ! -d "$1" ]; then
echo "'$1' is not a directory. Please provide the directory of the git repo"
exit 1
fi
for p in $1/objects/pack/pack-*.pack; do
echo "$p"
unpack_rm_corrupted "$p"
done
For use in Playground for fellow newbies, in Swift 5, Xcode 11:
Import UIKit
var secondsRemaining = 10
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (Timer) in
if secondsRemaining > 0 {
print ("\(secondsRemaining) seconds")
secondsRemaining -= 1
} else {
Timer.invalidate()
}
}
This error shows up when you are treating an array or string as a Hash. In this line myHash.each do |item|
you are assigning item
to a two-element array [key, value]
, so item[:symbol]
throws an error.
Don't use jQuery to manipulate the DOM when you're using React. React components should render a representation of what they should look like given a certain state; what DOM that translates to is taken care of by React itself.
What you want to do is store the "state which determines what gets rendered" higher up the chain, and pass it down. If you are rendering n
children, that state should be "owned" by whatever contains your component. eg:
class AppComponent extends React.Component {
state = {
numChildren: 0
}
render () {
const children = [];
for (var i = 0; i < this.state.numChildren; i += 1) {
children.push(<ChildComponent key={i} number={i} />);
};
return (
<ParentComponent addChild={this.onAddChild}>
{children}
</ParentComponent>
);
}
onAddChild = () => {
this.setState({
numChildren: this.state.numChildren + 1
});
}
}
const ParentComponent = props => (
<div className="card calculator">
<p><a href="#" onClick={props.addChild}>Add Another Child Component</a></p>
<div id="children-pane">
{props.children}
</div>
</div>
);
const ChildComponent = props => <div>{"I am child " + props.number}</div>;
Solution for me was (thx to David Ljung Madison post)
adb kill-server
git instaweb --httpd=webrick
from the git scm book
combine it with something like the approach described here for distributed development (credit to datagrok for the well described concept)
I tweeted this already but I thought it could use some expansion:
Enable decentralized git workflow: git config alias.serve "daemon --verbose --export-all --base-path=.git --reuseaddr --strict-paths .git/"
Say you use a git workflow that involves working with a core "official" repository that you pull and push your changes from and into. I'm sure many companies do this, as do many users of git hosting services like Github.
Say that server, or Github, goes down for a bit.
No worries, after all, one of the reasons you use git is so you have a copy of the entire project history in your local clone.
You can keep right on coding and committing, while you wait for the operations team to bring the server back to life. Note to self: buy doughnuts for operations team.
But what if, during this downtime, you want to collaborate with another person, who may not be a git expert, on the same repository?
Or, instead of downtime, what if you and your collaborator are in the field, and for some reason you can't get your VPN to let you connect to your official repo?
Or, what if you and your collaborator are spiking out a bunch of experimental changes, and even though you have access, you don't want to push your unfinished mess into the official central repository? (Not even as feature branches.) Maybe you're in the middle of cleaning up a disastrous rebase or merge and the branches are all over the place.
Well, git, as you are probably aware, is a "distributed" version control system.
Even though you might use a central "official" git repository in your workflow, you still have the ability to use git in a peer-to-peer manner, where you and your collaborator simply build and share commits with each other, and the central server never even has to know.
So, how do you get your branches and commits over to them, or vice versa?
You can probably think of other methods, too. But there's a super easy way: if you can see each other on the network, you can launch a one-off git server that they can use as their remote to clone, fetch, and pull your changes, and kill it when you're done with it.
The tool that enables this is git daemon
, which has a lot of options and functionality, but for the purpose of enabling this easy one-off "just serve up the repo I'm in," the way to use it is to create an alias. I like to call it git serve
. Run:
git config --global alias.serve "daemon --verbose --export-all --base-path=.git --reuseaddr --strict-paths .git/"
Using an alias is actually crucial, because git aliases are executed in the base directory of your working tree. So the path '.git' will always point to the right place, no matter where you are within the directory tree of your repository.
Use your new git serve
like so:
git serve
. "Ready to rumble," it will report. Git is bad-ass.git fetch git://192.168.1.123/
"You could also tell Jane to git clone git://192.168.1.123/ local-repo-name
if she does not yet have a clone of the repository. Or, use git pull git://192.168.1.123/ branchname
to do a fetch and merge at once, useful if you are working together on a feature branch.
Note however that you shouldn't do this on hostile networks if you keep secrets in your repository, because there's no authentication. It doesn't advertise its existence, but anybody with a a port scanner can find it, connect to it, and clone your repo.
But it's not super dangerous because it is read-only by default. Read the git daemon
man page carefully if you think that you want to enable write access. In the case where you want to obtain your collaborator's commits, it's much safer to leave it read-only, and ask your collaborator to also run this command, so you can pull from them.
Tangentially related: on the subject of one-off servers, if you want to temporarily share a bunch of static files over HTTP: python -m SimpleHTTPServer
$alphabet = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
For those using CygWin on Vista, Win7, or above, the native git
command can create "proper" symlinks that are recognized by Windows apps such as Android Studio. You just need to set the CYGWIN
environment variable to include winsymlinks:native
or winsymlinks:nativestrict
as such:
export CYGWIN="$CYGWIN winsymlinks:native"
The downside to this (and a significant one at that) is that the CygWin shell has to be "Run as Administrator" in order for it to have the OS permissions required to create those kind of symlinks. Once they're created, though, no special permissions are required to use them. As long they aren't changed in the repository by another developer, git
thereafter runs fine with normal user permissions.
Personally, I use this only for symlinks that are navigated by Windows apps (i.e. non-CygWin) because of this added difficulty.
For more information on this option, see this SO question: How to make symbolic link with cygwin in Windows 7
Your question will trigger discussion I suppose. The general idea is that it's good to separate behavior and structure. Furthermore, afaik, an inline click handler has to be eval
led to 'become' a real javascript function. And it's pretty old fashioned, allbeit that that's a pretty shaky argument. Ah, well, read some about it @quirksmode.org
There is a symbol before help menu on xcode which has Edit user script. On Un/Comment Selection under comments section change my $cCmt = "//"; to my $cCmt = "#"; or whatever your IDE works with. Then by selecting lines and command + / (It's my xcode default) you can comment and uncomment the selected lines.
This works for me in irb:
irb> (1..4).to_a
=> [1, 2, 3, 4]
I notice that:
irb> 1..4.to_a
(irb):1: warning: default `to_a' will be obsolete
ArgumentError: bad value for range
from (irb):1
So perhaps you are missing the parentheses?
(I am running Ruby 1.8.6 patchlevel 114)
add semi-colon the line before:
$total_pages = ceil($total_result / $per_page);
This is now supported in Chrome by the "Pause on all exceptions" button.
To enable it:
Note that this button has multiple states. Keep clicking the button to switch between
It depends. If by calling someObservable.subscribe()
, you start holding up some resource that must be manually freed-up when the lifecycle of your component is over, then you should call theSubscription.unsubscribe()
to prevent memory leak.
Let's take a closer look at your examples:
getHero()
returns the result of http.get()
. If you look into the angular 2 source code, http.get()
creates two event listeners:
_xhr.addEventListener('load', onLoad);
_xhr.addEventListener('error', onError);
and by calling unsubscribe()
, you can cancel the request as well as the listeners:
_xhr.removeEventListener('load', onLoad);
_xhr.removeEventListener('error', onError);
_xhr.abort();
Note that _xhr
is platform specific but I think it's safe to assume that it is an XMLHttpRequest()
in your case.
Normally, this is enough evidence to warrant a manual unsubscribe()
call. But according this WHATWG spec, the XMLHttpRequest()
is subject to garbage collection once it is "done", even if there are event listeners attached to it. So I guess that's why angular 2 official guide omits unsubscribe()
and lets GC clean up the listeners.
As for your second example, it depends on the implementation of params
. As of today, the angular official guide no longer shows unsubscribing from params
. I looked into src again and found that params
is a just a BehaviorSubject. Since no event listeners or timers were used, and no global variables were created, it should be safe to omit unsubscribe()
.
The bottom line to your question is that always call unsubscribe()
as a guard against memory leak, unless you are certain that the execution of the observable doesn't create global variables, add event listeners, set timers, or do anything else that results in memory leaks.
When in doubt, look into the implementation of that observable. If the observable has written some clean up logic into its unsubscribe()
, which is usually the function that is returned by the constructor, then you have good reason to seriously consider calling unsubscribe()
.
The full procedure that worked for me to transfer ALL branches and tags is, combining the answers of @vikas027 and @kumarahul:
~$ git clone <url_of_old_repo>
~$ cd <name_of_old_repo>
~$ git remote add new-origin <url_of_new_repo>
~$ git push new-origin --mirror
~$ git push new-origin refs/remotes/origin/*:refs/heads/*
~$ git push new-origin --delete HEAD
The last step is because a branch named HEAD
appears in the new remote due to the wildcard
Instead of calling /usr/bin/gcc
, use /usr/bin/c99
. This is the Single-Unix-approved way of invoking a C99 compiler. On an Ubuntu system, this points to a script which invokes gcc
after having added the -std=c99
flag, which is precisely what you want.
One way would be store the current colour for each row within the model. Here's a simple model that is fixed at 3 columns and 3 rows:
static class MyTableModel extends DefaultTableModel {
List<Color> rowColours = Arrays.asList(
Color.RED,
Color.GREEN,
Color.CYAN
);
public void setRowColour(int row, Color c) {
rowColours.set(row, c);
fireTableRowsUpdated(row, row);
}
public Color getRowColour(int row) {
return rowColours.get(row);
}
@Override
public int getRowCount() {
return 3;
}
@Override
public int getColumnCount() {
return 3;
}
@Override
public Object getValueAt(int row, int column) {
return String.format("%d %d", row, column);
}
}
Note that setRowColour
calls fireTableRowsUpdated
; this will cause just that row of the table to be updated.
The renderer can get the model from the table:
static class MyTableCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
MyTableModel model = (MyTableModel) table.getModel();
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
c.setBackground(model.getRowColour(row));
return c;
}
}
Changing a row's colour would be as simple as:
model.setRowColour(1, Color.YELLOW);
Here is a function to get the IP address using a filter for local and LAN IP addresses:
function get_IP_address()
{
foreach (array('HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_X_CLUSTER_CLIENT_IP',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'REMOTE_ADDR') as $key){
if (array_key_exists($key, $_SERVER) === true){
foreach (explode(',', $_SERVER[$key]) as $IPaddress){
$IPaddress = trim($IPaddress); // Just to be safe
if (filter_var($IPaddress,
FILTER_VALIDATE_IP,
FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)
!== false) {
return $IPaddress;
}
}
}
}
}
The best way to solve your problem is to set the UseSystemPasswordChar
property to true. Then, the Caps-lock message is shown when the user enters the field and the Caps-Lock is on (at least for Vista and Windows 7).
Another alternative is to set the PasswordChar
property to a character value (* for example). This also triggers the automatic Caps-Lock handling.
Throwing exceptions in a constructor is not bad practice. In fact, it is the only reasonable way for a constructor to indicate that there is a problem; e.g. that the parameters are invalid.
I also think that throwing checked exceptions can be OK1, assuming that the checked exception is 1) declared, 2) specific to the problem you are reporting, and 3) it is reasonable to expect the caller to deal with a checked exception for this2.
However explicitly declaring or throwing java.lang.Exception
is almost always bad practice.
You should pick an exception class that matches the exceptional condition that has occurred. If you throw Exception
it is difficult for the caller to separate this exception from any number of other possible declared and undeclared exceptions. This makes error recovery difficult, and if the caller chooses to propagate the Exception, the problem just spreads.
1 - Some people may disagree, but IMO there is no substantive difference between this case and the case of throwing exceptions in methods. The standard checked vs unchecked advice applies equally to both cases.
2 - For example, the existing FileInputStream
constructors will throw FileNotFoundException
if you try to open a file that does not exist. Assuming that it is reasonable for FileNotFoundException
to be a checked exception3, then the constructor is the most appropriate place for that exception to be thrown. If we threw the FileNotFoundException
the first time that (say) a read
or write
call was made, that is liable to make application logic more complicated.
3 - Given that this is one of the motivating examples for checked exceptions, if you don't accept this you are basically saying that all exceptions should be unchecked. That is not practical ... if you are going to use Java.
Someone suggested using assert
for checking arguments. The problem with this is that checking of assert
assertions can be turned on and off via a JVM command-line setting. Using assertions to check internal invariants is OK, but using them to implement argument checking that is specified in your javadoc is not a good idea ... because it means your method will only strictly implement the specification when assertion checking is enabled.
The second problem with assert
is that if an assertion fails, then AssertionError
will be thrown, and received wisdom is that it is a bad idea to attempt to catch Error
and any of its subtypes.
Besides the already mentioned use-cases, I often find enums useful for implementing the strategy pattern, following some basic OOP guidelines:
The simplest example would be a set of Comparator
implementations:
enum StringComparator implements Comparator<String> {
NATURAL {
@Override
public int compare(String s1, String s2) {
return s1.compareTo(s2);
}
},
REVERSE {
@Override
public int compare(String s1, String s2) {
return NATURAL.compare(s2, s1);
}
},
LENGTH {
@Override
public int compare(String s1, String s2) {
return new Integer(s1.length()).compareTo(s2.length());
}
};
}
This "pattern" can be used in far more complex scenarios, making extensive use of all the goodies that come with the enum: iterating over the instances, relying on their implicit order, retrieving an instance by its name, static methods providing the right instance for specific contexts etc. And still you have this all hidden behind the interface so your code will work with custom implementations without modification in case you want something that's not available among the "default options".
I've seen this successfully applied for modeling the concept of time granularity (daily, weekly, etc.) where all the logic was encapsulated in an enum (choosing the right granularity for a given time range, specific behavior bound to each granularity as constant methods etc.). And still, the Granularity
as seen by the service layer was simply an interface.
rows = a.shape[0] # 2
cols = a.shape[1] # 2
a.shape #(2,2)
a.size # rows * cols = 4
Do you even need them to be input elements in the first place? You can use Javascript to dynamically create divs or paragraphs or list items or whatever that contain the information you want to present.
But if the interactive element is important and it's a pain in the butt to place those elements outside the <form>
block, it ought to be possible to remove those elements from the form when the page gets submitted.
You can set up a meta-table to track the number of entries, this may be faster than iteration if this information is a needed frequently.
The easiest way I found:
<Setter Property="Focusable" Value="false"/>
The python interpreter will handle it for you, you just have to do your operations (+, -, *, /), and it will work as normal.
The int
value is unlimited.
Careful when doing division, by default the quotient is turned into float
, but float
does not support such large numbers. If you get an error message saying float
does not support such large numbers, then it means the quotient is too large to be stored in float
you’ll have to use floor division (//
).
It ignores any decimal that comes after the decimal point, this way, the result will be int
, so you can have a large number result.
>>>10//3
3
>>>10//4
2
You should be using java.sql.Timestamp instead of java.util.Date. Also using a PreparedStatement will save you worrying about the formatting.
With Python 3.2 and later, you can use int.to_bytes
and int.from_bytes
: https://docs.python.org/3/library/stdtypes.html#int.to_bytes
I use the following approach by combining this and this answer without using exception based programming and also supports pre-API 21 intent flag.
@SuppressWarnings("deprecation")
private Intent getRateIntent()
{
String url = isMarketAppInstalled() ? "market://details" : "https://play.google.com/store/apps/details";
Intent rateIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format("%s?id=%s", url, getPackageName())));
int intentFlags = Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
intentFlags |= Build.VERSION.SDK_INT >= 21 ? Intent.FLAG_ACTIVITY_NEW_DOCUMENT : Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET;
rateIntent.addFlags(intentFlags);
return rateIntent;
}
private boolean isMarketAppInstalled()
{
Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=anyText"));
return getPackageManager().queryIntentActivities(marketIntent, 0).size() > 0;
}
// use
startActivity(getRateIntent());
Since the intent flag FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET
is deprecated from API 21 I use the @SuppressWarnings("deprecation")
tag on the getRateIntent method because my app target SDK is below API 21.
I also tried the official Google way suggested on their website (Dec. 6th 2019). To what I see it doesn't handle the case if the Play Store app isn't installed:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(
"https://play.google.com/store/apps/details?id=com.example.android"));
intent.setPackage("com.android.vending");
startActivity(intent);
In order to avoid the modulo bias (suggested in other answers) you can always use:
arc4random_uniform(MAX-MIN)+MIN
Where "MAX" is the upper bound and "MIN" is lower bound. For example, for numbers between 10 and 20:
arc4random_uniform(20-10)+10
arc4random_uniform(10)+10
Simple solution and better than using "rand() % N".
Readonly textbox in Asp.net
<asp:TextBox ID="t" runat="server" Style="margin-left: 20px; margin-top: 24px;"
Width="335px" Height="41px" ReadOnly="true"></asp:TextBox>
In bash version 4 associative arrays were introduced.
declare -A arr
arr["key1"]=val1
arr+=( ["key2"]=val2 ["key3"]=val3 )
The arr array now contains the three key value pairs. Bash is fairly limited what you can do with them though, no sorting or popping etc.
for key in ${!arr[@]}; do
echo ${key} ${arr[${key}]}
done
Will loop over all key values and echo them out.
Note: Bash 4 does not come with Mac OS X because of its GPLv3 license; you have to download and install it. For more on that see here
Few answers have given a solution with height and width 100% but I recommend you to not use percentage in css, use top/bottom and left/right positionning.
This is a better approach that allow you to control margin.
Here is the code :
body {
position: relative;
height: 3000px;
}
body div {
top:0px;
bottom: 0px;
right: 0px;
left:0px;
background-color: yellow;
position: absolute;
}
Just create a new branch:
git checkout -b newBranch
And if you do git status
you'll see that the state of the code hasn't changed and you can commit it to the new branch.
If Image folder location is public/assets/img/default.jpg.
You can try in view
<img src="{{ URL::to('/assets/img/default.jpg') }}">
Noticing that user 42-'s perfect approach {
* "do while" = "repeat until not"
* The code equivalence:
do while (condition) # in other language
..statements..
endo
repeat{ # in R
..statements..
if(! condition){ break } # Negation is crucial here!
}
} did not receive enough attention from the others, I'll emphasize and bring forward his approach via a concrete example. If one does not negate the condition in do-while (via !
or by taking negation), then distorted situations (1. value persistence 2. infinite loop) exist depending on the course of the code.
In Gauss:
proc(0)=printvalues(y);
DO WHILE y < 5;
y+1;
y=y+1;
ENDO;
ENDP;
printvalues(0); @ run selected code via F4 to get the following @
1.0000000
2.0000000
3.0000000
4.0000000
5.0000000
In R:
printvalues <- function(y) {
repeat {
y=y+1;
print(y)
if (! (y < 5) ) {break} # Negation is crucial here!
}
}
printvalues(0)
# [1] 1
# [1] 2
# [1] 3
# [1] 4
# [1] 5
I still insist that without the negation of the condition in do-while, Salcedo's answer is wrong. One can check this via removing negation symbol in the above code.
My Kotlin solution is to use a static Application context:
class App : Application() {
companion object {
lateinit var instance: App private set
}
override fun onCreate() {
super.onCreate()
instance = this
}
}
And the Strings class, that I use everywhere:
object Strings {
fun get(@StringRes stringRes: Int, vararg formatArgs: Any = emptyArray()): String {
return App.instance.getString(stringRes, *formatArgs)
}
}
So you can have a clean way of getting resource strings
Strings.get(R.string.some_string)
Strings.get(R.string.some_string_with_arguments, "Some argument")
Please don't delete this answer, let me keep one.