If you're writing C++, I can't recommend using the Boost libraries strongly enough.
The latest version (1.55) includes a new Predef library which covers exactly what you're looking for, along with dozens of other platform and architecture recognition macros.
#include <boost/predef.h>
// ...
#if BOOST_OS_WINDOWS
#elif BOOST_OS_LINUX
#elif BOOST_OS_MACOS
#endif
Implement your adapter Filterable:
public class vJournalAdapter extends ArrayAdapter<JournalModel> implements Filterable{
private ArrayList<JournalModel> items;
private Context mContext;
....
then create your Filter class:
private class JournalFilter extends Filter{
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
List<JournalModel> allJournals = getAllJournals();
if(constraint == null || constraint.length() == 0){
result.values = allJournals;
result.count = allJournals.size();
}else{
ArrayList<JournalModel> filteredList = new ArrayList<JournalModel>();
for(JournalModel j: allJournals){
if(j.source.title.contains(constraint))
filteredList.add(j);
}
result.values = filteredList;
result.count = filteredList.size();
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.count == 0) {
notifyDataSetInvalidated();
} else {
items = (ArrayList<JournalModel>) results.values;
notifyDataSetChanged();
}
}
}
this way, your adapter is Filterable, you can pass filter item to adapter's filter and do the work. I hope this will be helpful.
I'm not aware of anything like a single table that lets you compare all of them in at one glance (I'm not sure such a table would even be feasible).
Of course the ISO standard document enumerates the complexity requirements in detail, sometimes in various rather readable tables, other times in less readable bullet points for each specific method.
Also the STL library reference at http://www.cplusplus.com/reference/stl/ provides the complexity requirements where appropriate.
I solved in this way: I logged in with root username
mysql -u root -p -h localhost
I created a new user with
CREATE USER 'francesco'@'localhost' IDENTIFIED BY 'some_pass';
then I created the database
CREATE DATABASE shop;
I granted privileges for new user for this database
GRANT ALL PRIVILEGES ON shop.* TO 'francesco'@'localhost';
Then I logged out root and logged in new user
quit;
mysql -u francesco -p -h localhost
I rebuilt my database using a script
source shop.sql;
And that's it.. Now from php works without problems with the call
$conn = new mysqli("localhost", "francesco", "some_pass", "shop");
Thanks to all for your time :)
You could probably do like below
# p and q are the numbers to be divided
if p//q==p/q:
print(p//q)
else:
print(p/q)
Answer by Caleb Spare posted in gonuts mailing list.
[...] It's not actually needed very often and [...] using
os.Stat
is easy enough for the cases where it is required.[...] For instance: if you are going to open the file, there's no reason to check whether it exists first. The file could disappear in between checking and opening, and anyway you'll need to check the
os.Open
error regardless. So you simply callos.IsNotExist(err)
after you try to open the file, and deal with its non-existence there (if that requires special handling).[...] You don't need to check for the paths existing at all (and you shouldn't).
os.MkdirAll
works whether or not the paths already exist. (Also you need to check the error from that call.)Instead of using
os.Create
, you should useos.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)
. That way you'll get an error if the file already exists. Also this doesn't have a race condition with something else making the file, unlike your version which checks for existence beforehand.
Taken from: https://groups.google.com/forum/#!msg/golang-nuts/Ayx-BMNdMFo/4rL8FFHr8v4J
Quite often the issue is a non-breaking space - CHAR(160)
- especially from Web text sources -that CLEAN
can't remove, so I would go a step further than this and try a formula like this which replaces any non-breaking spaces with a standard one
=TRIM(CLEAN(SUBSTITUTE(A1,CHAR(160)," ")))
Ron de Bruin has an excellent post on tips for cleaning data here
You can also remove the CHAR(160)
directly without a workaround formula by
ALT
and type 0160
using the numeric keypad//====================================================
// textFieldShouldReturn:
//====================================================
-(BOOL) textFieldShouldReturn:(UITextField*) textField {
[textField resignFirstResponder];
if(textField.returnKeyType != UIReturnKeyDone){
[[textField.superview viewWithTag: self.nextTextField] becomeFirstResponder];
}
return YES;
}
jqyery this is another version with jquery a little less shorter.
assuming that the <a>
element is inside de <li>
element
$(li).click(function(){
$(this).children().click();
});
Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.
So, first build a list, then use pickle.dump
to send it to a file...
Python 3.4.1 (default, May 21 2014, 12:39:51)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>
>>> import pickle
>>>
>>> with open('parrot.pkl', 'wb') as f:
... pickle.dump(mylist, f)
...
>>>
Then quit and come back later… and open with pickle.load
...
Python 3.4.1 (default, May 21 2014, 12:39:51)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
... mynewlist = pickle.load(f)
...
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>
Old question, but still no good up-to-date answer with insight imo.
As jQuery uses Javascript wording for events and handlers, but does its own undocumented, but different interpretation of those, let me first shed light on the difference from the pure Javascript viewpoint:
enter/over
gets a corresponding leave/out
(possibly late/jumpy)mouseenter/mouseleave
mouseenter/mouseleave
cycle (i.e. no events fire)mouseenter/mouseleave
event cyclesmouseenter/mouseleave
could look like, you end up with with something like mouseover/mouseout
mouseover/mouseout
mouseout
on the previously sampled elementmouseover
on the new elementtarget/relatedTarget
indicate new and previous element$(event.target).closest(...)
suits your needsNot-so-trivial mouseover/mouseout
example:
$('.side-menu, .top-widget')
.on('mouseover mouseout', event => {
const target = event.type === 'mouseover' ? event.target : event.relatedTarget;
const thing = $(target).closest('[data-thing]').attr('data-thing') || 'default';
// do something with `thing`
});
These days, all browsers support mouseover/mouseout
and mouseenter/mouseleave
natively. Nevertheless, jQuery does not register your handler to mouseenter/mouseleave
, but silently puts them on a wrappers around mouseover/mouseout
as the code below exposes.
The emulation is unnecessary, imperfect and a waste of CPU cycles: it filters out mouseover/mouseout
events that a mouseenter/mouseleave
would not get, but the target
is messed. The real mouseenter/mouseleave
would give the handler element as target, the emulation might indicate children of that element, i.e. whatever the mouseover/mouseout
carried.
For that reason I do not use jQuery for those events, but e.g.:
$el[0].addEventListener('mouseover', e => ...);
const list = document.getElementById('log');
const outer = document.getElementById('outer');
const $outer = $(outer);
function log(tag, event) {
const li = list.insertBefore(document.createElement('li'), list.firstChild);
// only jQuery handlers have originalEvent
const e = event.originalEvent || event;
li.append(`${tag} got ${e.type} on ${e.target.id}`);
}
outer.addEventListener('mouseenter', log.bind(null, 'JSmouseenter'));
$outer.on('mouseenter', log.bind(null, '$mouseenter'));
_x000D_
div {
margin: 20px;
border: solid black 2px;
}
#inner {
min-height: 80px;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div id=outer>
<ul id=log>
</ul>
</div>
</body>
_x000D_
Note: For delegate handlers never use jQuery’s “delegate handlers with selector registration”. (Reason in another answer.) Use this (or similar):
$(parent).on("mouseover", e => {
if ($(e.target).closest('.gold').length) {...};
});
instead of
$(parent).on("mouseover", '.gold', e => {...});
Use sed's substitution: sed 's/"//g'
s/X/Y/
replaces X with Y.
g
means all occurrences should be replaced, not just the first one.
IIF(Fields!HIGHLIGHT_COLOUR.Value="","#FFFFFF","#" & hex(Fields!HIGHLIGHT_COLOUR.Value) & StrDup(6-LEN(hex(Fields!HIGHLIGHT_COLOUR.Value)),"0"))
Is working for me as an expression in font colour
Using a Subquery:
select m.subid, m.stid, m.mark
from marks m,
(select m2.subid, max(m2.mark) max_mark
from marks m2
group by subid) subq
where subq.subid = m.subid
and subq.max_mark = m.mark
order by 1,2;
Using Rank with Partition:
select subid, stid, mark
from (select m.subid, m.stid, m.mark,
rank() over (partition by m.subid order by m.mark desc) Mark_Rank
from marks m)
where Mark_Rank = 1
order by 1,2;
In my case the error was probably due to an incorrect merge between .gitmodules on two branches with different submodules configurations. After taking suggestions from this forum, I solved the problem editing manually the .gitmodules file, adding the missing submodule entry is pretty easy. After that, the command git submodule update --init --recursive worked with no issues.
Assuming you're not using html5 routing, try $location.path("route")
.
This will redirect your browser to #/route
which might be what you want.
In Symfony 3.3 you can use
$projectRoot = $this->get('kernel')->getProjectDir();
to get the web/project root.
If you have a C++11 compiler you can prepare yourself for the future by using c++'s pseudo random number faculties:
//make sure to include the random number generators and such
#include <random>
//the random device that will seed the generator
std::random_device seeder;
//then make a mersenne twister engine
std::mt19937 engine(seeder());
//then the easy part... the distribution
std::uniform_int_distribution<int> dist(min, max);
//then just generate the integer like this:
int compGuess = dist(engine);
That might be slightly easier to grasp, being you don't have to do anything involving modulos and crap... although it requires more code, it's always nice to know some new C++ stuff...
Hope this helps - Luke
As Moneer Kamal said, you can do that simply:
SELECT id, client_id FROM order
WHERE rownum <= 100
ORDER BY create_time DESC;
Notice that the ordering is done after getting the 100 row. This might be useful for who does not want ordering.
Any solution to this problem boils down to a shared secret. I also don't like the hard-coded user-name and password option but it does have the benefit of being quite simple. The client certificate is also good but is it really much different? There's a cert on the server and one on the client. It's main advantage is that it's harder to brute force. Hopefully you've got other protections in place to protect against that though.
I don't think your point A for the client certificate solution is difficult to resolve. You just use a branch. if (client side certificat) { check it } else { http basic auth }
I'm no java expert and I've never worked with it to do client side certificates. However a quick Google leads us to this tutorial which looks right up your alley.
Despite all of this "what's best" discussion, let me just point out that there is another philosophy that says, "less code, less cleverness is better." (I personally hold this philosophy). The client certificate solution sounds like a lot of code.
I know you expressed questions about OAuth, but the OAuth2 proposal does include a solution to your problem called "bearer tokens" which must be used in conjunction with SSL. I think, for the sake of simplicity, I'd choose either the hard-coded user/pass (one per app so that they can be revoked individually) or the very similar bearer tokens.
In Xamarin Forms this worked for me. Just add this on AppDelegate.cs:
UINavigationBar.Appearance.ShadowImage = new UIImage();
Same happened to me, In my case I just needed to approve apple's ne terms of service over: https://developer.apple.com/membercenter
sth's solution didn't work for me
because in ...
Imaging/PIL/Image.pyc line 1423 -> raise KeyError(ext) # unknown extension
It was trying to detect the format from the extension in the filename , which doesn't exist in StringIO case
You can bypass the format detection by setting the format yourself in a parameter
import StringIO
output = StringIO.StringIO()
format = 'PNG' # or 'JPEG' or whatever you want
image.save(output, format)
contents = output.getvalue()
output.close()
In case someone wanted an example using variables...
#!/bin/bash
# Only continue for 'develop' or 'release/*' branches
BRANCH_REGEX="^(develop$|release//*)"
if [[ $BRANCH =~ $BRANCH_REGEX ]];
then
echo "BRANCH '$BRANCH' matches BRANCH_REGEX '$BRANCH_REGEX'"
else
echo "BRANCH '$BRANCH' DOES NOT MATCH BRANCH_REGEX '$BRANCH_REGEX'"
fi
For listing your tables use:
SELECT table_name FROM information_schema.tables WHERE table_schema='public'
It will only list tables that you create.
I work on Mercurial, but fundamentally I believe both systems are equivalent. They both work with the same abstractions: a series of snapshots (changesets) which make up the history. Each changeset knows where it came from (the parent changeset) and can have many child changesets. The recent hg-git extension provides a two-way bridge between Mercurial and Git and sort of shows this point.
Git has a strong focus on mutating this history graph (with all the consequences that entails) whereas Mercurial does not encourage history rewriting, but it's easy to do anyway and the consequences of doing so are exactly what you should expect them to be (that is, if I modify a changeset you already have, your client will see it as new if you pull from me). So Mercurial has a bias towards non-destructive commands.
As for light-weight branches, then Mercurial has supported repositories with multiple branches since..., always I think. Git repositories with multiple branches are exactly that: multiple diverged strands of development in a single repository. Git then adds names to these strands and allow you to query these names remotely. The Bookmarks extension for Mercurial adds local names, and with Mercurial 1.6, you can move these bookmarks around when you push/pull..
I use Linux, but apparently TortoiseHg is faster and better than the Git equivalent on Windows (due to better usage of the poor Windows filesystem). Both http://github.com and http://bitbucket.org provide online hosting, the service at Bitbucket is great and responsive (I haven't tried github).
I chose Mercurial since it feels clean and elegant -- I was put off by the shell/Perl/Ruby scripts I got with Git. Try taking a peek at the git-instaweb.sh
file if you want to know what I mean: it is a shell script which generates a Ruby script, which I think runs a webserver. The shell script generates another shell script to launch the first Ruby script. There is also a bit of Perl, for good measure.
I like the blog post that compares Mercurial and Git with James Bond and MacGyver -- Mercurial is somehow more low-key than Git. It seems to me, that people using Mercurial are not so easily impressed. This is reflected in how each system do what Linus described as "the coolest merge EVER!". In Git you can merge with an unrelated repository by doing:
git fetch <project-to-union-merge>
GIT_INDEX_FILE=.git/tmp-index git-read-tree FETCH_HEAD
GIT_INDEX_FILE=.git/tmp-index git-checkout-cache -a -u
git-update-cache --add -- (GIT_INDEX_FILE=.git/tmp-index git-ls-files)
cp .git/FETCH_HEAD .git/MERGE_HEAD
git commit
Those commands look quite arcane to my eye. In Mercurial we do:
hg pull --force <project-to-union-merge>
hg merge
hg commit
Notice how the Mercurial commands are plain and not special at all -- the only unusual thing is the --force
flag to hg pull
, which is needed since Mercurial will abort otherwise when you pull from an unrelated repository. It is differences like this that makes Mercurial seem more elegant to me.
Use asList()
method. From java Doc asList
List<String> species = Arrays.asList(speciesArr);
If it's a directory relative to the file that does the requiring (e.g. you want to load all files in the lib directory):
Dir[File.dirname(__FILE__) + '/lib/*.rb'].each {|file| require file }
Edit: Based on comments below, an updated version:
Dir[File.join(__dir__, 'lib', '*.rb')].each { |file| require file }
You were setting BCC but then overwriting the variable with the FROM
$to = "[email protected]";
$subject .= "".$emailSubject."";
$headers .= "Bcc: ".$emailList."\r\n";
$headers .= "From: [email protected]\r\n" .
"X-Mailer: php";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message = '<html><body>';
$message .= 'THE MESSAGE FROM THE FORM';
if (mail($to, $subject, $message, $headers)) {
$sent = "Your email was sent!";
} else {
$sent = ("Error sending email.");
}
For those who don't want to use HTML agility pack and want to get HtmlDocument from string using native .net code only here is a good article on how to convert string to HtmlDocument
Here is the code block to use
public System.Windows.Forms.HtmlDocument GetHtmlDocument(string html)
{
WebBrowser browser = new WebBrowser();
browser.ScriptErrorsSuppressed = true;
browser.DocumentText = html;
browser.Document.OpenNew(true);
browser.Document.Write(html);
browser.Refresh();
return browser.Document;
}
Sorry but all the answers I see here are either hacky or fail if you sneeze a little harder.
If you use a table you can (if you wish) add a space between the divs, set borders, padding...
<table width="100%" cellspacing="0">
<tr>
<td style="width:50%;">A</td>
<td style="width:50%;">B</td>
</tr>
</table>
Check a more complete example here: http://jsfiddle.net/qPduw/5/
If you are using Webdriver then the item you are looking for is Selected.
Often times in the render of the checkbox doesn't actually apply the attribute checked unless specified.
So what you would look for in Selenium Webdriver is this
isChecked = e.findElement(By.tagName("input")).Selected;
As there is no Selected in WebDriver Java API, the above code should be as follows:
isChecked = e.findElement(By.tagName("input")).isSelected();
Assuming task is to find last element that satisfies some condition in a list (i.e. first when looking backwards), I'm getting following numbers:
>>> min(timeit.repeat('for i in xrange(len(xs)-1,-1,-1):\n if 128 == xs[i]: break', setup='xs, n = range(256), 0', repeat=8))
4.6937971115112305
>>> min(timeit.repeat('for i in reversed(xrange(0, len(xs))):\n if 128 == xs[i]: break', setup='xs, n = range(256), 0', repeat=8))
4.809093952178955
>>> min(timeit.repeat('for i, x in enumerate(reversed(xs), 1):\n if 128 == x: break', setup='xs, n = range(256), 0', repeat=8))
4.931743860244751
>>> min(timeit.repeat('for i, x in enumerate(xs[::-1]):\n if 128 == x: break', setup='xs, n = range(256), 0', repeat=8))
5.548468112945557
>>> min(timeit.repeat('for i in xrange(len(xs), 0, -1):\n if 128 == xs[i - 1]: break', setup='xs, n = range(256), 0', repeat=8))
6.286104917526245
>>> min(timeit.repeat('i = len(xs)\nwhile 0 < i:\n i -= 1\n if 128 == xs[i]: break', setup='xs, n = range(256), 0', repeat=8))
8.384078979492188
So, the ugliest option xrange(len(xs)-1,-1,-1)
is the fastest.
You need to diagnosis the jvm usages like how many process is running and what about heap allocation. there exists a lot of ways to do that for example
only variable/object declaration statement are written outside of method
public class details{
public static void main(String arg[]){
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is your name?");
String name = in.readLine(); ;
System.out.println("Hello " + name);
}
}
here is example try to learn java book and see the syntax then try to develop the program
jQuery.ajax({
type: 'GET',
url: "../struktur2/load.php",
async: false,
contentType: "application/json",
dataType: 'json',
success: function(json) {
items = json;
},
error: function(e) {
console.log("jQuery error message = "+e.message);
}
});
Try this:
[(i, j) for i, j in enumerate(mylist)]
You need to put i,j
inside a tuple for the list comprehension to work. Alternatively, given that enumerate()
already returns a tuple, you can return it directly without unpacking it first:
[pair for pair in enumerate(mylist)]
Either way, the result that gets returned is as expected:
> [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
Try this for creating a column3 as a sum of column1 + column 2 in a table
tablename$column3=rowSums(cbind(tablename$column1,tablename$column2))
You Can Also Check It:
cmd /c cd /d C:\activiti-5.9\setup & ant demo.start
<?php
require_once ( 'username.php' );
if (isset($_POST['textfield'])) {
echo username();
return;
}
echo '
<form name="form1" method="post" action="">
<p>
<label>
<input type="text" name="textfield" id="textfield">
</label>
</p>
<p>
<label>
<input type="submit" name="button" id="button" value="Submit">
</label>
</p>
</form>';
?>
You need to run the function in the page the form is sent to.
The approach I use is to start the "Visual Studio Command Prompt" which can be found in the Start menu. E.g. my visual studio 2010 Express install has a shortcute Visual Studio Command Prompt (2010)
at Start Menu\Programs\Microsoft Visual Studio 2010\Visual Studio Tools
.
This shortcut prepares an environment by calling a script vcvarsall.bat
where the compiler, linker, etc. are setup from the right Visual Studio installation.
Alternatively, if you already have a prompt open, you can prepare the environment by calling a similar script:
:: For x86 (using the VS100COMNTOOLS env-var)
call "%VS100COMNTOOLS%"\..\..\VC\bin\vcvars32.bat
or
:: For amd64 (using the full path)
call C:\Program Files\Microsoft Visual Studio 10.0\VC\bin\amd64\vcvars64.bat
Your output (with the '$' prompt) suggests that you are attempting to run CMake from a MSys shell. In that case it might be better to run CMake for MSys or MinGW, by explicitly specifying a makefile generator:
cmake -G"MSYS Makefiles"
cmake -G"MinGW Makefiles"
Run cmake --help
to get a list of all possible generators.
It is naming convention used when passing callbacks in situations that require serial execution of actions, e.g. scan directory -> read file data -> do something with data. This is in preference to deeply nesting the callbacks. The first three sections of the following article on Tim Caswell's HowToNode blog give a good overview of this:
http://howtonode.org/control-flow
Also see the Sequential Actions section of the second part of that posting:
Ubuntu, which is a Debian derivative, follows a very precise structure when installing packages. In other words, all software installed through the packaging tools, such as apt-get or synaptic, will put the stuff in the same locations. If you become familiar with these locations, you'll always know where to find your stuff.
As a short cut, you can always open a tool like synaptic, find the installed package, and inspect the "properties". Under properties, you'll see a list of all installed files. Again, you can expect these to always follow the Debian/Ubuntu conventions; these are highly ordered Linux distributions. IN short, binaries will be in /usr/bin, or some other location on your path ( try 'echo $PATH' on the command line to see the possible locations ). Configuration is always in a subdirectory of /etc. And the "home" is typically in /usr/lib or /usr/share.
For instance, according to http://www.mkyong.com/maven/how-to-install-maven-in-ubuntu/, maven is installed like:
The Apt-get installation will install all the required files in the following folder structure
/usr/bin/mvn
/usr/share/maven2/
/etc/maven2
P.S The Maven configuration is store in /etc/maven2
Note, it's not just apt-get that will do this, it's any .deb package installer.
Another approach if you want to use a varying portion of the dataset instead of a single value is to use rollapply(data, width, FUN, ...)
. Using a vector of widths allows you to apply a function on a varying window of the dataset. I've used this to build an adaptive filtering routine, though it isn't very efficient.
echo $this->db->select('title, content, date')->get_compiled_select();
PEP 591 has the 'final' qualifier. Enforcement is down to the type checker.
So you can do:
MY_CONSTANT: Final = 12407
Note: Final
keyword is only applicable for Python 3.8 version
as a curiosity
String s1 = null;
String s2 = "hello";
s1 = s1 + s2;
System.out.println((s); // nullhello
If you are using macOS sierra there is a update in PHP version. you need to have Entrust.net Certificate Authority (2048) file added to the PHP code. more info check accepted answer here Push Notification in PHP using PEM file
Same solution via Jquery. Works if you have more than one file input in the page.
$j(".filebutton").click(function() {
var input = $j(this).next().find('input');
input.click();
});
$j(".fileinput").change(function(){
var file = $j(this).val();
var fileName = file.split("\\");
var pai =$j(this).parent().parent().prev();
pai.html(fileName[fileName.length-1]);
event.preventDefault();
});
I've written a script to get all child process pids of a parent process. Here is the code. Hope it will help.
function getcpid() {
cpids=`pgrep -P $1|xargs`
# echo "cpids=$cpids"
for cpid in $cpids;
do
echo "$cpid"
getcpid $cpid
done
}
getcpid $1
Couldn't we do something like this:
public class Singleton {
private int x;
// Private constructor prevents instantiation from other classes
private Singleton() {}
/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance(int x) {
Singleton instance = SingletonHolder.INSTANCE;
instance.x = x;
return instance;
}
}
You can try below:
find ./ ! \( -path ./tmp -prune \) ! \( -path ./scripts -prune \) -type f -name '*_peaks.bed'
You should use the Time.IsZero() function instead:
func (Time) IsZero
func (t Time) IsZero() bool
IsZero reports whether t represents the zero time instant, January 1, year 1, 00:00:00 UTC.
In my case, putting space after colon was wrong.
# Not work
curl -H Content-Type: application/json ~
# OK
curl -H Content-Type:application/json ~
'async': false
says it's depreciated. I did notice if I run console.log('test1');
on ajax success, then console.log('test2');
in normal js after the ajax function, test2
prints before test1
so the issue is an ajax call has a small delay, but doesn't stop the rest of the function to get results. The variable simply, was not set "yet", so you need to delay the next function.
function runPHP(){
var input = document.getElementById("input1");
var result = 'failed to run php';
$.ajax({ url: '/test.php',
type: 'POST',
data: {action: 'test'},
success: function(data) {
result = data;
}
});
setTimeout(function(){
console.log(result);
}, 1000);
}
on test.php (incase you need to test this function)
function test(){
print 'ran php';
}
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = htmlentities($_POST['action']);
switch($action) {
case 'test' : test();break;
}
}
If I were you, I would use BABEL: http://babel.pocoo.org/en/latest/index.html
I got the same issue here using Docker, I've tried every single step and didn't work well, always getting locale error, so I decided to use BABEL, and everything worked well.
Even if this is already answered (1 year ago) you could also let the fields be calculated automatically.
The HTML
<tr>
<td><input type="text" value="" ></td>
<td><input type="text" class="class_name" placeholder="bla bla"/></td>
</tr>
<tr>
<td><input type="text" value="" ></td>
<td><input type="text" class="class_name" placeholder="bla bla."/></td>
</tr>
The script
$(document).ready(function(){
$(".class_name").each(function(){
$(this).keyup(function(){
calculateSum()
;})
;})
;}
);
function calculateSum(){
var sum=0;
$(".class_name").each(function(){
if(!isNaN(this.value) && this.value.length!=0){
sum+=parseFloat(this.value);
}
else if(isNaN(this.value)) {
alert("Maybe an alert if they type , instead of .");
}
}
);
$("#sum").html(sum.toFixed(2));
}
Are you looking to play around with Reflection or are you looking to build a production piece of software? I would question why you're using reflection to set a property.
Double new_latitude;
Double.TryParse (value, out new_latitude);
ship.Latitude = new_latitude;
All the validation from model are skipped when we use validate: false
user = User.new(....)
user.save(validate: false)
You can still use console.log(), but it gets logged into a separate console. In order to view it - right click on the extension icon and select "Inspect popup".
You could do $stmt->queryString
to obtain the SQL query used in the statement. If you want to save the entire $stmt variable (I can't see why), you could just copy it. It is an instance of PDOStatement so there is apparently no advantage in storing it.
Try this:
subset(studentdata, Drink=='water')
that should do it.
git config information will stored in ~/.gitconfig
in unix platform.
In Windows it will be stored in C:/users/<NAME>/.gitconfig.
You can edit it manually by opening this files and deleting the fields which you are interested.
docker-compose exists to keep you having to write a ton of commands you would have to with docker-cli.
docker-compose also makes it easy to startup multiple containers at the same time and automatically connect them together with some form of networking.
The purpose of docker-compose is to function as docker cli but to issue multiple commands much more quickly.
To make use of docker-compose, you need to encode the commands you were running before into a docker-compose.yml
file.
You are not just going to copy paste them into the yaml file, there is a special syntax.
Once created, you have to feed it to the docker-compose cli and it will be up to the cli to parse the file and create all the different containers with the correct configuration we specify.
So you will have separate containers, let's say, one is redis-server
and the second one is node-app
, and you want that created using the Dockerfile
in your current directory.
Additionally, after making that container, you would map some port from the container to the local machine to access everything running inside of it.
So for your docker-compose.yml
file, you would want to start the first line like so:
version: '3'
That tells Docker the version of docker-compose
you want to use. After that, you have to add:
version: '3'
services:
redis-server:
image: 'redis'
node-app:
build: .
Please notice the indentation, very important. Also, notice for one service I am grabbing an image, but for another service I am telling docker-compose
to look inside the current directory to build the image that will be used for the second container.
Then you want to specify all the different ports that you want open on this container.
version: '3'
services:
redis-server:
image: 'redis'
node-app:
build: .
ports:
-
Please notice the dash, a dash in a yaml file is how we specify an array. In this example, I am mapping 8081
on my local machine to 8081
on the container like so:
version: '3'
services:
redis-server:
image: 'redis'
node-app:
build: .
ports:
- "8081:8081"
So the first port is your local machine, and the other is the port on the container, you could also distinguish between the two to avoid confusion like so:
version: '3'
services:
redis-server:
image: 'redis'
node-app:
build: .
ports:
- "4001:8081"
By developing your docker-compose.yml
file like this, it will create these containers on essentially the same network and they will have free access to communicate with each other any way they please and exchange as much information as they want.
When the two containers are created using docker-compose
, we do not need any port declarations.
Now in my example, we need to do some code configuration in the Nodejs app that looks something like this:
const express = require('express');
const redis = require('redis');
const app = express();
const client = redis.createClient({
host: 'redis-server'
});
I use this example above to make you aware that there may be some specific configuration you would have to do in addition to the docker-compose.yml
file that may be specific to your project.
Now, if you ever find yourself working with a Nodejs app and redis, you want to ensure you are aware of the default port Nodejs uses, so I will add this:
const express = require('express');
const redis = require('redis');
const app = express();
const client = redis.createClient({
host: 'redis-server',
port: 6379
});
So Docker is going to see that the Node app is looking for redis-server
and redirect that connection over to this running container.
The whole time, the Dockerfile
only contains this:
FROM node:alpine
WORKDIR '/app'
COPY /package.json ./
RUN npm install
COPY . .
CMD ["npm", "start"]
So, whereas before you would have to run docker run myimage
to create an instance of all the containers or services inside the file, you can instead run docker-compose up
and you don't have to specify an image because Docker will look in the current working directory and look for a docker-compose.yml
file inside.
Before docker-compose.yml
, we had to deal with two separate commands of docker build .
and docker run myimage
, but in the docker-compose
world, if you want to rebuild your images, you write docker-compose up --build
. That tells Docker to start up the containers again but rebuild it to get the latest changes.
So docker-compose
makes it easier for working with multiple containers. The next time you need to start this group of containers in the background, you can do docker-compose up -d
; and to stop them, you can do docker-compose down
.
var obj = {
webSiteName: 'StackOverFlow',
find: 'anything',
onDays: ['sun' // Object "obj" contains array "onDays"
,'mon',
'tue',
'wed',
'thu',
'fri',
'sat',
{name : "jack", age : 34},
// array "onDays"contains array object "manyNames"
{manyNames : ["Narayan", "Payal", "Suraj"]}, //
]
};
The best practice would be #4 if you are using non-modal forms.
Here's a quick tip to center align the action:
android:label=" YourTitle"
Assuming that you have Actionbar Enable, You can add this in your activity with some space (Can be adjusted) to place the title at the center.
However, This is just diddly and unreliable method. You probably shouldn't do that. So, The best thing to do is to create a custom ActionBar. So, What you wanna do is remove the default Actionbar and use this to replace it as an ActionBar.
<androidx.constraintlayout.widget.ConstraintLayout
android:elevation="30dp"
android:id="@+id/customAction"
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="@color/colorOnMain"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"
android:textAllCaps="true"
android:textColor="#FFF"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
I have used Constraint Layout to center the textView and used 10dp elevation with 56dp height so that it looks as same as the default ActionBar.
You can use my script from CodePen by just wrapping all the content within a .levit-container DIV.
~function () {
function Smooth () {
this.$container = document.querySelector('.levit-container');
this.$placeholder = document.createElement('div');
}
Smooth.prototype.init = function () {
var instance = this;
setContainer.call(instance);
setPlaceholder.call(instance);
bindEvents.call(instance);
}
function bindEvents () {
window.addEventListener('scroll', handleScroll.bind(this), false);
}
function setContainer () {
var style = this.$container.style;
style.position = 'fixed';
style.width = '100%';
style.top = '0';
style.left = '0';
style.transition = '0.5s ease-out';
}
function setPlaceholder () {
var instance = this,
$container = instance.$container,
$placeholder = instance.$placeholder;
$placeholder.setAttribute('class', 'levit-placeholder');
$placeholder.style.height = $container.offsetHeight + 'px';
document.body.insertBefore($placeholder, $container);
}
function handleScroll () {
this.$container.style.transform = 'translateZ(0) translateY(' + (window.scrollY * (- 1)) + 'px)';
}
var smooth = new Smooth();
smooth.init();
}();
grantUriPermission (from Android document)
Normally you should use Intent#FLAG_GRANT_READ_URI_PERMISSION or Intent#FLAG_GRANT_WRITE_URI_PERMISSION with the Intent being used to start an activity instead of this function directly. If you use this function directly, you should be sure to call revokeUriPermission(Uri, int) when the target should no longer be allowed to access it.
So I test and I see that.
If we use grantUriPermission
before we start a new activity, we DON'T need
FLAG_GRANT_READ_URI_PERMISSION
or FLAG_GRANT_WRITE_URI_PERMISSION
in Intent
to overcome SecurityException
If we don't use grantUriPermission
. We need to use FLAG_GRANT_READ_URI_PERMISSION
or FLAG_GRANT_WRITE_URI_PERMISSION
to overcome SecurityException
but
Uri
by setData
or setDataAndType
else SecurityException
still throw. (one interesting I see: setData
and setType
can not work well together so if you need both Uri
and type
you need setDataAndType
. You can check inside Intent
code, currently when you setType
, it will also set uri= null and when you setUri it will also set type=null)Here is an example of using a dynamic T-SQL query and then extracting the results should you have more than one column of returned values (notice the dynamic table name):
DECLARE
@strSQLMain nvarchar(1000),
@recAPD_number_key char(10),
@Census_sub_code varchar(1),
@recAPD_field_name char(100),
@recAPD_table_name char(100),
@NUMBER_KEY varchar(10),
if object_id('[Permits].[dbo].[myTempAPD_Txt]') is not null
DROP TABLE [Permits].[dbo].[myTempAPD_Txt]
CREATE TABLE [Permits].[dbo].[myTempAPD_Txt]
(
[MyCol1] char(10) NULL,
[MyCol2] char(1) NULL,
)
-- an example of what @strSQLMain is : @strSQLMain = SELECT @recAPD_number_key = [NUMBER_KEY], @Census_sub_code=TEXT_029 FROM APD_TXT0 WHERE Number_Key = '01-7212'
SET @strSQLMain = ('INSERT INTO myTempAPD_Txt SELECT [NUMBER_KEY], '+ rtrim(@recAPD_field_name) +' FROM '+ rtrim(@recAPD_table_name) + ' WHERE Number_Key = '''+ rtrim(@Number_Key) +'''')
EXEC (@strSQLMain)
SELECT @recAPD_number_key = MyCol1, @Census_sub_code = MyCol2 from [Permits].[dbo].[myTempAPD_Txt]
DROP TABLE [Permits].[dbo].[myTempAPD_Txt]
On linux, /etc/apache2/mods-enabled/php5.conf dans php5.load
exists. If not, enables this modules (may require to sudo apt-get install libapache2-mod-php5
).
For iTunes 12.9.5.5 and above you can install the apps by Copying
the IPA file and Paste
it (Cmd+V or Edit -> Paste in iTunes) in any categories as Music/Films/TV Programmes etc. The app will be installed automatically on your iPhone screen.
Tested on 29 Nov 2019.
From https://golang.org/doc/effective_go.html#composite_literals:
Sometimes the zero value isn't good enough and an initializing constructor is necessary, as in this example derived from package os.
func NewFile(fd int, name string) *File {
if fd < 0 {
return nil
}
f := new(File)
f.fd = fd
f.name = name
f.dirinfo = nil
f.nepipe = 0
return f
}
Create epoll
object,
open many client TCP sockets,
adjust their send buffers to be a bit more than request header,
send a request header — it should be immediate, just placing into a buffer,
register socket in epoll
object,
do .poll
on epoll
obect,
read first 3 bytes from each socket from .poll
,
write them to sys.stdout
followed by \n
(don't flush),
close the client socket.
Limit number of sockets opened simultaneously — handle errors when sockets are created. Create a new socket only if another is closed.
Adjust OS limits.
Try forking into a few (not many) processes: this may help to use CPU a bit more effectively.
// this is how I always do it
for (i = n; --i >= 0;){
...
}
I do not know whether this is the general opinion, but I've always differentiated the two by what they are used for. An emulator is used if you actually want to use the emulated machine for its output. A simulator, on the other hand, is for when you want to study the simulated machine or test its behaviour.
For example, if you want to write some state machine logic in your application (which is running on a general purpose CPU), you write a small state machine emulator. If you want to study the efficiency or viability of a state machine for a particular problem, you write a simulator.
Note to Sinan and brian: perlfaq3 is still wrong.
Using "groupby" and list comprehension:
Storing all the split dataframe in list variable and accessing each of the seprated dataframe by their index.
DF = pd.DataFrame({'chr':["chr3","chr3","chr7","chr6","chr1"],'pos':[10,20,30,40,50],})
ans = [pd.DataFrame(y) for x, y in DF.groupby('chr', as_index=False)]
accessing the separated DF like this:
ans[0]
ans[1]
ans[len(ans)-1] # this is the last separated DF
accessing the column value of the separated DF like this:
ansI_chr=ans[i].chr
There are certain circumstances in which even fatal errors should be caught (you might need to do some clean up before exiting gracefully and don’t just die..).
I have implemented a pre_system hook in my CodeIgniter applications so that I can get my fatal errors through emails, and this helped me finding bugs that were not reported (or were reported after they were fixed, as I already knew about them :)).
Sendemail checks if the error has already been reported so that it does not spam you with known errors multiple times.
class PHPFatalError {
public function setHandler() {
register_shutdown_function('handleShutdown');
}
}
function handleShutdown() {
if (($error = error_get_last())) {
ob_start();
echo "<pre>";
var_dump($error);
echo "</pre>";
$message = ob_get_clean();
sendEmail($message);
ob_start();
echo '{"status":"error","message":"Internal application error!"}';
ob_flush();
exit();
}
}
Updated for Swift 3
The answer below is a summary of the available options. Choose the one that best fits your needs.
reversed
: numbers in a rangeForward
for index in 0..<5 {
print(index)
}
// 0
// 1
// 2
// 3
// 4
Backward
for index in (0..<5).reversed() {
print(index)
}
// 4
// 3
// 2
// 1
// 0
reversed
: elements in SequenceType
let animals = ["horse", "cow", "camel", "sheep", "goat"]
Forward
for animal in animals {
print(animal)
}
// horse
// cow
// camel
// sheep
// goat
Backward
for animal in animals.reversed() {
print(animal)
}
// goat
// sheep
// camel
// cow
// horse
reversed
: elements with an indexSometimes an index is needed when iterating through a collection. For that you can use enumerate()
, which returns a tuple. The first element of the tuple is the index and the second element is the object.
let animals = ["horse", "cow", "camel", "sheep", "goat"]
Forward
for (index, animal) in animals.enumerated() {
print("\(index), \(animal)")
}
// 0, horse
// 1, cow
// 2, camel
// 3, sheep
// 4, goat
Backward
for (index, animal) in animals.enumerated().reversed() {
print("\(index), \(animal)")
}
// 4, goat
// 3, sheep
// 2, camel
// 1, cow
// 0, horse
Note that as Ben Lachman noted in his answer, you probably want to do .enumerated().reversed()
rather than .reversed().enumerated()
(which would make the index numbers increase).
Stride is way to iterate without using a range. There are two forms. The comments at the end of the code show what the range version would be (assuming the increment size is 1).
startIndex.stride(to: endIndex, by: incrementSize) // startIndex..<endIndex
startIndex.stride(through: endIndex, by: incrementSize) // startIndex...endIndex
Forward
for index in stride(from: 0, to: 5, by: 1) {
print(index)
}
// 0
// 1
// 2
// 3
// 4
Backward
Changing the increment size to -1
allows you to go backward.
for index in stride(from: 4, through: 0, by: -1) {
print(index)
}
// 4
// 3
// 2
// 1
// 0
Note the to
and through
difference.
Forward by increments of 2
let animals = ["horse", "cow", "camel", "sheep", "goat"]
I'm using 2
in this example just to show another possibility.
for index in stride(from: 0, to: 5, by: 2) {
print("\(index), \(animals[index])")
}
// 0, horse
// 2, camel
// 4, goat
Backward
for index in stride(from: 4, through: 0, by: -1) {
print("\(index), \(animals[index])")
}
// 4, goat
// 3, sheep
// 2, camel
// 1, cow
// 0, horse
@matt has an interesting solution where he defines his own reverse operator and calls it >>>
. It doesn't take much code to define and is used like this:
for index in 5>>>0 {
print(index)
}
// 4
// 3
// 2
// 1
// 0
You can use this:
bankHoliday= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month
def bank_holiday(month):
month -= 1#Takes away the numbers from the months, as months start at 1 (January) not at 0. There is no 0 month.
print(bankHoliday[month])
bank_holiday(int(input("Which month would you like to check out: ")))
I was have same problem and i found solution by adding path to file like:
@import "C:/xampp/htdocs/Scss_addons/Bootstrap/bootstrap";
@import "C:/xampp/htdocs/Scss_addons/Compass/compass";
var seconds = 60;_x000D_
var measuredTime = new Date(null);_x000D_
measuredTime.setSeconds(seconds); // specify value of SECONDS_x000D_
var Time = measuredTime.toISOString().substr(11, 8);_x000D_
document.getElementById("id1").value = Time;
_x000D_
<div class="form-group">_x000D_
<label for="course" class="col-md-4">Time</label>_x000D_
<div class="col-md-8">_x000D_
<input type="text" class="form-control" id="id1" name="field">Min_x000D_
</div>_x000D_
</div>
_x000D_
Demo here
Try this one
$('html').on('click', 'a.Link', function(event){
event.preventDefault();
});
If double backslash looks weird to you, C# also allows verbatim string literals where the escaping is not required.
Console.WriteLine(@"Mango \ Nightangle");
Don't you just wish Java had something like this ;-)
Here you can find "Adobe Acrobat Forms JavaScript Object Specification Version 4.0"
Revised: January 27, 1999
It’s very old, but it is still useful.
You cannot clear the browser history. It belongs to the user, not the developer. Also have a look at the MDN documentation.
Update: The link you were posting all over does not actually clear your browser history. It just prevents using the back button.
npm install -g @angular/cli --registry http://registry.npmjs.org/ worked for me
To see which packages have newer versions available, then use the following command:
npm outdated
to update just one dependency just use the following command:
npm install yourPackage@latest --save
For example:
My package.json
file has dependency:
"@progress/kendo-angular-dateinputs": "^1.3.1",
then I should write:
npm install @progress/kendo-angular-dateinputs@latest --save
Open the .project file and add java nature and builders.
<projectDescription>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
And in .classpath, reference the Java libs:
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
</classpath>
Oddly enough, the issue for me was I was trying to open 2012 SQL Server Integration Services on SSMS 2008 R2. When I opened the same in SSMS 2012, it connected right away.
Be sure to stringify
before sending. I leaned on the libraries too much and thought they would encode properly based on the contentType I was posting, but they do not seem to.
Works:
$.ajax({
url: _saveAllDevicesUrl
, type: 'POST'
, contentType: 'application/json'
, data: JSON.stringify(postData) //stringify is important
, success: _madeSave.bind(this)
});
I prefer this method to using a plugin like $.toJSON, although that does accomplish the same thing.
There could be two ways/syntax to bind a static
property. If p is a static
property in class MainWindow
, then binding
for textbox
will be:
1.
<TextBox Text="{x:Static local:MainWindow.p}" />
2.
<TextBox Text="{Binding Source={x:Static local:MainWindow.p},Mode=OneTime}" />
This is a little helper arrow function:
const letters = ['A', 'B', 'C', 'D'];
function checkInList(arr, val) {
return arr.some(arrVal => val === arrVal);
}
checkInList(letters, 'E'); // false
checkInList(letters, 'A'); // true
If we're just collecting basic ways of detecting visibility, let me not forget:
opacity > 0.01; // probably more like .1 to actually be visible, but YMMV
And as to how to obtain attributes:
element.getAttribute(attributename);
So, in your example:
document.getElementById('snDealsPanel').getAttribute('visibility');
But wha? It doesn't work here. Look closer and you'll find that visibility is being updated not as an attribute on the element, but using the style
property. This is one of many problems with trying to do what you're doing. Among others: you can't guarantee that there's actually something to see in an element, just because its visibility, display, and opacity all have the correct values. It still might lack content, or it might lack a height and width. Another object might obscure it. For more detail, a quick Google search reveals this, and even includes a library to try solving the problem. (YMMV)
Check out the following, which are possible duplicates of this question, with excellent answers, including some insight from the mighty John Resig. However, your specific use-case is slightly different from the standard one, so I'll refrain from flagging:
(EDIT: OP SAYS HE'S SCRAPING PAGES, NOT CREATING THEM, SO BELOW ISN'T APPLICABLE) A better option? Bind the visibility of elements to model properties and always make visibility contingent on that model, much as Angular does with ng-show. You can do that using any tool you want: Angular, plain JS, whatever. Better still, you can change the DOM implementation over time, but you'll always be able to read state from the model, instead of the DOM. Reading your truth from the DOM is Bad. And slow. Much better to check the model, and trust in your implementation to ensure that the DOM state reflects the model. (And use automated testing to confirm that assumption.)
A little late to the party, but I've tried every possible method, and nothing worked correctly. Here is my elegant solution:
I use a controller that governs all my pages with ui-router. It allows me to redirect users who aren't authenticated or validated to an appropriate location. Most people put their middleware in their app's config, but I required some http requests, therefore a global controller works better for me.
My index.html looks like:
<main ng-controller="InitCtrl">
<nav id="top-nav"></nav>
<div ui-view></div>
</main>
My initCtrl.js looks like:
angular.module('MyApp').controller('InitCtrl', function($rootScope, $timeout, $anchorScroll) {
$rootScope.$on('$locationChangeStart', function(event, next, current){
// middleware
});
$rootScope.$on("$locationChangeSuccess", function(){
$timeout(function() {
$anchorScroll('top-nav');
});
});
});
I've tried every possible option, this method works the best.
When cin
gets input it can't use, it sets failbit
:
int n;
cin >> n;
if(!cin) // or if(cin.fail())
{
// user didn't input a number
cin.clear(); // reset failbit
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); //skip bad input
// next, request user reinput
}
When cin
's failbit
is set, use cin.clear()
to reset the state of the stream, then cin.ignore()
to expunge the remaining input, and then request that the user re-input. The stream will misbehave so long as the failure state is set and the stream contains bad input.
You don't want to stretch the span in height?
You have the possiblity to affect one or more flex-items to don't stretch the full height of the container.
To affect all flex-items of the container, choose this:
You have to set align-items: flex-start;
to div
and all flex-items of this container get the height of their content.
div {_x000D_
align-items: flex-start;_x000D_
background: tan;_x000D_
display: flex;_x000D_
height: 200px;_x000D_
}_x000D_
span {_x000D_
background: red;_x000D_
}
_x000D_
<div>_x000D_
<span>This is some text.</span>_x000D_
</div>
_x000D_
To affect only a single flex-item, choose this:
If you want to unstretch a single flex-item on the container, you have to set align-self: flex-start;
to this flex-item. All other flex-items of the container aren't affected.
div {_x000D_
display: flex;_x000D_
height: 200px;_x000D_
background: tan;_x000D_
}_x000D_
span.only {_x000D_
background: red;_x000D_
align-self:flex-start;_x000D_
}_x000D_
span {_x000D_
background:green;_x000D_
}
_x000D_
<div>_x000D_
<span class="only">This is some text.</span>_x000D_
<span>This is more text.</span>_x000D_
</div>
_x000D_
Why is this happening to the span
?
The default value of the property align-items
is stretch
. This is the reason why the span
fill the height of the div
.
Difference between baseline
and flex-start
?
If you have some text on the flex-items, with different font-sizes, you can use the baseline of the first line to place the flex-item vertically. A flex-item with a smaller font-size have some space between the container and itself at top. With flex-start
the flex-item will be set to the top of the container (without space).
div {_x000D_
align-items: baseline;_x000D_
background: tan;_x000D_
display: flex;_x000D_
height: 200px;_x000D_
}_x000D_
span {_x000D_
background: red;_x000D_
}_x000D_
span.fontsize {_x000D_
font-size:2em;_x000D_
}
_x000D_
<div>_x000D_
<span class="fontsize">This is some text.</span>_x000D_
<span>This is more text.</span>_x000D_
</div>
_x000D_
You can find more information about the difference between
baseline
andflex-start
here:
What's the difference between flex-start and baseline?
Not related to Git, but below I will help with the Jenkins job configuration in detail with Mercurial. It may help others with a similar problem.
Poll SCM
option. Set the value to * * * * *
[URLTrigger] - Poll with a URL
.
Now you can select some options like modification date change, URL content, etc.Monitor change of content
Now, trigger some change to the Mercurial repository by some test check-ins.
See that the Jenkins job now runs by detecting the SCM changes. When the build is run due to Mercurial changes, then, you will see text Started by an SCM change
. Else, the user who manually started it.
What's the difference between an RDD's map and mapPartitions method?
The method map converts each element of the source RDD into a single element of the result RDD by applying a function. mapPartitions converts each partition of the source RDD into multiple elements of the result (possibly none).
And does flatMap behave like map or like mapPartitions?
Neither, flatMap works on a single element (as map
) and produces multiple elements of the result (as mapPartitions
).
In kotlin don't use getters and setters as like in java.The correct format of the kotlin is given below.
val textView: TextView = findViewById(R.id.android_text) as TextView
textView.setOnClickListener {
textView.text = getString(R.string.name)
}
To get the values from the Textview
we have to use this method
val str: String = textView.text.toString()
println("the value is $str")
In addition to the answer from @StephanBijzitter I would use the following PATH
variables instead:
%appdata%\npm
%ProgramFiles%\nodejs
So your new PATH
would look like:
[existing stuff];%appdata%\npm;%ProgramFiles%\nodejs
This has the advantage of neiter being user dependent nor 32/64bit dependent.
If like me, you got that message after installing jenv,
simply add netbeans_jdkhome="$JAVA_HOME"
to your [netbeans-installation-directory]/etc/netbeans.conf
file
I Found Very Simple Solution isAdded() method which is one of the fragment method to identify that this current fragment is attached to its Activity or not.
we can use this like everywhere in fragment class like:
if(isAdded())
{
// using this method, we can do whatever we want which will prevent **java.lang.IllegalStateException: Fragment not attached to Activity** exception.
}
I think you will probably spend most of your time trying to match words that can't possibly be built by your letter grid. So, the first thing I would do is try to speed up that step and that should get you most of the way there.
For this, I would re-express the grid as a table of possible "moves" that you index by the letter-transition you are looking at.
Start by assigning each letter a number from your entire alphabet (A=0, B=1, C=2, ... and so forth).
Let's take this example:
h b c d
e e g h
l l k l
m o f p
And for now, lets use the alphabet of the letters we have (usually you'd probably want to use the same whole alphabet every time):
b | c | d | e | f | g | h | k | l | m | o | p
---+---+---+---+---+---+---+---+---+---+----+----
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11
Then you make a 2D boolean array that tells whether you have a certain letter transition available:
| 0 1 2 3 4 5 6 7 8 9 10 11 <- from letter
| b c d e f g h k l m o p
-----+--------------------------------------
0 b | T T T T
1 c | T T T T T
2 d | T T T
3 e | T T T T T T T
4 f | T T T T
5 g | T T T T T T T
6 h | T T T T T T T
7 k | T T T T T T T
8 l | T T T T T T T T T
9 m | T T
10 o | T T T T
11 p | T T T
^
to letter
Now go through your word list and convert the words to transitions:
hello (6, 3, 8, 8, 10):
6 -> 3, 3 -> 8, 8 -> 8, 8 -> 10
Then check if these transitions are allowed by looking them up in your table:
[6][ 3] : T
[3][ 8] : T
[8][ 8] : T
[8][10] : T
If they are all allowed, there's a chance that this word might be found.
For example the word "helmet" can be ruled out on the 4th transition (m to e: helMEt), since that entry in your table is false.
And the word hamster can be ruled out, since the first (h to a) transition is not allowed (doesn't even exist in your table).
Now, for the probably very few remaining words that you didn't eliminate, try to actually find them in the grid the way you're doing it now or as suggested in some of the other answers here. This is to avoid false positives that result from jumps between identical letters in your grid. For example the word "help" is allowed by the table, but not by the grid.
Some further performance improvement tips on this idea:
Instead of using a 2D array, use a 1D array and simply compute the index of the second letter yourself. So, instead of a 12x12 array like above, make a 1D array of length 144. If you then always use the same alphabet (i.e. a 26x26 = 676x1 array for the standard english alphabet), even if not all letters show up in your grid, you can pre-compute the indices into this 1D array that you need to test to match your dictionary words. For example, the indices for 'hello' in the example above would be
hello (6, 3, 8, 8, 10):
42 (from 6 + 3x12), 99, 104, 128
-> "hello" will be stored as 42, 99, 104, 128 in the dictionary
Extend the idea to a 3D table (expressed as a 1D array), i.e. all allowed 3-letter combinations. That way you can eliminate even more words immediately and you reduce the number of array lookups for each word by 1: For 'hello', you only need 3 array lookups: hel, ell, llo. It will be very quick to build this table, by the way, as there are only 400 possible 3-letter-moves in your grid.
Pre-compute the indices of the moves in your grid that you need to include in your table. For the example above, you need to set the following entries to 'True':
(0,0) (0,1) -> here: h, b : [6][0]
(0,0) (1,0) -> here: h, e : [6][3]
(0,0) (1,1) -> here: h, e : [6][3]
(0,1) (0,0) -> here: b, h : [0][6]
(0,1) (0,2) -> here: b, c : [0][1]
.
:
I'm sure if you use this approach you can get your code to run insanely fast, if you have the dictionary pre-computed and already loaded into memory.
BTW: Another nice thing to do, if you are building a game, is to run these sort of things immediately in the background. Start generating and solving the first game while the user is still looking at the title screen on your app and getting his finger into position to press "Play". Then generate and solve the next game as the user plays the previous one. That should give you a lot of time to run your code.
(I like this problem, so I'll probably be tempted to implement my proposal in Java sometime in the next days to see how it would actually perform... I'll post the code here once I do.)
UPDATE:
Ok, I had some time today and implemented this idea in Java:
class DictionaryEntry {
public int[] letters;
public int[] triplets;
}
class BoggleSolver {
// Constants
final int ALPHABET_SIZE = 5; // up to 2^5 = 32 letters
final int BOARD_SIZE = 4; // 4x4 board
final int[] moves = {-BOARD_SIZE-1, -BOARD_SIZE, -BOARD_SIZE+1,
-1, +1,
+BOARD_SIZE-1, +BOARD_SIZE, +BOARD_SIZE+1};
// Technically constant (calculated here for flexibility, but should be fixed)
DictionaryEntry[] dictionary; // Processed word list
int maxWordLength = 0;
int[] boardTripletIndices; // List of all 3-letter moves in board coordinates
DictionaryEntry[] buildDictionary(String fileName) throws IOException {
BufferedReader fileReader = new BufferedReader(new FileReader(fileName));
String word = fileReader.readLine();
ArrayList<DictionaryEntry> result = new ArrayList<DictionaryEntry>();
while (word!=null) {
if (word.length()>=3) {
word = word.toUpperCase();
if (word.length()>maxWordLength) maxWordLength = word.length();
DictionaryEntry entry = new DictionaryEntry();
entry.letters = new int[word.length() ];
entry.triplets = new int[word.length()-2];
int i=0;
for (char letter: word.toCharArray()) {
entry.letters[i] = (byte) letter - 65; // Convert ASCII to 0..25
if (i>=2)
entry.triplets[i-2] = (((entry.letters[i-2] << ALPHABET_SIZE) +
entry.letters[i-1]) << ALPHABET_SIZE) +
entry.letters[i];
i++;
}
result.add(entry);
}
word = fileReader.readLine();
}
return result.toArray(new DictionaryEntry[result.size()]);
}
boolean isWrap(int a, int b) { // Checks if move a->b wraps board edge (like 3->4)
return Math.abs(a%BOARD_SIZE-b%BOARD_SIZE)>1;
}
int[] buildTripletIndices() {
ArrayList<Integer> result = new ArrayList<Integer>();
for (int a=0; a<BOARD_SIZE*BOARD_SIZE; a++)
for (int bm: moves) {
int b=a+bm;
if ((b>=0) && (b<board.length) && !isWrap(a, b))
for (int cm: moves) {
int c=b+cm;
if ((c>=0) && (c<board.length) && (c!=a) && !isWrap(b, c)) {
result.add(a);
result.add(b);
result.add(c);
}
}
}
int[] result2 = new int[result.size()];
int i=0;
for (Integer r: result) result2[i++] = r;
return result2;
}
// Variables that depend on the actual game layout
int[] board = new int[BOARD_SIZE*BOARD_SIZE]; // Letters in board
boolean[] possibleTriplets = new boolean[1 << (ALPHABET_SIZE*3)];
DictionaryEntry[] candidateWords;
int candidateCount;
int[] usedBoardPositions;
DictionaryEntry[] foundWords;
int foundCount;
void initializeBoard(String[] letters) {
for (int row=0; row<BOARD_SIZE; row++)
for (int col=0; col<BOARD_SIZE; col++)
board[row*BOARD_SIZE + col] = (byte) letters[row].charAt(col) - 65;
}
void setPossibleTriplets() {
Arrays.fill(possibleTriplets, false); // Reset list
int i=0;
while (i<boardTripletIndices.length) {
int triplet = (((board[boardTripletIndices[i++]] << ALPHABET_SIZE) +
board[boardTripletIndices[i++]]) << ALPHABET_SIZE) +
board[boardTripletIndices[i++]];
possibleTriplets[triplet] = true;
}
}
void checkWordTriplets() {
candidateCount = 0;
for (DictionaryEntry entry: dictionary) {
boolean ok = true;
int len = entry.triplets.length;
for (int t=0; (t<len) && ok; t++)
ok = possibleTriplets[entry.triplets[t]];
if (ok) candidateWords[candidateCount++] = entry;
}
}
void checkWords() { // Can probably be optimized a lot
foundCount = 0;
for (int i=0; i<candidateCount; i++) {
DictionaryEntry candidate = candidateWords[i];
for (int j=0; j<board.length; j++)
if (board[j]==candidate.letters[0]) {
usedBoardPositions[0] = j;
if (checkNextLetters(candidate, 1, j)) {
foundWords[foundCount++] = candidate;
break;
}
}
}
}
boolean checkNextLetters(DictionaryEntry candidate, int letter, int pos) {
if (letter==candidate.letters.length) return true;
int match = candidate.letters[letter];
for (int move: moves) {
int next=pos+move;
if ((next>=0) && (next<board.length) && (board[next]==match) && !isWrap(pos, next)) {
boolean ok = true;
for (int i=0; (i<letter) && ok; i++)
ok = usedBoardPositions[i]!=next;
if (ok) {
usedBoardPositions[letter] = next;
if (checkNextLetters(candidate, letter+1, next)) return true;
}
}
}
return false;
}
// Just some helper functions
String formatTime(long start, long end, long repetitions) {
long time = (end-start)/repetitions;
return time/1000000 + "." + (time/100000) % 10 + "" + (time/10000) % 10 + "ms";
}
String getWord(DictionaryEntry entry) {
char[] result = new char[entry.letters.length];
int i=0;
for (int letter: entry.letters)
result[i++] = (char) (letter+97);
return new String(result);
}
void run() throws IOException {
long start = System.nanoTime();
// The following can be pre-computed and should be replaced by constants
dictionary = buildDictionary("C:/TWL06.txt");
boardTripletIndices = buildTripletIndices();
long precomputed = System.nanoTime();
// The following only needs to run once at the beginning of the program
candidateWords = new DictionaryEntry[dictionary.length]; // WAAAY too generous
foundWords = new DictionaryEntry[dictionary.length]; // WAAAY too generous
usedBoardPositions = new int[maxWordLength];
long initialized = System.nanoTime();
for (int n=1; n<=100; n++) {
// The following needs to run again for every new board
initializeBoard(new String[] {"DGHI",
"KLPS",
"YEUT",
"EORN"});
setPossibleTriplets();
checkWordTriplets();
checkWords();
}
long solved = System.nanoTime();
// Print out result and statistics
System.out.println("Precomputation finished in " + formatTime(start, precomputed, 1)+":");
System.out.println(" Words in the dictionary: "+dictionary.length);
System.out.println(" Longest word: "+maxWordLength+" letters");
System.out.println(" Number of triplet-moves: "+boardTripletIndices.length/3);
System.out.println();
System.out.println("Initialization finished in " + formatTime(precomputed, initialized, 1));
System.out.println();
System.out.println("Board solved in "+formatTime(initialized, solved, 100)+":");
System.out.println(" Number of candidates: "+candidateCount);
System.out.println(" Number of actual words: "+foundCount);
System.out.println();
System.out.println("Words found:");
int w=0;
System.out.print(" ");
for (int i=0; i<foundCount; i++) {
System.out.print(getWord(foundWords[i]));
w++;
if (w==10) {
w=0;
System.out.println(); System.out.print(" ");
} else
if (i<foundCount-1) System.out.print(", ");
}
System.out.println();
}
public static void main(String[] args) throws IOException {
new BoggleSolver().run();
}
}
Here are some results:
For the grid from the picture posted in the original question (DGHI...):
Precomputation finished in 239.59ms:
Words in the dictionary: 178590
Longest word: 15 letters
Number of triplet-moves: 408
Initialization finished in 0.22ms
Board solved in 3.70ms:
Number of candidates: 230
Number of actual words: 163
Words found:
eek, eel, eely, eld, elhi, elk, ern, erupt, erupts, euro
eye, eyer, ghi, ghis, glee, gley, glue, gluer, gluey, glut
gluts, hip, hiply, hips, his, hist, kelp, kelps, kep, kepi
kepis, keps, kept, kern, key, kye, lee, lek, lept, leu
ley, lunt, lunts, lure, lush, lust, lustre, lye, nus, nut
nuts, ore, ort, orts, ouph, ouphs, our, oust, out, outre
outs, oyer, pee, per, pert, phi, phis, pis, pish, plus
plush, ply, plyer, psi, pst, pul, pule, puler, pun, punt
punts, pur, pure, puree, purely, pus, push, put, puts, ree
rely, rep, reply, reps, roe, roue, roup, roups, roust, rout
routs, rue, rule, ruly, run, runt, runts, rupee, rush, rust
rut, ruts, ship, shlep, sip, sipe, spue, spun, spur, spurn
spurt, strep, stroy, stun, stupe, sue, suer, sulk, sulker, sulky
sun, sup, supe, super, sure, surely, tree, trek, trey, troupe
troy, true, truly, tule, tun, tup, tups, turn, tush, ups
urn, uts, yeld, yelk, yelp, yelps, yep, yeps, yore, you
your, yourn, yous
For the letters posted as the example in the original question (FXIE...)
Precomputation finished in 239.68ms:
Words in the dictionary: 178590
Longest word: 15 letters
Number of triplet-moves: 408
Initialization finished in 0.21ms
Board solved in 3.69ms:
Number of candidates: 87
Number of actual words: 76
Words found:
amble, ambo, ami, amie, asea, awa, awe, awes, awl, axil
axile, axle, boil, bole, box, but, buts, east, elm, emboli
fame, fames, fax, lei, lie, lima, limb, limbo, limbs, lime
limes, lob, lobs, lox, mae, maes, maw, maws, max, maxi
mesa, mew, mewl, mews, mil, mile, milo, mix, oil, ole
sae, saw, sea, seam, semi, sew, stub, swam, swami, tub
tubs, tux, twa, twae, twaes, twas, uts, wae, waes, wamble
wame, wames, was, wast, wax, west
For the following 5x5-grid:
R P R I T
A H H L N
I E T E P
Z R Y S G
O G W E Y
it gives this:
Precomputation finished in 240.39ms:
Words in the dictionary: 178590
Longest word: 15 letters
Number of triplet-moves: 768
Initialization finished in 0.23ms
Board solved in 3.85ms:
Number of candidates: 331
Number of actual words: 240
Words found:
aero, aery, ahi, air, airt, airth, airts, airy, ear, egest
elhi, elint, erg, ergo, ester, eth, ether, eye, eyen, eyer
eyes, eyre, eyrie, gel, gelt, gelts, gen, gent, gentil, gest
geste, get, gets, gey, gor, gore, gory, grey, greyest, greys
gyre, gyri, gyro, hae, haet, haets, hair, hairy, hap, harp
heap, hear, heh, heir, help, helps, hen, hent, hep, her
hero, hes, hest, het, hetero, heth, hets, hey, hie, hilt
hilts, hin, hint, hire, hit, inlet, inlets, ire, leg, leges
legs, lehr, lent, les, lest, let, lethe, lets, ley, leys
lin, line, lines, liney, lint, lit, neg, negs, nest, nester
net, nether, nets, nil, nit, ogre, ore, orgy, ort, orts
pah, pair, par, peg, pegs, peh, pelt, pelter, peltry, pelts
pen, pent, pes, pest, pester, pesty, pet, peter, pets, phi
philter, philtre, phiz, pht, print, pst, rah, rai, rap, raphe
raphes, reap, rear, rei, ret, rete, rets, rhaphe, rhaphes, rhea
ria, rile, riles, riley, rin, rye, ryes, seg, sel, sen
sent, senti, set, sew, spelt, spelter, spent, splent, spline, splint
split, stent, step, stey, stria, striae, sty, stye, tea, tear
teg, tegs, tel, ten, tent, thae, the, their, then, these
thesp, they, thin, thine, thir, thirl, til, tile, tiles, tilt
tilter, tilth, tilts, tin, tine, tines, tirl, trey, treys, trog
try, tye, tyer, tyes, tyre, tyro, west, wester, wry, wryest
wye, wyes, wyte, wytes, yea, yeah, year, yeh, yelp, yelps
yen, yep, yeps, yes, yester, yet, yew, yews, zero, zori
For this I used the TWL06 Tournament Scrabble Word List, since the link in the original question no longer works. This file is 1.85MB, so it's a little bit shorter. And the buildDictionary
function throws out all words with less than 3 letters.
Here are a couple of observations about the performance of this:
It's about 10 times slower than the reported performance of Victor Nicollet's OCaml implementation. Whether this is caused by the different algorithm, the shorter dictionary he used, the fact that his code is compiled and mine runs in a Java virtual machine, or the performance of our computers (mine is an Intel Q6600 @ 2.4MHz running WinXP), I don't know. But it's much faster than the results for the other implementations quoted at the end of the original question. So, whether this algorithm is superior to the trie dictionary or not, I don't know at this point.
The table method used in checkWordTriplets()
yields a very good approximation to the actual answers. Only 1 in 3-5 words passed by it will fail the checkWords()
test (See number of candidates vs. number of actual words above).
Something you can't see above: The checkWordTriplets()
function takes about 3.65ms and is therefore fully dominant in the search process. The checkWords()
function takes up pretty much the remaining 0.05-0.20 ms.
The execution time of the checkWordTriplets()
function depends linearly on the dictionary size and is virtually independent of board size!
The execution time of checkWords()
depends on the board size and the number of words not ruled out by checkWordTriplets()
.
The checkWords()
implementation above is the dumbest first version I came up with. It is basically not optimized at all. But compared to checkWordTriplets()
it is irrelevant for the total performance of the application, so I didn't worry about it. But, if the board size gets bigger, this function will get slower and slower and will eventually start to matter. Then, it would need to be optimized as well.
One nice thing about this code is its flexibility:
initializeBoard()
.Ok, but I think by now this post is waaaay long enough. I can definitely answer any questions you might have, but let's move that to the comments.
Functionally, they are equivalent.
Performance-wise map[key] = value
would be quicker, as you are only making single lookup instead of two.
Style-wise, the shorter the better :)
The code will in most cases seem to work fine in multi-threaded context. It however is not thread-safe without extra synchronization.
Others have answered your question perfectly, but I just thought I would throw out another way. It's always a good idea to separate HTML markup, CSS styling, and javascript code when possible. The cleanest way to hide something, with that in mind, is using a class. It allows the definition of "hide" to be defined in the CSS where it belongs. Using this method, you could later decide you want the ul
to hide by scrolling up or fading away using CSS transition
, all without changing your HTML or code. This is longer, but I feel it's a better overall solution.
Demo: http://jsfiddle.net/ThinkingStiff/RkQCF/
HTML:
<a id="showTags" href="#" title="Show Tags">Show All Tags</a>
<ul id="subforms" class="subforums hide"><li>one</li><li>two</li><li>three</li></ul>
CSS:
#subforms {
overflow-x: visible;
overflow-y: visible;
}
.hide {
display: none;
}
Script:
document.getElementById( 'showTags' ).addEventListener( 'click', function () {
document.getElementById( 'subforms' ).toggleClass( 'hide' );
}, false );
Element.prototype.toggleClass = function ( className ) {
if( this.className.split( ' ' ).indexOf( className ) == -1 ) {
this.className = ( this.className + ' ' + className ).trim();
} else {
this.className = this.className.replace( new RegExp( '(\\s|^)' + className + '(\\s|$)' ), ' ' ).trim();
};
};
hash.keys.sort.each do |key|
puts "#{key}-----"
hash[key].each { |val| puts val }
end
Another way to do simultaneous animations if you want to call them separately (eg. from different code) is to use queue
. Again, as with Tinister's answer you would have to use animate for this and not fadeIn:
$('.tooltip').css('opacity', 0);
$('.tooltip').show();
...
$('.tooltip').animate({opacity: 1}, {queue: false, duration: 'slow'});
$('.tooltip').animate({ top: "-10px" }, 'slow');
I did a quick solution because I was short of time and it worked ok. Although I think the better option is use an Exception Filter, maybe my solution can help in the case that a simple solution is needed.
I did the following. In the controller method I returned a JsonResult with a property "Success" inside the Data:
[HttpPut]
public JsonResult UpdateEmployeeConfig(EmployeConfig employeToSave)
{
if (!ModelState.IsValid)
{
return new JsonResult
{
Data = new { ErrorMessage = "Model is not valid", Success = false },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.DenyGet
};
}
try
{
MyDbContext db = new MyDbContext();
db.Entry(employeToSave).State = EntityState.Modified;
db.SaveChanges();
DTO.EmployeConfig user = (DTO.EmployeConfig)Session["EmployeLoggin"];
if (employeToSave.Id == user.Id)
{
user.Company = employeToSave.Company;
user.Language = employeToSave.Language;
user.Money = employeToSave.Money;
user.CostCenter = employeToSave.CostCenter;
Session["EmployeLoggin"] = user;
}
}
catch (Exception ex)
{
return new JsonResult
{
Data = new { ErrorMessage = ex.Message, Success = false },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.DenyGet
};
}
return new JsonResult() { Data = new { Success = true }, };
}
Later in the ajax call I just asked for this property to know if I had an exception:
$.ajax({
url: 'UpdateEmployeeConfig',
type: 'PUT',
data: JSON.stringify(EmployeConfig),
contentType: "application/json;charset=utf-8",
success: function (data) {
if (data.Success) {
//This is for the example. Please do something prettier for the user, :)
alert('All was really ok');
}
else {
alert('Oups.. we had errors: ' + data.ErrorMessage);
}
},
error: function (request, status, error) {
alert('oh, errors here. The call to the server is not working.')
}
});
Hope this helps. Happy code! :P
I've changed my code like this and it works:
CREATE or REPLACE TRIGGER test001
AFTER INSERT OR UPDATE OR DELETE ON tabletest001
REFERENCING OLD AS old_buffer NEW AS new_buffer
FOR EACH ROW WHEN (new_buffer.field1 = 'HBP00' OR old_buffer.field1 = 'HBP00')
DECLARE
Operation NUMBER;
CustomerCode CHAR(10 BYTE);
BEGIN
IF DELETING THEN
Operation := 3;
CustomerCode := :old_buffer.field1;
END IF;
IF INSERTING THEN
Operation := 1;
CustomerCode := :new_buffer.field1;
END IF;
IF UPDATING THEN
Operation := 2;
CustomerCode := :new_buffer.field1;
END IF;
// DO SOMETHING ...
EXCEPTION
WHEN OTHERS THEN ErrorCode := SQLCODE;
END;
>>> sys.stdout.write(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: expected a string or other character buffer object
>>> sys.stdout.write("a")
a>>> sys.stdout.write("a") ; print(1)
a1
Observing the example above:
sys.stdout.write
won't write non-string object, but print
will
sys.stdout.write
won't add a new line symbol in the end, but print
will
If we dive deeply,
sys.stdout
is a file object which can be used for the output of print()
if file argument of print()
is not specified, sys.stdout
will be used
Below code 100% working.
Step 1: Paste below code in index.html file
<!DOCTYPE html>
<html ng-app="ang">
<head>
<title>Angular Test</title>
<meta charset="utf-8" />
</head>
<body>
<div ng-controller="myController">
<button ng-click="files()">Download All</button>
</div>
<script src="angular.min.js"></script>
<script src="index.js"></script>
</body>
</html>
Step 2: Paste below code in index.js file
"use strict";
var x = angular.module('ang', []);
x.controller('myController', function ($scope, $http) {
var arr = [
{file:"http://localhost/angularProject/w3logo.jpg", fileName: "imageone"},
{file:"http://localhost/angularProject/cv.doc", fileName: "imagetwo"},
{file:"http://localhost/angularProject/91.png", fileName: "imagethree"}
];
$scope.files = function() {
angular.forEach(arr, function(val, key) {
$http.get(val.file)
.then(function onSuccess(response) {
console.log('res', response);
var link = document.createElement('a');
link.setAttribute('download', val.fileName);
link.setAttribute('href', val.file);
link.style.display = 'none';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
})
.catch(function onError(error) {
console.log('error', error);
})
})
};
});
NOTE : Make sure that all three files which are going to download will be placed in same folder along with angularProject/index.html or angularProject/index.js files.
Without using CDATA, try
<xsl:value-of select="'
'" />
Note the double and single quotes.
That is particularly useful if you are not creating xml
aka text. <xsl:output method="text" />
Anyway, we have a "goes to" operator now. "-->"
is easy to be remembered as a direction, and "while x goes to zero" is meaning-straight.
Furthermore, it is a little more efficient than "for (x = 10; x > 0; x --)"
on some platforms.
Also, pay attention to ORDER BY in PARTITION (Standard AdventureWorks db is used for example) when using RANK.
SELECT as1.SalesOrderID, as1.SalesOrderDetailID, RANK() OVER (PARTITION BY as1.SalesOrderID ORDER BY as1.SalesOrderID ) ranknoequal , RANK() OVER (PARTITION BY as1.SalesOrderID ORDER BY as1.SalesOrderDetailId ) ranknodiff FROM Sales.SalesOrderDetail as1 WHERE SalesOrderId = 43659 ORDER BY SalesOrderDetailId;
Gives result:
SalesOrderID SalesOrderDetailID rank_same_as_partition rank_salesorderdetailidBut if change order by to (use OrderQty :
SELECT as1.SalesOrderID, as1.OrderQty, RANK() OVER (PARTITION BY as1.SalesOrderID ORDER BY as1.SalesOrderID ) ranknoequal , RANK() OVER (PARTITION BY as1.SalesOrderID ORDER BY as1.OrderQty ) rank_orderqty FROM Sales.SalesOrderDetail as1 WHERE SalesOrderId = 43659 ORDER BY OrderQty;
Gives:
SalesOrderID OrderQty rank_salesorderid rank_orderqtyNotice how the Rank changes when we use OrderQty (rightmost column second table) in ORDER BY and how it changes when we use SalesOrderDetailID (rightmost column first table) in ORDER BY.
delete from emp where rowid in
(
select rid from
(
select rowid rid,
dense_rank() over(partition by empno order by rowid
) rn
from emp
)
where rn > 1
);
If you mean you want to delete a drop from a table if it exists, you can use the DELETE
command, for example:
DELETE FROM users WHERE user_login = 'foobar'
If no rows match, it's not an error.
This will show only Cart Items Count.
global $woocommerce;
echo $woocommerce->cart->cart_contents_count;
import requests
response = requests.post('http://httpbin.org/post', data={'key1':'value1'})
print(response.request.url)
print(response.request.body)
print(response.request.headers)
Response
objects have a .request
property which is the original PreparedRequest
object that was sent.
You're right that it involves a loop, but this is, at least, made simple by use of the each()
method:
$('.target').each(
function(){
// iterate through each of the `.target` elements, and do stuff in here
// `this` and `$(this)` refer to the current `.target` element
var images = $(this).find('img'),
imageWidth = images.width(); // returns the width of the _first_ image
numImages = images.length;
$(this).css('width', (imageWidth*numImages));
});
References:
Just simply add or die(mysqli_error($db));
at the end of your query, this will print the mysqli error.
mysqli_query($db,"INSERT INTO stockdetails (`itemdescription`,`itemnumber`,`sellerid`,`purchasedate`,`otherinfo`,`numberofitems`,`isitdelivered`,`price`) VALUES ('$itemdescription','$itemnumber','$sellerid','$purchasedate','$otherinfo','$numberofitems','$numberofitemsused','$isitdelivered','$price')") or die(mysqli_error($db));
As a side note I'd say you are at risk of mysql injection
, check here How can I prevent SQL injection in PHP?. You should really use prepared statements to avoid any risk.
sys.maxint is not the largest integer supported by python. It's the largest integer supported by python's regular integer type.
You have two options:
Extend your .paging
class definition:
.paging:hover {
border:1px solid #999;
color:#000;
}
Use the DOM hierarchy to apply the CSS style:
div.paginate input:hover {
border:1px solid #999;
color:#000;
}
You need to set basicHttpBinding -> MaxReceivedMessageSize in the client configuration.
The accepted answer works only if you want exactly 31 days later. That means if you are using the date "2013-05-31" that you expect to not be in June which is not what I wanted.
If you want to have the next month, I suggest you to use the current year and month but keep using the 1st.
$date = date("Y-m-01");
$newdate = strtotime ( '+1 month' , strtotime ( $date ) ) ;
This way, you will be able to get the month and year of the next month without having a month skipped.
private T GetHeaderControl<T>(Repeater rp, string id) where T : Control
{
T returnValue = null;
if (rp != null && !String.IsNullOrWhiteSpace(id))
{
returnValue = rp.Controls.Cast<RepeaterItem>().Where(i => i.ItemType == ListItemType.Header).Select(h => h.FindControl(id) as T).Where(c => c != null).FirstOrDefault();
}
return returnValue;
}
Finds and casts the control. (Based on Piyey's VB answer)
The nested class doesn't know about the outer class, and protected
doesn't help. You'll have to pass some actual reference to objects of the nested class type. You could store a foo*
, but perhaps a reference to the integer is enough:
class Outer
{
int n;
public:
class Inner
{
int & a;
public:
Inner(int & b) : a(b) { }
int & get() { return a; }
};
// ... for example:
Inner inn;
Outer() : inn(n) { }
};
Now you can instantiate inner classes like Inner i(n);
and call i.get()
.
Your style should look like this:
<style parent="@android:style/Widget.ProgressBar" name="customProgressBar">
<item name="android:indeterminateDrawable">@anim/mp3</item>
</style>
By default hibernate lazily loads the collections (relationships) which means whenver you use the collection
in your code(here comments
field
in Topic
class)
the hibernate gets that from database, now the problem is that you are getting the collection in your controller (where the
JPA session is closed).This is the line of code that causes the exception
(where you are loading the comments
collection):
Collection<Comment> commentList = topicById.getComments();
You are getting "comments" collection (topic.getComments()) in your controller(where JPA session
has ended) and that causes the exception. Also if you had got
the comments
collection in your jsp file like this(instead of getting it in your controller):
<c:forEach items="topic.comments" var="item">
//some code
</c:forEach>
You would still have the same exception for the same reason.
Because you just can have only two collections with the FetchType.Eager
(eagerly fetched collection) in an Entity class and because lazy loading is more
efficient than eagerly loading, I think this way of solving your problem is better than just changing the FetchType
to eager:
If you want to have collection lazy initialized, and also make this work,
it is better to add this snippet of code to your web.xml
:
<filter>
<filter-name>SpringOpenEntityManagerInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SpringOpenEntityManagerInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
What this code does is that it will increase the length of your JPA session
or as the documentation says, it is used "to allow for lazy loading in web views despite the original transactions already being completed."
so
this way the JPA session will be open a bit longer and because of that
you can lazily load collections in your jsp files and controller classes.
Wanted to add numexpr into the mix:
import numpy as np
import numexpr as ne
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
np.where(ne.evaluate("(6 <= a) & (a <= 10)"))[0]
# array([3, 4, 5], dtype=int64)
Would only make sense for larger arrays with millions... or if you hitting a memory limits.
Based on the answer by Adam Boduch, I wrote this function which compares two objects in the deepest possible sense, returning paths that have different values as well as paths missing from one or the other object.
The code was not written with efficiency in mind, and improvements in that regard are most welcome, but here is the basic form:
var compare = function (a, b) {
var result = {
different: [],
missing_from_first: [],
missing_from_second: []
};
_.reduce(a, function (result, value, key) {
if (b.hasOwnProperty(key)) {
if (_.isEqual(value, b[key])) {
return result;
} else {
if (typeof (a[key]) != typeof ({}) || typeof (b[key]) != typeof ({})) {
//dead end.
result.different.push(key);
return result;
} else {
var deeper = compare(a[key], b[key]);
result.different = result.different.concat(_.map(deeper.different, (sub_path) => {
return key + "." + sub_path;
}));
result.missing_from_second = result.missing_from_second.concat(_.map(deeper.missing_from_second, (sub_path) => {
return key + "." + sub_path;
}));
result.missing_from_first = result.missing_from_first.concat(_.map(deeper.missing_from_first, (sub_path) => {
return key + "." + sub_path;
}));
return result;
}
}
} else {
result.missing_from_second.push(key);
return result;
}
}, result);
_.reduce(b, function (result, value, key) {
if (a.hasOwnProperty(key)) {
return result;
} else {
result.missing_from_first.push(key);
return result;
}
}, result);
return result;
}
You can try the code using this snippet (running in full page mode is recommended):
var compare = function (a, b) {_x000D_
_x000D_
var result = {_x000D_
different: [],_x000D_
missing_from_first: [],_x000D_
missing_from_second: []_x000D_
};_x000D_
_x000D_
_.reduce(a, function (result, value, key) {_x000D_
if (b.hasOwnProperty(key)) {_x000D_
if (_.isEqual(value, b[key])) {_x000D_
return result;_x000D_
} else {_x000D_
if (typeof (a[key]) != typeof ({}) || typeof (b[key]) != typeof ({})) {_x000D_
//dead end._x000D_
result.different.push(key);_x000D_
return result;_x000D_
} else {_x000D_
var deeper = compare(a[key], b[key]);_x000D_
result.different = result.different.concat(_.map(deeper.different, (sub_path) => {_x000D_
return key + "." + sub_path;_x000D_
}));_x000D_
_x000D_
result.missing_from_second = result.missing_from_second.concat(_.map(deeper.missing_from_second, (sub_path) => {_x000D_
return key + "." + sub_path;_x000D_
}));_x000D_
_x000D_
result.missing_from_first = result.missing_from_first.concat(_.map(deeper.missing_from_first, (sub_path) => {_x000D_
return key + "." + sub_path;_x000D_
}));_x000D_
return result;_x000D_
}_x000D_
}_x000D_
} else {_x000D_
result.missing_from_second.push(key);_x000D_
return result;_x000D_
}_x000D_
}, result);_x000D_
_x000D_
_.reduce(b, function (result, value, key) {_x000D_
if (a.hasOwnProperty(key)) {_x000D_
return result;_x000D_
} else {_x000D_
result.missing_from_first.push(key);_x000D_
return result;_x000D_
}_x000D_
}, result);_x000D_
_x000D_
return result;_x000D_
}_x000D_
_x000D_
var a_editor = new JSONEditor($('#a')[0], {_x000D_
name: 'a',_x000D_
mode: 'code'_x000D_
});_x000D_
var b_editor = new JSONEditor($('#b')[0], {_x000D_
name: 'b',_x000D_
mode: 'code'_x000D_
});_x000D_
_x000D_
var a = {_x000D_
same: 1,_x000D_
different: 2,_x000D_
missing_from_b: 3,_x000D_
missing_nested_from_b: {_x000D_
x: 1,_x000D_
y: 2_x000D_
},_x000D_
nested: {_x000D_
same: 1,_x000D_
different: 2,_x000D_
missing_from_b: 3_x000D_
}_x000D_
}_x000D_
_x000D_
var b = {_x000D_
same: 1,_x000D_
different: 99,_x000D_
missing_from_a: 3,_x000D_
missing_nested_from_a: {_x000D_
x: 1,_x000D_
y: 2_x000D_
},_x000D_
nested: {_x000D_
same: 1,_x000D_
different: 99,_x000D_
missing_from_a: 3_x000D_
}_x000D_
}_x000D_
_x000D_
a_editor.set(a);_x000D_
b_editor.set(b);_x000D_
_x000D_
var result_editor = new JSONEditor($('#result')[0], {_x000D_
name: 'result',_x000D_
mode: 'view'_x000D_
});_x000D_
_x000D_
var do_compare = function() {_x000D_
var a = a_editor.get();_x000D_
var b = b_editor.get();_x000D_
result_editor.set(compare(a, b));_x000D_
}
_x000D_
#objects {} #objects section {_x000D_
margin-bottom: 10px;_x000D_
}_x000D_
#objects section h1 {_x000D_
background: #444;_x000D_
color: white;_x000D_
font-family: monospace;_x000D_
display: inline-block;_x000D_
margin: 0;_x000D_
padding: 5px;_x000D_
}_x000D_
.jsoneditor-outer, .ace_editor {_x000D_
min-height: 230px !important;_x000D_
}_x000D_
button:hover {_x000D_
background: orangered;_x000D_
}_x000D_
button {_x000D_
cursor: pointer;_x000D_
background: red;_x000D_
color: white;_x000D_
text-align: left;_x000D_
font-weight: bold;_x000D_
border: 5px solid crimson;_x000D_
outline: 0;_x000D_
padding: 10px;_x000D_
margin: 10px 0px;_x000D_
}
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/jsoneditor/5.5.10/jsoneditor.min.css" rel="stylesheet" />_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jsoneditor/5.5.10/jsoneditor.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="objects">_x000D_
<section>_x000D_
<h1>a (first object)</h1>_x000D_
<div id="a"></div>_x000D_
</section>_x000D_
<section>_x000D_
<h1>b (second object)</h1>_x000D_
<div id="b"></div>_x000D_
</section>_x000D_
<button onClick="do_compare()">compare</button>_x000D_
<section>_x000D_
<h1>result</h1>_x000D_
<div id="result"></div>_x000D_
</section>_x000D_
</div>
_x000D_
You can save to a figure that is 1920x1080 (or 1080p) using:
fig = plt.figure(figsize=(19.20,10.80))
You can also go much higher or lower. The above solutions work well for printing, but these days you want the created image to go into a PNG/JPG or appear in a wide screen format.
Calling scp
command via subprocess doesn't allow to receive the progress report inside the script. pexpect
could be used to extract that info:
import pipes
import re
import pexpect # $ pip install pexpect
def progress(locals):
# extract percents
print(int(re.search(br'(\d+)%$', locals['child'].after).group(1)))
command = "scp %s %s" % tuple(map(pipes.quote, [srcfile, destination]))
pexpect.run(command, events={r'\d+%': progress})
If you need a directive more advanced, I recomend the solution that I implemnted, correctly tested on Internet Explorer 11, Chrome and FireFox.
I hope it, will be helpfull.
HTML :
<a href="#" class="btn btn-default" file-name="'fileName.extension'" ng-click="getFile()" file-download="myBlobObject"><i class="fa fa-file-excel-o"></i></a>
DIRECTIVE :
directive('fileDownload',function(){
return{
restrict:'A',
scope:{
fileDownload:'=',
fileName:'=',
},
link:function(scope,elem,atrs){
scope.$watch('fileDownload',function(newValue, oldValue){
if(newValue!=undefined && newValue!=null){
console.debug('Downloading a new file');
var isFirefox = typeof InstallTrigger !== 'undefined';
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
var isIE = /*@cc_on!@*/false || !!document.documentMode;
var isEdge = !isIE && !!window.StyleMedia;
var isChrome = !!window.chrome && !!window.chrome.webstore;
var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
var isBlink = (isChrome || isOpera) && !!window.CSS;
if(isFirefox || isIE || isChrome){
if(isChrome){
console.log('Manage Google Chrome download');
var url = window.URL || window.webkitURL;
var fileURL = url.createObjectURL(scope.fileDownload);
var downloadLink = angular.element('<a></a>');//create a new <a> tag element
downloadLink.attr('href',fileURL);
downloadLink.attr('download',scope.fileName);
downloadLink.attr('target','_self');
downloadLink[0].click();//call click function
url.revokeObjectURL(fileURL);//revoke the object from URL
}
if(isIE){
console.log('Manage IE download>10');
window.navigator.msSaveOrOpenBlob(scope.fileDownload,scope.fileName);
}
if(isFirefox){
console.log('Manage Mozilla Firefox download');
var url = window.URL || window.webkitURL;
var fileURL = url.createObjectURL(scope.fileDownload);
var a=elem[0];//recover the <a> tag from directive
a.href=fileURL;
a.download=scope.fileName;
a.target='_self';
a.click();//we call click function
}
}else{
alert('SORRY YOUR BROWSER IS NOT COMPATIBLE');
}
}
});
}
}
})
IN CONTROLLER:
$scope.myBlobObject=undefined;
$scope.getFile=function(){
console.log('download started, you can show a wating animation');
serviceAsPromise.getStream({param1:'data1',param1:'data2', ...})
.then(function(data){//is important that the data was returned as Aray Buffer
console.log('Stream download complete, stop animation!');
$scope.myBlobObject=new Blob([data],{ type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
},function(fail){
console.log('Download Error, stop animation and show error message');
$scope.myBlobObject=[];
});
};
IN SERVICE:
function getStream(params){
console.log("RUNNING");
var deferred = $q.defer();
$http({
url:'../downloadURL/',
method:"PUT",//you can use also GET or POST
data:params,
headers:{'Content-type': 'application/json'},
responseType : 'arraybuffer',//THIS IS IMPORTANT
})
.success(function (data) {
console.debug("SUCCESS");
deferred.resolve(data);
}).error(function (data) {
console.error("ERROR");
deferred.reject(data);
});
return deferred.promise;
};
BACKEND(on SPRING):
@RequestMapping(value = "/downloadURL/", method = RequestMethod.PUT)
public void downloadExcel(HttpServletResponse response,
@RequestBody Map<String,String> spParams
) throws IOException {
OutputStream outStream=null;
outStream = response.getOutputStream();//is important manage the exceptions here
ObjectThatWritesOnOutputStream myWriter= new ObjectThatWritesOnOutputStream();// note that this object doesn exist on JAVA,
ObjectThatWritesOnOutputStream.write(outStream);//you can configure more things here
outStream.flush();
return;
}
See also boost::format:
#include <boost/format.hpp>
std::string var = (boost::format("somtext %s sometext %s") % somevar % somevar).str();
First of all this code snippet
char *addr=NULL;
strcpy(addr,retstring().c_str());
is invalid because you did not allocate memory where you are going to copy retstring().c_str().
As for the error message then it is clear enough. The type of expression data.str().c_str() is const char * but the third parameter of the function is declared as char *. You may not assign an object of type const char * to an object of type char *. Either the function should define the third parameter as const char * if it does not change the object pointed by the third parameter or you may not pass argument of type const char *.
I would seriously consider making a CLR UDF instead and using regular expressions (both the string and the pattern can be passed in as parameters) to do a complete search and replace for a range of characters. It should easily outperform this SQL UDF.
Or simply
add to your element
[ngStyle]="{'color': myVariableColor}"
eg
<mat-icon [ngStyle]="{'color': myVariableColor}">{{ getActivityIcon() }}</mat-icon>
Where color
can be defined at another component etc
Make sure the folder with the standard header files is in the projects path.
I don't know where this is in Turbo C, but I would think there's a way of doing this.
You can declare the macro NULL. Add that after your #includes:
#define NULL 0
or
#ifndef NULL
#define NULL 0
#endif
No ";" at the end of the instructions...
This contribution does not really answer the initial question, but taking into account the hit-rate of this thread I assume that there are quite a few people dealing with the problem that API-MS-WIN-CORE- libraries cannot be found.
I was able to solve a problem where my application refused to start with the error message that API-MS-WIN-CORE-WINRT-STRING-L1-1-0.DLL is not found by simply updating Visual Studio.
I don't think that my build environment (Windows 7 Pro SP1, Visual Studio Ultimate 2012) was messed up completely, it worked fine for most of my projects. But under some very specific circumstances I got the error message (see below).
After updating Visual Studio 11 from the initial CD-Version (I forgot to look up the version number) to version 11.0.61030.00 Update 4 also the broken project was running again.
All Posted files will be come in $_FILES variable, for use codeigniter upload library we need to give field_name that we are using in for upload (by default it will be 'userfile'), so we get all posted file and create another files array that create our own name for each files, and give this name to codeigniter library do_upload function.
if(!empty($_FILES)){
$j = 1;
foreach($_FILES as $filekey=>$fileattachments){
foreach($fileattachments as $key=>$val){
if(is_array($val)){
$i = 1;
foreach($val as $v){
$field_name = "multiple_".$filekey."_".$i;
$_FILES[$field_name][$key] = $v;
$i++;
}
}else{
$field_name = "single_".$filekey."_".$j;
$_FILES[$field_name] = $fileattachments;
$j++;
break;
}
}
// Unset the useless one
unset($_FILES[$filekey]);
}
foreach($_FILES as $field_name => $file){
if(isset($file['error']) && $file['error']==0){
$config['upload_path'] = [upload_path];
$config['allowed_types'] = [allowed_types];
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload($field_name)){
$error = array('error' => $this->upload->display_errors());
echo "Error Message : ". $error['error'];
}else{
$data = $this->upload->data();
echo "Uploaded FileName : ".$data['file_name'];
// Code for insert into database
}
}
}
}
stdbool.h
defines macros true
and false
, but remember they are defined to be 1 and 0.
That is why sizeof(true)
is 4.
In my case it doesn't work, even with __DIR__
or getcwd()
it keeps picking the wrong path, I solved by defining a costant in every file I need with the absolute base path of the project:
if(!defined('THISBASEPATH')){ define('THISBASEPATH', '/mypath/'); }
require_once THISBASEPATH.'cache/crud.php';
/*every other require_once you need*/
I have MAMP with php 5.4.10 and my folder hierarchy is basilar:
q.php
w.php
e.php
r.php
cache/a.php
cache/b.php
setting/a.php
setting/b.php
....
Function isset()
is faster, check http://www.php.net/manual/en/function.array-key-exists.php#82867
I think this will work.
<gridview>
<Columns>
<asp:ButtonField ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" CommandArgument="<%# Container.DataItemIndex %>" />
</Columns>
</gridview>
Please run the below comments to update to Angular 6 from Angular 5
I have spent many hours trying to build a fat static library that will work on armv7, armv7s, and the simulator. Finally found a solution.
The gist is to build the two libraries (one for the device and then one for the simulator) separately, rename them to distinguish from each other, and then lipo -create them into one library.
lipo -create libPhone.a libSimulator.a -output libUniversal.a
I tried it and it works!
In the old days, when we could assume that most computers used ASCII, we would just do
int i = c[0] - '0';
But in these days of Unicode, it's not a good idea. It was never a good idea if your code had to run on a non-ASCII computer.
Edit: Although it looks hackish, evidently it is guaranteed by the standard to work. Thanks @Earwicker.
It's actually very straight forward with jQuery's $.map
var arr = $.map(obj, function(el) { return el });
and almost as easy without jQuery as well, converting the keys to an array and then mapping back the values with Array.map
var arr = Object.keys(obj).map(function(k) { return obj[k] });
That's assuming it's already parsed as a javascript object, and isn't actually JSON, which is a string format, in that case a run through JSON.parse
would be necessary as well.
In ES2015 there's Object.values
to the rescue, which makes this a breeze
var arr = Object.values(obj);
There is a static method on the Thread
Class that will return the number of active threads controlled by the JVM:
Thread.activeCount()
Returns the number of active threads in the current thread's thread group.
Additionally, external debuggers should list all active threads (and allow you to suspend any number of them) if you wish to monitor them in real-time.
If you have an embedded navigation controller created via Interface Builder, be sure to set the following in a class that manages your navigation controller:
-(UIStatusBarStyle)preferredStatusBarStyle{
return UIStatusBarStyleLightContent;
}
That should be all you need.
use this below code :
int index,top;
@Override
protected void onPause() {
super.onPause();
index = mList.getFirstVisiblePosition();
View v = challengeList.getChildAt(0);
top = (v == null) ? 0 : (v.getTop() - mList.getPaddingTop());
}
and whenever your refresh your data use this below code :
adapter.notifyDataSetChanged();
mList.setSelectionFromTop(index, top);
If you use bash and have the extglob
shell option set (which is usually the case):
mv ~/Linux/Old/!(Tux.png) ~/Linux/New/
Just use 0 or 1 directly in the code.
For C programmers, this is as intuitive as true or false.
Nullable types did not come in until 2.0.
If nullable types had been made in the beginning of the language then string would have been non-nullable and string? would have been nullable. But they could not do this du to backward compatibility.
A lot of people talk about ref-type or not ref type, but string is an out of the ordinary class and solutions would have been found to make it possible.
configure SSL in xampp/apache/conf/extra/httpd-vhost.conf
<VirtualHost *:80>
DocumentRoot "C:/xampp/htdocs/myproject/web"
ServerName www.myurl.com
<Directory "C:/xampp/htdocs/myproject/web">
Options All
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
<VirtualHost *:443>
DocumentRoot "C:/xampp/htdocs/myproject/web"
ServerName www.myurl.com
SSLEngine on
SSLCertificateFile "conf/ssl.crt/server.crt"
SSLCertificateKeyFile "conf/ssl.key/server.key"
<Directory "C:/xampp/htdocs/myproject/web">
Options All
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
make sure server.crt & server.key path given properly otherwise this will not work.
don't forget to enable vhost in httpd.conf
# Virtual hosts
Include etc/extra/httpd-vhosts.conf
Got similar issue. Did following steps, issue resolved:
<context:annotation-config>
activates many different annotations in beans, whether they are defined in XML or through component scanning.
<context:component-scan>
is for defining beans without using XML
For further information, read:
I may have not got your answer correct, but you can try this:
public void MusicController(View view) throws IOException{
switch (view.getId()){
case R.id.play: mplayer.start();break;
case R.id.pause: mplayer.pause(); break;
case R.id.stop:
if(mplayer.isPlaying()) {
mplayer.stop();
mplayer.prepare();
}
break;
}// where mplayer is defined in onCreate method}
as there is just one thread handling all, so stop() makes it die so we have to again prepare it If your intent is to start it again when your press start button(it throws IO Exception) Or for better understanding of MediaPlayer you can refer to Android Media Player
One correct way to get selected value would be
var selected_value = $('#fruit_name').val()
And then you should do
if(selected_value) { ... }
If you're using http/https
and you're looking to FULLY AUTOMATE the process without requiring any user input or any user prompt at all (for example: inside a CI/CD pipeline), you may use the following approach leveraging git credential.helper
GIT_CREDS_PATH="/my/random/path/to/a/git/creds/file"
# Or you may choose to not specify GIT_CREDS_PATH at all.
# See https://git-scm.com/docs/git-credential-store#FILES for the defaults used
git config --global credential.helper "store --file ${GIT_CREDS_PATH}"
echo "https://alice:${ALICE_GITHUB_PASSWORD}@github.com" > ${GIT_CREDS_PATH}
where you may choose to set the ALICE_GITHUB_PASSWORD
environment variable from a previous shell command or from your pipeline config etc.
Remember that "store" based git-credential-helper stores passwords & values in plain-text. So make sure your token/password has very limited permissions.
Now simply use https://[email protected]/my_repo.git wherever your automated system needs to fetch the repo - it will use the credentials for alice
in github.com
as store by git-credential-helper.
I am happy with the listings
package:
Here is how I configure it:
\lstset{
language=C,
basicstyle=\small\sffamily,
numbers=left,
numberstyle=\tiny,
frame=tb,
columns=fullflexible,
showstringspaces=false
}
I use it like this:
\begin{lstlisting}[caption=Caption example.,
label=a_label,
float=t]
// Insert the code here
\end{lstlisting}
I know this is and old thread, but I was fighting with this and I would like to share my solution.
This solution works with HttpClient
and MultipartFormDataContent
, from System.Net.Http
. You can release it with .NET Core 1.0
or higher, or .NET Framework 4.5
or higher.
As a quick summary, it's an asynchronous method that receives as parameters the URL in which you want to perform the POST, a key/value collection for sending strings, and a key/value collection for sending files.
private static async Task<HttpResponseMessage> Post(string url, NameValueCollection strings, NameValueCollection files)
{
var formContent = new MultipartFormDataContent(/* If you need a boundary, you can define it here */);
// Strings
foreach (string key in strings.Keys)
{
string inputName = key;
string content = strings[key];
formContent.Add(new StringContent(content), inputName);
}
// Files
foreach (string key in files.Keys)
{
string inputName = key;
string fullPathToFile = files[key];
FileStream fileStream = File.OpenRead(fullPathToFile);
var streamContent = new StreamContent(fileStream);
var fileContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
formContent.Add(fileContent, inputName, Path.GetFileName(fullPathToFile));
}
var myHttpClient = new HttpClient();
var response = await myHttpClient.PostAsync(url, formContent);
//string stringContent = await response.Content.ReadAsStringAsync(); // If you need to read the content
return response;
}
You can prepare your POST like this (you can add so many strings and files as you need):
string url = @"http://yoursite.com/upload.php"
NameValueCollection strings = new NameValueCollection();
strings.Add("stringInputName1", "The content for input 1");
strings.Add("stringInputNameN", "The content for input N");
NameValueCollection files = new NameValueCollection();
files.Add("fileInputName1", @"FullPathToFile1"); // Path + filename
files.Add("fileInputNameN", @"FullPathToFileN");
And finally, call the method like this:
var result = Post(url, strings, files).GetAwaiter().GetResult();
If you want, you can check your status code, and show the reason as below:
if (result.StatusCode == HttpStatusCode.OK)
{
// Logic if all was OK
}
else
{
// You can show a message like this:
Console.WriteLine(string.Format("Error. StatusCode: {0} | ReasonPhrase: {1}", result.StatusCode, result.ReasonPhrase));
}
And if someone need it, here I let a small example of how to receive store a file with PHP (at the other side of our .Net app):
<?php
if (isset($_FILES['fileInputName1']) && $_FILES['fileInputName1']['error'] === UPLOAD_ERR_OK)
{
$fileTmpPath = $_FILES['fileInputName1']['tmp_name'];
$fileName = $_FILES['fileInputName1']['name'];
move_uploaded_file($fileTmpPath, '/the/final/path/you/want/' . $fileName);
}
I hope you find it useful, I am attentive to your questions.
The optimal block size depends on various factors, including the operating system (and its version), and the various hardware buses and disks involved. Several Unix-like systems (including Linux and at least some flavors of BSD) define the st_blksize
member in the struct stat
that gives what the kernel thinks is the optimal block size:
#include <sys/stat.h>
#include <stdio.h>
int main(void)
{
struct stat stats;
if (!stat("/", &stats))
{
printf("%u\n", stats.st_blksize);
}
}
The best way may be to experiment: copy a gigabyte with various block sizes and time that. (Remember to clear kernel buffer caches before each run: echo 3 > /proc/sys/vm/drop_caches
).
However, as a rule of thumb, I've found that a large enough block size lets dd
do a good job, and the differences between, say, 64 KiB and 1 MiB are minor, compared to 4 KiB versus 64 KiB. (Though, admittedly, it's been a while since I did that. I use a mebibyte by default now, or just let dd
pick the size.)
This property will register an OpenEntityManagerInViewInterceptor
, which registers an EntityManager
to the current thread, so you will have the same EntityManager
until the web request is finished. It has nothing to do with a Hibernate SessionFactory
etc.
Lots of hard ways to do an easy thing:
<form name="foo" onsubmit="return false">
Try like this
Pass Camera Intent like below
Intent intent = new Intent(this);
startActivityForResult(intent, REQ_CAMERA_IMAGE);
And after capturing image Write an OnActivityResult
as below
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
knop.setVisibility(Button.VISIBLE);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), photo);
// CALL THIS METHOD TO GET THE ACTUAL PATH
File finalFile = new File(getRealPathFromURI(tempUri));
System.out.println(mImageCaptureUri);
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
String path = "";
if (getContentResolver() != null) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
path = cursor.getString(idx);
cursor.close();
}
}
return path;
}
And check log
Edit:
Lots of people are asking how to not get a thumbnail. You need to add this code instead for the getImageUri
method:
public Uri getImageUri(Context inContext, Bitmap inImage) {
Bitmap OutImage = Bitmap.createScaledBitmap(inImage, 1000, 1000,true);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), OutImage, "Title", null);
return Uri.parse(path);
}
The other method Compresses the file. You can adjust the size by changing the number 1000,1000
Number Zero parity | zero http://tinyurl.com/oexhr3k
Python code sequence.
# defining function for number parity check
def parity(number):
"""Parity check function"""
# if number is 0 (zero) return 'Zero neither ODD nor EVEN',
# otherwise number&1, checking last bit, if 0, then EVEN,
# if 1, then ODD.
return (number == 0 and 'Zero neither ODD nor EVEN') \
or (number&1 and 'ODD' or 'EVEN')
# cycle trough numbers from 0 to 13
for number in range(0, 14):
print "{0:>4} : {0:08b} : {1:}".format(number, parity(number))
Output:
0 : 00000000 : Zero neither ODD nor EVEN
1 : 00000001 : ODD
2 : 00000010 : EVEN
3 : 00000011 : ODD
4 : 00000100 : EVEN
5 : 00000101 : ODD
6 : 00000110 : EVEN
7 : 00000111 : ODD
8 : 00001000 : EVEN
9 : 00001001 : ODD
10 : 00001010 : EVEN
11 : 00001011 : ODD
12 : 00001100 : EVEN
13 : 00001101 : ODD
Use !=
.
if [[ ${testmystring} != *"c0"* ]];then
# testmystring does not contain c0
fi
See help [[
for more information.
If you are setting the contents of IFrame using javascript document.write()
then you must close the document by newWin.document.close();
otherwise the following code will not work and print will print the contents of whole page instead of only the IFrame contents.
var frm = document.getElementById(id).contentWindow;
frm.focus();// focus on contentWindow is needed on some ie versions
frm.print();
I made a PHP script to make it easier. Create an app. In the Graph API Explorer select your App and get a user token with manage_pages and publish_pages permission. Find your page's ID at the bottom of its About page. Fill in the config vars and run the script.
<?php
$args=[
'usertoken'=>'',
'appid'=>'',
'appsecret'=>'',
'pageid'=>''
];
echo generate_token($args);
function generate_token($args){
$r=json_decode(file_get_contents("https://graph.facebook.com/v2.8/oauth/access_token?grant_type=fb_exchange_token&client_id={$args['appid']}&client_secret={$args['appsecret']}&fb_exchange_token={$args['usertoken']}")); // get long-lived token
$longtoken=$r->access_token;
$r=json_decode(file_get_contents("https://graph.facebook.com/v2.8/me?access_token={$longtoken}")); // get user id
$userid=$r->id;
$r=json_decode(file_get_contents("https://graph.facebook.com/v2.8/{$userid}/accounts?access_token={$longtoken}")); // get permanent token
foreach($r->data as $d) if($d->id==$args['pageid']) return $d->access_token;
}
In order to do this in SQL Server, you must order the query by a column, so you can specify the rows you want.
Example:
select * from table order by [some_column]
offset 10 rows
FETCH NEXT 10 rows only
And you can't use the "TOP" keyword when doing this.
You can learn more here: https://technet.microsoft.com/pt-br/library/gg699618%28v=sql.110%29.aspx
You can think of a mysql database
as a schema/user in Oracle
. If you have the privileges, you can query the DBA_USERS
view to see the list of schema.
I know this is an old question but I find that the answers are not sufficent enough
The cleanest way to do this is to use this code
$(".myRadio").click(function() {
alert($(this).val());
});
:-)
Your form input data should look like this
<input type="radio" value="40000" name="pay" class="myRadio" />
<label for="40000">40000</label>
C does not have its own String data type like Java.
Only we can declare String datatype in C using character array or character pointer For example :
char message[10];
or
char *message;
But you need to declare at least:
char message[14];
to copy "Hello, world!" into message variable.
Swift 4.2
let closure = { [weak self] (_ parameter:Int) in
guard let self = self else { return }
self.method(parameter)
}
Unless I misunderstand your question, you can just open a file read only. Here is a simply example, without any checks.
To get the file path from the user use this function:
Private Function get_user_specified_filepath() As String
'or use the other code example here.
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = False
fd.Title = "Please select the file."
get_user_specified_filepath = fd.SelectedItems(1)
End Function
Then just open the file read only and assign it to a variable:
dim wb as workbook
set wb = Workbooks.Open(get_user_specified_filepath(), ReadOnly:=True)
This code should work for you, assuming that your JSON data is in a file called data.json
.
import json
import csv
with open("data.json") as file:
data = json.load(file)
with open("data.csv", "w") as file:
csv_file = csv.writer(file)
for item in data:
fields = list(item['fields'].values())
csv_file.writerow([item['pk'], item['model']] + fields)
Simply add this event to your text field. It will prevent a submission on pressing Enter, and you're free to add a submit button or call form.submit() as required:
onKeyPress="if (event.which == 13) return false;"
For example:
<input id="txt" type="text" onKeyPress="if (event.which == 13) return false;"></input>
This is called Responsive Web Development(RWD). To make page responsive to all device we need to use some basic fundamental such as:-
1. Set the viewport meta tag in head:
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0"/>
2.Use media queries.
Example:-
/* Smartphones (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px) {
/* Styles */
}
/* Smartphones (landscape) ----------- */
@media only screen
and (min-width : 321px) {
/* Styles */
}
/* Smartphones (portrait) ----------- */
@media only screen
and (max-width : 320px) {
/* Styles */
}
/* iPads (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px) {
/* Styles */
}
/* iPads (landscape) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape) {
/* Styles */
}
/* iPads (portrait) ----------- */
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait) {
/* Styles */
}
/* Desktops and laptops ----------- */
@media only screen
and (min-width : 1224px) {
/* Styles */
}
/* Large screens ----------- */
@media only screen
and (min-width : 1824px) {
/* Styles */
}
/* iPhone 4 ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */
}
3. Or we can directly use RWD framework:-
Some of good Article
Media Queries for Standard Devices - BY CHRIS COYIER
4. Larger Device, Medium Devices & Small Devices media queries. (Work in my Scenarios.)
Below media queries for generic Device type: - Larger Device, Medium Devices & Small Devices. This is just basic media types which work for all of scenario & easy to handle code instead of using various media queries just need to care of three media type.
/*###Desktops, big landscape tablets and laptops(Large, Extra large)####*/
@media screen and (min-width: 1024px){
/*Style*/
}
/*###Tablet(medium)###*/
@media screen and (min-width : 768px) and (max-width : 1023px){
/*Style*/
}
/*### Smartphones (portrait and landscape)(small)### */
@media screen and (min-width : 0px) and (max-width : 767px){
/*Style*/
}
Adding the missing important parts to make this question a complete resource, as this comes up in search results.
Object Destructuring
In object destructuring, you don't necessarily need to use the same key value as your variable name, you can assign a different variable name by defining it as below:
const newCodes = () => {
let dCodes = fg.codecsCodes.rs;
let dCodes2 = fg.codecsCodes2.rs;
return { dCodes, dCodes2 };
};
//destructuring
let { dCodes: code1, dCodes2: code2 } = newCodes();
//now it can be accessed by code1 & code2
console.log(code1, code2);
Array Destructuring
In array destructuring, you can skip the values you don't need.
const newCodes = () => {
//...
return [ dCodes, dCodes2, dCodes3 ];
};
let [ code1, code2 ] = newCodes(); //first two items
let [ code1, ,code3 ] = newCodes(); //skip middle item, get first & last
let [ ,, code3 ] = newCodes(); //skip first two items, get last
let [ code1, ...rest ] = newCodes(); //first item, and others as an array
It's worth noticing that ...rest
should always be at the end as it doesn't make any sense to destruct anything after everything else is aggregated to rest
.
I hope this will add some value to this question :)
In your particular case the fastest sort is probably the one described in this answer. It is exactly optimized for an array of 6 ints and uses sorting networks. It is 20 times (measured on x86) faster than library qsort. Sorting networks are optimal for sort of fixed length arrays. As they are a fixed sequence of instructions they can even be implemented easily by hardware.
Generally speaking there is many sorting algorithms optimized for some specialized case. The general purpose algorithms like heap sort or quick sort are optimized for in place sorting of an array of items. They yield a complexity of O(n.log(n)), n being the number of items to sort.
The library function qsort() is very well coded and efficient in terms of complexity, but uses a call to some comparizon function provided by user, and this call has a quite high cost.
For sorting very large amount of datas algorithms have also to take care of swapping of data to and from disk, this is the kind of sorts implemented in databases and your best bet if you have such needs is to put datas in some database and use the built in sort.
Laravel 5.2 You can use
$request->route()->getName()
It will give you current route name.
There is no need to have two functions within one element, you need just one that calls the other two!
<a href="#" onclick="my_func()" >click</a>
function my_func() {
my_func_1();
my_func_2();
}
It's actually not that easy, you have to interact with the C API. There is no alternative to scanf
. I've build a little example:
main.swift
import Foundation
var output: CInt = 0
getInput(&output)
println(output)
UserInput.c
#include <stdio.h>
void getInput(int *output) {
scanf("%i", output);
}
cliinput-Bridging-Header.h
void getInput(int *output);
You need to have some logs draining implemented and should be draining your logs there, to see all of the logs (manage historical logs as well):
heroku drains:add syslog+tls://splunk-server.com:514 -a app_name
And then login into your splunk server and search for any number of logs. I am using Splunk and this is working perfectly fine for me.
Second option - You can purchase add on to your App, like given below: (I haven't used these options, however these are the available ones).
You can also have a look at below options: If you want to have your logs in JSON format, as it will help if your are pushing your logs to external system like Splunk/ELK, it would become easy (performance wise also) to search in JSON.
https://github.com/goodeggs/heroku-log-normalizer
It is not having Readme.md, but some explanation is given at https://github.com/goodeggs/bites/issues/20
Lastly
And you can always use below command as mentioned by other users already:
The following command will tail the generating logs on heroku
heroku logs -t -a <app_name>
The following comand will show the 1000 number of lines of logs from heroku
heroku logs -n 1000 -a <app_name>
Note only 1500 latest lines of logs are available and rest of them gets deleted from heroku dyno.
Yes it is possible in Sony ericssion xylophone w20 .I have got this phone in 2010.but yet this type of phone I have not seen.
as pointed out by @JCastell, the online tester does a good job of testing individual redirects against an .htaccess file. However, more interesting is the api exposed which can be used to batch test a list of urls using a json object. However, to make it more useful, I have written a small bash script file which makes use of curl and jq to submit a list of urls and parse the json response into a CSV formated output with the line number and rule matched in the htaccess file along with the redirected url, making it quite handy to compare a list of urls in a spreadsheet and quickly determine which rules are not working.
In my case I had to set two categories for the <intent-filter>
and then it worked:
<intent-filter>
<data android:scheme="my.special.scheme" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
</intent-filter>
I'm a computational biologist, and when I had to compute the auto/cross-correlations between couples of time series of stochastic processes I realized that np.correlate
was not doing the job I needed.
Indeed, what seems to be missing from np.correlate
is the averaging over all the possible couples of time points at distance .
Here is how I defined a function doing what I needed:
def autocross(x, y):
c = np.correlate(x, y, "same")
v = [c[i]/( len(x)-abs( i - (len(x)/2) ) ) for i in range(len(c))]
return v
It seems to me none of the previous answers cover this instance of auto/cross-correlation: hope this answer may be useful to somebody working on stochastic processes like me.
You need to put the text-align:center
on the containing div, not on the input itself.
Using NUnitTestAdapter.WithFramework makes sure there are little/no inconsistencies across versions of NUnit and NUnit Adapter (i.e. "it just works")
Running rails g migration AddUserRefToSponsors user:references
will generate the following migration:
def change
add_reference :sponsors, :user, index: true
end
Deployment descriptor file "web.xml" : Through the proper use of the deployment descriptor file, web.xml, you can control many aspects of the Web application behavior, from preloading servlets, to restricting resource access, to controlling session time-outs.
web.xml : is used to control many facets of a Web application. Using web.xml, you can assign custom URLs for invoking servlets, specify initialization parameters for the entire application as well as for specific servlets, control session timeouts, declare filters, declare security roles, restrict access to Web resources based on declared security roles, and so on.