When writing queries with our server LIKE or INSTR (or CHARINDEX in T-SQL) takes too long, so we use LEFT like in the following structure:
select *
from little
left join big
on left( big.key, len(little.key) ) = little.key
I understand that might only work with varying endings to the query, unlike other suggestions with '%' + b + '%', but is enough and much faster if you only need b+'%'.
Another way to optimize it for speed (but not memory) is to create a column in "little" that is "len(little.key)" as "lenkey" and user that instead in the query above.
This method works for me well, and I think this is the simplest one to do this job.
The general idea is to redirect the user to some other pages after the form submission, which would stop the form resubmission on page refresh. Still, if you need to hold the user on the same page after the form is submitted, you can do it in multiple ways, but here I am describing the javascript method.
Javascript Method
This method is quite easy and blocks the pop up asking for form resubmission on refresh once the form is submitted. Just place this line of javascript code at the footer of your file and see the magic.
<script>_x000D_
if ( window.history.replaceState ) {_x000D_
window.history.replaceState( null, null, window.location.href );_x000D_
}_x000D_
</script>
_x000D_
You should be using the command substitution syntax $(command)
when you want to execute a command in script/command.
So your line would be
name=$(echo "$filename" | cut -f 1 -d '.')
Code explanation:
echo
get the value of the variable $filename
and send it to standard outputcut
commandcut
will use the . as delimiter (also known as separator) for cutting the string into segments and by -f
we select which segment we want to have in output$()
command substitution will get the output and return its valuename
Note that this gives the portion of the variable up to the first period .
:
$ filename=hello.world
$ echo "$filename" | cut -f 1 -d '.'
hello
$ filename=hello.hello.hello
$ echo "$filename" | cut -f 1 -d '.'
hello
$ filename=hello
$ echo "$filename" | cut -f 1 -d '.'
hello
Most recent answer (for Angular 8+):
this.http.post("your-url",params,{responseType:'arraybuffer' as 'json'}).subscribe(
(res) => {
this.showpdf(res);
}
)};
public Content:SafeResourceUrl;
showpdf(response:ArrayBuffer) {
var file = new Blob([response], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
this.Content = this.sanitizer.bypassSecurityTrustResourceUrl(fileURL);
}
HTML :
<embed [src]="Content" style="width:200px;height:200px;" type="application/pdf" />
As others have said, you could use
:set list
which will, in combination with
:set listchars=...
display invisible characters.
Now, there isn't an explicit option which you can use to show whitespace, but in listchars, you could set a character to show for everything BUT whitespace. For example, mine looks like this
:set listchars=eol:$,tab:>-,trail:~,extends:>,precedes:<
so, now, after you use
:set list
everything that isn't explicitly shown as something else, is then, really, a plain old whitespace.
As usual, to understand how listchars
works, use the help. It provides great information about what chars can be displayed (like trailing space, for instance) and how to do it:
:help listchars
It might be helpful to add a toggle to it so you can see the changes mid editing easily (source: VIM :set list! as a toggle in .vimrc):
noremap <F5> :set list!<CR>
inoremap <F5> <C-o>:set list!<CR>
cnoremap <F5> <C-c>:set list!<CR>
<?php
function executeCurl($arrOptions) {
$mixCH = curl_init();
foreach ($arrOptions as $strCurlOpt => $mixCurlOptValue) {
curl_setopt($mixCH, $strCurlOpt, $mixCurlOptValue);
}
$mixResponse = curl_exec($mixCH);
curl_close($mixCH);
return $mixResponse;
}
// If any HTTP authentication is needed.
$username = 'http-auth-username';
$password = 'http-auth-password';
$requestType = 'POST'; // This can be PUT or POST
// This is a sample array. You can use $arrPostData = $_POST
$arrPostData = array(
'key1' => 'value-1-for-k1y-1',
'key2' => 'value-2-for-key-2',
'key3' => array(
'key31' => 'value-for-key-3-1',
'key32' => array(
'key321' => 'value-for-key321'
)
),
'key4' => array(
'key' => 'value'
)
);
// You can set your post data
$postData = http_build_query($arrPostData); // Raw PHP array
$postData = json_encode($arrPostData); // Only USE this when request JSON data.
$mixResponse = executeCurl(array(
CURLOPT_URL => 'http://whatever-your-request-url.com/xyz/yii',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPGET => true,
CURLOPT_VERBOSE => true,
CURLOPT_AUTOREFERER => true,
CURLOPT_CUSTOMREQUEST => $requestType,
CURLOPT_POSTFIELDS => $postData,
CURLOPT_HTTPHEADER => array(
"X-HTTP-Method-Override: " . $requestType,
'Content-Type: application/json', // Only USE this when requesting JSON data
),
// If HTTP authentication is required, use the below lines.
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => $username. ':' . $password
));
// $mixResponse contains your server response.
Not sure whether it would help you or not but it works to me:
l = ["a", "b", "c", "d", "e"]
outRes = dict((l[i], l[i+1]) if i+1 < len(l) else (l[i], '') for i in xrange(len(l)))
plt.axis('scaled')
works well for me.
just use SQL :
disconnect;
conn tiger/scott as sysdba;
For the Background, make sure you have imported java.awt.Color
into your package.
In your main
method, i.e. public static void main(String[] args)
, call the already imported method:
JLabel name_of_your_label=new JLabel("the title of your label");
name_of_your_label.setBackground(Color.the_color_you_wish);
name_of_your_label.setOpaque(true);
NB: Setting opaque will affect its visibility. Remember the case sensitivity in Java.
d = dict([(x,0) for x in a])
**edit Tim's solution is better because it uses generators see the comment to his answer.
Most of these answers assume the input contains a space - not whitespace, and a single space at that. If you can safely make that assumption, then the accepted answer (from bennett) is quite elegant and also the method I'll be going with when I can.
When we can't make that assumption, a more robust solution needs to cover the following siutations that most answers here don't consider:
\n
) and Windows (\r\n
) newline charactersTo cover these cases this solution uses regex to convert all whitespace (including recurring and Windows newline characters) to a single space, trims, then splits by a single space:
Swift 3:
let searchInput = " First \r\n \n \t\t\tMiddle Last "
let searchTerms = searchInput
.replacingOccurrences(
of: "\\s+",
with: " ",
options: .regularExpression
)
.trimmingCharacters(in: .whitespaces)
.components(separatedBy: " ")
// searchTerms == ["First", "Middle", "Last"]
The given answer wont always work. If it does not fix your issue. Make sure that you are also using the correct symbol in your package.json
. This is very important to fix that headache. For example:
warning " > @angular/[email protected]" has incorrect peer dependency "typescript@>=2.4.2 <2.7".
warning " > [email protected]" has incorrect peer dependency "typescript@>=2.4.2 <2.6".
So my typescript needs to be between 2.4.2 and 2.6 right?
So I changed my typescript library from using "typescript": "^2.7"
to using "typescript": "^2.5"
. Seems correct?
Wrong.
The ^
means that you are okay with npm using "typescript": "2.5"
or "2.6"
or "2.7"
etc...
If you want to learn what the ^
and ~
it mean see: What's the difference between tilde(~) and caret(^) in package.json?
Also you have to make sure that the package exists. Maybe there is no "typescript": "2.5.9"
look up the package numbers. To be really safe just remove the ~
or the ^
if you dont want to read what they mean.
The reason to that might be the 2 lines in eclipse.ini
--launcher.library
C:\Users\UserName\.p2\pool\plugins\org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.400.v20160518-1444
for my case the reason was admin privilages so I had to move the folder from the path specified in ini to my eclipse plugins and change path in ini to :
plugins\org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.400.v20160518-1444
Above answers all assume that the object in question is an object with behaviour. An advanced strategy in OOP is to separate data objects (that do zip, only have fields) and behaviour objects.
With data objects, it is perfectly fine to omit getters and instead have public fields. They usually don't have setters, since they most commonly are immutable - their fields are set via the constructors, and never again. Have a look at Bob Martin's Clean Code or Pryce and Freeman's Growing OO Software... for details.
I have similar issue faced and solve with following solution: my date format is: 'Fri Dec 11 2020 05:00:00 GMT+0500 (Pakistan Standard Time)'
let currentDate = moment(new Date('Fri Dec 11 2020 05:00:00 GMT+0500 (Pakistan Standard Time)').format('DD-MM-YYYY'); // 'Fri Dec 11 2020 05:00:00 GMT+0500 (Pakistan Standard Time)'
let output=(moment(currentDate).isSameOrAfter('07-12-2020'));
I have used POI.
If you use that, keep on eye those cell formatters: create one and use it several times instead of creating each time for cell, it isa huge memory consumption difference or large data.
Global $myArr;
$myArr = array();
function someFuntion(){
global $myArr;
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal;
}
Be forewarned, generally people stick away from globals as it has some downsides.
You could try this
function someFuntion($myArr){
$myVal = //some processing here to determine value of $myVal
$myArr[] = $myVal;
return $myArr;
}
$myArr = someFunction($myArr);
That would make it so you aren't relying on Globals.
System.Management.Automation on Nuget
System.Management.Automation.dll on NuGet, newer package from 2015, not unlisted as the previous one!
Microsoft PowerShell team packages un NuGet
Update: package is now owned by PowerShell Team. Huzzah!
I'm assuming you have a line like this defining the nav area, based on Bootstrap examples and all
<div class="nav-collapse collapse" >
Simply add the properties as such, like on the MENU button
<div class="nav-collapse collapse" data-toggle="collapse" data-target=".nav-collapse">
I've added to <body>
as well, worked. Can't say I've profiled it or anything, but seems a treat to me...until you click on a random spot of the UI to open the menu, so not so good that.
DK
SVGs are different than bitmap images such as PNG etc. If an SVG has a viewBox
- as yours appear to - then it will be scaled to fit it's defined viewport. It won't directly scale like a PNG would.
So increasing the width
of the img
won't make the icons any taller if the height is restricted. You'll just end up with the img
horizontally centred in a wider box.
I believe your problem is that your SVGs have a fixed height defined in them. Open up the SVG files and make sure they either:
width
and height
defined, orwidth
and height
both set to "100%"
.That should solve your problem. If it doesn't, post one of your SVGs into your question so we can see how it is defined.
On a Mac you can can select the text that you are after then press: cmd + ctrl + G
This will select every instance of your selected text within the same document. If you now start typing to replace your original highlighted text, you will replace all of the other occurrences at the same time.
You have a ; at the end of the if
.
Change:
if (fp == NULL);
return 0;
to
if (fp == NULL)
return 0;
Shortest Yet !!!
=f.hidden_field :title, :value => "some value"
Shorter, DRYer and perhaps more obvious.
Of course with ruby 1.9 and the new hash format we can go 3 characters shorter with...
=f.hidden_field :title, value: "some value"
If someone is here who is using MySQL and felt that the code was working the previous day and now it doesn't, then I guess you must open MySQL CLI or MySQL Workbench and just make the connection to the database once. Once it gets connected, then the database also gets connected to the Java Application. I used to get the Hibernate Dialect error stating something wrong with com.mysql.jdbc.Driver. I think MySQL in some computers has a startup problem. This solved for me.
You need to create a header with a proper formatted User agent String, it server to communicate client-server.
You can check your own user agent Here.
Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0
Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:42.0) Gecko/20100101 Firefox/42.0
I found this module very simple to use, in one line of code it randomly generates a User agent string.
from user_agent import generate_user_agent, generate_navigator
from pprint import pprint
print(generate_user_agent())
# 'Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.3; Win64; x64)'
print(generate_user_agent(os=('mac', 'linux')))
# 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:36.0) Gecko/20100101 Firefox/36.0'
pprint(generate_navigator())
# {'app_code_name': 'Mozilla',
# 'app_name': 'Netscape',
# 'appversion': '5.0',
# 'name': 'firefox',
# 'os': 'linux',
# 'oscpu': 'Linux i686 on x86_64',
# 'platform': 'Linux i686 on x86_64',
# 'user_agent': 'Mozilla/5.0 (X11; Ubuntu; Linux i686 on x86_64; rv:41.0) Gecko/20100101 Firefox/41.0',
# 'version': '41.0'}
pprint(generate_navigator_js())
# {'appCodeName': 'Mozilla',
# 'appName': 'Netscape',
# 'appVersion': '38.0',
# 'platform': 'MacIntel',
# 'userAgent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:38.0) Gecko/20100101 Firefox/38.0'}
The difference between substring and slice - is how they work with negative and overlooking lines abroad arguments:
substring (start, end)
Negative arguments are interpreted as zero. Too large values ??are truncated to the length of the string: alert ( "testme" .substring (-2)); // "testme", -2 becomes 0
Furthermore, if start > end, the arguments are interchanged, i.e. plot line returns between the start and end:
alert ( "testme" .substring (4, -1)); // "test"
// -1 Becomes 0 -> got substring (4, 0)
// 4> 0, so that the arguments are swapped -> substring (0, 4) = "test"
slice
Negative values ??are measured from the end of the line:
alert ( "testme" .slice (-2)); // "me", from the end position 2
alert ( "testme" .slice (1, -1)); // "estm", from the first position to the one at the end.
It is much more convenient than the strange logic substring.
A negative value of the first parameter to substr supported in all browsers except IE8-.
If the choice of one of these three methods, for use in most situations - it will be slice: negative arguments and it maintains and operates most obvious.
With the code in the question, you're only dealing interacting with the first of the four entries returned by that selector.
Code below as a fiddle: https://jsfiddle.net/c4nhpqgb/
I want to be overly clear that you have four items that matched that selector, so you need to deal with each explicitly. Using eq()
is a little more explicit making this point than the answers using map
, though map
or each
is what you'd probably use "in real life" (jquery docs for eq
here).
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
</head>
<body>
<div class="mbox">Block One</div>
<div class="mbox">Block Two</div>
<div class="mbox">Block Three</div>
<div class="mbox">Block Four</div>
<div id="outige"></div>
<script>
// using the $ prefix to use the "jQuery wrapped var" convention
var i, $mvar = $('.mbox');
// convenience method to display unprocessed html on the same page
function logit( string )
{
var text = document.createTextNode( string );
$('#outige').append(text);
$('#outige').append("<br>");
}
logit($mvar.length);
for (i=0; i<$mvar.length; i++) {
logit($mvar.eq(i).html());
}
</script>
</body>
</html>
Output from logit
calls (after the initial four div
's display):
4
Block One
Block Two
Block Three
Block Four
Your example is as concise as it gets with the switch
construct.
The problem here is that you have two different languages that solve two different problems... its like comparing C++ with assembler.
Python is for rapid application development and for when performance is a minimal concern.
C++ is not for rapid application development and inherits a legacy of speed from C - for low level programming.
This is not quite the answer to this question, but it may be useful for some: as @SWeko said, thanks to covariance and contravariance, List<X>
can not be cast in List<Y>
, but List<X>
can be cast into IEnumerable<Y>
, and even with implicit cast.
Example:
List<Y> ListOfY = new List<Y>();
List<X> ListOfX = (List<X>)ListOfY; // Compile error
but
List<Y> ListOfY = new List<Y>();
IEnumerable<X> EnumerableOfX = ListOfY; // No issue
The big advantage is that it does not create a new list in memory.
Right click on the project in Eclipse -> Android tools -> Export without signed key. Connect your device. Mount it by sdk/tools.
jQuery Validation Unobtrusive Native is a collection of ASP.Net MVC HTML helper extensions. These make use of jQuery Validation's native support for validation driven by HTML 5 data attributes. Microsoft shipped jquery.validate.unobtrusive.js back with MVC 3. It provided a way to apply data model validations to the client side using a combination of jQuery Validation and HTML 5 data attributes (that's the "unobtrusive" part).
Try this simple, specific function:
function resizeElementHeight(element) {
var height = 0;
var body = window.document.body;
if (window.innerHeight) {
height = window.innerHeight;
} else if (body.parentElement.clientHeight) {
height = body.parentElement.clientHeight;
} else if (body && body.clientHeight) {
height = body.clientHeight;
}
element.style.height = ((height - element.offsetTop) + "px");
}
It does not depend on the current distance from the top of the body being specified (in case your 300px changes).
EDIT: By the way, you would want to call this on that div every time the user changed the browser's size, so you would need to wire up the event handler for that, of course.
I'm suspicious of the ActiveFileName
property. According to the log4j javadoc, there isn't such a property on the TimeBasedRollingPolicy
class. (No setActiveFileName
or getActiveFileName
methods.)
I don't know what specifying an unknown property would do, but it is possible that it will cause the containing object to be abandoned, and that could lead to the warnings that you saw.
Try leaving it out and seeing what happens.
ArrayIndexOutOfBoundsException whenever this exception is coming it mean you are trying to use an index of array which is out of its bounds or in lay man terms you are requesting more than than you have initialised.
To prevent this always make sure that you are not requesting a index which is not present in array i.e. if array length is 10 then your index must range between 0 to 9
create resource layout file list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/header_text"
android:layout_height="0dp"
android:layout_width="fill_parent"
android:layout_weight="1"
android:text="Header"
/>
<TextView
android:id="@+id/item_text"
android:layout_height="0dp"
android:layout_width="fill_parent"
android:layout_weight="1"
android:text="dynamic text"
/>
</LinearLayout>
and initialise adaptor like this
adapter = new ArrayAdapter<String>(this, R.layout.list_item,R.id.item_text,data_array);
There is no :unchecked pseudo class however if you use the :checked pseudo class and the sibling selector you can differentiate between both states. I believe all of the latest browsers support the :checked pseudo class, you can find more info from this resource: http://www.whatstyle.net/articles/18/pretty_form_controls_with_css
Your going to get better browser support with jquery... you can use a click function to detect when the click happens and if its checked or not, then you can add a class or remove a class as necessary...
You can define the drawables that are used for the background, and the switcher part like this:
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:thumb="@drawable/switch_thumb"
android:track="@drawable/switch_bg" />
Now you need to create a selector that defines the different states for the switcher drawable. Here the copies from the Android sources:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:drawable="@drawable/switch_thumb_disabled_holo_light" />
<item android:state_pressed="true" android:drawable="@drawable/switch_thumb_pressed_holo_light" />
<item android:state_checked="true" android:drawable="@drawable/switch_thumb_activated_holo_light" />
<item android:drawable="@drawable/switch_thumb_holo_light" />
</selector>
This defines the thumb drawable, the image that is moved over the background. There are four ninepatch images used for the slider:
The deactivated version (xhdpi version that Android is using)
The pressed slider:
The activated slider (on state):
The default version (off state):
There are also three different states for the background that are defined in the following selector:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:drawable="@drawable/switch_bg_disabled_holo_dark" />
<item android:state_focused="true" android:drawable="@drawable/switch_bg_focused_holo_dark" />
<item android:drawable="@drawable/switch_bg_holo_dark" />
</selector>
The deactivated version:
The focused version:
And the default version:
To have a styled switch just create this two selectors, set them to your Switch View and then change the seven images to your desired style.
You have a lot of type-mismatches in your code such as trying to put an int
value where BigDecimal
is required. The corrected version of your code:
public class Payment
{
BigDecimal itemCost = BigDecimal.ZERO;
BigDecimal totalCost = BigDecimal.ZERO;
public BigDecimal calculateCost(int itemQuantity, BigDecimal itemPrice)
{
itemCost = itemPrice.multiply(new BigDecimal(itemQuantity));
totalCost = totalCost.add(itemCost);
return totalCost;
}
}
Your statement matches any string that contains a letter or digit anywhere, even if it contains other non-alphanumeric characters. Try this:
SELECT * FROM table WHERE column REGEXP '^[A-Za-z0-9]+$';
^
and $
require the entire string to match rather than just any portion of it, and +
looks for 1 or more alphanumberic characters.
You could also use a named character class if you prefer:
SELECT * FROM table WHERE column REGEXP '^[[:alnum:]]+$';
quick answer is this:
sh "ls -l > commandResult"
result = readFile('commandResult').trim()
I think there exist a feature request to be able to get the result of sh step, but as far as I know, currently there is no other option.
EDIT: JENKINS-26133
EDIT2: Not quite sure since what version, but sh/bat steps now can return the std output, simply:
def output = sh returnStdout: true, script: 'ls -l'
A problem with using DateTime.TryParse
is that it doesn't support the very common data-entry use case of dates entered without separators, e.g. 011508
.
Here's an example of how to support this. (This is from a framework I'm building, so its signature is a little weird, but the core logic should be usable):
private static readonly Regex ShortDate = new Regex(@"^\d{6}$");
private static readonly Regex LongDate = new Regex(@"^\d{8}$");
public object Parse(object value, out string message)
{
msg = null;
string s = value.ToString().Trim();
if (s.Trim() == "")
{
return null;
}
else
{
if (ShortDate.Match(s).Success)
{
s = s.Substring(0, 2) + "/" + s.Substring(2, 2) + "/" + s.Substring(4, 2);
}
if (LongDate.Match(s).Success)
{
s = s.Substring(0, 2) + "/" + s.Substring(2, 2) + "/" + s.Substring(4, 4);
}
DateTime d = DateTime.MinValue;
if (DateTime.TryParse(s, out d))
{
return d;
}
else
{
message = String.Format("\"{0}\" is not a valid date.", s);
return null;
}
}
}
List<String> result = Arrays.asList("abc".split(""));
You actually need 3 meta
tags to support Android, iPhone and Windows Phone
<!-- Chrome, Firefox OS and Opera -->
<meta name="theme-color" content="#4285f4">
<!-- Windows Phone -->
<meta name="msapplication-navbutton-color" content="#4285f4">
<!-- iOS Safari -->
<meta name="apple-mobile-web-app-status-bar-style" content="#4285f4">
A weird thing I found was that the environment variable SYSTEMROOT
must be set otherwise getaddrinfo()
will fail on Windows 10.
Use command line and not python.
TLDR; On Windows, do:
python -m pip --version
OR
py -m pip --version
Details:
On Windows, ~> (open windows terminal)
Start (or Windows Key) > type "cmd" Press Enter
You should see a screen that looks like this
To check to see if pip is installed.
python -m pip --version
if pip is installed, go ahead and use it. for example:
Z:\>python -m pip install selenium
if not installed, install pip, and you may need to
add its path to the environment variables. (basic - windows)
add path to environment variables (basic+advanced)
if python is NOT installed you will get a result similar to the one below
Install python. add its path to environment variables.
UPDATE: for newer versions of python replace "python" with py - see @gimmegimme's comment and link https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/
There is a bug reported for Pillow here, which indicates that libjpeg
and zlib
are now required as of Pillow 3.0.0.
The installation instructions for Pillow on Linux give advice of how to install these packages. Note that not all of the following packages may be missing on your machine (comments suggest that only libjpeg8-dev
is actually missing).
The latest releases of Pillow are available on PyPi as wheels — the new standard packaging mechanism for Python. These prebuilt packages include all neccessary binary dependencies to allow Pillow to run and should be used if you want to install Pillow using PyPi
To use wheels, you need to have a version of pip>=1.4
. If you are using an earlier version (pip --version
) upgrade pip using the following:
pip install --upgrade pip
Once pip
is upgraded, pip install
will use platform-specific wheel files by default if they are available. Use the following command to upgrade Pillow to the latest version available on PyPi:
pip install --upgrade pillow
sudo apt-get install libtiff4-dev libjpeg8-dev zlib1g-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.5-dev tk8.5-dev python-tk
sudo apt-get install libtiff5-dev libjpeg8-dev zlib1g-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev python-tk
sudo apt install libjpeg8-dev zlib1g-dev
The Fedora 20 equivalent of libjpeg8-dev
is libjpeg-devel
.
sudo yum install libtiff-devel libjpeg-devel libzip-devel freetype-devel lcms2-devel libwebp-devel tcl-devel tk-devel
On Mac OS X with Homebrew this can be fixed using:
brew install libjpeg zlib
You may also need to force-link zlib using the following:
brew link zlib --force
Update April 2019: In Mojave the above will not work and you need to run the following as taken from this bug report on Pillow
sudo installer -pkg /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg -target /
Update July 2016: There is no longer a formula for zlib
available in the main repository (Homebrew will prompt you to install lzlib
which is a different library and will not solve this problem).
There is a formula available in the dupes repository. You can either tap this repository, and install as normal:
brew tap homebrew/dupes
brew install zlib
Or you can install zlib
via xcode
instead, as follows:
xcode-select --install
Thanks to phoenix, Panos Angelopoulou, nelsonvarela, benjaminz and Kal in the comments
After these are installed the pip installation of Pillow should work normally.
Just add this below JS file
<script type="text/javascript">
$(document).ready(function () {
$('your input's id or class with # or .').datepicker({
format: "dd/mm/yyyy"
});
});
</script>
With iOS 13 and above, you can simply use
let image = UIImage(named: "Heart")?.withRenderingMode(.alwaysTemplate)
if #available(iOS 13.0, *) {
imageView.image = image?.withTintColor(UIColor.white)
}
What about this:
var txt="";
var nyc = {
fullName: "New York City",
mayor: "Michael Bloomberg",
population: 8000000,
boroughs: 5
};
for (var x in nyc){
txt += nyc[x];
}
The previous posters made a little mistake. The accept attribute is only a display filter. It will not validate your entry before submitting.
This attribute forces the file dialog to display the required mime type only. But the user can override that filter. He can choose . and see all the files in the current directory. By doing so, he can select any file with any extension, and submit the form.
So, to answer to the original poster, NO. You cannot restrict the input file to one particular extension by using HTML.
But you can use javascript to test the filename that has been chosen, just before submitting. Just insert an onclick attribute on your submit button and call the code that will test the input file value. If the extension is forbidden, you'll have to return false to invalidate the form. You may even use a jQuery custom validator and so on, to validate the form.
Finally, you'll have to test the extension on the server side too. Same problem about the maximum allowed file size.
You haven't posted the findvertex
method, but Access Reading Violation with an offset like 0x00000048
means that the Vertex* f;
in your getCost function is receiving null, and when trying to access the member adj
in the null
Vertex pointer (that is, in f
), it is offsetting to adj
(in this case, 72 bytes ( 0x48 bytes in decimal )), it's reading near the 0
or null
memory address.
Doing a read like this violates Operating-System protected memory, and more importantly means whatever you're pointing at isn't a valid pointer. Make sure findvertex
isn't returning null, or do a comparisong for null on f
before using it to keep yourself sane (or use an assert):
assert( f != null ); // A good sanity check
EDIT:
If you have a map
for doing something like a find, you can just use the map's find
method to make sure the vertex exists:
Vertex* Graph::findvertex(string s)
{
vmap::iterator itr = map1.find( s );
if ( itr == map1.end() )
{
return NULL;
}
return itr->second;
}
Just make sure you're still careful to handle the error case where it does return NULL
. Otherwise, you'll keep getting this access violation.
You could create a date for the first of the next month, and then use strtotime("-1 day", $firstOfNextMonth)
To indicate execution status.
status 0 means the program succeeded.
status different from 0 means the program exited due to error or anomaly.
return n; from your main entry function will terminate your process and report to the parent process (the one that executed your process) the result of your process. 0 means SUCCESS. Other codes usually indicates a failure and its meaning.
An enum declares a set of ordered values - the typedef just adds a handy name to this. The 1st element is 0 etc.
typedef enum {
Monday=1,
...
} WORKDAYS;
WORKDAYS today = Monday;
The above is just an enumeration of shapeType tags.
According to nginx documentation
there is no syntax for NOT matching a regular expression. Instead, match the target regular expression and assign an empty block, then use location / to match anything else
So you could define something like
location ~ (dir1|file2\.php) {
# empty
}
location / {
rewrite ^/(.*) http://example.com/$1 permanent;
}
Constructors are not inherited. They are called implicitly or explicitly by the child constructor.
The compiler creates a default constructor (one with no arguments) and a default copy constructor (one with an argument which is a reference to the same type). But if you want a constructor that will accept an int, you have to define it explicitly.
class A
{
public:
explicit A(int x) {}
};
class B: public A
{
public:
explicit B(int x) : A(x) { }
};
UPDATE: In C++11, constructors can be inherited. See Suma's answer for details.
I got this error in Expo because I had exported the wrong component name, e.g.
const Wonk = props => (
<Text>Hi!</Text>
)
export default Stack;
"abcd4yyyy" | grep 4 -c
gives the count as 1
The following does it in a single line:
dataTable.Rows.OfType<DataRow>()
.Select(dr => dr.Field<MyType>(columnName)).ToList();
[Edit: Add a reference to System.Data.DataSetExtensions
to your project if this does not compile]
Based on your comments, you would be better off with Text-finder plugin.
It allows to search file(s), as well as console, for a regular expression and then set the build either unstable
or failed
if found.
As for the Groovy, you can use the following to access ${WORKSPACE}
environment variable:
def workspace = manager.build.getEnvVars()["WORKSPACE"]
Integer value of ARGB color to hexadecimal string:
String hex = Integer.toHexString(color); // example for green color FF00FF00
Hexadecimal string to integer value of ARGB color:
int color = (Integer.parseInt( hex.substring( 0,2 ), 16) << 24) + Integer.parseInt( hex.substring( 2 ), 16);
In native Hibernate XML mappings, you can accomplish this by declaring a one-to-one mapping with the constrained attribute set to true. I am not sure what the Hibernate/JPA annotation equivalent of that is, and a quick search of the doc provided no answer, but hopefully that gives you a lead to go on.
Your example is perfect: the field is private and it has a getter. This is the normal way to access a field. If you need a direct access to an object field, use reflection. Using reflection to get a field's value is a hack and should be used in extreme cases such as using a library whose code you cannot change.
simply "CUT" project folder and move it out of workspace directory and do the following
file=>import=>(select new directory)=> mark (copy to my workspace) checkbox
and you done !
Do not hold me to this but I am pretty sure it depends on the application it self. I know many always open on the main monitor, some will reopen to the same monitor they were previously run in, and some you can set. I know for example I have shortcuts to open command windows to particular directories, and each has an option in their properties to the location to open the window in. While Outlook just remembers and opens in the last screen it was open in. Then other apps open in what ever window the current focus is in.
So I am not sure there is a way to tell every program where to open. Hope that helps some.
String id = id.substring(0,id.length()-4)
In my case with Android 8.0(Oreo), no one of this solutions worked! If you have more than 1 user, then you should go to Settings->Applications->All Applications->Find the application and uninstall for all users! After this steps, it worked!
DESCRIPTION: SC is a command line program used for communicating with the NT Service Controller and services. USAGE: sc [command] [service name] ...
The option <server> has the form "\\ServerName"
Further help on commands can be obtained by typing: "sc [command]"
Commands:
query-----------Queries the status for a service, or
enumerates the status for types of services.
queryex---------Queries the extended status for a service, or
enumerates the status for types of services.
start-----------Starts a service.
pause-----------Sends a PAUSE control request to a service.
interrogate-----Sends an INTERROGATE control request to a service.
continue--------Sends a CONTINUE control request to a service.
stop------------Sends a STOP request to a service.
config----------Changes the configuration of a service (persistant).
description-----Changes the description of a service.
failure---------Changes the actions taken by a service upon failure.
qc--------------Queries the configuration information for a service.
qdescription----Queries the description for a service.
qfailure--------Queries the actions taken by a service upon failure.
delete----------Deletes a service (from the registry).
create----------Creates a service. (adds it to the registry).
control---------Sends a control to a service.
sdshow----------Displays a service's security descriptor.
sdset-----------Sets a service's security descriptor.
GetDisplayName--Gets the DisplayName for a service.
GetKeyName------Gets the ServiceKeyName for a service.
EnumDepend------Enumerates Service Dependencies.
The following commands don't require a service name:
sc <server> <command> <option>
boot------------(ok | bad) Indicates whether the last boot should
be saved as the last-known-good boot configuration
Lock------------Locks the Service Database
QueryLock-------Queries the LockStatus for the SCManager Database
EXAMPLE: sc start MyService
If you're using .NET 4.0 you should be able to allow these urls via the web.config
<system.web>
<httpRuntime
requestPathInvalidCharacters="<,>,%,&,:,\,?" />
</system.web>
Note, I've just removed the asterisk (*), the original default string is:
<httpRuntime
requestPathInvalidCharacters="<,>,*,%,&,:,\,?" />
See this question for more details.
Had the same problem....managed to get it to work after a little while.
Thing to do is follow instructions on installing FFmpeg - which is (at least on windows) a bundle of executables you need to set a path to in your environment variables
http://www.wikihow.com/Install-FFmpeg-on-Windows
Hope this helps someone - even after a while after the question - good luck
I'm pretty new to iOS and Phonegap as well, but I was able to do this by adding in an eventListener. I did the same thing (using the example you reference), and couldn't get it to work. But this seemed to do the trick:
// Event listener to determine change (horizontal/portrait)
window.addEventListener("orientationchange", updateOrientation);
function updateOrientation(e) {
switch (e.orientation)
{
case 0:
// Do your thing
break;
case -90:
// Do your thing
break;
case 90:
// Do your thing
break;
default:
break;
}
}
You may have some luck searching the PhoneGap Google Group for the term "orientation".
One example I read about as an example on how to detect orientation was Pie Guy: (game, js file). It's similar to the code you've posted, but like you... I couldn't get it to work.
One caveat: the eventListener worked for me, but I'm not sure if this is an overly intensive approach. So far it's been the only way that's worked for me, but I don't know if there are better, more streamlined ways.
UPDATE fixed the code above, it works now
Try handling the change event of the select
and using this.value
to determine whether it's 'Yes' or not.
JS
document.getElementById('test').addEventListener('change', function () {
var style = this.value == 1 ? 'block' : 'none';
document.getElementById('hidden_div').style.display = style;
});
HTML
<select id="test" name="form_select">
<option value="0">No</option>
<option value ="1">Yes</option>
</select>
<div id="hidden_div" style="display: none;">Hello hidden content</div>
I guess ch
is a declared as char
. Since char
is a primitive data type and not and object, you can't call any methof from it. You should use Character.isLetter(ch)
.
If you need just to execute your VLC playback process and only give control back to your application process when it is done and nothing more complex, then i suppose you can use just:
system("The same thing you type into console");
Well for me it was my own bug. I was trying to run an INSERT
using SqlCommand.executeReader()
when I should have been using SqlCommand.ExecuteNonQuery()
. It was opened and never closed, causing the error. Watch out for this oversight.
I would say not.
If the column does accept null values, then there's nothing to stop you inserting a null value into the field. As far as I'm aware, the default value only applies on creation of a new row.
With not null set, then you can't insert a null value into the field as it'll throw an error.
Think of it as a fail safe mechanism to prevent nulls.
To change to a directory with spaces on the name you just have to type like this:
cd My\ Documents
Hit enter and you will be good
I fixed mine by closing eclipse and deleting the whole .metadata folder inside my workspace folder.
Rather than try to target @media rules at specific devices, it is arguably more practical to base them on your particular layout instead. That is, gradually narrow your desktop browser window and observe the natural breakpoints for your content. It's different for every site. As long as the design flows well at each browser width, it should work pretty reliably on any screen size (and there are lots and lots of them out there.)
Just to make this absolutely clear for all:
A .MDF file is “typically” a SQL Server data file however it is important to note that it does NOT have to be.
This is because .MDF is nothing more than a recommended/preferred notation but the extension itself does not actually dictate the file type.
To illustrate this, if someone wanted to create their primary data file with an extension of .gbn they could go ahead and do so without issue.
To qualify the preferred naming conventions:
Ruby
Some of the tutorials I found that are easy to understand are:
It makes way more sense to break up your list into page-sized chunks, and only query your database one chunk at a time. This drastically reduces server processing time and page load time, as well as gives your user smaller pieces of info to digest, so he doesn't choke on whatever crap you're trying to feed him. The act of doing this is called pagination.
A basic pagination routine seems long and scary at first, but once you close your eyes, take a deep breath, and look at each piece of the script individually, you will find it's actually pretty easy stuff
The script:
// find out how many rows are in the table
$sql = "SELECT COUNT(*) FROM numbers";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
$r = mysql_fetch_row($result);
$numrows = $r[0];
// number of rows to show per page
$rowsperpage = 10;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);
// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
// cast var as int
$currentpage = (int) $_GET['currentpage'];
} else {
// default page num
$currentpage = 1;
} // end if
// if current page is greater than total pages...
if ($currentpage > $totalpages) {
// set current page to last page
$currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
// set current page to first page
$currentpage = 1;
} // end if
// the offset of the list, based on current page
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db
$sql = "SELECT id, number FROM numbers LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) {
// echo data
echo $list['id'] . " : " . $list['number'] . "<br />";
} // end while
/****** build the pagination links ******/
// range of num links to show
$range = 3;
// if not on page 1, don't show back links
if ($currentpage > 1) {
// show << link to go back to page 1
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
// get previous page num
$prevpage = $currentpage - 1;
// show < link to go back to 1 page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
} // end if
// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
// if it's a valid page number...
if (($x > 0) && ($x <= $totalpages)) {
// if we're on current page...
if ($x == $currentpage) {
// 'highlight' it but don't make a link
echo " [<b>$x</b>] ";
// if not current page...
} else {
// make it a link
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
} // end else
} // end if
} // end for
// if not on last page, show forward and last page links
if ($currentpage != $totalpages) {
// get next page
$nextpage = $currentpage + 1;
// echo forward link for next page
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
// echo forward link for lastpage
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
} // end if
/****** end build pagination links ******/
?>
This tutorial is intended for developers who wish to give their users the ability to step through a large number of database rows in manageable chunks instead of the whole lot in one go.
A simple solution is to wrap the query into a subselect with the ORDER statement first and applying the GROUP BY later:
SELECT * FROM (
SELECT `timestamp`, `fromEmail`, `subject`
FROM `incomingEmails`
ORDER BY `timestamp` DESC
) AS tmp_table GROUP BY LOWER(`fromEmail`)
This is similar to using the join but looks much nicer.
Using non-aggregate columns in a SELECT with a GROUP BY clause is non-standard. MySQL will generally return the values of the first row it finds and discard the rest. Any ORDER BY clauses will only apply to the returned column value, not to the discarded ones.
IMPORTANT UPDATE Selecting non-aggregate columns used to work in practice but should not be relied upon. Per the MySQL documentation "this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate."
As of 5.7.5 ONLY_FULL_GROUP_BY is enabled by default so non-aggregate columns cause query errors (ER_WRONG_FIELD_WITH_GROUP)
As @mikep points out below the solution is to use ANY_VALUE() from 5.7 and above
See http://www.cafewebmaster.com/mysql-order-sort-group https://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_any-value
If you are using this query to generate an input file for your Data Warehouse, then you need to format the data appropriately. Essentially in that case you are converting the date (which does have a time component) to a string. You need to explicitly format your string or change your nls_date_format to set the default. In your query you could simply do:
select to_char(some_date, 'yyyy-mm-dd hh24:mi:ss') my_date
from some_table;
The difference is in the arguments. It's very common to generate a random number from a uniform distribution in the range [0.0, 1.0), so random.random()
just does this. Use random.uniform(a, b)
to specify a different range.
For me, simply adding the current directory worked.
Using the following structure:
+-- myproject
+-- a.py
+-- b.py
a.py:
from b import some_object
# returns ModuleNotFound error
from myproject.b import some_object
# works
This: http://archives.postgresql.org/pgsql-bugs/2007-10/msg00234.php is also a nice and fast solution, and works for multiple schemas in one database:
Tables
SELECT 'ALTER TABLE '|| schemaname || '."' || tablename ||'" OWNER TO my_new_owner;'
FROM pg_tables WHERE NOT schemaname IN ('pg_catalog', 'information_schema')
ORDER BY schemaname, tablename;
Sequences
SELECT 'ALTER SEQUENCE '|| sequence_schema || '."' || sequence_name ||'" OWNER TO my_new_owner;'
FROM information_schema.sequences WHERE NOT sequence_schema IN ('pg_catalog', 'information_schema')
ORDER BY sequence_schema, sequence_name;
Views
SELECT 'ALTER VIEW '|| table_schema || '."' || table_name ||'" OWNER TO my_new_owner;'
FROM information_schema.views WHERE NOT table_schema IN ('pg_catalog', 'information_schema')
ORDER BY table_schema, table_name;
Materialized Views
Based on this answer
SELECT 'ALTER TABLE '|| oid::regclass::text ||' OWNER TO my_new_owner;'
FROM pg_class WHERE relkind = 'm'
ORDER BY oid;
This generates all the required ALTER TABLE
/ ALTER SEQUENCE
/ ALTER VIEW
statements, copy these and paste them back into plsql to run them.
Check your work in psql by doing:
\dt *.*
\ds *.*
\dv *.*
Modifying the answer from @mre to get the list just from one command (valid at least for Docker Registry v2).
docker exec -it <your_registry_container_id> ls -a /var/lib/registry/docker/registry/v2/repositories/
It may be that the Windows Credential Manager is holding onto credentials for the network share.
Load up Credential Manager (the easiest way is perhaps just to Search for that in the Start Menu), see if there are any Windows Credentials for your network share, and try deleting/updating them.
Another way (a new way) to use named tuple is using NamedTuple from typing package: Type hints in namedtuple
Let's use the example of the top answer in this post to see how to use it.
(1) Before using the named tuple, the code is like this:
pt1 = (1.0, 5.0)
pt2 = (2.5, 1.5)
from math import sqrt
line_length = sqrt((pt1[0] - pt2[0])**2 + (pt1[1] - pt2[1])**2)
print(line_length)
(2) Now we use the named tuple
from typing import NamedTuple
inherit the NamedTuple class and define the variable name in the new class. test is the name of the class.
class test(NamedTuple):
x: float
y: float
create instances from the class and assign values to them
pt1 = test(1.0, 5.0) # x is 1.0, and y is 5.0. The order matters
pt2 = test(2.5, 1.5)
use the variables from the instances to calculate
line_length = sqrt((pt1.x - pt2.x)**2 + (pt1.y - pt2.y)**2)
print(line_length)
If what you want is to show with an alert() the content of an array of objects, i recomend you to define in the object the method toString() so with a simple alert(MyArray); the full content of the array will be shown in the alert.
Here is an example:
//-------------------------------------------------------------------
// Defininf the Point object
function Point(CoordenadaX, CoordenadaY) {
// Sets the point coordinates depending on the parameters defined
switch (arguments.length) {
case 0:
this.x = null;
this.y = null;
break;
case 1:
this.x = CoordenadaX;
this.y = null;
break;
case 2:
this.x = CoordenadaX;
this.y = CoordenadaY;
break;
}
// This adds the toString Method to the point object so the
// point can be printed using alert();
this.toString = function() {
return " (" + this.x + "," + this.y + ") ";
};
}
Then if you have an array of points:
var MyArray = [];
MyArray.push ( new Point(5,6) );
MyArray.push ( new Point(7,9) );
You can print simply calling:
alert(MyArray);
Hope this helps!
If your fingers default to CTRL-A CTRL-C
, then try the mappings from $VIMRUNTIME/mswin.vim
.
" CTRL-C and CTRL-Insert are Copy
vnoremap <C-C> "+y
" CTRL-A is Select all
noremap <C-A> gggH<C-O>G
inoremap <C-A> <C-O>gg<C-O>gH<C-O>G
cnoremap <C-A> <C-C>gggH<C-O>G
onoremap <C-A> <C-C>gggH<C-O>G
snoremap <C-A> <C-C>gggH<C-O>G
xnoremap <C-A> <C-C>ggVG
I have them mapped to <Leader><C-a>
and <Leader><C-c>
.
You need to update the output of json.load with a_dict and then dump the result. And you cannot append to the file but you need to overwrite it.
To work around this problem, use one of the following methods:
For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest() method instead of Response.End to bypass the code execution to the Application_EndRequest event.
For Response.Redirect, use an overload, Response.Redirect(String url, bool endResponse) that passes false for the endResponse parameter to suppress the internal call to Response.End. For example:
Response.Redirect ("nextpage.aspx", false);
If you use this workaround, the code that follows Response.Redirect is executed.For Server.Transfer, use the Server.Execute method instead.
If you use the Response.End, Response.Redirect, or Server.Transfer method, a ThreadAbortException exception occurs. You can use a try-catch statement to catch this exception.
The Response.End method ends the page execution and shifts the execution to the Application_EndRequest event in the application's event pipeline. The line of code that follows Response.End is not executed.
This problem occurs in the Response.Redirect and Server.Transfer methods because both methods call Response.End internally.
This behavior is by design.
Article ID: 312629 - Last Review: August 30, 2012 - Revision: 4.0
Applies to
- Microsoft ASP.NET 4.5
- Microsoft ASP.NET 4
- Microsoft ASP.NET 3.5
- Microsoft ASP.NET 2.0
- Microsoft ASP.NET 1.1
- Microsoft ASP.NET 1.0
Keywords: kbexcepthandling kbprb KB312629
Source: PRB: ThreadAbortException Occurs If You Use Response.End, Response.Redirect, or Server.Transfer
select column_name,* from information_schema.columns
where table_name = 'YourTableName'
order by ordinal_position
A good rule of thumb is for anything that you need to compare in the loop condition against something that is naturally a std::size_t
itself.
std::size_t
is the type of any sizeof
expression and as is guaranteed to be able to express the maximum size of any object (including any array) in C++. By extension it is also guaranteed to be big enough for any array index so it is a natural type for a loop by index over an array.
If you are just counting up to a number then it may be more natural to use either the type of the variable that holds that number or an int
or unsigned int
(if large enough) as these should be a natural size for the machine.
You could try sp_help <Name of object>
Try like this,
>>> s = set([1,2,3])
>>> s = list(s)
>>> s
[1, 2, 3]
>>> str = ', '.join(str(e) for e in s)
>>> str = 'set(%s)' % str
>>> str
'set(1, 2, 3)'
A while ago i wrote a detailed article about Hibernate key generators: http://blog.eyallupu.com/2011/01/hibernatejpa-identity-generators.html
Choosing the correct generator is a complicated task but it is important to try and get it right as soon as possible - a late migration might be a nightmare.
A little off topic but a good chance to raise a point usually overlooked which is sharing keys between applications (via API). Personally I always prefer surrogate keys and if I need to communicate my objects with other systems I don't expose my key (even though it is a surrogate one) – I use an additional ‘external key’. As a consultant I have seen more than once 'great' system integrations using object keys (the 'it is there let's just use it' approach) just to find a year or two later that one side has issues with the key range or something of the kind requiring a deep migration on the system exposing its internal keys. Exposing your key means exposing a fundamental aspect of your code to external constrains shouldn’t really be exposed to.
You can use format strings as well.
string time = DateTime.Now.ToString("hh:mm:ss"); // includes leading zeros
string date = DateTime.Now.ToString("dd/MM/yy"); // includes leading zeros
or some shortcuts if the format works for you
string time = DateTime.Now.ToShortTimeString();
string date = DateTime.Now.ToShortDateString();
Either should work.
Here is gradle console updates:
5:01 PM Gradle build finished in 1s 252ms
5:13 PM Executing tasks: [:app:assembleDebug]
5:13 PM Gradle build finished with 15 error(s) in 1s 125ms
5:15 PM Executing tasks: [:app:assembleDebug]
5:15 PM Gradle build finished with 13 error(s) in 1s 608ms
5:16 PM Executing tasks: [:app:assembleDebug]
.click
events only work when element gets rendered and are only attached to elements loaded when the DOM is ready.
.on
events are dynamically attached to DOM elements, which is helpful when you want to attach an event to DOM elements that are rendered on ajax request or something else (after the DOM is ready).
you could use binary search to find intervals of missing (or contiguous) numbers. The run time should be around (num intervals) * log(avg interval length) * N. Useful if there aren't many intervals.
Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order. you are selecting
t1.ID, t2.ReceivedDate from Table t1
union
t2.ID from Table t2
which is incorrect.
so you have to write
t1.ID, t1.ReceivedDate from Table t1 union t2.ID, t2.ReceivedDate from Table t1
you can use sub query here
SELECT tbl1.ID, tbl1.ReceivedDate FROM
(select top 2 t1.ID, t1.ReceivedDate
from tbl1 t1
where t1.ItemType = 'TYPE_1'
order by ReceivedDate desc
) tbl1
union
SELECT tbl2.ID, tbl2.ReceivedDate FROM
(select top 2 t2.ID, t2.ReceivedDate
from tbl2 t2
where t2.ItemType = 'TYPE_2'
order by t2.ReceivedDate desc
) tbl2
so it will return only distinct values by default from both table.
SHA doesn't require anything but an input to be applied, while AES requires at least 3 things - what you're encrypting/decrypting, an encryption key, and the initialization vector.
.img-responsive {
margin: 0 auto;
}
you can write like above code in your document so no need to add one another class in image tag.
use for each loop...
ArrayList<Character> al = new ArrayList<>();
String input="hello";
for (int i = 0; i < input.length(); i++){
al.add(input.charAt(i));
}
for (Character ch : al) {
System.Out.println(ch);
}
You can also check Restlet which has full client-side capabilities, more REST oriented that lower-level libraries such as HttpURLConnection or Apache HTTP Client (which we can leverage as connectors).
Best regards, Jerome Louvel
A lot of people here are suggesting to use the triangles, but sometimes you need a chevron.
We had a case where our button shows a chevron, and wanted the user's manual to refer to the button in a way which will be recognized by a non-technical user too. So we needed a chevron sign.
We used ? in the end. It is known as PRESENTATION FORM FOR VERTICAL RIGHT ANGLE BRACKET and its code is U+FE40.
Both if (one.length() > 0) {}
and if (!"".equals(one)) {}
will check against an empty foo parameter, and an empty parameter is what you'd get if the the form is submitted with no value in the foo
text field.
If there's any chance you can use the Expression Language to handle the parameter, you could
access it with empty param.foo
in an expression.
<c:if test='${not empty param.foo}'>
This page code gets rendered.
</c:if>
As of Rails 5, the rake
commandline tool has been aliased as rails
so now
rails db:reset
instead of rake db:reset
will work just as well
Chr(10)
is the Line Feed character and Chr(13)
is the Carriage Return character.
You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.
Historically, Line Feed would move down a line but not return to column 1:
This
is
a
test.
Similarly Carriage Return would return to column 1 but not move down a line:
This
is
a
test.
Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.
In Java 9, if you have an object which has another object as property and that nested objects has a method yielding a string, then you can use this construct to return an empty string if the embeded object is null :
String label = Optional.ofNullable(org.getDiffusion()).map(Diffusion::getLabel).orElse("")
In this example :
org
is an instance of an object of type Organism
Organism
has a Diffusion
property (another object)Diffusion
has a String label
property (and getLabel()
getter).With this example, if org.getDiffusion()
is not null, then it returns the getLabel
property of its Diffusion
object (this returns a String
). Otherwise, it returns an empty string.
Your command line should have a -d/--data inserted before the string you want to send in the PUT, and you want to set the Content-Type and not Accept.
curl -H 'Content-Type: application/json' -X PUT -d '[JSON]' \
http://example.com/service
Using the exact JSON data from the question, the full command line would become:
curl -H 'Content-Type: application/json' -X PUT \
-d '{"tags":["tag1","tag2"],
"question":"Which band?",
"answers":[{"id":"a0","answer":"Answer1"},
{"id":"a1","answer":"answer2"}]}' \
http://example.com/service
Note: JSON data wrapped only for readability, not valid for curl
request.
This question is pretty old already, but haven't seen anyone mentioning CutyCapt so I will :)
CutyCapt
CutyCapt is a small cross-platform command-line utility to capture WebKit's rendering of a web page into a variety of vector and bitmap formats, including SVG, PDF, PS, PNG, JPEG, TIFF, GIF, and BMP
If you are facing same problem as mine. Here is the solution which works for me.
If you get any error, type in command prompt
pip install module_name
I hope it will work for you too
listView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
return false;
}
});
Definitely does the trick.
SHORT ANSWER
How to do in your case:
int argument = 5; // example with int but could be another type
Mockito.when(mockMyAgent.otherMethod(Mockito.anyInt()).thenReturn(requiredReturnArg(argument));
LONG ANSWER
Actually what you want to do is possible, at least in Java 8. Maybe you didn't get this answer by other people because I am using Java 8 that allows that and this question is before release of Java 8 (that allows to pass functions, not only values to other functions).
Let's simulate a call to a DataBase query. This query returns all the rows of HotelTable that have FreeRoms = X and StarNumber = Y. What I expect during testing, is that this query will give back a List of different hotel: every returned hotel has the same value X and Y, while the other values and I will decide them according to my needs. The following example is simple but of course you can make it more complex.
So I create a function that will give back different results but all of them have FreeRoms = X and StarNumber = Y.
static List<Hotel> simulateQueryOnHotels(int availableRoomNumber, int starNumber) {
ArrayList<Hotel> HotelArrayList = new ArrayList<>();
HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Rome, 1, 1));
HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Krakow, 7, 15));
HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Madrid, 1, 1));
HotelArrayList.add(new Hotel(availableRoomNumber, starNumber, Athens, 4, 1));
return HotelArrayList;
}
Maybe Spy is better (please try), but I did this on a mocked class. Here how I do (notice the anyInt() values):
//somewhere at the beginning of your file with tests...
@Mock
private DatabaseManager mockedDatabaseManager;
//in the same file, somewhere in a test...
int availableRoomNumber = 3;
int starNumber = 4;
// in this way, the mocked queryOnHotels will return a different result according to the passed parameters
when(mockedDatabaseManager.queryOnHotels(anyInt(), anyInt())).thenReturn(simulateQueryOnHotels(availableRoomNumber, starNumber));
A small improvement from the accepted answer is to do the null check and also get full object.
public class DateComparator {
public static void main(String[] args) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
List<Employee> employees = new ArrayList<>();
employees.add(new Employee(1, "name1", addDays(new Date(), 1)));
employees.add(new Employee(2, "name2", addDays(new Date(), 3)));
employees.add(new Employee(3, "name3", addDays(new Date(), 6)));
employees.add(new Employee(4, "name4", null));
employees.add(new Employee(5, "name5", addDays(new Date(), 4)));
employees.add(new Employee(6, "name6", addDays(new Date(), 5)));
System.out.println(employees);
Date maxDate = employees.stream().filter(emp -> emp.getJoiningDate() != null).map(Employee::getJoiningDate).max(Date::compareTo).get();
System.out.println(format.format(maxDate));
//Comparator<Employee> comparator = (p1, p2) -> p1.getJoiningDate().compareTo(p2.getJoiningDate());
Comparator<Employee> comparator = Comparator.comparing(Employee::getJoiningDate);
Employee maxDatedEmploye = employees.stream().filter(emp -> emp.getJoiningDate() != null).max(comparator).get();
System.out.println(" maxDatedEmploye : " + maxDatedEmploye);
Employee minDatedEmployee = employees.stream().filter(emp -> emp.getJoiningDate() != null).min(comparator).get();
System.out.println(" minDatedEmployee : " + minDatedEmployee);
}
public static Date addDays(Date date, int days) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, days); // minus number would decrement the days
return cal.getTime();
}
}
You would get below results :
[Employee [empId=1, empName=name1, joiningDate=Wed Mar 21 13:33:09 EDT 2018],
Employee [empId=2, empName=name2, joiningDate=Fri Mar 23 13:33:09 EDT 2018],
Employee [empId=3, empName=name3, joiningDate=Mon Mar 26 13:33:09 EDT 2018],
Employee [empId=4, empName=name4, joiningDate=null],
Employee [empId=5, empName=name5, joiningDate=Sat Mar 24 13:33:09 EDT 2018],
Employee [empId=6, empName=name6, joiningDate=Sun Mar 25 13:33:09 EDT 2018]
]
2018-03-26
maxDatedEmploye : Employee [empId=3, empName=name3, joiningDate=Mon Mar 26 13:33:09 EDT 2018]
minDatedEmployee : Employee [empId=1, empName=name1, joiningDate=Wed Mar 21 13:33:09 EDT 2018]
Update : What if list itself is empty ?
Date maxDate = employees.stream().filter(emp -> emp.getJoiningDate() != null).map(Employee::getJoiningDate).max(Date::compareTo).orElse(new Date());
System.out.println(format.format(maxDate));
Comparator<Employee> comparator = Comparator.comparing(Employee::getJoiningDate);
Employee maxDatedEmploye = employees.stream().filter(emp -> emp.getJoiningDate() != null).max(comparator).orElse(null);
System.out.println(" maxDatedEmploye : " + maxDatedEmploye);
you can use -v option from cli, this facility is not available via Dockerfile
docker run -t -i -v <host_dir>:<container_dir> ubuntu /bin/bash
where host_dir is the directory from host which you want to mount. you don't need to worry about directory of container if it doesn't exist docker will create it.
If you do any changes in host_dir from host machine (under root privilege) it will be visible to container and vice versa.
I've just published an article about this exact issue at https://developers.google.com/web/updates/2017/06/play-request-was-interrupted that tells you exactly what is happening and how to fix it.
You can create a Pipe and use it wherever you want in your system.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
// tslint:disable-next-line:pipe-naming
name: 'toNumber',
pure: false }) export class ToNumberPipe implements PipeTransform {
public transform(items: any): any {
if (!items) {
return 0;
}
return parseInt(items, 10);
} }
In the HTML
{{ attr.text | toNumber }}
Remember to declare this Pipe to be accessfull in your modules file.
This may help you to reset your sa password for SQL 2008 and 2012
EXEC sp_password NULL, 'yourpassword', 'sa'
Find the local IP address of computer A and find the port that your website is running on. Then from computer B open a web browser and go to IP:port. Example: 192.168.1.5:80 if computer A's IP is 192.168.1.5 and your website is running on port 80
I stumble upon this question and it grabbed my interest. The accepted answer is completely correct, but I thought I do provide my findings at JVM byte code level to explain why the OP encounter the ClassCastException
.
I have the code which is pretty much the same as OP's code:
public static <T> T convertInstanceOfObject(Object o) {
try {
return (T) o;
} catch (ClassCastException e) {
return null;
}
}
public static void main(String[] args) {
String k = convertInstanceOfObject(345435.34);
System.out.println(k);
}
and the corresponding byte code is:
public static <T> T convertInstanceOfObject(java.lang.Object);
Code:
0: aload_0
1: areturn
2: astore_1
3: aconst_null
4: areturn
Exception table:
from to target type
0 1 2 Class java/lang/ClassCastException
public static void main(java.lang.String[]);
Code:
0: ldc2_w #3 // double 345435.34d
3: invokestatic #5 // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
6: invokestatic #6 // Method convertInstanceOfObject:(Ljava/lang/Object;)Ljava/lang/Object;
9: checkcast #7 // class java/lang/String
12: astore_1
13: getstatic #8 // Field java/lang/System.out:Ljava/io/PrintStream;
16: aload_1
17: invokevirtual #9 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
20: return
Notice that checkcast
byte code instruction happens in the main method not the convertInstanceOfObject
and convertInstanceOfObject
method does not have any instruction that can throw ClassCastException
. Because the main method does not catch the ClassCastException
hence when you execute the main method you will get a ClassCastException
and not the expectation of printing null
.
Now I modify the code to the accepted answer:
public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
try {
return clazz.cast(o);
} catch (ClassCastException e) {
return null;
}
}
public static void main(String[] args) {
String k = convertInstanceOfObject(345435.34, String.class);
System.out.println(k);
}
The corresponding byte code is:
public static <T> T convertInstanceOfObject(java.lang.Object, java.lang.Class<T>);
Code:
0: aload_1
1: aload_0
2: invokevirtual #2 // Method java/lang/Class.cast:(Ljava/lang/Object;)Ljava/lang/Object;
5: areturn
6: astore_2
7: aconst_null
8: areturn
Exception table:
from to target type
0 5 6 Class java/lang/ClassCastException
public static void main(java.lang.String[]);
Code:
0: ldc2_w #4 // double 345435.34d
3: invokestatic #6 // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
6: ldc #7 // class java/lang/String
8: invokestatic #8 // Method convertInstanceOfObject:(Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object;
11: checkcast #7 // class java/lang/String
14: astore_1
15: getstatic #9 // Field java/lang/System.out:Ljava/io/PrintStream;
18: aload_1
19: invokevirtual #10 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
22: return
Notice that there is an invokevirtual
instruction in the convertInstanceOfObject
method that calls Class.cast()
method which throws ClassCastException
which will be catch by the catch(ClassCastException e)
bock and return null
; hence, "null" is printed to console without any exception.
If none of the above answers work, you can run the test in IDE, get the class path and use it in your command. Ex: If you are using Intellij IDEA, you can find it at the top of the console(screenshot below).
Clicking on the highlighted part expands and displays the complete class path.
you need to remove the references to jars inside the folder: JetBrains\IntelliJ IDEA Community Edition 2019.1.3
java -cp "path_copied" org.testng.TestNG testng.xml
I just figured out a way to fix the alignment issue. Changing the width of div containing the static header will fix its alignment. The optimal width I found is 98%. Please refer to the code.
The auto generated div:
<div class="dataTables_scrollHead" style="overflow: hidden; position: relative; border: 0px none; width: 100%;">
Width here is 100%, change it to 98% on initializing and reloading the data table.
jQuery('#dashboard').dataTable({
"sEcho": "1",
"aaSorting": [[aasortvalue, 'desc']],
"bServerSide": true,
"sAjaxSource": "NF.do?method=loadData&Table=dashboardReport",
"bProcessing": true,
"sPaginationType": "full_numbers",
"sDom": "lrtip", // Add 'f' to add back in filtering
"bJQueryUI": false,
"sScrollX": "100%",
"sScrollY": "450px",
"iDisplayLength": '<%=recordCount%>',
"bScrollCollapse": true,
"bScrollAutoCss": true,
"fnInitComplete": function () {
jQuery('.dataTables_scrollHead').css('width', '98%'); //changing the width
},
"fnDrawCallback": function () {
jQuery('.dataTables_scrollHead').css('width', '98%');//changing the width
}
});
My approach was a mixture of things.
My objective was to have a grid adapting to the screen size. I wanted 3 columns for lg
, 2 columns for sm
and md
, and 1 column for xs
.
First, I created the following scope function, using angular $window
service:
$scope.findColNumberPerRow = function() {
var nCols;
var width = $window.innerWidth;
if (width < 768) {
// xs
nCols = 1;
}
else if(width >= 768 && width < 1200) {
// sm and md
nCols = 2
} else if (width >= 1200) {
// lg
nCols = 3;
}
return nCols;
};
Then, I used the class proposed by @Cumulo Nimbus:
.new-row {
clear: left;
}
In the div containing the ng-repeat
, I added the resizable
directive, as explained in this page, so that every time window is resized, angular $window
service is updated with the new values.
Ultimately, in the repeated div I have:
ng-repeat="user in users" ng-class="{'new-row': ($index % findColNumberPerRow() === 0) }"
Please, let me know any flaws in this approach.
Hope it can be helpful.
I know LOTS of people wouldn't agree, but this is what I do and I really enjoy such a coding style: I actually don't use any quote in HTML unless it is absolutely necessary.
Example:
<form method=post action=#>
<fieldset>
<legend>Register here: </legend>
<label for=account>Account: </label>
<input id=account type=text name=account required><br>
<label for=password>Password: </label>
<input id=password type=password name=password required><br>
...
Double quotes are used only when there are spaces in the attribute values or whatever:
<form class="val1 val2 val3" method=post action=#>
...
</form>
When signing into the server to execute the code use this instead:
ssh -X username@servername
the -X
will get rid of the no display name and no $DISPLAY environment variable
error
:)
__cplusplus
In C++0x the macro __cplusplus will be set to a value that differs from (is greater than) the current 199711L.
Use this Way in this circle image is also working + you have preloader also for network image:
new ClipRRect(
borderRadius: new BorderRadius.circular(30.0),
child: FadeInImage.assetNetwork(
placeholder:'asset/loader.gif',
image: 'Your Image Path',
),
)
Try this
for(int i = 0; i != 5; ++i, ++j)
do_something(i,j);
Call HttpURLConnection.setRequestMethod("POST")
and HttpURLConnection.setDoOutput(true);
Actually only the latter is needed as POST then becomes the default method.
This is pretty much what the generic method Value()
is for. You get exactly the behavior you want if you combine it with nullable value types and the ??
operator:
width = jToken.Value<double?>("width") ?? 100;
I suppose you're probably using the Decimal()
objects from the decimal
module? (If you need exactly two digits of precision beyond the decimal point with arbitrarily large numbers, you definitely should be, and that's what your question's title suggests...)
If so, the Decimal FAQ section of the docs has a question/answer pair which may be useful for you:
Q. In a fixed-point application with two decimal places, some inputs have many places and need to be rounded. Others are not supposed to have excess digits and need to be validated. What methods should be used?
A. The quantize() method rounds to a fixed number of decimal places. If the Inexact trap is set, it is also useful for validation:
>>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
>>> # Round to two places
>>> Decimal('3.214').quantize(TWOPLACES)
Decimal('3.21')
>>> # Validate that a number does not exceed two places
>>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Decimal('3.21')
>>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Traceback (most recent call last):
...
Inexact: None
The next question reads
Q. Once I have valid two place inputs, how do I maintain that invariant throughout an application?
If you need the answer to that (along with lots of other useful information), see the aforementioned section of the docs. Also, if you keep your Decimal
s with two digits of precision beyond the decimal point (meaning as much precision as is necessary to keep all digits to the left of the decimal point and two to the right of it and no more...), then converting them to strings with str
will work fine:
str(Decimal('10'))
# -> '10'
str(Decimal('10.00'))
# -> '10.00'
str(Decimal('10.000'))
# -> '10.000'
Remove the newline/linefeed characters (\n
with Notepad++). Excel will still recognise the carriage return character (\r
) to separate records.
As mentioned newline characters are supported inside CSV fields but Excel doesn't always handle them gracefully. I faced a similar issue with a third party CSV that possibly had encoding issues but didn't improve with encoding changes.
What worked for me was removing all newline characters (\n
). This has the effect of collapsing fields to a single record assuming that your records are separated by the combination of a carriage return and a newline (CR/LF). Excel will then properly import the file and recognise new records by the carriage return.
Obviously a cleaner solution is to first replace the real newlines (\r\n
) with a temporary character combination, replacing the newlines (\n
) with your seperating character of choice (e.g. comma in a semicolon file) and then replacing the temporary characters with proper newlines again.
Here is my solution for Keyboard dismissing and scrolling to tapped TextInput (I am using ScrollView with keyboardDismissMode prop):
import React from 'react';
import {
Platform,
KeyboardAvoidingView,
ScrollView
} from 'react-native';
const DismissKeyboard = ({ children }) => {
const isAndroid = Platform.OS === 'android';
const behavior = isAndroid ? false : 'padding';
return (
<KeyboardAvoidingView
enabled
behavior={ behavior }
style={{ flex: 1}}
>
<ScrollView
keyboardShouldPersistTaps={'always'}
keyboardDismissMode={'on-drag'}
>
{ children }
</ScrollView>
</KeyboardAvoidingView>
);
};
export default DismissKeyboard;
usage:
render(){
return(
<DismissKeyboard>
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1}}
onChangeText={(text) => this.setState({text})}
value={this.state.text}
/>
</DismissKeyboard>
);
}
You can also use package data.table and it's Like function, details given below How to select R data.table rows based on substring match (a la SQL like)
For good performance, combine answers from aznilamir and from FrustratedWithFormsDesigner
private static final String BLANKS = " ";
private static String getBlankLine( int length )
{
if( length <= BLANKS.length() )
{
return BLANKS.substring( 0, length );
}
else
{
char[] array = new char[ length ];
Arrays.fill( array, ' ' );
return new String( array );
}
}
Adjust size of BLANKS
depending on your requirements. My specific BLANKS
string is about 200 characters length.
You might not have the ability to install Expect on the target server. This is often the case when one writes, say, a Jenkins job.
If so, I would consider something like the answer to the following on askubuntu.com:
https://askubuntu.com/questions/338857/automatically-enter-input-in-command-line
printf 'y\nyes\nno\nmaybe\n' | ./script_that_needs_user_input
Note that in some rare cases the command does not require the user to press enter after the character. in that case leave the newlines out:
printf 'yyy' | ./script_that_needs_user_input
For sake of completeness you can also use a here document:
./script_that_needs_user_input << EOF
y
y
y
EOF
Or if your shell supports it a here string:
./script <<< "y
y
y
"
Or you can create a file with one input per line:
./script < inputfile
Again, all credit for this answer goes to the author of the answer on askubuntu.com, lesmana.
I think this solution uses less code and is easy to understand even for newbie.
For string field in struct, you can use pointer and reassigning the string to that pointer will be straightforward and simpler.
Define definition of struct:
typedef struct {
int number;
char *name;
char *address;
char *birthdate;
char gender;
} Patient;
Initialize variable with type of that struct:
Patient patient;
patient.number = 12345;
patient.address = "123/123 some road Rd.";
patient.birthdate = "2020/12/12";
patient.gender = "M";
It is that simple. Hope this answer helps many developers.
Try \vspace{-5mm}
before the itemize.
If I'm not using any category then how can I use this code? Actually, I want to use this code for custom post type.
Latest findings...
https://gist.github.com/luislavena/f064211759ee0f806c88
Most importantly...download https://raw.githubusercontent.com/rubygems/rubygems/master/lib/rubygems/ssl_certs/rubygems.org/AddTrustExternalCARoot-2048.pem
Figure out where to stick it
C:\>gem which rubygems
C:/Ruby21/lib/ruby/2.1.0/rubygems.rb
Then just copy the .pem file in ../2.1.0/rubygems/ssl_certs/ and go on about your business.
Instead of directly comparing the strings (VB won't find them equal since GetEnvironmentVariable returns a string of length 255) write this:
Private Sub Workbook_Open()
If InStr(1, GetEnvironmentVariable("InBatch"), "TRUE", vbTextCompare) Then
Debug.Print "Batch"
Call Macro
Else
Debug.Print "Normal"
End If
End Sub
You need to use the string concatenation operator +
String both = name + "-" + dest;
You can try this regular expression : [^\W\d_]
or [a-zA-Z]
.
You can also do git push -u origin $(current_branch)
The actual information represented by a boolean value in Java is one bit: 1 for true, 0 for false. However, the actual size of a boolean variable in memory is not precisely defined by the Java specification. See Primitive Data Types in Java.
The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.
Thanks for your feed back got it to work I used the sshpass tool.
sshpass -p 'password' scp [email protected]:sys_config /var/www/dev/
If this android:divider="@null"
doesn't work, maybe changing your ListViews for Recycler Views?
The following code did it for me to make a shadow inset of the right side:
-moz-box-shadow: inset -10px 0px 10px -10px #000;
-webkit-box-shadow: inset -10px 0px 10px -10px #000;
box-shadow: inset -10px 0px 10px -10px #000;
Hope it will help!!!!
:: =============================================================
:: Batch file to display Date and Time seprated by undescore.
:: =============================================================
:: Read the system date.
:: =============================================================
@SET MyDate=%DATE%
@SET MyDate=%MyDate:/=:%
@SET MyDate=%MyDate:-=:%
@SET MyDate=%MyDate: =:%
@SET MyDate=%MyDate:\=:%
@SET MyDate=%MyDate::=_%
:: =============================================================
:: Read the system time.
:: =============================================================
@SET MyTime=%TIME%
@SET MyTime=%MyTime: =0%
@SET MyTime=%MyTime:.=:%
@SET MyTime=%MyTime::=_%
:: =============================================================
:: Build the DateTime string.
:: =============================================================
@SET DateTime=%MyDate%_%MyTime%
:: =============================================================
:: Display the Date and Time as it is now.
:: =============================================================
@ECHO MyDate="%MyDate%" MyTime="%MyTime%" DateTime="%DateTime%"
:: =============================================================
:: Wait before close.
:: =============================================================
@PAUSE
:: =============================================================
SELECT ...
SELECT SLEEP(5);
SELECT ...
But what are you using this for? Are you trying to circumvent/reinvent mutexes or transactions?
Another way is configuring ~/.curlrc
like this
-w "\n\n==== cURL measurements stats ====\ntotal: %{time_total} seconds \nsize: %{size_download} bytes \ndnslookup: %{time_namelookup} seconds \nconnect: %{time_connect} seconds \nappconnect: %{time_appconnect} seconds \nredirect: %{time_redirect} seconds \npretransfer: %{time_pretransfer} seconds \nstarttransfer: %{time_starttransfer} seconds \ndownloadspeed: %{speed_download} byte/sec \nuploadspeed: %{speed_upload} byte/sec \n\n"
So the output of curl
is
?? curl -I https://google.com
HTTP/2 301
location: https://www.google.com/
content-type: text/html; charset=UTF-8
date: Mon, 04 Mar 2019 08:02:43 GMT
expires: Wed, 03 Apr 2019 08:02:43 GMT
cache-control: public, max-age=2592000
server: gws
content-length: 220
x-xss-protection: 1; mode=block
x-frame-options: SAMEORIGIN
alt-svc: quic=":443"; ma=2592000; v="44,43,39"
==== cURL measurements stats ====
total: 0.211117 seconds
size: 0 bytes
dnslookup: 0.067179 seconds
connect: 0.098817 seconds
appconnect: 0.176232 seconds
redirect: 0.000000 seconds
pretransfer: 0.176438 seconds
starttransfer: 0.209634 seconds
downloadspeed: 0.000 byte/sec
uploadspeed: 0.000 byte/sec
Firstly, you can not shift a byte
in java, you can only shift an int
or a long
. So the byte
will undergo promotion first, e.g.
00101011
-> 00000000000000000000000000101011
or
11010100
-> 11111111111111111111111111010100
Now, x >> N
means (if you view it as a string of binary digits):
00000000000000000000000000101011 >> 2
-> 00000000000000000000000000001010
11111111111111111111111111010100 >> 2
-> 11111111111111111111111111110101
I am trying to set a div to a certain percentage height in CSS
Percentage of what?
To set a percentage height, its parent element(*) must have an explicit height. This is fairly self-evident, in that if you leave height as auto
, the block will take the height of its content... but if the content itself has a height expressed in terms of percentage of the parent you've made yourself a little Catch 22. The browser gives up and just uses the content height.
So the parent of the div must have an explicit height
property. Whilst that height can also be a percentage if you want, that just moves the problem up to the next level.
If you want to make the div height a percentage of the viewport height, every ancestor of the div, including <html>
and <body>
, have to have height: 100%
, so there is a chain of explicit percentage heights down to the div.
(*: or, if the div is positioned, the ‘containing block’, which is the nearest ancestor to also be positioned.)
Alternatively, all modern browsers and IE>=9 support new CSS units relative to viewport height (vh
) and viewport width (vw
):
div {
height:100vh;
}
See here for more info.
You can use the git show
command.
To get the last commit date from git repository in a long(Unix epoch timestamp):
git show -s --format=%ct
1605103148
Note: You can visit the git-show documentation to get a more detailed description of the options.
For more detailed textual output, please try:
git log --graph --date-order -C -M --pretty=format:"<%h> %ad [%an] %Cgreen%d%Creset %s" --all --date=short
You can write alias in $HOME/.gitconfig
[alias]
graph = log --graph --date-order -C -M --pretty=format:\"<%h> %ad [%an] %Cgreen%d%Creset %s\" --all --date=short
It seems you have found your solution, but still it will be helpful to others, on this page on point based on Chrome 59.
4.Note the red triangle in the top-right of the Animation Frame Fired event. Whenever you see a red triangle, it's a warning that there may be an issue related to this event.
If you hover on these triangle you can see those are the violation handler errors and as per point 4. yes there is some issue related to that event.
I think restful authentication involves the passing of an authentication token as a parameter in the request. Examples are the use of apikeys by api's. I don't believe the use of cookies or http auth qualifies.
Well, for starters, a struct is passed by value rather than by reference. Structs are good for relatively simple data structures, while classes have a lot more flexibility from an architectural point of view via polymorphism and inheritance.
Others can probably give you more detail than I, but I use structs when the structure that I am going for is simple.
FlatButton(
onPressed: null,
child: Text('Button', style: TextStyle(
color: Colors.blue
)
),
textColor: MyColor.white,
shape: RoundedRectangleBorder(side: BorderSide(
color: Colors.blue,
width: 1,
style: BorderStyle.solid
), borderRadius: BorderRadius.circular(50)),
)
@Mike On Mac, type this in Terminal:
open -b com.google.chrome --args --disable-web-security
The syntax of ng-style
is not quite that. It accepts a dictionary of keys (attribute names) and values (the value they should take, an empty string unsets them) rather than only a string. I think what you want is this:
<div ng-style="{ 'width' : width, 'background' : bgColor }"></div>
And then in your controller:
$scope.width = '900px';
$scope.bgColor = 'red';
This preserves the separation of template and the controller: the controller holds the semantic values while the template maps them to the correct attribute name.
I think this way should be faster; cause it doesn't split string and join it again; just using regex.
var str = text.replace(/(^\w{1})|(\s{1}\w{1})/g, match => match.toUpperCase());
Explanation:
(^\w{1})
: match first char of string|
: or (\s{1}\w{1})
: match one char that came after one spaceg
: match allAnother dirty but working workaround. Assumes you are on top level of your package.
import sys
from os.path import dirname, basename
if __package__ is None:
sys.path.append('..')
__package__ = basename(dirname(sys.argv[0]))
from . import your_module
The advantage vs another answer here is that you don't need to change imports which are autogenerated by IDE.
This is an example to read and write binary jjpg or wmv video file. FILE *fout; FILE *fin;
Int ch;
char *s;
fin=fopen("D:\\pic.jpg","rb");
if(fin==NULL)
{ printf("\n Unable to open the file ");
exit(1);
}
fout=fopen("D:\\ newpic.jpg","wb");
ch=fgetc(fin);
while (ch!=EOF)
{
s=(char *)ch;
printf("%c",s);
ch=fgetc (fin):
fputc(s,fout);
s++;
}
printf("data read and copied");
fclose(fin);
fclose(fout);
Here is what worked for me (sugested by soulBit):
1) Restart using restart from the file menu
2) Once it started again, manually close and open it.
This is the simplest solution ever and it completely removes the annoying thing.
jQuery Mobile has a datepicker too. Source
Just include the following files,
<script src="jQuery.ui.datepicker.js"></script>
<script src="jquery.ui.datepicker.mobile.js"></script>
This XML file does not appear to have any style information associated with it. The document tree is shown below.
You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml
instead of text/html
and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.
In case of JSF/Facelets files which have the default extension of .xhtml
, that can in turn happen if the HTTP request hasn't invoked the FacesServlet
and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml
file extension which is in your Firefox configuration apparently by default interpreted as text/xml
.
You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern>
of the FacesServlet
as registered in webapp's web.xml
, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf
, then you need to open the page by /some.jsf
instead of /some.xhtml
. Alternatively, you can also just change the <url-pattern>
to *.xhtml
. This way you never need to fiddle with virtual URLs.
Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.
Tightly coupled code relies on a concrete implementation. If I need a list of strings in my code and I declare it like this (in Java)
ArrayList<String> myList = new ArrayList<String>();
then I'm dependent on the ArrayList implementation.
If I want to change that to loosely coupled code, I make my reference an interface (or other abstract) type.
List<String> myList = new ArrayList<String>();
This prevents me from calling any method on myList
that's specific to the ArrayList implementation. I'm limited to only those methods defined in the List interface. If I decide later that I really need a LinkedList, I only need to change my code in one place, where I created the new List, and not in 100 places where I made calls to ArrayList methods.
Of course, you can instantiate an ArrayList using the first declaration and restrain yourself from not using any methods that aren't part of the List interface, but using the second declaration makes the compiler keep you honest.
Control Panel -> System -> Advanced system settings -> Environment Variables
I changed JAVA_HOME to JAVA and again changed JAVA to JAVA_HOME.
and Its working fine.
Use the source, Luke!
In CPython, range(...).__contains__
(a method wrapper) will eventually delegate to a simple calculation which checks if the value can possibly be in the range. The reason for the speed here is we're using mathematical reasoning about the bounds, rather than a direct iteration of the range object. To explain the logic used:
start
and stop
, andFor example, 994
is in range(4, 1000, 2)
because:
4 <= 994 < 1000
, and(994 - 4) % 2 == 0
.The full C code is included below, which is a bit more verbose because of memory management and reference counting details, but the basic idea is there:
static int
range_contains_long(rangeobject *r, PyObject *ob)
{
int cmp1, cmp2, cmp3;
PyObject *tmp1 = NULL;
PyObject *tmp2 = NULL;
PyObject *zero = NULL;
int result = -1;
zero = PyLong_FromLong(0);
if (zero == NULL) /* MemoryError in int(0) */
goto end;
/* Check if the value can possibly be in the range. */
cmp1 = PyObject_RichCompareBool(r->step, zero, Py_GT);
if (cmp1 == -1)
goto end;
if (cmp1 == 1) { /* positive steps: start <= ob < stop */
cmp2 = PyObject_RichCompareBool(r->start, ob, Py_LE);
cmp3 = PyObject_RichCompareBool(ob, r->stop, Py_LT);
}
else { /* negative steps: stop < ob <= start */
cmp2 = PyObject_RichCompareBool(ob, r->start, Py_LE);
cmp3 = PyObject_RichCompareBool(r->stop, ob, Py_LT);
}
if (cmp2 == -1 || cmp3 == -1) /* TypeError */
goto end;
if (cmp2 == 0 || cmp3 == 0) { /* ob outside of range */
result = 0;
goto end;
}
/* Check that the stride does not invalidate ob's membership. */
tmp1 = PyNumber_Subtract(ob, r->start);
if (tmp1 == NULL)
goto end;
tmp2 = PyNumber_Remainder(tmp1, r->step);
if (tmp2 == NULL)
goto end;
/* result = ((int(ob) - start) % step) == 0 */
result = PyObject_RichCompareBool(tmp2, zero, Py_EQ);
end:
Py_XDECREF(tmp1);
Py_XDECREF(tmp2);
Py_XDECREF(zero);
return result;
}
static int
range_contains(rangeobject *r, PyObject *ob)
{
if (PyLong_CheckExact(ob) || PyBool_Check(ob))
return range_contains_long(r, ob);
return (int)_PySequence_IterSearch((PyObject*)r, ob,
PY_ITERSEARCH_CONTAINS);
}
The "meat" of the idea is mentioned in the line:
/* result = ((int(ob) - start) % step) == 0 */
As a final note - look at the range_contains
function at the bottom of the code snippet. If the exact type check fails then we don't use the clever algorithm described, instead falling back to a dumb iteration search of the range using _PySequence_IterSearch
! You can check this behaviour in the interpreter (I'm using v3.5.0 here):
>>> x, r = 1000000000000000, range(1000000000000001)
>>> class MyInt(int):
... pass
...
>>> x_ = MyInt(x)
>>> x in r # calculates immediately :)
True
>>> x_ in r # iterates for ages.. :(
^\Quit (core dumped)
When you have an assignment operator in a statement, the LHS of the operator must be something the language calls an lvalue. If the LHS of the operator does not evaluate to an lvalue, the value from the RHS cannot be assigned to the LHS.
You cannot use:
10 = 20;
since 10
does not evaluate to an lvalue.
You can use:
int i;
i = 20;
since i
does evaluate to an lvalue.
You cannot use:
int i;
i + 1 = 20;
since i + 1
does not evaluate to an lvalue.
In your case, p + 1
does not evaluate to an lavalue. Hence, you cannot use
p + 1 = p;
I know the OP is asking about international country codes but for North America, you could use the following:
<a href="tel:+1-847-555-5555">1-847-555-5555</a>
<a href="tel:+18475555555">Click Here To Call Support 1-847-555-5555</a>
_x000D_
This might help you.
Add "android-support-v7-appcompat.jar" to Android Private Libraries
JSONArray jsonArray = new JSONArray(yourJsonString);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj1 = jsonArray.getJSONObject(i);
JSONArray results = patient.getJSONArray("results");
String indexForPhone = patientProfile.getJSONObject(0).getString("indexForPhone"));
}
Change to JSONArray, then convert to JSONObject.
useState
Use defaultValue
to select the default value.
const statusOptions = [
{ value: 1, label: 'Publish' },
{ value: 0, label: 'Unpublish' }
];
const [statusValue, setStatusValue] = useState('');
const handleStatusChange = e => {
setStatusValue(e.value);
}
return(
<>
<Select options={statusOptions}
defaultValue={[{ value: published, label: published == 1 ? 'Publish' : 'Unpublish' }]}
onChange={handleStatusChange}
value={statusOptions.find(obj => obj.value === statusValue)} required />
</>
)
Try this:
<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />
Use File.ReadAllText passing file location as an argument.
However, if your real goal is to parse html then I would recommend using Html Agility Pack.
I also got this error many times and I solved it. This error will be faced in case of memory management in native side.
Your application is accessing memory outside of its address space. This is most likely an invalid pointer access. SIGSEGV = segmentation fault in native code. Since it is not occurring in Java code you won't see a stack trace with details. However, you may still see some stack trace information in the logcat if you look around a bit after the application process crashes. It will not tell you the line number within the file, but will tell you which object files and addresses were in use in the call chain. From there you can often figure out which area of the code is problematic. You can also setup a gdb native connection to the target process and catch it in the debugger.
Import datetime and timedelta:
>>> from datetime import datetime, timedelta
>>> str(datetime.now() + timedelta(hours=9))[11:19]
'01:41:44'
But the better way is:
>>> (datetime.now() + timedelta(hours=9)).strftime('%H:%M:%S')
'01:42:05'
You can refer strptime
and strftime
behavior to better understand how python processes dates and time field
You can insert an image that looks like a button. Then attach a script to the image.
You can insert any image. The image can be edited in the spreadsheet
Image of a Button
Assign a function name to an image:
This just works:
$body = @{
"UserSessionId"="12345678"
"OptionalEmail"="[email protected]"
} | ConvertTo-Json
$header = @{
"Accept"="application/json"
"connectapitoken"="97fe6ab5b1a640909551e36a071ce9ed"
"Content-Type"="application/json"
}
Invoke-RestMethod -Uri "http://MyServer/WSVistaWebClient/RESTService.svc/member/search" -Method 'Post' -Body $body -Headers $header | ConvertTo-HTML
SWIFT 4.2
func reloadYourRows(name: <anyname>) {
let row = <your array name>.index(of: <name passing in>)
let reloadPath = IndexPath(row: row!, section: 0)
tableView.reloadRows(at: [reloadPath], with: .middle)
}
We just open-sourced this jquery plug-in Github: tactivos/jquery-sew.
If you get this error when you try to pipe/redirect output of your script
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)
Just export PYTHONIOENCODING in console and then run your code.
export PYTHONIOENCODING=utf8
I also had the same issue. I changed it to the following and it worked.
Java :
@RequestMapping(value = "/test", method = RequestMethod.GET)
HTML code:
<form action="<%=request.getContextPath() %>/test" method="GET">
<input type="submit" value="submit">
</form>
By default if you do not specify http method in a form it uses GET. To use POST method you need specifically state it.
Hope this helps.
Use map.panTo();
does not do anything if the point is in the current view. Use map.setView()
instead.
I had a polyline and I had to center map to a new point in polyline at every second. Check the code : GOOD: https://jsfiddle.net/nstudor/xcmdwfjk/
mymap.setView(point, 11, { animation: true });
BAD: https://jsfiddle.net/nstudor/Lgahv905/
mymap.panTo(point);
mymap.setZoom(11);