This usually happens when the version of one of the DLLs of the testing environment does not match the development environment.
Clean and Build your solution and take all your DLLs to the environment where the error is happening that should fix it
The limit for the length of a command line is not imposed by the shell, but by the operating system. This limit is usually in the range of hundred kilobytes. POSIX denotes this limit ARG_MAX
and on POSIX conformant systems you can query it with
$ getconf ARG_MAX # Get argument limit in bytes
E.g. on Cygwin this is 32000, and on the different BSDs and Linux systems I use it is anywhere from 131072 to 2621440.
If you need to process a list of files exceeding this limit, you might want to look at the xargs
utility, which calls a program repeatedly with a subset of arguments not exceeding ARG_MAX
.
To answer your specific question, yes, it is possible to attempt to run a command with too long an argument list. The shell will error with a message along "argument list too long".
Note that the input to a program (as read on stdin or any other file descriptor) is not limited (only by available program resources). So if your shell script reads a string into a variable, you are not restricted by ARG_MAX
. The restriction also does not apply to shell-builtins.
You can use strptime(3)
to parse the time, and then mktime(3)
to convert it to a time_t
:
const char *time_details = "16:35:12";
struct tm tm;
strptime(time_details, "%H:%M:%S", &tm);
time_t t = mktime(&tm); // t is now your desired time_t
You can use Instance.ToShortDateString() for the date,
and Instance.ToShortTimeString() for the time to get date and time from the same instance.
^\w+$
will allow a-zA-Z0-9_
Use ^[a-zA-Z0-9]+$
to disallow underscore.
Note that both of these require the string not to be empty. Using *
instead of +
allows empty strings.
do you called the ViewTreeObserver and not remove it.
mEtEnterlive.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
// do nothing here can cause such problem
});
Step 1 (same is in accepted answer written by KavinduWije):
netstat -ano | findstr :yourPortNumber
Change in Step 2 to:
tskill typeyourPIDhere
Note: taskkill
is not working in some git bash terminal
@RequestMapping(value = "/books", method = { RequestMethod.GET,
RequestMethod.POST })
public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter,
HttpServletRequest request)
throws ParseException {
//your code
}
This will works for both GET and POST.
For GET if your pojo(BooksFilter) have to contain the attribute which you're using in request parameter
like below
public class BooksFilter{
private String parameter1;
private String parameter2;
//getters and setters
URl should be like below
/books?parameter1=blah
Like this way u can use it for both GET and POST
If you're open to a PHP solution:
<td><img src='<?PHP
$path1 = "path/to/your/image.jpg";
$path2 = "alternate/path/to/another/image.jpg";
echo file_exists($path1) ? $path1 : $path2;
?>' alt='' />
</td>
////EDIT OK, here's a JS version:
<table><tr>
<td><img src='' id='myImage' /></td>
</tr></table>
<script type='text/javascript'>
document.getElementById('myImage').src = "newImage.png";
document.getElementById('myImage').onload = function() {
alert("done");
}
document.getElementById('myImage').onerror = function() {
alert("Inserting alternate");
document.getElementById('myImage').src = "alternate.png";
}
</script>
In my case, none of the above approaches worked for me till I had to enable an Android DEBUG Bridge Option under the BlueStack emulator. Check the picture below.
An approach inspired from : Vlad Voytenko
I Hope It's Helps Someone!
Here is a simple Typescript with Lodash deep difference checker which will produce a new object with just the differences between an old object and a new object.
For example, if we had:
const oldData = {a: 1, b: 2};
const newData = {a: 1, b: 3};
the resulting object would be:
const result: {b: 3};
It is also compatible with multi-level deep objects, for arrays it may need some tweaking.
import * as _ from "lodash";
export const objectDeepDiff = (data: object | any, oldData: object | any) => {
const record: any = {};
Object.keys(data).forEach((key: string) => {
// Checks that isn't an object and isn't equal
if (!(typeof data[key] === "object" && _.isEqual(data[key], oldData[key]))) {
record[key] = data[key];
}
// If is an object, and the object isn't equal
if ((typeof data[key] === "object" && !_.isEqual(data[key], oldData[key]))) {
record[key] = objectDeepDiff(data[key], oldData[key]);
}
});
return record;
};
Here is the latest sample of Google's geocode Web Service
https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_API_KEY
Simply change the YOUR_API_KEY
to the API key you get from Google Geocoding API
P/S: Geocoding API is under Places NOT Maps ;)
Another one is to use the -F option but pass it regex to print the text between left and or right parenthesis ()
.
The file content:
528(smbw)
529(smbt)
530(smbn)
10115(smbs)
The command:
awk -F"[()]" '{print $2}' filename
result:
smbw
smbt
smbn
smbs
Using awk to just print the text between []
:
Use awk -F'[][]'
but awk -F'[[]]'
will not work.
http://stanlo45.blogspot.com/2020/06/awk-multiple-field-separators.html
I have found the perfect answer to this, all thanks to a guy called Allan that deserves all of the credit here. (http://www.allannienhuis.com/archives/2013/11/03/blocked-3rd-party-session-cookies-in-iframes/)
His solution is simple and easy to understand.
On iframe content server (domain 2), add a file called startsession.php at the root domain level that contains:
<?php
// startsession.php
session_start();
$_SESSION['ensure_session'] = true;
die(header('location: '.$_GET['return']));
Now on the top level website containing the iframe (domain1), the call to the page containing the iframe should look like:
<a href="https://domain2/startsession.php?return=http://domain1/pageWithiFrame.html">page with iFrame</a>
And that's it! Simples :)
The reason this works is because you are directing the browser to a third party URL and thus telling it to trust it before showing content from it within the iframe.
According to official documentation, you can set or remove the "executable" flag on any tracked file using update-index
sub-command.
To set the flag, use following command:
git update-index --chmod=+x path/to/file
To remove it, use:
git update-index --chmod=-x path/to/file
Under the hood
While this looks like the regular unix files permission system, actually it is not. Git maintains a special "mode" for each file in its internal storage:
100644
for regular files100755
for executable onesYou can visualize it using ls-file
subcommand, with --stage
option:
$ git ls-files --stage
100644 aee89ef43dc3b0ec6a7c6228f742377692b50484 0 .gitignore
100755 0ac339497485f7cc80d988561807906b2fd56172 0 my_executable_script.sh
By default, when you add a file to a repository, Git will try to honor its filesystem attributes and set the correct filemode accordingly. You can disable this by setting core.fileMode
option to false:
git config core.fileMode false
Troubleshooting
If at some point the Git filemode is not set but the file has correct filesystem flag, try to remove mode and set it again:
git update-index --chmod=-x path/to/file
git update-index --chmod=+x path/to/file
Bonus
Starting with Git 2.9, you can stage a file AND set the flag in one command:
git add --chmod=+x path/to/file
Remove Postmaster file in "C:\Program Files\PostgreSQL\9.6\data"
and restart the PostgreSQL services
Let's say you have an array of IDs and equivalent array of statuses - here is an example how to do this with a static SQL (a sql query that doesn't change due to different values) of the arrays :
drop table if exists results_dummy;
create table results_dummy (id int, status text, created_at timestamp default now(), updated_at timestamp default now());
-- populate table with dummy rows
insert into results_dummy
(id, status)
select unnest(array[1,2,3,4,5]::int[]) as id, unnest(array['a','b','c','d','e']::text[]) as status;
select * from results_dummy;
-- THE update of multiple rows with/by different values
update results_dummy as rd
set status=new.status, updated_at=now()
from (select unnest(array[1,2,5]::int[]) as id,unnest(array['a`','b`','e`']::text[]) as status) as new
where rd.id=new.id;
select * from results_dummy;
-- in code using **IDs** as first bind variable and **statuses** as the second bind variable:
update results_dummy as rd
set status=new.status, updated_at=now()
from (select unnest(:1::int[]) as id,unnest(:2::text[]) as status) as new
where rd.id=new.id;
@OMG Ponies - One of my reasons of not using the following code
SELECT t.col1 as a,
CASE WHEN t.col1 = 'test' THEN 'yes' END as value
FROM TABLE t;
can be that the t.col1 is not an actual column in the table. For example, it can be a value from a XML column like
Select XMLColumnName.value('(XMLPathOfTag)[1]', 'varchar(max)')
as XMLTagAlias from Table
Use this :
<div style="width:700px; background:#F2F2F2">
<table style="width:100%;padding: 25px; margin: 0 auto; font-family:'Open Sans', 'Helvetica', 'Arial';">
<tr align="center" style="margin: 0; padding: 0;">
<td>
<table style="width:100%;border-style:solid; border-width:2px; border-color: #c3d2d9;" cellspacing="0">
<tr style="background-color: white;">
<td style=" padding: 10px 15px 10px 15px; color: #000000;">
<p>Some content here</p>
<span style="font-weight: bold;">My Signature</span><br/>
My Title<br/>
My Company<br/>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
For Windows, first install the git base from here: https://git-scm.com/downloads
Next, set the environment variable:
C:\Program Files\Git\git-bash.exe
To test it, open the command window: press Windows+R, type cmd and then type ssh.
Yes, it is possible:
git clone https://github.com/pitosalas/st3_packages Packages
You can specify the local root directory when using git clone.
<directory>
The name of a new directory to clone into.
The "humanish" part of the source repository is used if no directory is explicitly given (repo
for/path/to/repo.git
andfoo
forhost.xz:foo/.git
).
Cloning into an existing directory is only allowed if the directory is empty.
As Chris comments, you can then rename that top directory.
Git only cares about the .git
within said top folder, which you can get with various commands:
git rev-parse --show-toplevel git rev-parse --git-dir
Try this -->
new DzieckoAndOpiekun(
p.Imie,
p.Nazwisko,
p.Opiekun.Imie,
p.Opiekun.Nazwisko).ToList()
The answers on here are specific to using the custom UI Editor. I spent some time creating the interface without that wonderful program, so I am documenting the solution here to help anyone else decide if they need that custom UI editor or not.
I came across the following microsoft help webpage - https://msdn.microsoft.com/en-us/library/office/ff861787.aspx. This shows how to set up the interface manually, but I had some trouble when pointing to my custom add-in code.
To get the buttons to work with your custom macros, setup the macro in your .xlam subs to be called as described in this SO answer - Calling an excel macro from the ribbon. Basically, you'll need to add that "control As IRibbonControl" paramter to any module pointed from your ribbon xml. Also, your ribbon xml should have the onAction="myaddin!mymodule.mysub" syntax to properly call any modules loaded by the add in.
Using those instructions I was able to create an excel add in (.xlam file) that has a custom tab loaded when my VBA gets loaded into Excel along with the add in. The buttons execute code from the add in and the custom tab uninstalls when I remove the add in.
Another solution:
<input type="button" value="Print" onclick="document.getElementById('PDFtoPrint').focus(); document.getElementById('PDFtoPrint').contentWindow.print();">
It is possible to send Emails without using any heavy libraries I have included my example here.
lightweight SMTP Email sender for PHP
https://github.com/jerryurenaa/EZMAIL
Tested in both environments production and development.
and most importantly emails will not go to spam unless your IP is blacklisted by the server.
cheers.
I would just allow everything (except an empty string) and assume the user knows what his name is.
There are 2 common cases:
In case (1), you can allow all characters because you're checking against a paper document.
In case (2), you may as well allow all characters because "123 456" is really no worse a pseudonym than "Abc Def".
In C# it also works with a null as the 4th parameter.
@Html.ActionLink( "Front Page", "Index", "Home", null, new { @class = "MenuButtons" })
The ObservableCollection
and its derivatives raises its property changes internally. The code in your setter should only be triggered if you assign a new TrulyObservableCollection<MyType>
to the MyItemsSource
property. That is, it should only happen once, from the constructor.
From that point forward, you'll get property change notifications from the collection, not from the setter in your viewmodel.
width, height = map(int, input().split())
def rectanglePerimeter(width, height):
return ((width + height)*2)
print(rectanglePerimeter(width, height))
Running it like this produces:
% echo "1 2" | test.py
6
I suspect IDLE is simply passing a single string to your script. The first input()
is slurping the entire string. Notice what happens if you put some print statements in after the calls to input()
:
width = input()
print(width)
height = input()
print(height)
Running echo "1 2" | test.py
produces
1 2
Traceback (most recent call last):
File "/home/unutbu/pybin/test.py", line 5, in <module>
height = input()
EOFError: EOF when reading a line
Notice the first print statement prints the entire string '1 2'
. The second call to input()
raises the EOFError
(end-of-file error).
So a simple pipe such as the one I used only allows you to pass one string. Thus you can only call input()
once. You must then process this string, split it on whitespace, and convert the string fragments to ints yourself. That is what
width, height = map(int, input().split())
does.
Note, there are other ways to pass input to your program. If you had run test.py
in a terminal, then you could have typed 1
and 2
separately with no problem. Or, you could have written a program with pexpect to simulate a terminal, passing 1
and 2
programmatically. Or, you could use argparse to pass arguments on the command line, allowing you to call your program with
test.py 1 2
If you are using Eclipse,
They should all be in there. Right click and "checkout."
It is much more accurate to use IndexOf:
If dt.Columns.IndexOf("ColumnName") = -1 Then
'Column not exist
End If
If the Contains is used it would not differentiate between ColumName and ColumnName2.
It is possible to avoid constructor annotations with jdk8 where optionally the compiler will introduce metadata with the names of the constructor parameters. Then with jackson-module-parameter-names module Jackson can use this constructor. You can see an example at post Jackson without annotations
Try declaring the unit of width:
e1.style.width = "400px"; // width in PIXELS
The JavaScript Date
object can help here.
The first step is to convert those strings to Date
instances. That's easily done:
var str = "06/07/2012"; // E.g., "mm/dd/yyyy";
var dt = new Date(parseInt(str.substring(6), 10), // Year
parseInt(str.substring(0, 2), 10) - 1, // Month (0-11)
parseInt(str.substring(3, 5), 10)); // Day
Then you can do all sorts of useful calculations. JavaScript dates understand leap years and such. They use an idealized concept of "day" which is exactly 86,400 seconds long. Their underlying value is the number of milliseconds since The Epoch (midnight, Jan 1st, 1970); it can be a negative number for dates prior to The Epoch.
More on the MDN page on Date
.
You might also consider using a library like MomentJS, which will help with parsing, doing date math, formatting...
try this for hide
$('#table_id').DataTable({
"info": false
});
and try this for change label
$('#table_id').DataTable({
"oLanguage": {
"sInfo" : "Showing _START_ to _END_ of _TOTAL_ entries",// text you want show for info section
},
});
@papigee should work on Windows 10 just fine. I'm using the integrated VSCode terminal with git bash and this always works for me.
winpty docker exec -it <container-id> //bin//sh
With Sharepoint Designer you can edit the CAML of your XSLT List View.
If you set the Scope attribute of the View element to Recursive or RecursiveAll, which returns all Files and Folders, you can filter the documents by FileDirRef:
<Where>
<Contains>
<FieldRef Name='FileDirRef' />
<Value Type='Lookup'>MyFolder</Value>
</Contains>
</Where>
This returns all documents which contain the string 'MyFolder' in their path.
I found infos about this on http://platinumdogs.wordpress.com/2009/07/21/querying-document-libraries-or-pulling-teeth-with-caml/ and useful information abouts fields at http://blog.thekid.me.uk/archive/2007/03/21/wss-field-display-amp-internal-names-for-lists-amp-document-libraries.aspx
This is what I used when I had similar requirement. This determines the PID of the Java process correctly. Let your java code spawn a server on a pre-defined port number and then execute OS commands to find out the PID listening on the port. For Linux
netstat -tupln | grep portNumber
You can use a combination of the AWS metadata tool (to retrieve your instance ID) and the new Tag API to retrieve the tags for the current instance.
Use:
#include <iostream>
...
std::cout << std::hex << a;
There are many other options to control the exact formatting of the output number, such as leading zeros and upper/lower case.
This is how I usually generate random numbers. Then I use "NUM_1" as the variable for the port number I use. Here is a short example script.
#!/bin/bash
clear
echo 'Choose how many digits you want for port# (1-5)'
read PORT
NUM_1="$(tr -dc '0-9' </dev/urandom | head -c $PORT)"
echo "$NUM_1"
if [ "$PORT" -gt "5" ]
then
clear
echo -e "\x1b[31m Choose a number between 1 and 5! \x1b[0m"
sleep 3
clear
exit 0
fi
You can use:
File.WriteAllBytes("Foo.txt", arrBytes); // Requires System.IO
If you have an enumerable and not an array, you can use:
File.WriteAllBytes("Foo.txt", arrBytes.ToArray()); // Requires System.Linq
It's not a query waiting for connection; it's a connection pointer waiting for the timeout to terminate.
It doesn't have an impact on performance. The only thing it's using is a few bytes as every connection does.
The really worst case: It's using one connection of your pool; If you would connect multiple times via console client and just close the client without closing the connection, you could use up all your connections and have to wait for the timeout to be able to connect again... but this is highly unlikely :-)
See MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"? and https://dba.stackexchange.com/questions/1558/how-long-is-too-long-for-mysql-connections-to-sleep for more information.
Standing on the shoulders of @ChrisJohnson, I extended the answer from Feb 2016 with a custom dialect for reading. This shell pipeline tool does not need to connect to your database, handles random commas and quotes in the input, and works nicely in Python2 and Python3!
#!/usr/bin/env python
import csv
import sys
# fields are separated by tabs; double-quotes may occur anywhere
csv.register_dialect("mysql", delimiter="\t", quoting=csv.QUOTE_NONE)
tab_in = csv.reader(sys.stdin, dialect="mysql")
comma_out = csv.writer(sys.stdout, dialect=csv.excel)
for row in tab_in:
# print("row: {}".format(row))
comma_out.writerow(row)
Use that print statement to convince yourself it's parsing your input correctly :)
A major caveat: treatment of carriage return characters, ^M aka control-M, \r in linux terms. Altho batch-mode Mysql output correctly escapes embedded newline characters, so there is truly one row per line (defined by linux newline character \n), mysql puts no quotes around column data. If a data item has an embedded carriage-return character, csv.reader rejects that input with this exception:
new-line character seen in unquoted field -
do you need to open the file in universal-newline mode?
Please don't @ me saying I should use universal file mode by re-opening sys.stdin.fileno with mode 'rU'. I tried that, it causes the embedded \r characters to be treated as end-of-record markers, so a single input record is incorrectly transformed into many incomplete output records. I have not found a Python solution to this limitation of Python's csv.reader module. I think the root cause is the csv.reader implementation/limitation noted in their documentation https://docs.python.org/3/library/csv.html#csv.reader:
The reader is hard-coded to recognise either '\r' or '\n' as end-of-line,
and ignores lineterminator.
The weak & unsatisfying solution I can offer is to change each \r character to the two-character sequence '\n' before Python's csv.reader sees the data. I used the sed command. Here's an example of a pipeline with a mysql select and the python script from above:
mysql -u user db --execute="select * from table where id=12345" \
| sed -e 's/\r/\\n/g' \
| mysqlTsvToCsv.py
After fighting this for some time I think Python is not the right solution. If you can live with perl, I think the one-liner script offered by @artfulrobot may be the most-effective and simplest solution.
Take a look at Simple JavaScript Inheritance and Inheritance Patterns in JavaScript.
The simplest method is probably functional inheritance but there are pros and cons.
Above screenshot taken from this live example: https://regex101.com/r/cU5lC2/1
I'll be using the phpsh interactive shell on Ubuntu 12.10 to demonstrate the PCRE regex engine through the method known as preg_match
Start phpsh, put some content into a variable, match on word.
el@apollo:~/foo$ phpsh
php> $content1 = 'badger'
php> $content2 = '1234'
php> $content3 = '$%^&'
php> echo preg_match('(\w+)', $content1);
1
php> echo preg_match('(\w+)', $content2);
1
php> echo preg_match('(\w+)', $content3);
0
The preg_match method used the PCRE engine within the PHP language to analyze variables: $content1
, $content2
and $content3
with the (\w)+
pattern.
$content1 and $content2 contain at least one word, $content3 does not.
el@apollo:~/foo$ phpsh
php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'darty gun';
php> $gun4 = 'unicorn gun';
php> echo preg_match('(dart|fart)', $gun1);
1
php> echo preg_match('(dart|fart)', $gun2);
1
php> echo preg_match('(dart|fart)', $gun3);
1
php> echo preg_match('(dart|fart)', $gun4);
0
Variables gun1
and gun2
contain the string dart
or fart
which is correct, but gun3 contains darty
and still matches, that is the problem. So onto the next example.
Word Boundaries can be force matched with \b
, see:
Regex Visual Image acquired from http://jex.im/regulex and https://github.com/JexCheng/regulex Example:
el@apollo:~/foo$ phpsh
php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'darty gun';
php> $gun4 = 'unicorn gun';
php> echo preg_match('(\bdart\b|\bfart\b)', $gun1);
1
php> echo preg_match('(\bdart\b|\bfart\b)', $gun2);
1
php> echo preg_match('(\bdart\b|\bfart\b)', $gun3);
0
php> echo preg_match('(\bdart\b|\bfart\b)', $gun4);
0
The \b
asserts that we have a word boundary, making sure " dart " is matched, but " darty " isn't.
If you use ArrayList instead of list then also your problem wil be solved. In your code only modify List into ArrayList.
private List<Item> data;
I know this question is a little old (and has had it's answer selected already) but for those wanting another option that're coming across this question through Google (like I did), I found this dynamic text shortener:
Dynamically shortened Text with “Show More” link using jQuery
I found it was better because you could set the character limit, rather than extra spans in the code, or setting a specific height to a container.
Hope it helps someone else out!
To round out the possibilities, you can use writeLines()
with sink()
, if you want:
> sink("tempsink", type="output")
> writeLines("Hello\nWorld")
> sink()
> file.show("tempsink", delete.file=TRUE)
Hello
World
To me, it always seems most intuitive to use print()
, but if you do that the output won't be what you want:
...
> print("Hello\nWorld")
...
[1] "Hello\nWorld"
If you find any ... let me know!
Seriously, as Josh Smith points out in this post, it's amazing there isn't a CodePlex community or something for this. Heck, it is amazing that there aren't more for purchase!
The only one that I have found (for sale) is reuxables. A little pricey, if you ask me, but you do get 9 themes/61 variations.
After I posted my answer, I thought, heck, I should go see if any CodePlex project exists for this already. I didn't find any specific project just for themes, but I did discover the WPF Contrib project ... which does have 1 theme that they never released.
Rudi Grobler (above) just created CodePlex community for this ... starting with converted themes he mentions above. See his blog post for more info. Way to go Rudi!
As another answer below has mentioned, since this question and my answer were written, the WPF Toolkit has incorporated some free themes, in particular, the themes from the Silverlight Toolkit. Rudi's project goes a little further and adds several more ... but depending on your situation, the WPF Toolkit might be all you need (and you might be installing it already).
Selenium WebDriver
WebDriver.Close()
This method is used to close the current open window. It closes the current open window on which driver has focus on.
WebDriver.Quit()
This method is used to destroy the instance of WebDriver. It closes all Browser Windows associated with that driver and safely ends the session. WebDriver.Quit() calls Dispose.
WebDriver.Dispose()
This method closes all Browser windows and safely ends the session
The reason it isn't working is because you have UseShellExecute = false
.
If you don't use the shell, you will have to supply the complete path to the python executable as FileName
, and build the Arguments
string to supply both your script and the file you want to read.
Also note, that you can't RedirectStandardOutput
unless UseShellExecute = false
.
I'm not quite sure how the argument string should be formatted for python, but you will need something like this:
private void run_cmd(string cmd, string args)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "my/full/path/to/python.exe";
start.Arguments = string.Format("{0} {1}", cmd, args);
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using(Process process = Process.Start(start))
{
using(StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
Console.Write(result);
}
}
}
It is because you haven't qualified Cells(1, 1)
with a worksheet object, and the same holds true for Cells(10, 2)
. For the code to work, it should look something like this:
Dim ws As Worksheet
Set ws = Sheets("SheetName")
Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents
Alternately:
With Sheets("SheetName")
Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With
EDIT: The Range object will inherit the worksheet from the Cells objects when the code is run from a standard module or userform. If you are running the code from a worksheet code module, you will need to qualify Range
also, like so:
ws.Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents
or
With Sheets("SheetName")
.Range(.Cells(1, 1), .Cells(10, 2)).ClearContents
End With
You can add the model error on any property of your model, I suggest if there is nothing related to create a new property.
As an exemple we check if the email is already in use in DB and add the error to the Email property in the action so when I return the view, they know that there's an error and how to show it up by using
<%: Html.ValidationSummary(true)%>
<%: Html.ValidationMessageFor(model => model.Email) %>
and
ModelState.AddModelError("Email", Resources.EmailInUse);
Difference between STATIC MEMORY ALLOCATION & DYNAMIC MEMORY ALLOCATION
Memory is allocated before the execution of the program begins
(During Compilation).
Memory is allocated during the execution of the program.
No memory allocation or deallocation actions are performed during Execution.
Memory Bindings are established and destroyed during the Execution.
Variables remain permanently allocated.
Allocated only when program unit is active.
Implemented using stacks and heaps.
Implemented using data segments.
Pointer is needed to accessing variables.
No need of Dynamically allocated pointers.
Faster execution than Dynamic.
Slower execution than static.
More memory Space required.
Less Memory space required.
please try this
echo $VAR | grep ClNonZ | awk '{print $3}';
or
echo cat filename | grep ClNonZ | awk '{print $3}';
Use dictionary comprehension way,
x = {k:v for k,v in enumerate(states) if v == True}
Input:
states = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]
Output:
{4: True, 5: True, 7: True}
My images were not getting displayed even after putting them in the correct folder, problem was they did not have the right permission, I changed the permission to read write execute. I used chmod 777 image.png. All worked then, images were getting displayed. :)
If your example represents your real code, the problem is not in the push
, it's that your constructor doesn't do anything.
You need to declare and initialize the x
and y
members.
Explicitly:
export class Pixel {
public x: number;
public y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
Or implicitly:
export class Pixel {
constructor(public x: number, public y: number) {}
}
Add the directory "C:\Program Files (x86)\Microsoft VS Code Insiders\bin"
at %PATH% environmental variable.
then go to the folder that you want to open with vs code and type:
code-insders .
I had this problem before and to fix this, Just make sure :
My problem (before) :
I had class : Core, Router, Permissions and Render
Core include's the Router class, Router then calls Permissions class, then Router __destruct calls the Render class and the error "Cannot declare class because the name is already in use" appeared.
Solution :
I added __destruct on Permission class and the __destruct was empty and it's fixed...
Lot of good tips here, but inside Powershell I could not get it to work.
I am a .NET developer and we mainly still use Windows OS as we haven't made use of .Net core and cross platform so much, so my everyday use with Git is in a Windows environment, where the shell used is more often Powershell and not Git bash.
The following procedure can be followed to create an aliased function for adding untracked files in a Git repository.
Inside your $profile file of Powershell (in case it is missing - you can run: New-Item $Profile)
notepad $Profile
Now add this Powershell method:
function AddUntracked-Git() {
&git ls-files -o --exclude-standard | select | foreach { git add $_ }
}
Save the $profile file and reload it into Powershell. Then reload your $profile file with: . $profile
This is similar to the source command in *nix environments IMHO.
So next time you, if you are developer using Powershell in Windows against Git repo and want to just include untracked files you can run:
AddUntracked-Git
This follows the Powershell convention where you have verb-nouns.
Because $newDate
is an object of type DateTime
, not a string. The documentation is explicit:
Returns new
DateTime
object formatted according to the specified format.
If you want to convert from a string to DateTime
back to string to change the format, call DateTime::format
at the end to get a formatted string out of your DateTime
.
$newDate = DateTime::createFromFormat("l dS F Y", $dateFromDB);
$newDate = $newDate->format('d/m/Y'); // for example
There is a HUGE difference between VARCHAR and TEXT. While VARCHAR fields can be indexed, TEXT fields cannot. VARCHAR type fields are stored inline while TEXT are stored offline, only pointers to TEXT data is actually stored in the records.
If you have to index your field for faster search, update or delete than go for VARCHAR, no matter how big. A VARCHAR(10000000) will never be the same as a TEXT field bacause these two data types are different in nature.
than go for TEXT.
Add reference Project->References Microsoft XML, 6.0 and you can use example code:
Dim xml As String
xml = "<root><person><name>Me </name> </person> <person> <name>No Name </name></person></root> "
Dim oXml As MSXML2.DOMDocument60
Set oXml = New MSXML2.DOMDocument60
oXml.loadXML xml
Dim oSeqNodes, oSeqNode As IXMLDOMNode
Set oSeqNodes = oXml.selectNodes("//root/person")
If oSeqNodes.length = 0 Then
'show some message
Else
For Each oSeqNode In oSeqNodes
Debug.Print oSeqNode.selectSingleNode("name").Text
Next
End If
be careful with xml node //Root/Person is not same with //root/person, also selectSingleNode("Name").text is not same with selectSingleNode("name").text
I believe you can do this using a Unicode encoding, but I doubt this is what you really want.
The ==
is the unicode value 2A76 so I belive you can do this:
char c = '\u2A76';
I can't test this at the moment but I'd be interested to know if that works for you.
You will need to dig around for the others. Here is a unicode table if you want to look:
do you mean a method?
$('div.foo').attr('id', 'foo123');
Just be careful that you don't set multiple elements to the same ID.
What you want to do is a combination of part of 1 and all of 2.
You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.
But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.
From the javadoc:
Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.
The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.
Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:
import static org.mockito.Mockito.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
class ClassWithStatics {
public static String getString() {
return "String";
}
public static int getInt() {
return 1;
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
@Test
public void test() {
PowerMockito.mockStatic(ClassWithStatics.class);
when(ClassWithStatics.getString()).thenReturn("Hello!");
System.out.println("String: " + ClassWithStatics.getString());
System.out.println("Int: " + ClassWithStatics.getInt());
}
}
The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.
@mplungjan, @eduard-luca
function isDate(str) {
var parms = str.split(/[\.\-\/]/);
var yyyy = parseInt(parms[2],10);
var mm = parseInt(parms[1],10);
var dd = parseInt(parms[0],10);
var date = new Date(yyyy,mm-1,dd,12,0,0,0);
return mm === (date.getMonth()+1) &&
dd === date.getDate() &&
yyyy === date.getFullYear();
}
new Date() uses local time, hour 00:00:00 will show the last day when we have "Summer Time" or "DST (Daylight Saving Time)" events.
Example:
new Date(2010,9,17)
Sat Oct 16 2010 23:00:00 GMT-0300 (BRT)
Another alternative is to use getUTCDate().
The only subquery appears to be this - try adding a ROWNUM
limit to the where to be sure:
(SELECT C.I_WORKDATE
FROM T_COMPENSATION C
WHERE C.I_COMPENSATEDDATE = A.I_REQDATE AND ROWNUM <= 1
AND C.I_EMPID = A.I_EMPID)
You do need to investigate why this isn't unique, however - e.g. the employee might have had more than one C.I_COMPENSATEDDATE
on the matched date.
For performance reasons, you should also see if the lookup subquery can be rearranged into an inner / left join, i.e.
SELECT
...
REPLACE(TO_CHAR(C.I_WORKDATE, 'DD-Mon-YYYY'),
' ',
'') AS WORKDATE,
...
INNER JOIN T_EMPLOYEE_MS E
...
LEFT OUTER JOIN T_COMPENSATION C
ON C.I_COMPENSATEDDATE = A.I_REQDATE
AND C.I_EMPID = A.I_EMPID
...
Try this, perhaps it works ;)
.factory('authInterceptor', function($location, $q, $window) {
return {
request: function(config) {
config.headers = config.headers || {};
config.headers.Authorization = 'xxxx-xxxx';
return config;
}
};
})
.config(function($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
})
And make sure your back end works too, try this. I'm using RESTful CodeIgniter.
class App extends REST_Controller {
var $authorization = null;
public function __construct()
{
parent::__construct();
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
if ( "OPTIONS" === $_SERVER['REQUEST_METHOD'] ) {
die();
}
if(!$this->input->get_request_header('Authorization')){
$this->response(null, 400);
}
$this->authorization = $this->input->get_request_header('Authorization');
}
}
This worked for me:
// After logout redirect user to Loing Activity
Intent i = new Intent(_context, MainActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
#include <iostream>
#include <map>
#define IDMAP(x) (x,#x)
std::map<int , std::string> enToStr;
class mapEnumtoString
{
public:
mapEnumtoString(){ }
mapEnumtoString& operator()(int i,std::string str)
{
enToStr[i] = str;
return *this;
}
public:
std::string operator [] (int i)
{
return enToStr[i];
}
};
mapEnumtoString k;
mapEnumtoString& init()
{
return k;
}
int main()
{
init()
IDMAP(1)
IDMAP(2)
IDMAP(3)
IDMAP(4)
IDMAP(5);
std::cout<<enToStr[1];
std::cout<<enToStr[2];
std::cout<<enToStr[3];
std::cout<<enToStr[4];
std::cout<<enToStr[5];
}
Try perl -MCPAN -e "upgrade /(.\*)/"
. It works fine for me.
Use a case
statement:
select id,
case report.type
when 'P' then amount
when 'N' then -amount
end as amount
from
`report`
You have not placed the script tags for angular js
you can do so by using cdn or downloading the angularjs for your project and then referencing it
after this you have to add your own java script in your case main.js
that should do
I set the column widths in the HTML markup like so:
<thead>
<tr>
<th style='width: 5%;'>ProjectId</th>
<th style='width: 15%;'>Title</th>
<th style='width: 40%;'>Abstract</th>
<th style='width: 20%;'>Keywords</th>
<th style='width: 10%;'>PaperName</th>
<th style='width: 10%;'>PaperURL</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr id="@item.ID">
<td>@item.ProjectId</td>
<td>@item.Title</td>
<td>@item.Abstract</td>
<td>@item.Keywords</td>
<td>@item.PaperName</td>
<td>@item.PaperURL</td>
</tr>
}
</tbody>
</table>
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"JukeboxV2.0\JukeboxV2.0\Datos\ich will.mp3")
base directory + your filename
A compiler who uses a binary tree for a representation of a AST, can use known algorithms for parsing the tree like postorder,inorder.The programmer does not need to come up with it's own algorithm. Because a binary tree for a source file is higher than the n-ary tree,it's building takes more time. Take this production: selstmnt := "if" "(" expr ")" stmnt "ELSE" stmnt In a binary tree it will have 3levels of nodes, but the n-ary tree will have 1 level(of chids)
That's why Unix based OS-s are slow.
You want to use absolute positioning.
An absolute position element is positioned relative to the first parent element that has a position other than static. If no such element is found, the containing block is html
For instance :
.yourDiv{
position:absolute;
top: 123px;
}
To get it to work, the parent needs to be relative (position:relative
)
In your case this should do the trick:
.suggestionsBox{position:absolute; top:40px;}
#specific_locations_add{position:relative;}
def attributeSelection():
balance = 25
print("Your SP balance is currently 25.")
strength = input("How much SP do you want to put into strength?")
balanceAfterStrength = balance - int(strength)
if balanceAfterStrength == 0:
print("Your SP balance is now 0.")
attributeConfirmation()
elif strength < 0:
print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
attributeSelection()
elif strength > balance:
print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
attributeSelection()
elif balanceAfterStrength > 0 and balanceAfterStrength < 26:
print("Ok. You're balance is now at " + str(balanceAfterStrength) + " skill points.")
else:
print("That is an invalid input. Restarting attribute selection.")
attributeSelection()
For clarity, I'd like to illustrate @Joey's answer above with these gifs :
Show
Show Detail
Present Modally
Present As Popover
A trick to make a PDF with complex features is to make a dummy activity with the desired xml layout. You can then open this dummy activity, take a screenshot programmatically and convert that image to pdf using this library. Of course there are limitations such as not being able to scroll, not more than one page,but for a limited application this is quick and easy. Hope this helps someone!
If you do not want to specify a message with your stashed changes, pass the filename after a double-dash.
$ git stash -- filename.ext
If it's an untracked/new file, you will have to stage it first.
This method works in git versions 2.13+
If it's inside a closure, i'm pretty sure you can't.
Otherwise you just do functionName();
and hit return.
As Paddy mentioned: if you use an overload of UrlHelper.Action()
that explicitly specifies the protocol to use, the generated URL will be absolute and fully qualified instead of being relative.
I wrote a blog post called How to build absolute action URLs using the UrlHelper class in which I suggest to write a custom extension method for the sake of readability:
/// <summary>
/// Generates a fully qualified URL to an action method by using
/// the specified action name, controller name and route values.
/// </summary>
/// <param name="url">The URL helper.</param>
/// <param name="actionName">The name of the action method.</param>
/// <param name="controllerName">The name of the controller.</param>
/// <param name="routeValues">The route values.</param>
/// <returns>The absolute URL.</returns>
public static string AbsoluteAction(this UrlHelper url,
string actionName, string controllerName, object routeValues = null)
{
string scheme = url.RequestContext.HttpContext.Request.Url.Scheme;
return url.Action(actionName, controllerName, routeValues, scheme);
}
You can then simply use it like that in your view:
@Url.AbsoluteAction("Action", "Controller")
In your home folder /.android/avd//config.ini add the line hw.keyboard=yes
It is maybe cheating, but it's works:
@foreach (var yourEnum in Html.GetEnumSelectList<YourEnum>())
{
@yourEnum.Text
}
A later answer, but because no one gave this solution...
If you do not want to set the header on the HttpClient
instance by adding it to the DefaultRequestHeaders
, you could set headers per request.
But you will be obliged to use the SendAsync()
method.
This is the right solution if you want to reuse the HttpClient
-- which is a good practice for
Use it like this:
using (var requestMessage =
new HttpRequestMessage(HttpMethod.Get, "https://your.site.com"))
{
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", your_token);
httpClient.SendAsync(requestMessage);
}
I have found the answer to this, and it is annoyingly/frustratingly simple! Basically the reply to addresses needed to be added before the from address as such:
$mail->addReplyTo('[email protected]', 'Reply to name');
$mail->SetFrom('[email protected]', 'Mailbox name');
Looking at the phpmailer code in more detail this is the offending line:
public function SetFrom($address, $name = '',$auto=1) {
$address = trim($address);
$name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
if (!self::ValidateAddress($address)) {
$this->SetError($this->Lang('invalid_address').': '. $address);
if ($this->exceptions) {
throw new phpmailerException($this->Lang('invalid_address').': '.$address);
}
echo $this->Lang('invalid_address').': '.$address;
return false;
}
$this->From = $address;
$this->FromName = $name;
if ($auto) {
if (empty($this->ReplyTo)) {
$this->AddAnAddress('ReplyTo', $address, $name);
}
if (empty($this->Sender)) {
$this->Sender = $address;
}
}
return true;
}
Specifically this line:
if (empty($this->ReplyTo)) {
$this->AddAnAddress('ReplyTo', $address, $name);
}
Thanks for your help everyone!
Be aware that this property isn't as useful as many people think it is. Just because your app is running on a Windows machine, for example, doesn't mean the file it's reading will be using Windows-style line separators. Many web pages contain a mixture of "\n" and "\r\n", having been cobbled together from disparate sources. When you're reading text as a series of logical lines, you should always look for all three of the major line-separator styles: Windows ("\r\n"), Unix/Linux/OSX ("\n") and pre-OSX Mac ("\r").
When you're writing text, you should be more concerned with how the file will be used than what platform you're running on. For example, if you expect people to read the file in Windows Notepad, you should use "\r\n" because it only recognizes the one kind of separator.
There must be also an answer for people who want a hassle free https on ec2 for mainly demo and testing purposes, one way they can achieve that very fast is:
With my answer here which describes How you can achieve https for testing purposes in minutes with EC2 without the hassle of creating certificates
Because strip()
only strips trailing and leading characters, based on what you provided. I suggest:
>>> import re
>>> name = "Barack (of Washington)"
>>> name = re.sub('[\(\)\{\}<>]', '', name)
>>> print(name)
Barack of Washington
This has been answered for the most part, but I will expand...
Step 1
My goal was to enable zoom at certain times, and disable it at others.
// enable pinch zoom
var $viewport = $('head meta[name="viewport"]');
$viewport.attr('content', 'width=device-width, initial-scale=1, maximum-scale=4');
// ...later...
// disable pinch zoom
$viewport.attr('content', 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no');
Step 2
The viewport tag would update, but pinch zoom was still active!! I had to find a way to get the page to pick up the changes...
It's a hack solution, but toggling the opacity of body did the trick. I'm sure there are other ways to accomplish this, but here's what worked for me.
// after updating viewport tag, force the page to pick up changes
document.body.style.opacity = .9999;
setTimeout(function(){
document.body.style.opacity = 1;
}, 1);
Step 3
My problem was mostly solved at this point, but not quite. I needed to know the current zoom level of the page so I could resize some elements to fit on the page (think of map markers).
// check zoom level during user interaction, or on animation frame
var currentZoom = $document.width() / window.innerWidth;
I hope this helps somebody. I spent several hours banging my mouse before finding a solution.
Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.
The following res:
(resource) references need to point to your model.
<add name="Entities" connectionString="metadata=
res://*/Models.WraithNath.co.uk.csdl|
res://*/Models.WraithNath.co.uk.ssdl|
res://*/Models.WraithNath.co.uk.msl;
Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).
It also may help to specify the assembly rather than using "//*/".
Worst case, you can check everything (a bit slower but should always find the resource) by using
<add name="Entities" connectionString="metadata=
res://*/;provider= <!-- ... -->
Mini snippet:
var speedtest = {};
function speedTest_start(name) { speedtest[name]= +new Date(); }
function speedTest_stop(name) { return +new Date() - speedtest[name] + (delete
speedtest[name]?0:0); }
use like:
speedTest_start("test1");
// ... some code
speedTest_stop("test1");
// returns the time duration in ms
Also more tests possible:
speedTest_start("whole");
// ... some code
speedTest_start("part");
// ... some code
speedTest_stop("part");
// returns the time duration in ms of "part"
// ... some code
speedTest_stop("whole");
// returns the time duration in ms of "whole"
I would suggest you read this article and focus more on how to optimize the overall response to the user request (either a page, a search result etc.)
A good argument for this is the example they give about using gzip to compress the page. Even though ttfb is faster when you do not compress, the overall experience of the user is worst because it takes longer to download content that is not zipped.
I could install it in a windows machine and using Anaconda/Spyder with python 2.7 through the following commands:
!pip install psycopg2
Then to establish the connection to the database:
import psycopg2
conn = psycopg2.connect(dbname='dbname',host='host_name',port='port_number', user='user_name', password='password')
Yarn is a recent package manager that probably deserves to be mentioned.
So, here it is: https://yarnpkg.com/
As far as I know it can fetch both npm and bower dependencies and has other appreciated features.
I'm surprised that the realpath
command hasn't been mentioned here. My understanding is that it is widely portable / ported.
Your initial solution becomes:
SCRIPT=`realpath $0`
SCRIPTPATH=`dirname $SCRIPT`
And to leave symbolic links unresolved per your preference:
SCRIPT=`realpath -s $0`
SCRIPTPATH=`dirname $SCRIPT`
I faced this issue few days back and this is the approach I followed and it works for me.
For me this was happening when i was trying to fetch data using axios or fetch libraries as i am under a corporate firewall, so we had certain particular certificates which node js certificate store was not able to point to.
So for my loclahost i followed this approach. I created a folder in my project and kept the entire chain of certificates in the folder and in my scripts for dev-server(package.json) i added this alongwith server script so that node js can reference the path.
"dev-server":set NODE_EXTRA_CA_CERTS=certificates/certs-bundle.crt
For my servers(different environments),I created a new environment variable as below and added it.I was using Openshift,but i suppose the concept will be same for others as well.
"name":NODE_EXTRA_CA_CERTS
"value":certificates/certs-bundle.crt
I didn't generate any certificate in my case as the entire chain of certificates was already available for me.
In SQL*Plus putting SET DEFINE ?
at the top of the script will normally solve this. Might work for Oracle SQL Developer as well.
First off it's important to understand that there are two kinds of "event listeners":
Scope event listeners registered via $on
:
$scope.$on('anEvent', function (event, data) {
...
});
Event handlers attached to elements via for example on
or bind
:
element.on('click', function (event) {
...
});
When $scope.$destroy()
is executed it will remove all listeners registered via $on
on that $scope.
It will not remove DOM elements or any attached event handlers of the second kind.
This means that calling $scope.$destroy()
manually from example within a directive's link function will not remove a handler attached via for example element.on
, nor the DOM element itself.
Note that remove
is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.
When element.remove()
is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on
.
It will not destroy the $scope associated with the element.
To make it more confusing there is also a jQuery event called $destroy
. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:
element.on('$destroy', function () {
scope.$destroy();
});
This depends on how the directive is "destroyed".
A normal case is that a directive is destroyed because ng-view
changes the current view. When this happens the ng-view
directive will destroy the associated $scope, sever all the references to its parent scope and call remove()
on the element.
This means that if that view contains a directive with this in its link function when it's destroyed by ng-view
:
scope.$on('anEvent', function () {
...
});
element.on('click', function () {
...
});
Both event listeners will be removed automatically.
However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references
.
Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.
For example if you have registered a listener on $rootScope
:
var unregisterFn = $rootScope.$on('anEvent', function () {});
scope.$on('$destroy', unregisterFn);
This is needed since $rootScope
is never destroyed during the lifetime of the application.
The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.
Another situation would be to cancel $interval
/$timeout
:
var promise = $interval(function () {}, 1000);
scope.$on('$destroy', function () {
$interval.cancel(promise);
});
If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:
var windowClick = function () {
...
};
angular.element(window).on('click', windowClick);
scope.$on('$destroy', function () {
angular.element(window).off('click', windowClick);
});
These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view
or ng-if
.
If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.
In addition to the answers above, you can check the type of object using type(plt.subplots())
which returns a tuple, on the other hand, type(plt.subplot())
returns matplotlib.axes._subplots.AxesSubplot
which you can't unpack.
cat filename | grep -v "pattern" > filename.1
mv filename.1 filename
There is a nifty plugin built from yonran
that can do the detection. Here is his previously answered question on StackOverflow. It works for most of the browsers. Application is as simple as this:
window.onresize = function onresize() {
var r = DetectZoom.ratios();
zoomLevel.innerHTML =
"Zoom level: " + r.zoom +
(r.zoom !== r.devicePxPerCssPx
? "; device to CSS pixel ratio: " + r.devicePxPerCssPx
: "");
}
I found the solution here in this link.
You just have to place below code in your Android application class. And that is enough. Don't need to do any changes in your Retrofit settings. It saved my day.
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
try {
// Google Play will install latest OpenSSL
ProviderInstaller.installIfNeeded(getApplicationContext());
SSLContext sslContext;
sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, null, null);
sslContext.createSSLEngine();
} catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException
| NoSuchAlgorithmException | KeyManagementException e) {
e.printStackTrace();
}
}
}
Hope this will be of help. Thank you.
Let's enjoy some hacky things:
Here is a Style
of Slider
as a NumericUpDown
, simple and easy to use, without any hidden code or third party library.
<Style TargetType="{x:Type Slider}">
<Style.Resources>
<Style x:Key="RepeatButtonStyle" TargetType="{x:Type RepeatButton}">
<Setter Property="Focusable" Value="false" />
<Setter Property="IsTabStop" Value="false" />
<Setter Property="Padding" Value="0" />
<Setter Property="Width" Value="20" />
</Style>
</Style.Resources>
<Setter Property="Stylus.IsPressAndHoldEnabled" Value="false" />
<Setter Property="SmallChange" Value="1" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Slider}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBox Grid.RowSpan="2"
Height="Auto"
Margin="0" Padding="0" VerticalAlignment="Stretch" VerticalContentAlignment="Center"
Text="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=Value}" />
<RepeatButton Grid.Row="0" Grid.Column="1" Command="{x:Static Slider.IncreaseLarge}" Style="{StaticResource RepeatButtonStyle}">
<Path Data="M4,0 L0,4 8,4 Z" Fill="Black" />
</RepeatButton>
<RepeatButton Grid.Row="1" Grid.Column="1" Command="{x:Static Slider.DecreaseLarge}" Style="{StaticResource RepeatButtonStyle}">
<Path Data="M0,0 L4,4 8,0 Z" Fill="Black" />
</RepeatButton>
<Border x:Name="TrackBackground" Visibility="Collapsed">
<Rectangle x:Name="PART_SelectionRange" Visibility="Collapsed" />
</Border>
<Thumb x:Name="Thumb" Visibility="Collapsed" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Notice: Trying to get property of non-object in C:\wamp\www\phone\pages\init.php on line 22
@22 is
<?php echo $sidemenu->mname."<br />";?>
$sidemenu
is not an object, and you are trying to access one of its properties.
That is the reason for your error.
Shared_ptr
: Performs two heap allocation
Make_shared
: Performs only one heap allocation
You could try updating the table to get rid of these characters:
UPDATE dbo.[audit]
SET UserID = REPLACE(UserID, CHAR(0), '')
WHERE CHARINDEX(CHAR(0), UserID) > 0;
But then you'll also need to fix whatever is putting this bad data into the table in the first place. In the meantime perhaps try:
SELECT CONVERT(INT, REPLACE(UserID, CHAR(0), ''))
FROM dbo.[audit];
But that is not a long term solution. Fix the data (and the data type while you're at it). If you can't fix the data type immediately, then you can quickly find the culprit by adding a check constraint:
ALTER TABLE dbo.[audit]
ADD CONSTRAINT do_not_allow_stupid_data
CHECK (CHARINDEX(CHAR(0), UserID) = 0);
EDIT
Ok, so that is definitely a 4-digit integer followed by six instances of CHAR(0). And the workaround I posted definitely works for me:
DECLARE @foo TABLE(UserID VARCHAR(32));
INSERT @foo SELECT 0x31353831000000000000;
-- this succeeds:
SELECT CONVERT(INT, REPLACE(UserID, CHAR(0), '')) FROM @foo;
-- this fails:
SELECT CONVERT(INT, UserID) FROM @foo;
Please confirm that this code on its own (well, the first SELECT
, anyway) works for you. If it does then the error you are getting is from a different non-numeric character in a different row (and if it doesn't then perhaps you have a build where a particular bug hasn't been fixed). To try and narrow it down you can take random values from the following query and then loop through the characters:
SELECT UserID, CONVERT(VARBINARY(32), UserID)
FROM dbo.[audit]
WHERE UserID LIKE '%[^0-9]%';
So take a random row, and then paste the output into a query like this:
DECLARE @x VARCHAR(32), @i INT;
SET @x = CONVERT(VARCHAR(32), 0x...); -- paste the value here
SET @i = 1;
WHILE @i <= LEN(@x)
BEGIN
PRINT RTRIM(@i) + ' = ' + RTRIM(ASCII(SUBSTRING(@x, @i, 1)))
SET @i = @i + 1;
END
This may take some trial and error before you encounter a row that fails for some other reason than CHAR(0)
- since you can't really filter out the rows that contain CHAR(0)
because they could contain CHAR(0)
and CHAR(something else)
. For all we know you have values in the table like:
SELECT '15' + CHAR(9) + '23' + CHAR(0);
...which also can't be converted to an integer, whether you've replaced CHAR(0)
or not.
I know you don't want to hear it, but I am really glad this is painful for people, because now they have more war stories to push back when people make very poor decisions about data types.
I usually use (new Error()).stack
in Chrome.
The nice thing is that this also gives you the line numbers where the caller called the function. The downside is that it limits the length of the stack to 10, which is why I came to this page in the first place.
(I'm using this to collect callstacks in a low-level constructor during execution, to view and debug later, so setting a breakpoint isn't of use since it will be hit thousands of times)
I had some issues with the MouseDown part of this, but here is some code that might get your started.
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<Control VerticalAlignment="Top">
<Control.Template>
<ControlTemplate>
<StackPanel>
<TextBox x:Name="MyText"></TextBox>
<Popup x:Name="Popup" PopupAnimation="Fade" VerticalAlignment="Top">
<Border Background="Red">
<TextBlock>Test Popup Content</TextBlock>
</Border>
</Popup>
</StackPanel>
<ControlTemplate.Triggers>
<EventTrigger RoutedEvent="UIElement.MouseEnter" SourceName="MyText">
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="Popup" Storyboard.TargetProperty="(Popup.IsOpen)">
<DiscreteBooleanKeyFrame KeyTime="00:00:00" Value="True"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger RoutedEvent="UIElement.MouseLeave" SourceName="MyText">
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="Popup" Storyboard.TargetProperty="(Popup.IsOpen)">
<DiscreteBooleanKeyFrame KeyTime="00:00:00" Value="False"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Control.Template>
</Control>
</Grid>
</Window>
One option is using Object.keys()
:
Object.keys(driversCounter)
It works fine for modern browsers (however, Internet Explorer supports it starting from version 9 only).
To add compatible support you can copy the code snippet provided in MDN.
I like to use Log.d(TAG, some string, often a String.format ()).
TAG is always the class name
Transform Log.d(TAG, --> Logd( in the text of your class
private void Logd(String str){
if (MainClass.debug) Log.d(className, str);
}
In this way when you are ready to make a release version, set MainClass.debug to false!
In my case, the root cause of this exception comes from using an old version mysql-connector and I had this error :
unable to load authentication plugin 'caching_sha2_password'. mysql
Adding this line to the mysql server configuration file (my.cnf or my.ini) fix this issue :
default_authentication_plugin=mysql_native_password
from the sourcecode at http://mozilla.github.com/pdf.js/build/pdf.js
/**
* This is the main entry point for loading a PDF and interacting with it.
* NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR)
* is used, which means it must follow the same origin rules that any XHR does
* e.g. No cross domain requests without CORS.
*
* @param {string|TypedAray|object} source Can be an url to where a PDF is
* located, a typed array (Uint8Array) already populated with data or
* and parameter object with the following possible fields:
* - url - The URL of the PDF.
* - data - A typed array with PDF data.
* - httpHeaders - Basic authentication headers.
* - password - For decrypting password-protected PDFs.
*
* @return {Promise} A promise that is resolved with {PDFDocumentProxy} object.
*/
So a standard XMLHttpRequest(XHR) is used for retrieving the document. The Problem with this is that XMLHttpRequests do not support data: uris (eg. data:application/pdf;base64,JVBERi0xLjUK...).
But there is the possibility of passing a typed Javascript Array to the function. The only thing you need to do is to convert the base64 string to a Uint8Array. You can use this function found at https://gist.github.com/1032746
var BASE64_MARKER = ';base64,';
function convertDataURIToBinary(dataURI) {
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for(var i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
tl;dr
var pdfAsDataUri = "data:application/pdf;base64,JVBERi0xLjUK..."; // shortened
var pdfAsArray = convertDataURIToBinary(pdfAsDataUri);
PDFJS.getDocument(pdfAsArray)
I was in a position where I had 6 identical arrays and I needed to pick the right one depending on another variable and then assign values to it. In the case shown here $comp_cat was 'a' so I needed to pick my 'a' array ( I also of course had 'b' to 'f' arrays)
Note that the values for the position of the variable in the array go after the closing brace.
${'comp_cat_'.$comp_cat.'_arr'}[1][0] = "FRED BLOGGS";
${'comp_cat_'.$comp_cat.'_arr'}[1][1] = $file_tidy;
echo 'First array value is '.$comp_cat_a_arr[1][0].' and the second value is .$comp_cat_a_arr[1][1];
I use this alias in my global ~/.gitconfig
# ~/.gitconfig
[alias]
aliases = !git config --get-regexp ^alias\\. | sed -e s/^alias.// -e s/\\ /\\ $(printf \"\\043\")--\\>\\ / | column -t -s $(printf \"\\043\") | sort -k 1
to produce the following output
$ git aliases
aliases --> !git config --get-regexp ^alias\. | sed -e s/^alias.// -e s/\ /\ $(printf "\043")--\>\ / | column -t -s $(printf "\043") | sort -k 1
ci --> commit -v
cim --> commit -m
co --> checkout
logg --> log --graph --decorate --oneline
pl --> pull
st --> status
... --> ...
(Note: This works for me in git bash on Windows. For other terminals you may need to adapt the escaping.)
!git config --get-regexp ^alias\\.
prints all lines from git config that start with alias.
sed -e s/^alias.//
removes alias.
from the linesed -e s/\\ /\\ $(printf \"\\043\")--\\>\\ /
replaces the first occurrence of a space with \\ $(printf \"\\043\")--\\>
(which evaluates to #-->
).column -t -s $(printf \"\\043\")
formats all lines into an evenly spaced column table. The character $(printf \"\\043\")
which evaluates to #
is used as separator.sort -k 1
sorts all lines based on the value in the first column$(printf \"\043\")
This just prints the character #
(hex 043) which is used for column separation. I use this little hack so the aliases
alias itself does not literally contain the #
character. Otherwise it would replace those #
characters when printing.
Note: Change this to another character if you need aliases with literal #
signs.
$ mysql -u root -p
Enter password: (enter your root password)
(Replace your_new_password
with the password you want to use)
mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_new_password';
mysql> FLUSH PRIVILEGES;
mysql> quit
Then try connecting using node
This will update the new characters in the file to be unix style. More info on "Newline Representation" in Emacs can be found here:
http://ergoemacs.org/emacs/emacs_line_ending_char.html
Note: The above steps could be made into an Emacs script if one preferred to execute this from the command line.
If you have a look at Preferences -> General
you will notice at the bottom of the panel, there is a setting Load preferences from a custom folder or URL:
. There is a button next to it Save settings to Folder
.
So all you need to do is save your settings first and load it after you reinstalled your OS.
If the Save settings to Folder
is disabled, select a folder (e.g. empty) in the Load preferences from a custom folder or URL:
text box.
In iTerm2 3.3 on OSX the sequence is: iTerm2 menu, Preferences, General tab, Preferences subtab
Here's a gist I put together. I was wondering the same and this helped improve my understanding. Open this up in an Xcode Playground to see what's going on.
protocol YelpRequestDelegate {
func getYelpData() -> AnyObject
func processYelpData(data: NSData) -> NSData
}
class YelpAPI {
var delegate: YelpRequestDelegate?
func getData() {
println("data being retrieved...")
let data: AnyObject? = delegate?.getYelpData()
}
func processYelpData(data: NSData) {
println("data being processed...")
let data = delegate?.processYelpData(data)
}
}
class Controller: YelpRequestDelegate {
init() {
var yelpAPI = YelpAPI()
yelpAPI.delegate = self
yelpAPI.getData()
}
func getYelpData() -> AnyObject {
println("getYelpData called")
return NSData()
}
func processYelpData(data: NSData) -> NSData {
println("processYelpData called")
return NSData()
}
}
var controller = Controller()
Yes, your compiler is expecting void *. Just cast them to void *.
/* for instance... */
printf("The value of s is: %p\n", (void *) s);
printf("The direction of s is: %p\n", (void *) &s);
Using Extension Methods:
public static class ObjectExtension
{
public static bool In(this object obj, params object[] objects)
{
if (objects == null || obj == null)
return false;
object found = objects.FirstOrDefault(o => o.GetType().Equals(obj.GetType()) && o.Equals(obj));
return (found != null);
}
}
Now you can do this:
string role= "Admin";
if (role.In("Admin", "Director"))
{
...
}
Swift 3 version with scale and Orientation from @kuzdu answer
extension UIImage {
func mask(_ color: UIColor) -> UIImage? {
let maskImage = cgImage!
let width = (cgImage?.width)!
let height = (cgImage?.height)!
let bounds = CGRect(x: 0, y: 0, width: width, height: height)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)!
context.clip(to: bounds, mask: maskImage)
context.setFillColor(color.cgColor)
context.fill(bounds)
if let cgImage = context.makeImage() {
let coloredImage = UIImage.init(cgImage: cgImage, scale: scale, orientation: imageOrientation)
return coloredImage
} else {
return nil
}
}
}
What you're looking for is called a "reverse merge". You should consult the docs regarding the merge function in the SVN book (as luapyad, or more precisely the first commenter on that post, points out). If you're using Tortoise, you can also just go into the log view and right-click and choose "revert changes from this revision" on the one where you made the mistake.
git reset --hard CommitId
git push -f origin master
1st command will rest your head to commitid and 2nd command will delete all commit after that commit id on master branch.
Note: Don't forget to add -f in push otherwise it will be rejected.
install.packages("ggplot2movies")
data(movies, package="ggplot2movies")
Plot average Length vs Rating
rating_by_len = tapply(movies$length,
movies$rating,
mean)
plot(names(rating_by_len), rating_by_len, ylim=c(0, 200)
,xlab = "Rating", ylab = "Length", main="Average Rating by Movie Length", pch=21)
Add error bars to the plot: mean - sd, mean + sd
sds = tapply(movies$length, movies$rating, sd)
upper = rating_by_len + sds
lower = rating_by_len - sds
segments(x0=as.numeric(names(rating_by_len)),
y0=lower,
y1=upper)
Hope that helps.
full solution here:
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/oragne_toggle_btn"
android:checked="true"
android:text="RadioButton" />
<RadioButton
android:id="@+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/oragne_toggle_btn"
android:layout_marginTop="20dp"
android:text="RadioButton" />
<RadioButton
android:id="@+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/oragne_toggle_btn"
android:layout_marginTop="20dp"
android:text="RadioButton" />
</RadioGroup>
selector XML
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/orange_btn_selected" android:state_checked="true"/>
<item android:drawable="@drawable/orange_btn_unselected" android:state_checked="false"/>
</selector>
The git will ignore the files matched .gitignore pattern after you add it to .gitignore.
But the files already existed in repository will be still in.
use git rm files_ignored; git commit -m 'rm no use files'
to delete ignored files.
Have you got org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
configured in webapp's web.xml
(assuming your application is a webapp), or wrapping calls accordingly?
To update the content of existing rows use the UPDATE
statement:
UPDATE table_name SET table_column = 'test';
<add key="ValidationSettings:UnobtrusiveValidationMode" value="WebForms" />
this line was not in my WebConfig so : I simple solved this by downgrading targetting .Net version to 4.0 :)
Here is an example from the MDN docs itself:
var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
var regexp = /[A-E]/gi;
var matches_array = str.match(regexp);
console.log(matches_array);
// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']
SCENARIO 1 - wait for async task completion: I agree that WaitHandle/Auto|ManualResetEvent should be used in scenario where a thread is waiting for task on another thread to complete.
SCENARIO 2 - timing while loop: However, as a crude timing mechanism (while+Thread.Sleep) is perfectly fine for 99% of applications which does NOT require knowing exactly when the blocked Thread should "wake up*. The argument that it takes 200k cycles to create the thread is also invalid - the timing loop thread needs be created anyway and 200k cycles is just another big number (tell me how many cycles to open a file/socket/db calls?).
So if while+Thread.Sleep works, why complicate things? Only syntax lawyers would, be practical!
Also, look at your perfmon counters. They can tell you where a lot of that cpu time is being spent. Here's a link to the most common counters to use:
"As I also currently write a desktop application for my work with Python, I found in data-entry application when there is lots of entry and which some are not mandatory thus user can left it blank, for validation purpose, it is easy to grab all entries and then discard empty key or value of a dictionary. So my code above a show how we can easy take them out, using dictionary comprehension and keep dictionary value element which is not blank. I use Python 3.8.3
data = {'':'', '20':'', '50':'', '100':'1.1', '200':'1.2'}
dic = {key:value for key,value in data.items() if value != ''}
print(dic)
{'100': '1.1', '200': '1.2'}
Normally svn add *
works. But if you get message like svn: warning: W150002:
due to mix off versioned and non-versioned files in working copy. Use this command:
svn add <path to directory> --force
or
svn add * --force
The PowerShell is almost exactly the same.
$webclient = new-object System.Net.WebClient
$webclient.Credentials = new-object System.Net.NetworkCredential($username, $password, $domain)
$webpage = $webclient.DownloadString($url)
If you came here from Google, trying to find where your previously created virtualenv installation ended up, and why there is no command to find it, here's the low-down.
The design of virtualenv
has a fundamental flaw of not being able to keep track of it's own created environments. Someone was not quite in their right mind when they created virtualenv
without having a rudimentary way to keep track of already created environments, and certainly not fit for a time and age when most pip requirements require multi-giga-byte installations, which should certainly not go into some obscure .virtualenvs
sub-directory of your ~/home.
IMO, the created virtualenv directory should be created in $CWD
and a file called ~/.virtualenv
(in home) should keep track of the name and path of that creation. Which is a darn good reason to use Conda/Miniconda3 instead, which does seem to keep good track of this.
As answered here, the only way to keep track of this, is to install yet another package called virtualenvwrapper
. If you don't do that, you will have to search for the created directory by yourself. Clearly, if you don't remember the name or the location it was created with/at, you will most likely never find your virtual environment again...
One try to remedy the situation in windows, is by putting the following functions into your powershell profile:
# wrap virtualenv.exe and write last argument (presumably
# your virtualenv name) to the file: $HOME/.virtualenv.
function ven { if( $args.count -eq 0) {Get-Content ~/.virtualenv } else {virtualenv.exe "$args"; Write-Output ("{0} `t{1}" -f $args[-1],$PWD) | Out-File -Append $HOME/.virtualenv }}
# List what's in the file or the directories under ~/.virtualenvs
function lsven { try {Get-Content ~/.virtualenv } catch {Get-ChildItem ~\.virtualenvs -Directory | Select-Object -Property Name } }
WARNING: This will write to ~\.virtualenv
...
Use Pre-request script tab to write javascript to get and save the date into a variable:
const dateNow= new Date();
pm.environment.set('currentDate', dateNow.toISOString());
and then use it in the request body as follows:
"currentDate": "{{currentDate}}"
Open a command prompt as admin and run this command:
bcdedit /set {current} hypervisorlaunchtype off
After a reboot, Hyper-V is still installed but the Hypervisor is no longer running. Now you can use VMware without any issues.
If you need Hyper-V again, open a command prompt as admin and run this command:
bcdedit /set {current} hypervisorlaunchtype auto
If a special character other than $, _, and # is used in the name of a column or table, the name must be enclosed in double quotations. Link
For Windows, I've created a build.cmd
file:
(replace the keystore path and alias)
For Cordova:
@echo off
set /P spassw="Store Password: " && set /P kpassw="Key Password: " && cordova build android --release -- --keystore=../../local/my.keystore --storePassword=%spassw% --alias=tmpalias --password=%kpassw%
And for Ionic:
@echo off
set /P spassw="Store Password: " && set /P kpassw="Key Password: " && ionic build --prod && cordova build android --release -- --keystore=../../local/my.keystore --storePassword=%spassw% --alias=tmpalias --password=%kpassw%
Save it in the ptoject's directory, you can double click or open it with cmd.
For Powershell scripts
I have seen this problem multiple times while scheduling Powershell scripts with parameters on multiple Windows servers. The solution has always been to use the -File parameter:
Happy scheduling!
I've tried many times.
And at last I just put autoindex on;
in http
but outside of server
, and it's OK.
Use fnmatch: https://docs.python.org/2/library/fnmatch.html
import fnmatch
import os
for file in os.listdir('.'):
if fnmatch.fnmatch(file, '*.txt'):
print file
Status code '0' can occur because of three reasons
1) The Client cannot connect to the server
2) The Client cannot receive the response within the timeout period
3) The Request was "stopped(aborted)" by the Client.
But these three reasons are not standardized
The input operator for number skips leading whitespace, so you can just read the number in a loop:
while (myfile >> a)
{
// ...
}
I've seen this error in a similar situation to mentioned in Joe's answer:
description: Too high 5xx responses rate: {{ .Value }} > 0.05
We have a colon in description value. So, the problem is in missing quotes around description value. It can be resolved by adding quotes:
description: 'Too high 5xx responses rate: {{ .Value }} > 0.05'
Shoud be stated on the top of the page.
Something like.
/* =========================================================
* bootstrap-modal.js v1.4.0
* http://twitter.github.com/bootstrap/javascript.html#modal
* =========================================================
* Copyright 2011 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ========================================================= */
An improvement on var dict = {}
is to use var dict = Object.create(null)
.
This will create an empty object that does not have Object.prototype
as it's prototype.
var dict1 = {};
if (dict1["toString"]){
console.log("Hey, I didn't put that there!")
}
var dict2 = Object.create(null);
if (dict2["toString"]){
console.log("This line won't run :)")
}
Note you can do something like this(at least in MVC3):
<td align="left" @(isOddRow ? "class=TopBorder" : "style=border:0px") >
What I believed was razor adding quotes was actually the browser. As Rism pointed out when testing with MVC 4(I haven't tested with MVC 3 but I assume behavior hasn't changed), this actually produces class=TopBorder
but browsers are able to parse this fine. The HTML parsers are somewhat forgiving on missing attribute quotes, but this can break if you have spaces or certain characters.
<td align="left" class="TopBorder" >
OR
<td align="left" style="border:0px" >
If you try to use some of the usual C# conventions for nested quotes, you'll end up with more quotes than you bargained for because Razor is trying to safely escape them. For example:
<button type="button" @(true ? "style=\"border:0px\"" : string.Empty)>
This should evaluate to <button type="button" style="border:0px">
but Razor escapes all output from C# and thus produces:
style="border:0px"
You will only see this if you view the response over the network. If you use an HTML inspector, often you are actually seeing the DOM, not the raw HTML. Browsers parse HTML into the DOM, and the after-parsing DOM representation already has some niceties applied. In this case the Browser sees there aren't quotes around the attribute value, adds them:
style=""border:0px""
But in the DOM inspector HTML character codes display properly so you actually see:
style=""border:0px""
In Chrome, if you right-click and select Edit HTML, it switch back so you can see those nasty HTML character codes, making it clear you have real outer quotes, and HTML encoded inner quotes.
So the problem with trying to do the quoting yourself is Razor escapes these.
Use Html.Raw to prevent quote escaping:
<td @Html.Raw( someBoolean ? "rel='tooltip' data-container='.drillDown a'" : "" )>
Renders as:
<td rel='tooltip' title='Drilldown' data-container='.drillDown a'>
The above is perfectly safe because I'm not outputting any HTML from a variable. The only variable involved is the ternary condition. However, beware that this last technique might expose you to certain security problems if building strings from user supplied data. E.g. if you built an attribute from data fields that originated from user supplied data, use of Html.Raw means that string could contain a premature ending of the attribute and tag, then begin a script tag that does something on behalf of the currently logged in user(possibly different than the logged in user). Maybe you have a page with a list of all users pictures and you are setting a tooltip to be the username of each person, and one users named himself '/><script>$.post('changepassword.php?password=123')</script>
and now any other user who views this page has their password instantly changed to a password that the malicious user knows.
Many people had difficulty in using this keyword when we have iteration of Drop-downs with same elements but different values or say as Multi line data in USER INTERFACE. : Here is the code snippet : $(this).find('option[value=yourvalue]');
Hope you got this.
JS does not have a sleep function, it has setTimeout() or setInterval() functions.
If you can move the code that you need to run after the pause into the setTimeout()
callback, you can do something like this:
//code before the pause
setTimeout(function(){
//do what you need here
}, 2000);
see example here : http://jsfiddle.net/9LZQp/
This won't halt the execution of your script, but due to the fact that setTimeout()
is an asynchronous function, this code
console.log("HELLO");
setTimeout(function(){
console.log("THIS IS");
}, 2000);
console.log("DOG");
will print this in the console:
HELLO
DOG
THIS IS
(note that DOG is printed before THIS IS)
You can use the following code to simulate a sleep for short periods of time:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
now, if you want to sleep for 1 second, just use:
sleep(1000);
example: http://jsfiddle.net/HrJku/1/
please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.
I am having the same problem, I found the below on the web somewhere....
Event handlers in Docs are a little tricky though. Because docs can handle multiple simultaneous edits by multiple users, the event handlers are handled server-side. The major issue with this structure is that when an event trigger script fails, it fails on the server. If you want to see the debug info you'll need to setup an explicit trigger under the triggers menu that emails you the debug info when the event fails or else it will fail silently.
There is no support for MapFragment
, Android team says is working on it since Android 3.0. Here more information about the issue But what you can do it by creating a Fragment that returns a MapActivity
. Here is a code example. Thanks to inazaruk:
How it works :
FragmentActivity
and hosts two MapFragments.MapView.
LocalActivityManagerFragment
hosts LocalActivityManager.LocalActivityManagerFragment
and with help of TabHost
creates internal instance of MyMapActivity. If you have any doubt please let me know
This is probably because an empty line at the end of your input file.
Try this:
for x in f:
try:
print int(x.strip(),16)
except ValueError:
print "Invalid input:", x
Although this is an "old" thread, I still would like to add the following to it:
I've experienced the next case:
int SetI2cSlaveAddress( UCHAR addr, bool force );
int CI2cHal::SetI2cSlaveAddress( UCHAR addr, bool force = false ) { ... }
As one can see, I had put the default value of the parameter "force" in the class source file, not in the class header file.
Then I used that function in a derived class as follows (derived class inherited the base class in a public way):
SetI2cSlaveAddress( addr );
assuming it would take the "force" parameter as "false" 'for granted'.
However, the compiler (put in c++11 mode) complained and gave me the following compiler error:
/home/.../mystuff/domoproject/lib/i2cdevs/max6956io.cpp: In member function 'void CMax6956Io::Init(unsigned char, unsigned char, unsigned int)':
/home/.../mystuff/domoproject/lib/i2cdevs/max6956io.cpp:26:30: error: no matching function for call to 'CMax6956Io::SetI2cSlaveAddress(unsigned char&)'
/home/.../mystuff/domoproject/lib/i2cdevs/max6956io.cpp:26:30: note: candidate is:
In file included from /home/geertvc/mystuff/domoproject/lib/i2cdevs/../../include/i2cdevs/max6956io.h:35:0,
from /home/geertvc/mystuff/domoproject/lib/i2cdevs/max6956io.cpp:1:
/home/.../mystuff/domoproject/lib/i2cdevs/../../include/i2chal/i2chal.h:65:9: note: int CI2cHal::SetI2cSlaveAddress(unsigned char, bool)
/home/.../mystuff/domoproject/lib/i2cdevs/../../include/i2chal/i2chal.h:65:9: note: candidate expects 2 arguments, 1 provided
make[2]: *** [lib/i2cdevs/CMakeFiles/i2cdevs.dir/max6956io.cpp.o] Error 1
make[1]: *** [lib/i2cdevs/CMakeFiles/i2cdevs.dir/all] Error 2
make: *** [all] Error 2
But when I added the default parameter in the header file of the base class:
int SetI2cSlaveAddress( UCHAR addr, bool force = false );
and removed it from the source file of the base class:
int CI2cHal::SetI2cSlaveAddress( UCHAR addr, bool force )
then the compiler was happy and all code worked as expected (I could give one or two parameters to the function SetI2cSlaveAddress()
)!
So, not only for the user of a class it's important to put the default value of a parameter in the header file, also compiling and functional wise it apparently seems to be a must!
Please try this ... hope it helps
JSONObject jsonObj1=null;
JSONObject jsonObj2=null;
JSONArray array=new JSONArray();
JSONArray array2=new JSONArray();
jsonObj1=new JSONObject();
jsonObj2=new JSONObject();
array.put(new JSONObject().put("firstName", "John").put("lastName","Doe"))
.put(new JSONObject().put("firstName", "Anna").put("v", "Smith"))
.put(new JSONObject().put("firstName", "Peter").put("v", "Jones"));
array2.put(new JSONObject().put("firstName", "John").put("lastName","Doe"))
.put(new JSONObject().put("firstName", "Anna").put("v", "Smith"))
.put(new JSONObject().put("firstName", "Peter").put("v", "Jones"));
jsonObj1.put("employees", array);
jsonObj1.put("manager", array2);
Response response = null;
response = Response.status(Status.OK).entity(jsonObj1.toString()).build();
return response;
In your case it should suffice to just add another hidden field to your form dynamically.
var input = $("<input>").attr("type", "hidden").val("Bla");
$('#form').append($(input));
It might be smart to also just create a new list if the current list item meets the desired criteria.
so:
for item in originalList:
if (item != badValue):
newList.append(item)
and to avoid having to re-code the entire project with the new lists name:
originalList[:] = newList
note, from Python documentation:
copy.copy(x) Return a shallow copy of x.
copy.deepcopy(x) Return a deep copy of x.
From the fine manual:
ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;
There's no need to specify the type when you're just changing the nullability.
For those who use ASP.NET Identity 2.1 and have changed the primary key from the default string
to either int
or Guid
, if you're still getting
EntityType 'xxxxUserLogin' has no key defined. Define the key for this EntityType.
EntityType 'xxxxUserRole' has no key defined. Define the key for this EntityType.
you probably just forgot to specify the new key type on IdentityDbContext
:
public class AppIdentityDbContext : IdentityDbContext<
AppUser, AppRole, int, AppUserLogin, AppUserRole, AppUserClaim>
{
public AppIdentityDbContext()
: base("MY_CONNECTION_STRING")
{
}
......
}
If you just have
public class AppIdentityDbContext : IdentityDbContext
{
......
}
or even
public class AppIdentityDbContext : IdentityDbContext<AppUser>
{
......
}
you will get that 'no key defined' error when you are trying to add migrations or update the database.
The best way using background with gradient as it does not increase app size of your app images are poison for android app so try to use it less instead of using one color as a background you can use multiple colors in one background.
you can get method parameter and its value and if annotated with a annotation with following code:
Map<String, Object> annotatedParameterValue = getAnnotatedParameterValue(MethodSignature.class.cast(jp.getSignature()).getMethod(), jp.getArgs());
....
private Map<String, Object> getAnnotatedParameterValue(Method method, Object[] args) {
Map<String, Object> annotatedParameters = new HashMap<>();
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
Parameter[] parameters = method.getParameters();
int i = 0;
for (Annotation[] annotations : parameterAnnotations) {
Object arg = args[i];
String name = parameters[i++].getDeclaringExecutable().getName();
for (Annotation annotation : annotations) {
if (annotation instanceof AuditExpose) {
annotatedParameters.put(name, arg);
}
}
}
return annotatedParameters;
}
You should use this one too:
./gradlew :app:dependencies
(Mac and Linux) -With ./
gradlew :app:dependencies
(Windows) -Without ./
The libs you are using internally using any other versions of google play service.If yes then remove or update those libs.
Actually, to properly support sorting, filtering, etc. a CollectionViewSource should be used as a link between the DataGrid and the list, like this:
<Window.Resources>
<CollectionViewSource x:Key="ItemCollectionViewSource" CollectionViewType="ListCollectionView"/>
</Window.Resources>
The DataGrid line looks like this:
<DataGrid
DataContext="{StaticResource ItemCollectionViewSource}"
ItemsSource="{Binding}"
AutoGenerateColumns="False">
In the code behind, you link CollectionViewSource with your link.
CollectionViewSource itemCollectionViewSource;
itemCollectionViewSource = (CollectionViewSource)(FindResource("ItemCollectionViewSource"));
itemCollectionViewSource.Source = itemList;
For detailed example see my article on CoedProject: http://www.codeproject.com/Articles/683429/Guide-to-WPF-DataGrid-formatting-using-bindings
A little OOC code to add:
#include <stdio.h>
struct Node {
int somevar;
};
void print() {
printf("Hello from an object-oriented C method!");
};
struct Tree {
struct Node * NIL;
void (*FPprint)(void);
struct Node *root;
struct Node NIL_t;
} TreeA = {&TreeA.NIL_t,print};
int main()
{
struct Tree TreeB;
TreeB = TreeA;
TreeB.FPprint();
return 0;
}
Java 8 now supports BASE64 Encoding and Decoding. You can use the following classes:
java.util.Base64
, java.util.Base64.Encoder
and java.util.Base64.Decoder
.
Example usage:
// encode with padding
String encoded = Base64.getEncoder().encodeToString(someByteArray);
// encode without padding
String encoded = Base64.getEncoder().withoutPadding().encodeToString(someByteArray);
// decode a String
byte [] barr = Base64.getDecoder().decode(encoded);
Does this work for you?
interface IMessage
{
void Process(object source);
}
class LoginMessage : IMessage
{
public void Process(object source)
{
}
}
abstract class MessageProcessor
{
public abstract void ProcessMessage(object source, object type);
}
class MessageProcessor<T> : MessageProcessor where T: IMessage
{
public override void ProcessMessage(object source, object o)
{
if (!(o is T)) {
throw new NotImplementedException();
}
ProcessMessage(source, (T)o);
}
public void ProcessMessage(object source, T type)
{
type.Process(source);
}
}
class Program
{
static void Main(string[] args)
{
Dictionary<Type, MessageProcessor> messageProcessors = new Dictionary<Type, MessageProcessor>();
messageProcessors.Add(typeof(string), new MessageProcessor<LoginMessage>());
LoginMessage message = new LoginMessage();
Type key = message.GetType();
MessageProcessor processor = messageProcessors[key];
object source = null;
processor.ProcessMessage(source, message);
}
}
This gives you the correct object. The only thing I am not sure about is whether it is enough in your case to have it as an abstract MessageProcessor.
Edit: I added an IMessage interface. The actual processing code should now become part of the different message classes that should all implement this interface.
Your return data
approach is correct, that's an example of promise chaining. If you return a promise from your .then()
callback, JavaScript will resolve that promise and pass the data to the next then()
callback.
Just be careful and make sure you handle errors with .catch()
. Promise.all()
rejects as soon as one of the promises in the array rejects.
If you want to copy something from one directory into the current directory, do this:
cp dir1/* .
This assumes you're not trying to copy hidden files.
If you use Spring Boot, you can also enable a “debug” mode by starting your application with a --debug flag.
java -jar myapp.jar --debug
You can also specify debug=true in your application.properties.
When the debug mode is enabled, a selection of core loggers (embedded container, Hibernate, and Spring Boot) are configured to output more information. Enabling the debug mode does not configure your application to log all messages with DEBUG level.
Alternatively, you can enable a “trace” mode by starting your application with a --trace flag (or trace=true in your application.properties). Doing so enables trace logging for a selection of core loggers (embedded container, Hibernate schema generation, and the whole Spring portfolio).
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html
I went through both your question and a another duplicate.
In the end, the following answer helped me sorting things out:
uncaught-typeerror-draggable-is-not-a-function
To get rid of :
$(".draggable").draggable is not a function anymore
I had to put links to Javascript libraries above the script tag I expected to be working.
My code:
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.min.css"/>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js" />
<script type="text/javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" />
<script>
$(function(){
$("#container-speed").draggable();
});
</script>
<div class="content">
<div class="container-fluid">
<div class="row">
<div class="rowbackground"style="width: 600px; height: 400px; margin: 0 auto">
<div id="container-speed" style="width: 300px; height: 200px; float: left"></div>
<div id="container-rpm" style="width: 300px; height: 200px; float: left"></div>
</div>
</div>
</div>
</div>
Try to configure the setting of your projects, it is usually due to x86/x64 architecture problems:
Go and set your choice as shown:
%s is for string %d is for decimal (or int) %c is for character
It appears to be chewing through an array of characters, and printing out whatever string exists starting at each subsequent position. The strings will stop at the first null in each case.
The commas are just separating the arguments to a function that takes a variable number of args; this number corresponds to the number of % args in the format descriptor at the front.
This is an old question, but here's another way to do it.
You can modify the R code itself instead of the chunk options, by wrapping the source
call in suppressPackageStartupMessages()
, suppressMessages()
, and/or suppressWarnings()
. E.g:
```{r echo=FALSE}
suppressWarnings(suppressMessages(suppressPackageStartupMessages({
source("C:/Rscripts/source.R")
})
```
You can also put those functions around your library()
calls inside the "source.R"
script.
In swift 3 use:
let url = URL(string: "Whatever url you have(eg: https://google.com)")
If the XAMPP server
is running for the moment, stop XAMPP server.
Follow these steps to change the port number.
Open the file in following location.
[XAMPP Installation Folder]/apache/conf/httpd.conf
Open the httpd.conf
file and search for the String:
Listen 80
This is the port number used by XAMMP.
Then search for the string ServerName and update the Port Number which you entered earlier for Listen
Now save and re-start XAMPP server.
Edit (by @dk14 as suggested by moderators and comments)
WARNING: If you use credential.helper store
from the answer, your password is going to be stored completely unencrypted ("as is") at ~/.git-credentials
. Please consult the comments section below or the answers from the "Linked" section, especially if your employer has zero tolerance for security issues.
Even though accepted, it doesn't answer the actual OP's question about omitting a username only (not password). For the readers with that exact problem @grawity's answer might come in handy.
Original answer (by @Alexander Zhu):
You can store your credentials using the following command
$ git config credential.helper store
$ git push http://example.com/repo.git
Username: <type your username>
Password: <type your password>
Also I suggest you to read
$ git help credentials
Please add try catch also in your code so that you can be sure that there in no exception.
try {
$hostname = "servername";
$dbname = "dbname";
$username = "username";
$pw = "password";
$pdo = new PDO ("mssql:host=$hostname;dbname=$dbname","$username","$pw");
} catch (PDOException $e) {
echo "Failed to get DB handle: " . $e->getMessage() . "\n";
exit;
}
SqlBulkCopy class is best for SQL server,
Doing Bulk Upload/Insert of DataTable to a Table in SQL server in C#
This error tells you that you do not have the razor engine properly associated with your project.
Solution: In the Solution Explorer window right click on your web project and select "Manage Nuget Packages..." then install "Microsoft ASP.NET Razor". This will make sure that the properly package is installed and it will add the necessary entries into your web.config file.
I edited your plunker to include ABOS's solution.
<body ng-controller="MainCtrl">
<ul ng-repeat='item in items'>
<li ng-if='item.color'>The color is {{item.color}}</li>
<li ng-if='item.shipping !== undefined'>The shipping cost is {{item.shipping}}</li>
</ul>
</body>
Sometimes it's better to think like a parser, like T-SQL parser. While executing the statement, parser does not have any value in Pivot section and you can't have any check expression in that section. By the way, you can simply use this:
SELECT CLASS
, IsNull([AZ], 0)
, IsNull([CA], 0)
, IsNull([TX], 0)
FROM #TEMP
PIVOT (
SUM(DATA)
FOR STATE IN (
[AZ]
, [CA]
, [TX]
)
) AS PVT
ORDER BY CLASS
If you are using Dot.Net then the code you need is
Environment.GetFolderPath(Environment.SpecialFolder.InternetCache)
Click my name if you want the code to delete these files plus FireFox temp files and Flash shared object/Flash Cookies
You can use properties tool.
Set 2 properties for your JFrame:
extendedState 6
resizeable true
way of getting home directory of current user is
String currentUsersHomeDir = System.getProperty("user.home");
and to append path separator
String otherFolder = currentUsersHomeDir + File.separator + "other";
The system-dependent default name-separator character, represented as a string for convenience. This string contains a single character, namely separatorChar.
For Intellij IDEA Community 2019.1 you will need to follow these steps :
File -> New -> Edit File Templates.. -> Class -> /* Created by ${USER} on ${DATE} */
You can also do something:
SELECT CAST(CAST(34512367.392 AS decimal(30,9)) AS NVARCHAR(100))
Output:
34512367.392000000
I am thinking this may not be possible in Java because annotation and its parameters are resolved at compile time.
With Seam 2 http://seamframework.org/ you were able to resolve annotation parameters at runtime, with expression language inside double quotes.
In Seam 3 http://seamframework.org/Seam3/Solder, this feature is the module Seam Solder
Note: You can first preview what your patch will do:
First the stats:
git apply --stat a_file.patch
Then a dry run to detect errors:
git apply --check a_file.patch
Finally, you can use git am
to apply your patch as a commit. This also allows you to sign off an applied patch.
This can be useful for later reference.
git am --signoff < a_file.patch
See an example in this article:
In your git log, you’ll find that the commit messages contain a “Signed-off-by” tag. This tag will be read by Github and others to provide useful info about how the commit ended up in the code.
Try like this for query string:
from flask import Flask, request
app = Flask(__name__)
@app.route('/parameters', methods=['GET'])
def query_strings():
args1 = request.args['args1']
args2 = request.args['args2']
args3 = request.args['args3']
return '''<h1>The Query String are...{}:{}:{}</h1>''' .format(args1,args2,args3)
if __name__ == '__main__':
app.run(debug=True)
I'm also running XP SP2, and this works perfectly (from the command line...):
start control schedtasks
For the me issue was that I had 2 other Android Emulators running. Once I closed those, I was able to start the new one.
I am not exactly sure which part to blame, but here's why MemoryStream
doesn't work for you:
As you write to MemoryStream
, it increments it's Position
property.
The constructor of StreamContent
takes into account the stream's current Position
. So if you write to the stream, then pass it to StreamContent
, the response will start from the nothingness at the end of the stream.
There's two ways to properly fix this:
1) construct content, write to stream
[HttpGet]
public HttpResponseMessage Test()
{
var stream = new MemoryStream();
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StreamContent(stream);
// ...
// stream.Write(...);
// ...
return response;
}
2) write to stream, reset position, construct content
[HttpGet]
public HttpResponseMessage Test()
{
var stream = new MemoryStream();
// ...
// stream.Write(...);
// ...
stream.Position = 0;
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StreamContent(stream);
return response;
}
2) looks a little better if you have a fresh Stream, 1) is simpler if your stream does not start at 0
Try this:
HTML:
<div id="container">
<div id="content">
// Content here
</div>
</div>
CSS:
#container{
height: 100%;
width: 100%;
overflow: hidden;
}
#content{
width: 100%;
height: 99%;
overflow: auto;
padding-right: 15px;
}
html, body{
height: 99%;
overflow:hidden;
}
Tested on FF and Safari.