content
doesn't support HTML, only text. You should probably use javascript, jQuery or something like that.
Another problem with your code is "
inside a "
block. You should mix '
and "
(class='headingDetail'
).
If content
did support HTML you could end up in an infinite loop where content
is added inside content
.
Go to the root of the project using terminal and then paste the below mentioned line
rm -rf ~/Library/Developer/Xcode/DerivedData
Once it is executed, you can verify by going to Xcode > Preference > Locations -> Tap arrow shows ["DeriveData"] end point.
From the shell command line:
python file.py
From the Python command line
import file
or
from file import *
Problem was apparently not the SQL server, but the NAV system that updates the field. There is a compression property that can be used on BLOB fields in NAV, that is not a part of SQL Server. So the custom compression made the data unreadable, though the conversion worked.
The solution was to turn off compression through the Object Designer, Table Designer, Properties for the field (Shift+F4 on the field row).
After that the extraction of data can be made with e.g.: select convert(varchar(max), cast(BLOBFIELD as binary)) from Table
Thanks for all answers that were correct in many ways!
iPad Media Queries (All generations - including iPad mini)
Thanks to Apple's work in creating a consistent experience for users, and easy time for developers, all 5 different iPads (iPads 1-5 and iPad mini) can be targeted with just one CSS media query. The next few lines of code should work perfect for a responsive design.
iPad in portrait & landscape
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px) { /* STYLES GO HERE */}
iPad in landscape
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape) { /* STYLES GO HERE */}
iPad in portrait
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait) { /* STYLES GO HERE */ }
iPad 3 & 4 Media Queries
If you're looking to target only 3rd and 4th generation Retina iPads (or tablets with similar resolution) to add @2x graphics, or other features for the tablet's Retina display, use the following media queries.
Retina iPad in portrait & landscape
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */}
Retina iPad in landscape
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */}
Retina iPad in portrait
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */ }
iPad 1 & 2 Media Queries
If you're looking to supply different graphics or choose different typography for the lower resolution iPad display, the media queries below will work like a charm in your responsive design!
iPad 1 & 2 in portrait & landscape
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (-webkit-min-device-pixel-ratio: 1){ /* STYLES GO HERE */}
iPad 1 & 2 in landscape
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 1) { /* STYLES GO HERE */}
iPad 1 & 2 in portrait
@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px)
and (orientation : portrait)
and (-webkit-min-device-pixel-ratio: 1) { /* STYLES GO HERE */ }
Source: http://stephen.io/mediaqueries/
You should be able to call print("yo!") since there is a constructor for std::string which takes a const char*. These single argument constructors define implicit conversions from their aguments to their class type (unless the constructor is declared explicit which is not the case for std::string). Have you actually tried to compile this code?
void print(std::string input)
{
cout << input << endl;
}
int main()
{
print("yo");
}
It compiles fine for me in GCC. However, if you declared print like this void print(std::string& input)
then it would fail to compile since you can't bind a non-const reference to a temporary (the string would be a temporary constructed from "yo")
You can use ax.figure.savefig()
, as suggested in a comment on the question:
import pandas as pd
df = pd.DataFrame([0, 1])
ax = df.plot.line()
ax.figure.savefig('demo-file.pdf')
This has no practical benefit over ax.get_figure().savefig()
as suggested in other answers, so you can pick the option you find the most aesthetically pleasing. In fact, get_figure()
simply returns self.figure
:
# Source from snippet linked above
def get_figure(self):
"""Return the `.Figure` instance the artist belongs to."""
return self.figure
The below code worked for me :)
window.open('your current page URL', '_self', '');
window.close();
If you already know the filename
, you can use the boto3
builtin download_fileobj
import boto3
from io import BytesIO
session = boto3.Session()
s3_client = session.client("s3")
f = BytesIO()
s3_client.download_fileobj(bucket_name, filename, f)
f.seek(0)
print(f.getvalue())
First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.
For example,
> z <- factor(letters[c(3, 2, 3, 4)])
# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d
# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"
here, z
has 4 elements.
The index is 2, 1, 2, 3
in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.
Then, as.numeric
converts simply the index part of factor into numeric.
as.character
handles the index and levels, and generates character vector expressed by its level.
?as.numeric
says that Factors are handled by the default method.
To answer this point:
I want Sleep to be an async method so it can await other methods
you can maybe rewrite the Sleep
function like this:
private static async Task<int> Sleep(int ms)
{
Console.WriteLine("Sleeping for " + ms);
var task = Task.Run(() => Thread.Sleep(ms));
await task;
Console.WriteLine("Sleeping for " + ms + "END");
return ms;
}
static void Main(string[] args)
{
Console.WriteLine("Starting");
var task1 = Sleep(2000);
var task2 = Sleep(1000);
int totalSlept = task1.Result +task2.Result;
Console.WriteLine("Slept for " + totalSlept + " ms");
Console.ReadKey();
}
running this code will output :
Starting
Sleeping for 2000
Sleeping for 1000
*(one second later)*
Sleeping for 1000END
*(one second later)*
Sleeping for 2000END
Slept for 3000 ms
Use std::make_pair
:
revenue.push_back(std::make_pair("string",map[i].second));
In 2020, you can use css snap, but before Chrome 81 the layout change will not trigger re-snap, a pure css chat ui works on Chrome 81, also you can check Can I use CSS snap.
This demo will snap the last element if visible, scroll to bottom to see the effect.
.container {
overflow-y: scroll;
overscroll-behavior-y: contain;
scroll-snap-type: y proximity;
}
.container > div > div:last-child {
scroll-snap-align: end;
}
.container > div > div {
background: lightgray;
height: 3rem;
font-size: 1.5rem;
}
.container > div > div:nth-child(2n) {
background: gray;
}
_x000D_
<div class="container" style="height:6rem">
<div>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
</div>
_x000D_
EDIT
use scroll-snap-type: y proximity;
, scroll up easier.
First off target refers to the BlockID found in either HTML code or chromes developer tools that you are trying to link to. Each code is different and you will need to do some digging to find the ID you are trying to reference. It should look something like div class="page-container drawer-page-content" id"PageContainer"
Note that this is the format for the whole referenced section, not an individual text or image. To do that you would need to find the same piece of code but relating to your target block. For example dv id="your-block-id"
Anyways I was just reading over this thread and an idea came to my mind, if you are a Shopify user and want to do this it is pretty much the same thing as stated.
But instead of
> http://url.to.site/index.html#target
You would put
> http://storedomain.com/target
For example, I am setting up a disclaimer page with links leading to a newsletter signup and shopping blocks on my home page so I insert https://mystore-classifier.com/#shopify-section-1528945200235
for my hyperlink.
Please note that the -classifier is for my internal use and doesn't apply to you. This is just so I can keep track of my stores.
If you want to link to something other than your homepage you would put
> http://mystore-classifier.com/pagename/#BlockID
I hope someone found this useful, if there is something wrong with my explanation please let me know as I am not an HTML programmer my language is C#!
Spent two hours trying all solutions mentioned above.
This is what finally worked for me:
var vid = document.getElementById("myVideo");
vid.muted = true;
A browser request "127.0.0.1/somefile.html" arrives unchanged to the local webserver, while "localhost/somefile.html" may arrive as "0:0:0:0:0:0:0:1/somefile.html" if IPv6 is supported. So the latter can be processed as going from a domain to another.
XML is easy to use, via serialization. Use Isolated storage.
See also How to decide where to store per-user state? Registry? AppData? Isolated Storage?
public class UserDB
{
// actual data to be preserved for each user
public int A;
public string Z;
// metadata
public DateTime LastSaved;
public int eon;
private string dbpath;
public static UserDB Load(string path)
{
UserDB udb;
try
{
System.Xml.Serialization.XmlSerializer s=new System.Xml.Serialization.XmlSerializer(typeof(UserDB));
using(System.IO.StreamReader reader= System.IO.File.OpenText(path))
{
udb= (UserDB) s.Deserialize(reader);
}
}
catch
{
udb= new UserDB();
}
udb.dbpath= path;
return udb;
}
public void Save()
{
LastSaved= System.DateTime.Now;
eon++;
var s= new System.Xml.Serialization.XmlSerializer(typeof(UserDB));
var ns= new System.Xml.Serialization.XmlSerializerNamespaces();
ns.Add( "", "");
System.IO.StreamWriter writer= System.IO.File.CreateText(dbpath);
s.Serialize(writer, this, ns);
writer.Close();
}
}
I know its already accepted, but for thoses like me who look for "remove ALL whitespaces" (not just at the begining and endingof the string):
select SUBSTRING_INDEX('1234 243', ' ', 1);
// returns '1234'
EDIT 2019/6/20 : Yeah, that's not good. The function returns the part of the string since "when the character space occured for the first time". So, I guess that saying this remove the leading and trailling whitespaces and returns the first word :
select SUBSTRING_INDEX(TRIM(' 1234 243'), ' ', 1);
You need to add playsinline autoplay muted loop
, chrome do not allow a video to autostart if it is not muted, also right now I dont know why it is not working in all android devices, im trying to look if it's a version specific, If I found something I'll let you know
Chrome issue: After some research i have found that it doesnt work on chrome sometimes because in responsive you can activate the data saver, and it blocks any video to autostart
This code works perfectly well:
Actions builder = new Actions(driver);
WebElement element = driver.findElement(By.linkText("Put your text here"));
builder.moveToElement(element).build().perform();
After the mouse over, you can then go on to perform the next action you want on the revealed information
I had a similar problem and just found a way to solve it (by single-stepping through log4j-extras
source, no less...)
The good news is that, unlike what's written everywhere, it turns out that you actually CAN configure TimeBasedRollingPolicy using log4j.properties (XML config not needed! At least in versions of log4j >1.2.16 see this bug report)
Here is an example:
log4j.appender.File = org.apache.log4j.rolling.RollingFileAppender
log4j.appender.File.rollingPolicy = org.apache.log4j.rolling.TimeBasedRollingPolicy
log4j.appender.File.rollingPolicy.FileNamePattern = logs/worker-${instanceId}.%d{yyyyMMdd-HHmm}.log
BTW the ${instanceId}
bit is something I am using on Amazon's EC2 to distinguish the logs from all my workers -- I just need to set that property before calling PropertyConfigurator.configure()
, as follow:
p.setProperty("instanceId", EC2Util.getMyInstanceId());
PropertyConfigurator.configure(p);
No, enums are supposed to be a complete static enumeration.
At compile time, you might want to generate your enum .java file from another source file of some sort. You could even create a .class file like this.
In some cases you might want a set of standard values but allow extension. The usual way to do this is have an interface
for the interface and an enum
that implements that interface
for the standard values. Of course, you lose the ability to switch
when you only have a reference to the interface
.
Let's take an example: You want to contribute to django, so you fork its repository. In the while you work on your feature, there is much work done on the original repo by other people. So the code you forked is not the most up to date. setting a remote upstream and fetching it time to time makes sure your forked repo is in sync with the original repo.
This still loops through the cartesian product of the two lists, but it does it one line:
>>> lines1 = ['soup', 'butter', 'venison']
>>> lines2 = ['prune', 'rye', 'turkey']
>>> search_strings = ['a', 'b', 'c']
>>> any(s in l for l in lines1 for s in search_strings)
True
>>> any(s in l for l in lines2 for s in search_strings)
False
This also have the advantage that any
short-circuits, and so the looping stops as soon as a match is found. Also, this only finds the first occurrence of a string from search_strings
in linesX
. If you want to find multiple occurrences you could do something like this:
>>> lines3 = ['corn', 'butter', 'apples']
>>> [(s, l) for l in lines3 for s in search_strings if s in l]
[('c', 'corn'), ('b', 'butter'), ('a', 'apples')]
If you feel like coding something more complex, it seems the Aho-Corasick algorithm can test for the presence of multiple substrings in a given input string. (Thanks to Niklas B. for pointing that out.) I still think it would result in quadratic performance for your use-case since you'll still have to call it multiple times to search multiple lines. However, it would beat the above (cubic, on average) algorithm.
The answer is to DISABLE "Enable auto-completion on each input". Tested and works perfectly.
You might find some help on migrating SVN repositories in Chapter 5. Repository Administration, Migrating a repository.
This approach requires access to svnadmin.
This is untested but will probably work.
In your .htaccess file put:
<Files ~ "\.html?$">
Header set Content-Type "text/html; charset=utf-8"
</Files>
However, this will require mod_headers on the server.
new Buffer(number) // Old
Buffer.alloc(number) // New
new Buffer(string) // Old
Buffer.from(string) // New
new Buffer(string, encoding) // Old
Buffer.from(string, encoding) // New
new Buffer(...arguments) // Old
Buffer.from(...arguments) // New
Note that Buffer.alloc() is also faster on the current Node.js versions than new Buffer(size).fill(0), which is what you would otherwise need to ensure zero-filling.
You could detect position of the mouse pointer and then move the web page (with body position relative) so they hover over what you want them to click.
For an example you can paste this code on the current page in your browser console (and refresh afterwards)
var upvote_position = $('#answer-12878316').position();
$('body').mousemove(function (event) {
$(this).css({
position: 'relative',
left: (event.pageX - upvote_position.left - 22) + 'px',
top: (event.pageY - upvote_position.top - 35) + 'px'
});
});
PHP 5.4 has a function called http_response_code, so if you're using PHP 5.4 you can just do:
http_response_code(500);
I've written a polyfill for this function (Gist) if you're running a version of PHP under 5.4.
To answer your follow-up question, the HTTP 1.1 RFC says:
The reason phrases listed here are only recommendations -- they MAY be replaced by local equivalents without affecting the protocol.
That means you can use whatever text you want (excluding carriage returns or line feeds) after the code itself, and it'll work. Generally, though, there's usually a better response code to use. For example, instead of using a 500 for no record found, you could send a 404 (not found), and for something like "conditions failed" (I'm guessing a validation error), you could send something like a 422 (unprocessable entity).
Unfortunately solutions provided above, aren't beginner friendly.
It's
keytool -list -v -keystore keystore_name.jks
RSabet's answer doesn't work in cases where the dates don't have the same exact time.
Original problem:
from datetime import datetime
fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.strptime('2010-01-01 17:31:22', fmt)
d2 = datetime.strptime('2010-01-03 17:31:22', fmt)
daysDiff = (d2-d1).days
print daysDiff
> 2
# Convert days to minutes
minutesDiff = daysDiff * 24 * 60
print minutesDiff
> 2880
d2-d1 gives you a datetime.timedelta and when you use days it will only show you the days in the timedelta. In this case it works fine, but if you would have the following.
from datetime import datetime
fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.strptime('2010-01-01 16:31:22', fmt)
d2 = datetime.strptime('2010-01-03 20:15:14', fmt)
daysDiff = (d2-d1).days
print daysDiff
> 2
# Convert days to minutes
minutesDiff = daysDiff * 24 * 60
print minutesDiff
> 2880 # that is wrong
It would have still given you the same answer since it still returns 2 for days; it ignores the hour, min and second from the timedelta.
A better approach would be to convert the dates to a common format and then do the calculation. The easiest way to do this is to convert them to Unix timestamps. Here is the code to do that.
from datetime import datetime
import time
fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.strptime('2010-01-01 17:31:22', fmt)
d2 = datetime.strptime('2010-01-03 20:15:14', fmt)
# Convert to Unix timestamp
d1_ts = time.mktime(d1.timetuple())
d2_ts = time.mktime(d2.timetuple())
# They are now in seconds, subtract and then divide by 60 to get minutes.
print int(d2_ts-d1_ts) / 60
> 3043 # Much better
You are probably using a locale where the month names are not "January", "February", etc. but some other words in your local language.
Try specifying the locale you wish to use, for example Locale.US
:
DateFormat fmt = new SimpleDateFormat("MMMM dd, yyyy", Locale.US);
Date d = fmt.parse("June 27, 2007");
Also, you have an extra space in the date string, but actually this has no effect on the result. It works either way.
Not certain what the HTML looks like (that would help with answers). If it's
<div class="testimonials content">stuff</div>
then simply remove the space in your css. A la...
.testimonials.content { css here }
UPDATE:
Okay, after seeing HTML see if this works...
.testimonials .wrapper .content { css here }
or just
.testimonials .wrapper { css here }
or
.desc-container .wrapper { css here }
all 3 should work.
If by 'current directory' you mean the directory in which the zip file is, then I would use this command:
find . -name '*.zip' -execdir unzip {} \;
excerpt from find's man page
-execdir command ;
-execdir command {} +
Like -exec, but the specified command is run from the subdirectory containing the matched file, which is not normally the directory in which you started find. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec option, the '+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your $PATH environment variable does not reference the current directory; otherwise, an attacker can run any commands they like by leaving an appropriately-named file in a directory in which you will run -execdir.
You can pass the variable to the Makefile like below:
run:
@echo ./prog $$FOO
Usage:
$ make run FOO="the dog kicked the cat"
./prog the dog kicked the cat
or:
$ FOO="the dog kicked the cat" make run
./prog the dog kicked the cat
Alternatively use the solution provided by Beta:
run:
@echo ./prog $(filter-out $@,$(MAKECMDGOALS))
%:
@:
%:
- rule which match any task name;@:
- empty recipe = do nothing
Usage:
$ make run the dog kicked the cat
./prog the dog kicked the cat
This is modified from an answer above to support 'children' instead of a data array.
Note: The use of styled-components is of no importance to the solution.
import {useEffect, useRef} from "react";
import React from "react";
import styled from "styled-components";
export interface Props {
children: Array<any> | any,
}
export function AutoScrollList(props: Props) {
const bottomRef: any = useRef();
const scrollToBottom = () => {
bottomRef.current.scrollIntoView({
behavior: "smooth",
block: "start",
});
};
useEffect(() => {
scrollToBottom()
}, [props.children])
return (
<Container {...props}>
<div key={'child'}>{props.children}</div>
<div key={'dummy'} ref={bottomRef}/>
</Container>
);
}
const Container = styled.div``;
Try:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Remove("configFilePath");
config.AppSettings.Settings.Add("configFilePath", configFilePath);
config.Save(ConfigurationSaveMode.Modified,true);
config.SaveAs(@"C:\Users\USERNAME\Documents\Visual Studio 2010\Projects\ADI2v1.4\ADI2CE2\App.config",ConfigurationSaveMode.Modified, true);
Just setting json
option to true
, the body will contain the parsed json:
request({
url: 'http://...',
json: true
}, function(error, response, body) {
console.log(body);
});
For Java SE 5: According to Garbage Collector Ergonomics [Oracle]:
initial heap size:
Larger of 1/64th of the machine's physical memory on the machine or some reasonable minimum. Before J2SE 5.0, the default initial heap size was a reasonable minimum, which varies by platform. You can override this default using the -Xms command-line option.
maximum heap size:
Smaller of 1/4th of the physical memory or 1GB. Before J2SE 5.0, the default maximum heap size was 64MB. You can override this default using the -Xmx command-line option.
UPDATE:
As pointed out by Tom Anderson in his comment, the above is for server-class machines. From Ergonomics in the 5.0 JavaTM Virtual Machine:
In the J2SE platform version 5.0 a class of machine referred to as a server-class machine has been defined as a machine with
- 2 or more physical processors
- 2 or more Gbytes of physical memory
with the exception of 32 bit platforms running a version of the Windows operating system. On all other platforms the default values are the same as the default values for version 1.4.2.
In the J2SE platform version 1.4.2 by default the following selections were made
- initial heap size of 4 Mbyte
- maximum heap size of 64 Mbyte
This is how I've done it.
#copyright {_x000D_
float: left;_x000D_
padding-bottom: 10px;_x000D_
padding-top: 10px;_x000D_
text-align: center;_x000D_
bottom: 0px;_x000D_
width: 100%;_x000D_
}
_x000D_
<div id="copyright">_x000D_
Copyright 2018 © Steven Clough_x000D_
</div>
_x000D_
I'd just like to add something to this post for asp:button
. I've tried clientId and it doesn't seem to work for me:
__doPostBack('<%= btn.ClientID%>', '');
However, getting the UniqueId seems to post back to the server, like below:
__doPostBack('<%= btn.UniqueID%>', '');
This might help someone else in future, hence posting this.
You cannot session_start(); when your buffer has already been partly sent.
This mean, if your script already sent informations (something you want, or an error report) to the client, session_start() will fail.
This is, in effect, a way to check whether the expression e can be evaluated to be 0, and if not, to fail the build.
The macro is somewhat misnamed; it should be something more like BUILD_BUG_OR_ZERO
, rather than ...ON_ZERO
. (There have been occasional discussions about whether this is a confusing name.)
You should read the expression like this:
sizeof(struct { int: -!!(e); }))
(e)
: Compute expression e
.
!!(e)
: Logically negate twice: 0
if e == 0
; otherwise 1
.
-!!(e)
: Numerically negate the expression from step 2: 0
if it was 0
; otherwise -1
.
struct{int: -!!(0);} --> struct{int: 0;}
: If it was zero, then we declare a struct with an anonymous integer bitfield that has width zero. Everything is fine and we proceed as normal.
struct{int: -!!(1);} --> struct{int: -1;}
: On the other hand, if it isn't zero, then it will be some negative number. Declaring any bitfield with negative width is a compilation error.
So we'll either wind up with a bitfield that has width 0 in a struct, which is fine, or a bitfield with negative width, which is a compilation error. Then we take sizeof
that field, so we get a size_t
with the appropriate width (which will be zero in the case where e
is zero).
Some people have asked: Why not just use an assert
?
keithmo's answer here has a good response:
These macros implement a compile-time test, while assert() is a run-time test.
Exactly right. You don't want to detect problems in your kernel at runtime that could have been caught earlier! It's a critical piece of the operating system. To whatever extent problems can be detected at compile time, so much the better.
I have combined all the above answers into a script that polls the counters and writes the measurements in the terminal:
$totalRam = (Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property capacity -Sum).Sum
while($true) {
$date = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$cpuTime = (Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples.CookedValue
$availMem = (Get-Counter '\Memory\Available MBytes').CounterSamples.CookedValue
$date + ' > CPU: ' + $cpuTime.ToString("#,0.000") + '%, Avail. Mem.: ' + $availMem.ToString("N0") + 'MB (' + (104857600 * $availMem / $totalRam).ToString("#,0.0") + '%)'
Start-Sleep -s 2
}
This produces the following output:
2020-02-01 10:56:55 > CPU: 0.797%, Avail. Mem.: 2,118MB (51.7%)
2020-02-01 10:56:59 > CPU: 0.447%, Avail. Mem.: 2,118MB (51.7%)
2020-02-01 10:57:03 > CPU: 0.089%, Avail. Mem.: 2,118MB (51.7%)
2020-02-01 10:57:07 > CPU: 0.000%, Avail. Mem.: 2,118MB (51.7%)
You can hit Ctrl+C
to abort the loop.
So, you can connect to any Windows machine with this command:
Enter-PSSession -ComputerName MyServerName -Credential MyUserName
...paste it in, and run it, to get a "live" measurement. If connecting to the machine doesn't work directly, take a look here.
Please keep an eye on the mailing list for problems/solutions discussed by community members. https://groups.google.com/forum/?fromgroups#!forum/angular . It's been really useful to me.
Old question, but where others use JOIN to combine unrelated queries to rows in one table, this is my solution to combine unrelated queries to one row, e.g:
select
(select count(*) c from v$session where program = 'w3wp.exe') w3wp,
(select count(*) c from v$session) total,
sysdate
from dual;
which gives the following one-row output:
W3WP TOTAL SYSDATE
----- ----- -------------------
14 290 2020/02/18 10:45:07
(which tells me that our web server currently uses 14 Oracle sessions out of the total of 290 sessions; I log this output without headers in an sqlplus script that runs every so many minutes)
Chrome 30> supports video alpha transparency.
http://updates.html5rocks.com/2013/07/Alpha-transparency-in-Chrome-video
from subprocess import Popen, PIPE
from tempfile import SpooledTemporaryFile as tempfile
f = tempfile()
f.write('one\ntwo\nthree\nfour\nfive\nsix\n')
f.seek(0)
print Popen(['/bin/grep','f'],stdout=PIPE,stdin=f).stdout.read()
f.close()
If you don't want to use list comprehension by some reasons, you can use map and operator.itemgetter:
>>> from operator import itemgetter
>>> rows = [(1, 2), (3, 4), (5, 6)]
>>> map(itemgetter(1), rows)
[2, 4, 6]
>>>
Math.Ceiling((double)list.Count() / 10);
C# equivalent of your code is
class Imagedata : PDFStreamEngine
{
// C# uses "base" keyword whenever Java uses "super"
// so instead of super(...) in Java we should call its C# equivalent (base):
public Imagedata()
: base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true))
{ }
// Java methods are virtual by default, when C# methods aren't.
// So we should be sure that processOperator method in base class
// (that is PDFStreamEngine)
// declared as "virtual"
protected override void processOperator(PDFOperator operations, List arguments)
{
base.processOperator(operations, arguments);
}
}
The Python 3 range()
object doesn't produce numbers immediately; it is a smart sequence object that produces numbers on demand. All it contains is your start, stop and step values, then as you iterate over the object the next integer is calculated each iteration.
The object also implements the object.__contains__
hook, and calculates if your number is part of its range. Calculating is a (near) constant time operation *. There is never a need to scan through all possible integers in the range.
From the range()
object documentation:
The advantage of the
range
type over a regularlist
ortuple
is that a range object will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores thestart
,stop
andstep
values, calculating individual items and subranges as needed).
So at a minimum, your range()
object would do:
class my_range:
def __init__(self, start, stop=None, step=1, /):
if stop is None:
start, stop = 0, start
self.start, self.stop, self.step = start, stop, step
if step < 0:
lo, hi, step = stop, start, -step
else:
lo, hi = start, stop
self.length = 0 if lo > hi else ((hi - lo - 1) // step) + 1
def __iter__(self):
current = self.start
if self.step < 0:
while current > self.stop:
yield current
current += self.step
else:
while current < self.stop:
yield current
current += self.step
def __len__(self):
return self.length
def __getitem__(self, i):
if i < 0:
i += self.length
if 0 <= i < self.length:
return self.start + i * self.step
raise IndexError('my_range object index out of range')
def __contains__(self, num):
if self.step < 0:
if not (self.stop < num <= self.start):
return False
else:
if not (self.start <= num < self.stop):
return False
return (num - self.start) % self.step == 0
This is still missing several things that a real range()
supports (such as the .index()
or .count()
methods, hashing, equality testing, or slicing), but should give you an idea.
I also simplified the __contains__
implementation to only focus on integer tests; if you give a real range()
object a non-integer value (including subclasses of int
), a slow scan is initiated to see if there is a match, just as if you use a containment test against a list of all the contained values. This was done to continue to support other numeric types that just happen to support equality testing with integers but are not expected to support integer arithmetic as well. See the original Python issue that implemented the containment test.
* Near constant time because Python integers are unbounded and so math operations also grow in time as N grows, making this a O(log N) operation. Since it’s all executed in optimised C code and Python stores integer values in 30-bit chunks, you’d run out of memory before you saw any performance impact due to the size of the integers involved here.
In my case (Mac OS X), the problem was the file's break type. Try this:
1.- Open the .pem file with TextWrangler
2.- At Bottom of app, verify if the Break Type is "Windows(CRLF)".
For my development, I find that Chrome has a great solution.
https://superuser.com/a/512833
With developer tools open, simply long click the refresh button and let go once you hover over "Empty Cache and Hard Reload".
This is my best friend, and is a super lightweight way to get what you want!
You can config global timezone with the library tzdata:
npm install tzdata -y
After set your environment with the variable for example: TZ=America/Bogota
And testing in your project:
new Date()
I hope helpyou
Check it out this code, it works for me
// Slide up animation
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration="@android:integer/config_mediumAnimTime"
android:fromYDelta="100%"
android:interpolator="@android:anim/accelerate_interpolator"
android:toXDelta="0" />
</set>
// Slide dowm animation
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration="@android:integer/config_mediumAnimTime"
android:fromYDelta="0%p"
android:interpolator="@android:anim/accelerate_interpolator"
android:toYDelta="100%p" />
</set>
// Style
<style name="DialogAnimation">
<item name="android:windowEnterAnimation">@anim/slide_up</item>
<item name="android:windowExitAnimation">@anim/slide_down</item>
</style>
// Inside Dialog Fragment
@Override
public void onActivityCreated(Bundle arg0) {
super.onActivityCreated(arg0);
getDialog().getWindow()
.getAttributes().windowAnimations = R.style.DialogAnimation;
}
You probably need to reference it from the Rows
rather than as a cell:
var cellValue = dt.Rows[i][j];
Run these two commands from the terminal to set User email and Name
git config --global user.email "[email protected]"
git config --global user.name "your name"
Java 8+ version for Integer
, Long
, Double
and Float
List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5);
List<Long> longs = Arrays.asList(1L, 2L, 3L, 4L, 5L);
List<Double> doubles = Arrays.asList(1.2d, 2.3d, 3.0d, 4.0d, 5.0d);
List<Float> floats = Arrays.asList(1.3f, 2.2f, 3.0f, 4.0f, 5.0f);
long intSum = ints.stream()
.mapToLong(Integer::longValue)
.sum();
long longSum = longs.stream()
.mapToLong(Long::longValue)
.sum();
double doublesSum = doubles.stream()
.mapToDouble(Double::doubleValue)
.sum();
double floatsSum = floats.stream()
.mapToDouble(Float::doubleValue)
.sum();
System.out.println(String.format(
"Integers: %s, Longs: %s, Doubles: %s, Floats: %s",
intSum, longSum, doublesSum, floatsSum));
15, 15, 15.5, 15.5
I would like to avoid using full python directory path in the Notepad++ macro. I tried other solutions given in this page, they failed.
The one working on my PC is:
In Notepad++, press F5.
Copy/paste this:
cmd /k cd /d $(CURRENT_DIRECTORY) && py -3 -i $(FULL_CURRENT_PATH)
Enter.
Your problem is that you're not closing your HEREDOC correctly. The line containing END;
must not contain any whitespace afterwards.
Objective-C code for copy Table from a Database to another Database
-(void) createCopyDatabase{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *maindbPath = [documentsDir stringByAppendingPathComponent:@"User.sqlite"];;
NSString *newdbPath = [documentsDir stringByAppendingPathComponent:@"User_copy.sqlite"];
NSFileManager *fileManager = [NSFileManager defaultManager];
char *error;
if ([fileManager fileExistsAtPath:newdbPath]) {
[fileManager removeItemAtPath:newdbPath error:nil];
}
sqlite3 *database;
//open database
if (sqlite3_open([newdbPath UTF8String], &database)!=SQLITE_OK) {
NSLog(@"Error to open database");
}
NSString *attachQuery = [NSString stringWithFormat:@"ATTACH DATABASE \"%@\" AS aDB",maindbPath];
sqlite3_exec(database, [attachQuery UTF8String], NULL, NULL, &error);
if (error) {
NSLog(@"Error to Attach = %s",error);
}
//Query for copy Table
NSString *sqlString = @"CREATE TABLE Info AS SELECT * FROM aDB.Info";
sqlite3_exec(database, [sqlString UTF8String], NULL, NULL, &error);
if (error) {
NSLog(@"Error to copy database = %s",error);
}
//Query for copy Table with Where Clause
sqlString = @"CREATE TABLE comments AS SELECT * FROM aDB.comments Where user_name = 'XYZ'";
sqlite3_exec(database, [sqlString UTF8String], NULL, NULL, &error);
if (error) {
NSLog(@"Error to copy database = %s",error);
}
}
For sudo there is a -S option for accepting the password from standard input. Here is the man entry:
-S The -S (stdin) option causes sudo to read the password from
the standard input instead of the terminal device.
This will allow you to run a command like:
echo myPassword | sudo -S ls /tmp
As for ssh, I have made many attempts to automate/script it's usage with no success. There doesn't seem to be any build-in way to pass the password into the command without prompting. As others have mentioned, the "expect" utility seems like it is aimed at addressing this dilemma but ultimately, setting up the correct private-key authorization is the correct way to go when attempting to automate this.
I was ultimately able to resolve the solution by setting the column type in the flat file connection to be of type "database date [DT_DBDATE]"
Apparently the differences between these date formats are as follow:
DT_DATE A date structure that consists of year, month, day, and hour.
DT_DBDATE A date structure that consists of year, month, and day.
DT_DBTIMESTAMP A timestamp structure that consists of year, month, hour, minute, second, and fraction
By changing the column type to DT_DBDATE the issue was resolved - I attached a Data Viewer and the CYCLE_DATE value was now simply "12/20/2010" without a time component, which apparently resolved the issue.
Refer to this link :https://gis.stackexchange.com/questions/84885/whats-the-difference-between-vincenty-and-great-circle-distance-calculations
this actually gives two ways of getting distance. They are Haversine and Vincentys. From my research I came to know that Vincentys is relatively accurate. Also use import statement to make the implementation.
You can use that gist, pretty easy to use, stores your settings in local storage: https://gist.github.com/4533361
Do whatever you want to do after the file loads successfully.just after the completion of your file processing set the value of file control to blank string.so the .change() will always be called even the file name changes or not. like for example you can do this thing and worked for me like charm
$('#myFile').change(function () {
LoadFile("myFile");//function to do processing of file.
$('#myFile').val('');// set the value to empty of myfile control.
});
You said you copied files from another computer. After you copied them, did you 'Unblock' them? Specifically the .snk file should be checked to make sure it is not marked as unsafe.
In my case I use chrono and c function localtime_r which is thread-safe (in opposition to std::localtime).
#include <iostream>
#include <chrono>
#include <ctime>
#include <time.h>
#include <iomanip>
int main() {
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
std::time_t currentTime = std::chrono::system_clock::to_time_t(now);
std::chrono::milliseconds now2 = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
struct tm currentLocalTime;
localtime_r(¤tTime, ¤tLocalTime);
char timeBuffer[80];
std::size_t charCount { std::strftime( timeBuffer, 80,
"%b %d %T",
¤tLocalTime)
};
if (charCount == 0) return -1;
std::cout << timeBuffer << "." << std::setfill('0') << std::setw(3) << now2.count() % 1000 << std::endl;
return 0;
}
Spinner don't support Hint, i recommend you to make a custom spinner adapter.
check this link : https://stackoverflow.com/a/13878692/1725748
In order for Bootstrap Beta to function properly, you must place the scripts in the following order.
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/popper.min.js"></script>
<script src="js/bootstrap.min.js"></script>
I like this example, which for now, leaves out the check which you could add inside the while block:
ifstream iFile("input.txt"); // input.txt has integers, one per line
int x;
while (iFile >> x)
{
cerr << x << endl;
}
Not sure how safe it is...
In my opinion the bare minimum implementation has two requirements. A state that keeps track of whether the modal is open or not, and a portal to render the modal outside of the standard react tree.
The ModalContainer component below implements those requirements along with corresponding render functions for the modal and the trigger, which is responsible for executing the callback to open the modal.
import React from 'react';
import PropTypes from 'prop-types';
import Portal from 'react-portal';
class ModalContainer extends React.Component {
state = {
isOpen: false,
};
openModal = () => {
this.setState(() => ({ isOpen: true }));
}
closeModal = () => {
this.setState(() => ({ isOpen: false }));
}
renderModal() {
return (
this.props.renderModal({
isOpen: this.state.isOpen,
closeModal: this.closeModal,
})
);
}
renderTrigger() {
return (
this.props.renderTrigger({
openModal: this.openModal
})
)
}
render() {
return (
<React.Fragment>
<Portal>
{this.renderModal()}
</Portal>
{this.renderTrigger()}
</React.Fragment>
);
}
}
ModalContainer.propTypes = {
renderModal: PropTypes.func.isRequired,
renderTrigger: PropTypes.func.isRequired,
};
export default ModalContainer;
And here's a simple use case...
import React from 'react';
import Modal from 'react-modal';
import Fade from 'components/Animations/Fade';
import ModalContainer from 'components/ModalContainer';
const SimpleModal = ({ isOpen, closeModal }) => (
<Fade visible={isOpen}> // example use case with animation components
<Modal>
<Button onClick={closeModal}>
close modal
</Button>
</Modal>
</Fade>
);
const SimpleModalButton = ({ openModal }) => (
<button onClick={openModal}>
open modal
</button>
);
const SimpleButtonWithModal = () => (
<ModalContainer
renderModal={props => <SimpleModal {...props} />}
renderTrigger={props => <SimpleModalButton {...props} />}
/>
);
export default SimpleButtonWithModal;
I use render functions, because I want to isolate state management and boilerplate logic from the implementation of the rendered modal and trigger component. This allows the rendered components to be whatever you want them to be. In your case, I suppose the modal component could be a connected component that receives a callback function that dispatches an asynchronous action.
If you need to send dynamic props to the modal component from the trigger component, which hopefully doesn't happen too often, I recommend wrapping the ModalContainer with a container component that manages the dynamic props in its own state and enhance the original render methods like so.
import React from 'react'
import partialRight from 'lodash/partialRight';
import ModalContainer from 'components/ModalContainer';
class ErrorModalContainer extends React.Component {
state = { message: '' }
onError = (message, callback) => {
this.setState(
() => ({ message }),
() => callback && callback()
);
}
renderModal = (props) => (
this.props.renderModal({
...props,
message: this.state.message,
})
)
renderTrigger = (props) => (
this.props.renderTrigger({
openModal: partialRight(this.onError, props.openModal)
})
)
render() {
return (
<ModalContainer
renderModal={this.renderModal}
renderTrigger={this.renderTrigger}
/>
)
}
}
ErrorModalContainer.propTypes = (
ModalContainer.propTypes
);
export default ErrorModalContainer;
Note that HTTP doesn't typically keep TCP connections open for any longer than it takes to transmit the page to the client; and it usually takes much more time for the user to read a web page than it takes to download the page... while the user is viewing the page, he adds no load to the server at all.
So the number of people that can be simultaneously viewing your web site is much larger than the number of TCP connections that it can simultaneously serve.
Better way till now:
If you give display:inline-block; to inner divs then child elements of inner divs will also get this property and disturb alignment of inner divs.
Better way is to use two different classes for inner divs with width, margin and float.
Best way till now:
Use flexbox.
let mainString = "Hello World"
let stringToColor = "World"
SWIFT 5
let range = (mainString as NSString).range(of: stringToColor)
let mutableAttributedString = NSMutableAttributedString.init(string: mainString)
mutableAttributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: range)
textField = UITextField.init(frame: CGRect(x:10, y:20, width:100, height: 100))
textField.attributedText = mutableAttributedString
SWIFT 4.2
let range = (mainString as NSString).range(of: stringToColor)
let mutableAttributedString = NSMutableAttributedString.init(string: mainString)
mutableAttributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: range)
textField = UITextField.init(frame: CGRect(x:10, y:20, width:100, height: 100))
textField.attributedText = mutableAttributedString
Naming convention for collection
In order to name a collection few precautions to be taken :
Things to keep in mind while creating a database name are :
For more information. Please check the below link : http://www.tutorial-points.com/2016/03/schema-design-and-naming-conventions-in.html
Yes. The entire text of an HTTPS session is secured by SSL. That includes the query and the headers. In that respect, a POST and a GET would be exactly the same.
As to the security of your method, there's no real way to say without proper inspection.
--no-pager
to Git will tell it to not use a pager. Passing the option -F
to less
will tell it to not page if the output fits in a single screen.
Usage:
git --no-pager diff
Other options from the comments include:
# Set an evaporating environment variable to use 'cat' for your pager
GIT_PAGER=cat git diff
# Tells 'less' not to paginate if less than a page
export LESS="-F -X $LESS"
# ...then Git as usual
git diff
These are Unicode property shortcuts (\p{L}
for Unicode letters, \p{N}
for Unicode digits). They are supported by .NET, Perl, Java, PCRE, XML, XPath, JGSoft, Ruby (1.9 and higher) and PHP (since 5.1.0)
At any rate, that's a very strange regex. You should not be using alternation when a character class would suffice:
[\p{L}\p{N}_.-]*
When you want to open an activity within your app then you can call the startActivity() method with an Intent as parameter. That intent would be the activity that you want to open. First you have to create an object of that intent with first parameter to be the context and second parameter to be the targeted activity class.
Intent intent = new Intent(this, Activity_a.class);
startActivity(intent);
Hope this will help.
The key to debugging situations like these is to run the subquery/inline view on its' own to see what the output is:
SELECT TOP 1
dm.marker_value,
dum.profile_id
FROM DPS_USR_MARKERS dum (NOLOCK)
JOIN DPS_MARKERS dm (NOLOCK) ON dm.marker_id= dum.marker_id
AND dm.marker_key = 'moneyBackGuaranteeLength'
ORDER BY dm.creation_date
Running that, you would see that the profile_id
value didn't match the u.id
value of u162231993
, which would explain why any mbg
references would return null
(thanks to the left join; you wouldn't get anything if it were an inner join).
You've coded yourself into a corner using TOP
, because now you have to tweak the query if you want to run it for other users. A better approach would be:
SELECT u.id,
x.marker_value
FROM DPS_USER u
LEFT JOIN (SELECT dum.profile_id,
dm.marker_value,
dm.creation_date
FROM DPS_USR_MARKERS dum (NOLOCK)
JOIN DPS_MARKERS dm (NOLOCK) ON dm.marker_id= dum.marker_id
AND dm.marker_key = 'moneyBackGuaranteeLength'
) x ON x.profile_id = u.id
JOIN (SELECT dum.profile_id,
MAX(dm.creation_date) 'max_create_date'
FROM DPS_USR_MARKERS dum (NOLOCK)
JOIN DPS_MARKERS dm (NOLOCK) ON dm.marker_id= dum.marker_id
AND dm.marker_key = 'moneyBackGuaranteeLength'
GROUP BY dum.profile_id) y ON y.profile_id = x.profile_id
AND y.max_create_date = x.creation_date
WHERE u.id = 'u162231993'
With that, you can change the id
value in the where
clause to check records for any user in the system.
When doing a git pull
, I got this message fatal: refusing to merge unrelated histories
for a repo module where I hadn't updated the local copy for a while.
I ran this command just to refresh local from origin. I just wanted latest from remote and didn't need any local changes.
git reset --hard origin/master
This fixed it in my case.
You need the following code below. At a glance, this may look like any old code that I made up. However, what I did was look at the source code for http://grepcode.com/file/repo1.maven.org/maven2/mysql/mysql-connector-java/5.1.31/com/mysql/jdbc/PreparedStatement.java. Then after that, I carefully looked through the code of setString(int parameterIndex, String x) to find the characters which it escapes and customised this to my own class so that it can be used for the purposes that you need. After all, if this is the list of characters that Oracle escapes, then knowing this is really comforting security-wise. Maybe Oracle need a nudge to add a method similar to this one for the next major Java release.
public class SQLInjectionEscaper {
public static String escapeString(String x, boolean escapeDoubleQuotes) {
StringBuilder sBuilder = new StringBuilder(x.length() * 11/10);
int stringLength = x.length();
for (int i = 0; i < stringLength; ++i) {
char c = x.charAt(i);
switch (c) {
case 0: /* Must be escaped for 'mysql' */
sBuilder.append('\\');
sBuilder.append('0');
break;
case '\n': /* Must be escaped for logs */
sBuilder.append('\\');
sBuilder.append('n');
break;
case '\r':
sBuilder.append('\\');
sBuilder.append('r');
break;
case '\\':
sBuilder.append('\\');
sBuilder.append('\\');
break;
case '\'':
sBuilder.append('\\');
sBuilder.append('\'');
break;
case '"': /* Better safe than sorry */
if (escapeDoubleQuotes) {
sBuilder.append('\\');
}
sBuilder.append('"');
break;
case '\032': /* This gives problems on Win32 */
sBuilder.append('\\');
sBuilder.append('Z');
break;
case '\u00a5':
case '\u20a9':
// escape characters interpreted as backslash by mysql
// fall through
default:
sBuilder.append(c);
}
}
return sBuilder.toString();
}
}
If you don't need any special processing, this should do what you're looking for
$lines = file($filename, FILE_IGNORE_NEW_LINES);
Don't overuse Vue.component()
, it registers components globally. You can create file, name it MyTask.vue, export there Vue object
https://vuejs.org/v2/guide/single-file-components.html
and then import in your main file, and don't forget to register it:
new Vue({
...
components: { myTask }
...
})
Also worth noting window.scrollBy(dx,dy)
(ref)
Although @dunedin15's fantastic answer has served me well on a number of occasions, it can give inaccurate results for some edge-cases, such as when debugging build settings of a static lib for an Archive build.
As an alternative, a Run Script Build Phase can be easily added to any target to “Log Build Settings” when it's built:
To add, (with the target in question selected) under the Build Phases tab-section click the little ? button a dozen-or-so pixels up-left-ward from the Target Dependencies section, and set the shell to /bin/bash
and the command to export
. You'll also probably want to drag the phase upwards so that it happens just after Target Dependencies and before Copy Headers or Compile Sources. Renaming the phase from “Run Script” to “Log Build Settings” isn't a bad idea.
The result is this incredibly helpful listing of current environment variables used for building:
I just ran into the exact same problem while configuring my server 2008 and windows 7 vm's in VMware workstation 9. what helped is disabling the firewall and running the following command at the windows command prompt
netsh firewall set icmpsetting 8 enable
at that point I was able to ping one VM then both once I performed the command on both. this differnce between our scenarios is I have my VM configured using Bridged connections
To stop or start mysql on most linux systems the following should work:
/etc/init.d/mysqld stop
/etc/init.d/mysqld start
The other answers look good for accessing the mysql client from the command line.
Good luck!
If the locked repo was the original, I can't imagine it was modifying it to clone it, so it was only preventing you from changing it in the middle and messing up the clone. It should be fine after removing the lock.
The new cloned copy (if it was a local clone) could be in any sort of malformed state, though, so you should throw it out and start it over. (If it was a remote clone, I would hope it failed and already threw out the incomplete copy.)
In case you just want to add a whitespace between the words, it is as simple as
string res = Regex.Replace(PublishStatusses.NotCompleted, "[A-Z]", " $0").Trim();
The easiest way is to JSON-encode your object and then decode it back to an array:
$array = json_decode(json_encode($object), true);
Or if you prefer, you can traverse the object manually, too:
foreach ($object as $value)
$array[] = $value->post_id;
You need to add this line into your settings.xml
(or uncomment if it's already there).
<localRepository>C:\Users\me\.m2\repo</localRepository>
Also it's possible to run your commands with mvn clean install -gs C:\Users\me\.m2\settings.xml
- this parameter will force maven to use different settings.xml
then the default one (which is in $HOME/.m2/settings.xml
)
This is the code that I write according to @Mark Coleman answer:
$(window).resize(function() {
clearTimeout(window.resizedFinished);
window.resizedFinished = setTimeout(function(){
console.log('Resized finished.');
}, 250);
});
Thanks Mark!
Without any assumptions the answer is:
{% if var is null %}
But this will be true only if var
is exactly NULL
, and not any other value that evaluates to false
(such as zero, empty string and empty array). Besides, it will cause an error if var
is not defined. A safer way would be:
{% if var is not defined or var is null %}
which can be shortened to:
{% if var|default is null %}
If you don't provide an argument to the default
filter, it assumes NULL
(sort of default default). So the shortest and safest way (I know) to check whether a variable is empty (null, false, empty string/array, etc):
{% if var|default is empty %}
The problem: The format of the file as to how it is saved.
Use a proper text editor and save it with the .py
extension
and run it in terminal.
eg: file name should be saved as `example.py`
run
python example
If I remember correctly, you'll need to set the netbeans_jdkhome
property in your netbeans config file. Should be in your etc/netbeans.conf
file.
I want to change the width and height of a div. data attributes did not change it. Instead I use:
var size = $("#theme_photo_size").val().split("x");
$("#imageupload_img").width(size[0]);
$("#imageupload_img").attr("data-width", size[0]);
$("#imageupload_img").height(size[1]);
$("#imageupload_img").attr("data-height", size[1]);
be careful:
$("#imageupload_img").data("height", size[1]); //did not work
did not set it
$("#imageupload_img").attr("data-height", size[1]); // yes it worked!
this has set it.
$ ls -ld directory
ls
is the list command.
-
indicates the beginning of the command options.
l
asks for a long list which includes the permissions.
d
indicates that the list should concern the named directory itself; not its contents. If no directory name is given, the list output will pertain to the current directory.
The \s
metacharacter matches whitespace characters.
Pip allows to specify the version
pip install tensorflow==1.1
Escape characters are dependent on whatever system is interpreting them. \n
is interpreted as a newline character by many programming languages, but that doesn't necessarily hold true for the other utilities you mention. Even if they do treat \n
as newline, there may be some other techniques to get them to behave how you want. You would have to consult their documentation (or see other answers here).
For DOS/Windows systems, the newline is actually two characters: Carriage Return (ASCII 13, AKA \r
), followed by Line Feed (ASCII 10). On Unix systems (including Mac OSX) it's just Line Feed. On older Macs it was a single Carriage Return.
I'm a little bit late and i will talk about Python3. To understand what id() is and how it (and Python) works, consider next example:
>>> x=1000
>>> y=1000
>>> id(x)==id(y)
False
>>> id(x)
4312240944
>>> id(y)
4312240912
>>> id(1000)
4312241104
>>> x=1000
>>> id(x)
4312241104
>>> y=1000
>>> id(y)
4312241200
You need to think about everything on the right side as objects. Every time you make assignment - you create new object and that means new id. In the middle you can see a "wild" object which is created only for function - id(1000). So, it's lifetime is only for that line of code. If you check the next line - you see that when we create new variable x, it has the same id as that wild object. Pretty much it works like memory address.
PowerShell (Core-compatible) one-liner to ease copypaste scenarios:
netstat -aon | Select-String 8080 | ForEach-Object { $_ -replace '\s+', ',' } | ConvertFrom-Csv -Header @('Empty', 'Protocol', 'AddressLocal', 'AddressForeign', 'State', 'PID') | ForEach-Object { $portProcess = Get-Process | Where-Object Id -eq $_.PID; $_ | Add-Member -NotePropertyName 'ProcessName' -NotePropertyValue $portProcess.ProcessName; Write-Output $_ } | Sort-Object ProcessName, State, Protocol, AddressLocal, AddressForeign | Select-Object ProcessName, State, Protocol, AddressLocal, AddressForeign | Format-Table
Output:
ProcessName State Protocol AddressLocal AddressForeign
----------- ----- -------- ------------ --------------
System LISTENING TCP [::]:8080 [::]:0
System LISTENING TCP 0.0.0.0:8080 0.0.0.0:0
Same code, developer-friendly:
$Port = 8080
# Get PID's listening to $Port, as PSObject
$PidsAtPortString = netstat -aon `
| Select-String $Port
$PidsAtPort = $PidsAtPortString `
| ForEach-Object { `
$_ -replace '\s+', ',' `
} `
| ConvertFrom-Csv -Header @('Empty', 'Protocol', 'AddressLocal', 'AddressForeign', 'State', 'PID')
# Enrich port's list with ProcessName data
$ProcessesAtPort = $PidsAtPort `
| ForEach-Object { `
$portProcess = Get-Process `
| Where-Object Id -eq $_.PID; `
$_ | Add-Member -NotePropertyName 'ProcessName' -NotePropertyValue $portProcess.ProcessName; `
Write-Output $_;
}
# Show output
$ProcessesAtPort `
| Sort-Object ProcessName, State, Protocol, AddressLocal, AddressForeign `
| Select-Object ProcessName, State, Protocol, AddressLocal, AddressForeign `
| Format-Table
They are not different from the point of view of JVM. Immutable objects don't have methods that can change the instance variables. And the instance variables are private; therefore you can't change it after you create it. A famous example would be String. You don't have methods like setString, or setCharAt. And s1 = s1 + "w" will create a new string, with the original one abandoned. That's my understanding.
At the command line paste the following
export QUERY_STRING="param1=abc¶m2=xyz" ;
POST_STRING="name=John&lastname=Doe" ; php -e -r
'parse_str($_SERVER["QUERY_STRING"], $_GET); parse_str($_SERVER["POST_STRING"],
$_POST); include "index.php";'
On Windows 2008 R2, I have seen application crash dumps under either
C:\Users\[Some User]\Microsoft\Windows\WER\ReportArchive
or
C:\ProgramData\Microsoft\Windows\WER\ReportArchive
I don't know how Windows decides which directory to use.
You may try with below query :
INSERT INTO errortable (dateupdated,table1id)
VALUES (to_date(to_char(sysdate,'dd/mon/yyyy hh24:mi:ss'), 'dd/mm/yyyy hh24:mi:ss' ),1083 );
To view the result of it:
SELECT to_char(hire_dateupdated, 'dd/mm/yyyy hh24:mi:ss')
FROM errortable
WHERE table1id = 1083;
Add:
DELIMITER
at the beginning and end of the SP.validar_egreso
; at the beginning@variableName
.This works for me. (I modified some part of your script so ANYONE can run it with out having your tables).
DROP PROCEDURE IF EXISTS `validar_egreso`;
DELIMITER $$
CREATE DEFINER='root'@'localhost' PROCEDURE `validar_egreso` (
IN codigo_producto VARCHAR(100),
IN cantidad INT,
OUT valido INT(11)
)
BEGIN
DECLARE resta INT;
SET resta = 0;
SELECT (codigo_producto - cantidad) INTO resta;
IF(resta > 1) THEN
SET valido = 1;
ELSE
SET valido = -1;
END IF;
SELECT valido;
END $$
DELIMITER ;
-- execute the stored procedure
CALL validar_egreso(4, 1, @val);
-- display the result
select @val;
To bind the data to ComboBox
List<ComboData> ListData = new List<ComboData>();
ListData.Add(new ComboData { Id = "1", Value = "One" });
ListData.Add(new ComboData { Id = "2", Value = "Two" });
ListData.Add(new ComboData { Id = "3", Value = "Three" });
ListData.Add(new ComboData { Id = "4", Value = "Four" });
ListData.Add(new ComboData { Id = "5", Value = "Five" });
cbotest.ItemsSource = ListData;
cbotest.DisplayMemberPath = "Value";
cbotest.SelectedValuePath = "Id";
cbotest.SelectedValue = "2";
ComboData
looks like:
public class ComboData
{
public int Id { get; set; }
public string Value { get; set; }
}
(note that Id
and Value
have to be properties, not class fields)
There should be svn
utility on you box, if installed:
$ svn checkout http://example.com/svn/somerepo somerepo
This will check out a working copy from a specified repository to a directory somerepo
on our file system.
You may want to print commands, supported by this utility:
$ svn help
uname -a
output in your question is identical to one, used by Parallels Virtuozzo Containers for Linux 4.0 kernel, which is based on Red Hat 5 kernel, thus your friends are rpm
or the following command:
$ sudo yum install subversion
Here example on plain JS:
document.querySelector('#myDiv').addEventListener('keyup', function (e) {_x000D_
console.log(e.key)_x000D_
})
_x000D_
#myDiv {_x000D_
outline: none;_x000D_
}
_x000D_
<div _x000D_
id="myDiv"_x000D_
tabindex="0"_x000D_
>_x000D_
Press me and start typing_x000D_
</div>
_x000D_
I normally concatenate the field's value (i.e. before it's updated) with the key associated with the key event. The following uses recent JS so would need adjusting for support in older IE's.
Recent JS example
document.querySelector('#test').addEventListener('keypress', function(evt) {
var real_val = this.value + String.fromCharCode(evt.which);
if (evt.which == 8) real_val = real_val.substr(0, real_val.length - 2);
alert(real_val);
}, false);
Support for older IEs example
//get field
var field = document.getElementById('test');
//bind, somehow
if (window.addEventListener)
field.addEventListener('keypress', keypress_cb, false);
else
field.attachEvent('onkeypress', keypress_cb);
//callback
function keypress_cb(evt) {
evt = evt || window.event;
var code = evt.which || evt.keyCode,
real_val = this.value + String.fromCharCode(code);
if (code == 8) real_val = real_val.substr(0, real_val.length - 2);
}
[EDIT - this approach, by default, disables key presses for things like back space, CTRL+A. The code above accommodates for the former, but would need further tinkering to allow for the latter, and a few other eventualities. See Ian Boyd's comment below.]
days = (endDate - beginDate)/(60*60*24)
"You must specify a region" is a not an ECS specific error, it can happen with any AWS API/CLI/SDK command.
For the CLI, either set the AWS_DEFAULT_REGION
environment variable. e.g.
export AWS_DEFAULT_REGION=us-east-1
or add it into the command (you will need this every time you use a region-specific command)
AWS_DEFAULT_REGION=us-east-1 aws ecs list-container-instances --cluster default
or set it in the CLI configuration file: ~/.aws/config
[default]
region=us-east-1
or pass/override it with the CLI call:
aws ecs list-container-instances --cluster default --region us-east-1
You should use as_json
method which converts ActiveRecord objects to Ruby Hashes despite its name
tasks_records = TaskStoreStatus.all
tasks_records = tasks_records.as_json
# You can now add new records and return the result as json by calling `to_json`
tasks_records << TaskStoreStatus.last.as_json
tasks_records << { :task_id => 10, :store_name => "Koramanagala", :store_region => "India" }
tasks_records.to_json
You can also convert any ActiveRecord objects to a Hash with serializable_hash
and you can convert any ActiveRecord results to an Array with to_a
, so for your example :
tasks_records = TaskStoreStatus.all
tasks_records.to_a.map(&:serializable_hash)
And if you want an ugly solution for Rails prior to v2.3
JSON.parse(tasks_records.to_json) # please don't do it
You can use backslash to quote "funny" characters in your jQuery selectors:
$('#input\\[23\\]')
For attribute values, you can use quotes:
$('input[name="weirdName[23]"]')
Now, I'm a little confused by your example; what exactly does your HTML look like? Where does the string "inputName" show up, in particular?
edit fixed bogosity; thanks @Dancrumb
For Tomcat 8:
Linux :
Create setenv.sh and update it with following:
export SPRING_PROFILES_ACTIVE=dev
Windows:
Create setenv.bat and update it with following:
set SPRING_PROFILES_ACTIVE=dev
I just discovered a nice way to set your page title if you're using routing:
JavaScript:
var myApp = angular.module('myApp', ['ngResource'])
myApp.config(
['$routeProvider', function($routeProvider) {
$routeProvider.when('/', {
title: 'Home',
templateUrl: '/Assets/Views/Home.html',
controller: 'HomeController'
});
$routeProvider.when('/Product/:id', {
title: 'Product',
templateUrl: '/Assets/Views/Product.html',
controller: 'ProductController'
});
}]);
myApp.run(['$rootScope', function($rootScope) {
$rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
$rootScope.title = current.$$route.title;
});
}]);
HTML:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title ng-bind="'myApp — ' + title">myApp</title>
...
Edit: using the ng-bind
attribute instead of curlies {{}}
so they don't show on load
Following up on Mat's answer (use Cygwin), here are some detailed instructions for : installing gcc on Windows The packages you want are gcc, gdb and make. Cygwin installer lets you install additional packages if you need them.
I have just downloaded Tomcat and want to stop it (Windows).
To stop tomcat
run cmd as administrator (I used Cmder)
find process ID
tasklist /fi "Imagename eq tomcat*"
C:\Users\Admin
tasklist /fi "Imagename eq tomcat*"
Image Name PID Session Name Session# Mem Usage
========================= ======== ================ =========== ============
Tomcat8aaw.exe 6376 Console 1 7,300 K
Tomcat8aa.exe 5352 Services 0 124,748 K
C:\Users\Admin
taskkill /f /pid 6376
SUCCESS: The process with PID 6376 has been terminated.
C:\Users\Admin
taskkill /f /pid 5352
SUCCESS: The process with PID 5352 has been terminated.
Using TypedArray.from:
Uint8Array.from(atob(base64_string), c => c.charCodeAt(0))
Performance to be compared with the for loop version of Goran.it answer.
Instead of adding Reader("Name")
you add a new ListItem
. ListItem
has a Text
and a Value
property that you can set.
On a Linux Debian-based (so Ubuntu included) you have also to go to /etc/default/tomcat7
, uncomment the #AUTHBIND=no
line and set its value to 'yes', in order to let the server bind on a privileged port.
If you are using Android Studio 3.0 or above make sure your project build.gradle should have content similar to-
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
}
}
allprojects {
repositories {
google()
jcenter()
}
}
Note- position really matters add google() before jcenter()
And for below Android Studio 3.0 and starting from support libraries 26.+ your project build.gradle must look like this-
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
}
check these links below for more details-
use
select convert(varchar(10),GETDATE(), 103) +
' '+
right(convert(varchar(32),GETDATE(),108),8) AS Date_Time
It will Produce:
Date_Time 30/03/2015 11:51:40
A solution that actually works:
public void Test() {
throw new MyCustomException("You can't do that!");
}
[TestMethod]
public void ThisWillPassIfExceptionThrown()
{
var exception = Assert.ThrowsException<MyCustomException>(
() => Test(),
"This should have thrown!");
Assert.AreEqual("You can't do that!", exception.Message);
}
This works with using Microsoft.VisualStudio.TestTools.UnitTesting;
.
If you meant .. to REDIRECT from that page to another, the function is really simple
header("Location:www.google.com");
Trident provides the ::-ms-check
pseudo-element for checkbox and radio button controls. For example:
<input type="checkbox">
<input type="radio">
::-ms-check {
color: red;
background: black;
padding: 1em;
}
This displays as follows in IE10 on Windows 8:
@ck's and @Marlon Tarak's answers are the only ones to use a char[]
, which for applications that have several calls to padding methods per second is the best approach. However, they don't take advantage of any array manipulation optimizations and are a little overwritten for my taste; this can be done with no loops at all.
public static String pad(String source, char fill, int length, boolean right){
if(source.length() > length) return source;
char[] out = new char[length];
if(right){
System.arraycopy(source.toCharArray(), 0, out, 0, source.length());
Arrays.fill(out, source.length(), length, fill);
}else{
int sourceOffset = length - source.length();
System.arraycopy(source.toCharArray(), 0, out, sourceOffset, source.length());
Arrays.fill(out, 0, sourceOffset, fill);
}
return new String(out);
}
Simple test method:
public static void main(String... args){
System.out.println("012345678901234567890123456789");
System.out.println(pad("cats", ' ', 30, true));
System.out.println(pad("cats", ' ', 30, false));
System.out.println(pad("cats", ' ', 20, false));
System.out.println(pad("cats", '$', 30, true));
System.out.println(pad("too long for your own good, buddy", '#', 30, true));
}
Outputs:
012345678901234567890123456789
cats
cats
cats
cats$$$$$$$$$$$$$$$$$$$$$$$$$$
too long for your own good, buddy
I ran into the same issue on windows 7. I managed to get it working by creating a "pip" folder with a "pip.ini" file inside it. I put this folder inside "C:\Users\{my.username}\AppData\Roaming", because according to the Python documentation:
On Windows the configuration file is %APPDATA%\pip\pip.ini
In the pip.ini file I have only:
[global]
proxy = [proxy address]:[proxy port]
So no username:password. And it is working just fine.
Select-Object returns a custom PSObject with just the properties specified. Even with a single property, you don't get the ACTUAL variable; it is wrapped inside the PSObject.
Instead, do:
Get-Date | Select-Object -ExpandProperty DayOfWeek
That will get you the same result as:
(Get-Date).DayOfWeek
The difference is that if Get-Date returns multiple objects, the pipeline way works better than the parenthetical way as (Get-ChildItem)
, for example, is an array of items. This has changed in PowerShell v3 and (Get-ChildItem).FullPath
works as expected and returns an array of just the full paths.
You can just return ItemViewType and use it. See below code:
@Override
public int getItemViewType(int position) {
Message item = messageList.get(position);
// return my message layout
if(item.getUsername() == Message.userEnum.I)
return R.layout.item_message_me;
else
return R.layout.item_message; // return other message layout
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(viewType, viewGroup, false);
return new ViewHolder(view);
}
var a = {"apples": 3, "oranges": 4, "bananas": 42};
var array_keys = new Array();
var array_values = new Array();
for (var key in a) {
array_keys.push(key);
array_values.push(a[key]);
}
alert(array_keys);
alert(array_values);
Try this code. You can use $.get
instead of $.ajax
$( "input.suggest-user" ).autocomplete({
source: function( request, response ) {
$.ajax({
dataType: "json",
type : 'Get',
url: 'yourURL',
success: function(data) {
$('input.suggest-user').removeClass('ui-autocomplete-loading');
// hide loading image
response( $.map( data, function(item) {
// your operation on data
}));
},
error: function(data) {
$('input.suggest-user').removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3,
open: function() {},
close: function() {},
focus: function(event,ui) {},
select: function(event, ui) {}
});
The directive can access any attribute that is defined on the same element, even if the directive itself is not the element.
Template:
<div example-directive example-number="99" example-function="exampleCallback()"></div>
Directive:
app.directive('exampleDirective ', function () {
return {
restrict: 'A', // 'A' is the default, so you could remove this line
scope: {
callback : '&exampleFunction',
},
link: function (scope, element, attrs) {
var num = scope.$eval(attrs.exampleNumber);
console.log('number=',num);
scope.callback(); // calls exampleCallback()
}
};
});
If the value of attribute example-number
will be hard-coded, I suggest using $eval
once, and storing the value. Variable num
will have the correct type (a number).
You would call myBigDecimal.intValueExact()
(or just intValue()
) and it will even throw an exception if you would lose information. That returns an int but autoboxing takes care of that.
You need to use overflow option like below:
.nav{
max-height: 300px;
overflow-y: scroll;
}
Change the height according to amount of items you need to show
I would say AnyEdit too. It does not provide this specific functionalities. However, if you and your team use the AnyEdit features at each save actions, then when you open a file, it must not have any trailing whitespace.
So, if you modify this file, and if you add new trailing spaces, then during the save operation, AnyEdit will remove only these new spaces, as they are the only trailing spaces in this file.
If, for some reasons, you need to keep the trailing spaces on the lines that were not modified by you, then I have no answer for you, and I am not sure this kind of feature exists in any Eclipse plugin...
Windows 7 x32 I found that no matter what I did, the driver being used dated back to 2006. It would not update, in fact Windows appears to be preferring the old driver to the new. I eventually found a way to sort it.
The Device Manager contains 'ghost' drivers that need to be deleted (if you have the same problem as I). To see them requires setting a variable in the registry, restarting and then deleting the likely redundant drivers.
Open the Device Manager from the command line use devmgmt.msc There are other ways, but this is easiest to describe. Currently it shows only 'current' drivers.
Open the System Properties box. Via Command line use sysdm.cpl
** Be aware that playing with area of your computer can break it. Back away if you are at all unsure of this. **
Re-open the Device Manager, under view click Show Hidden Devices.
From here delete what you think are the problems then follow the advise you will have read elsewhere. On two seperate computers I have done this and found all I needed to do following this was download and install the standard google drivers as per user3079537's answer above. Good luck.
ref: http://www.petri.co.il/removing-old-drivers-from-vista-and-windows7.htm#
You can use Decode
as well:
SELECT DISTINCT a.item, decode(b.salesman,'VIKKIE','ICKY',Else),NVL(a.manufacturer,'Not Set')Manufacturer
FROM inv_items a, arv_sales b
WHERE a.co = b.co
AND A.ITEM_KEY = b.item_key
AND a.co = '100'
AND a.item LIKE 'BX%'
AND b.salesman in ('01','15')
AND trans_date BETWEEN to_date('010113','mmddrr')
and to_date('011713','mmddrr')
GROUP BY a.item, b.salesman, a.manufacturer
ORDER BY a.item
The new C++11 style:
#include <algorithm>
#include <string>
#include <cctype>
/// Try to find in the Haystack the Needle - ignore case
bool findStringIC(const std::string & strHaystack, const std::string & strNeedle)
{
auto it = std::search(
strHaystack.begin(), strHaystack.end(),
strNeedle.begin(), strNeedle.end(),
[](char ch1, char ch2) { return std::toupper(ch1) == std::toupper(ch2); }
);
return (it != strHaystack.end() );
}
Explanation of the std::search can be found on cplusplus.com.
When serialising an XML document to a .NET string, the encoding must be set to UTF-16. Strings are stored as UTF-16 internally, so this is the only encoding that makes sense. If you want to store data in a different encoding, you use a byte array instead.
SQL Server works on a similar principle; any string passed into an xml
column must be encoded as UTF-16. SQL Server will reject any string where the XML declaration does not specify UTF-16. If the XML declaration is not present, then the XML standard requires that it default to UTF-8, so SQL Server will reject that as well.
Bearing this in mind, here are some utility methods for doing the conversion.
public static string Serialize<T>(T value) {
if(value == null) {
return null;
}
XmlSerializer serializer = new XmlSerializer(typeof(T));
XmlWriterSettings settings = new XmlWriterSettings()
{
Encoding = new UnicodeEncoding(false, false), // no BOM in a .NET string
Indent = false,
OmitXmlDeclaration = false
};
using(StringWriter textWriter = new StringWriter()) {
using(XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings)) {
serializer.Serialize(xmlWriter, value);
}
return textWriter.ToString();
}
}
public static T Deserialize<T>(string xml) {
if(string.IsNullOrEmpty(xml)) {
return default(T);
}
XmlSerializer serializer = new XmlSerializer(typeof(T));
XmlReaderSettings settings = new XmlReaderSettings();
// No settings need modifying here
using(StringReader textReader = new StringReader(xml)) {
using(XmlReader xmlReader = XmlReader.Create(textReader, settings)) {
return (T) serializer.Deserialize(xmlReader);
}
}
}
var e= CKEDITOR.instances['sample'];
e.destroy();
e= null;
Date
is Comparable
& Equatable
(as of Swift 3)This answer complements @Ankit Thakur's answer.
Since Swift 3 the Date
struct (based on the underlying NSDate
class) adopts the Comparable
and Equatable
protocols.
Comparable
requires that Date
implement the operators: <
, <=
, >
, >=
.Equatable
requires that Date
implement the ==
operator.Equatable
allows Date
to use the default implementation of the !=
operator (which is the inverse of the Equatable
==
operator implementation).The following sample code exercises these comparison operators and confirms which comparisons are true with print
statements.
import Foundation
func describeComparison(date1: Date, date2: Date) -> String {
var descriptionArray: [String] = []
if date1 < date2 {
descriptionArray.append("date1 < date2")
}
if date1 <= date2 {
descriptionArray.append("date1 <= date2")
}
if date1 > date2 {
descriptionArray.append("date1 > date2")
}
if date1 >= date2 {
descriptionArray.append("date1 >= date2")
}
if date1 == date2 {
descriptionArray.append("date1 == date2")
}
if date1 != date2 {
descriptionArray.append("date1 != date2")
}
return descriptionArray.joined(separator: ", ")
}
let now = Date()
describeComparison(date1: now, date2: now.addingTimeInterval(1))
// date1 < date2, date1 <= date2, date1 != date2
describeComparison(date1: now, date2: now.addingTimeInterval(-1))
// date1 > date2, date1 >= date2, date1 != date2
describeComparison(date1: now, date2: now)
// date1 <= date2, date1 >= date2, date1 == date2
For a popup javascript is required. Put this in your header:
<script>
function myFunction()
{
alert("I am an alert box!"); // this is the message in ""
}
</script>
And this in your body:
<input type="button" onclick="myFunction()" value="Show alert box">
When the button is pressed a box pops up with the message set in the header.
This can be put in any html or php file without the php tags.
-----EDIT-----
To display it using php try this:
<?php echo '<script>myfunction()</script>'; ?>
It may not be 100% correct but the principle is the same.
To display different messages you can either create lots of functions or you can pass a variable in to the function when you call it.
Function can't change its parameters via the pointer/reference you gave it.
I go to this page every time I need to think about it:
http://www.parashift.com/c++-faq-lite/const-correctness.html
I believe there's also a good chapter in Meyers' "More Effective C++".
Use .map without return in simple way. Also start using let and const instead of var because let and const is more recommended
const rockets = [_x000D_
{ country:'Russia', launches:32 },_x000D_
{ country:'US', launches:23 },_x000D_
{ country:'China', launches:16 },_x000D_
{ country:'Europe(ESA)', launches:7 },_x000D_
{ country:'India', launches:4 },_x000D_
{ country:'Japan', launches:3 }_x000D_
];_x000D_
_x000D_
const launchOptimistic = rockets.map(elem => (_x000D_
{_x000D_
country: elem.country,_x000D_
launches: elem.launches+10_x000D_
} _x000D_
));_x000D_
_x000D_
console.log(launchOptimistic);
_x000D_
In our project, we are using a role hierarchy, while most of the above answers only aim at checking for a specific role, i.e. would only check for the role given, but not for that role and up the hierarchy.
A solution for this:
@Component
public class SpringRoleEvaluator {
@Resource(name="roleHierarchy")
private RoleHierarchy roleHierarchy;
public boolean hasRole(String role) {
UserDetails dt = AuthenticationUtils.getSessionUserDetails();
for (GrantedAuthority auth: roleHierarchy.getReachableGrantedAuthorities(dt.getAuthorities())) {
if (auth.toString().equals("ROLE_"+role)) {
return true;
}
}
return false;
}
RoleHierarchy is defined as a bean in spring-security.xml.
This is because you are referring to property of controller named HttpContext
. To access the current context use full class name:
System.Web.HttpContext.Current
However this is highly not recommended to access context like this in ASP.NET MVC, so yes, you can think of System.Web.HttpContext.Current
as being deprecated inside ASP.NET MVC. The correct way to access current context is
this.ControllerContext.HttpContext
or if you are inside a Controller, just use member
this.HttpContext
I see permutation has been suggested. In fact it can be made into one line:
>>> A = np.random.randint(5, size=(10,3))
>>> np.random.permutation(A)[:2]
array([[0, 3, 0],
[3, 1, 2]])
echo '<a href="' . $folder_path . '">Link text</a>';
Please note that you must use the path relative to your domain and, if the folder path is outside the public htdocs directory, it will not work.
EDIT: maybe i misreaded the question; you have a file on your pc and want to insert the path on the html page, and then send it to the server?
Base64 is a way to represent bytes in a textual form (as a string). So there is no such thing as a Base64 encoded byte[]. You'd have a base64 encoded string, which you could decode back to a byte[]
.
However, if you want to end up with a byte array, you could take the base64 encoded string and convert it to a byte array, like:
string base64String = Convert.ToBase64String(bytes);
byte[] stringBytes = Encoding.ASCII.GetBytes(base64String);
This, however, makes no sense because the best way to represent a byte[] as a byte[], is the byte[] itself :)
Its work for all external devices, But make sure only get external device folder name and then you need to get file from given location using File class.
public static List<String> getExternalMounts() {
final List<String> out = new ArrayList<>();
String reg = "(?i).*vold.*(vfat|ntfs|exfat|fat32|ext3|ext4).*rw.*";
String s = "";
try {
final Process process = new ProcessBuilder().command("mount")
.redirectErrorStream(true).start();
process.waitFor();
final InputStream is = process.getInputStream();
final byte[] buffer = new byte[1024];
while (is.read(buffer) != -1) {
s = s + new String(buffer);
}
is.close();
} catch (final Exception e) {
e.printStackTrace();
}
// parse output
final String[] lines = s.split("\n");
for (String line : lines) {
if (!line.toLowerCase(Locale.US).contains("asec")) {
if (line.matches(reg)) {
String[] parts = line.split(" ");
for (String part : parts) {
if (part.startsWith("/"))
if (!part.toLowerCase(Locale.US).contains("vold"))
out.add(part);
}
}
}
}
return out;
}
Calling:
List<String> list=getExternalMounts();
if(list.size()>0)
{
String[] arr=list.get(0).split("/");
int size=0;
if(arr!=null && arr.length>0) {
size= arr.length - 1;
}
File parentDir=new File("/storage/"+arr[size]);
if(parentDir.listFiles()!=null){
File parent[] = parentDir.listFiles();
for (int i = 0; i < parent.length; i++) {
// get file path as parent[i].getAbsolutePath());
}
}
}
Getting access to external storage
In order to read or write files on the external storage, your app must acquire the READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE system permissions. For example:
<manifest ...>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
...
</manifest>
Try surrounding the path in quotes. i.e "C:\Program Files\Appname\config.file"
Does it have to be specifically an InputStreamReader? How about using StringReader?
Otherwise, you could use StringBufferInputStream, but it's deprecated because of character conversion issues (which is why you should prefer StringReader).
You don't need to create a button. The facility exists by default.
Just right click on the arrow buttons on the bottom left hand corner of the Excel window. These are the arrow buttons which if you left click move left or right one worksheet.
If you right-click on these arrows Excel will pop up a dialogue with a list of worksheets from which you can click to set your chosen sheet active.
if (intent.resolveActivity(getPackageManager()) == null) {
Utils.showToast(activity, no_app_available_to_complete_this_task);
} else {
startActivityForResult(intent, 1);
}
This is expected behavior for an uncaught exception with display_errors off.
Your options here are to turn on display_errors via php or in the ini file or catch and output the exception.
ini_set("display_errors", 1);
or
try{
// code that may throw an exception
} catch(Exception $e){
echo $e->getMessage();
}
If you are throwing exceptions, the intention is that somewhere further down the line something will catch and deal with it. If not it is a server error (500).
Another option for you would be to use set_exception_handler to set a default error handler for your script.
function default_exception_handler(Exception $e){
// show something to the user letting them know we fell down
echo "<h2>Something Bad Happened</h2>";
echo "<p>We fill find the person responsible and have them shot</p>";
// do some logging for the exception and call the kill_programmer function.
}
set_exception_handler("default_exception_handler");
if [ "$x" = "valid" ]; then
echo "x has the value 'valid'"
fi
If you want to do something when they don't match, replace =
with !=
. You can read more about string operations and arithmetic operations in their respective documentation.
$x
?You want the quotes around $x
, because if it is empty, your Bash script encounters a syntax error as seen below:
if [ = "valid" ]; then
==
operatorNote that Bash allows ==
to be used for equality with [
, but this is not standard.
Use either the first case wherein the quotes around $x
are optional:
if [[ "$x" == "valid" ]]; then
or use the second case:
if [ "$x" = "valid" ]; then
You don't need case
in the where
statement, just use parentheses and or
:
Select * From Times
WHERE StartDate <= @Date AND EndDate >= @Date
AND (
(@day = 'Monday' AND Monday = 1)
OR (@day = 'Tuesday' AND Tuesday = 1)
OR Wednesday = 1
)
Additionally, your syntax is wrong for a case. It doesn't append things to the string--it returns a single value. You'd want something like this, if you were actually going to use a case
statement (which you shouldn't):
Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date)
AND 1 = CASE WHEN @day = 'Monday' THEN Monday
WHEN @day = 'Tuesday' THEN Tuesday
ELSE Wednesday
END
And just for an extra umph, you can use the between
operator for your date:
where @Date between StartDate and EndDate
Making your final query:
select
*
from
Times
where
@Date between StartDate and EndDate
and (
(@day = 'Monday' and Monday = 1)
or (@day = 'Tuesday' and Tuesday = 1)
or Wednesday = 1
)
Use the native PHP $_SERVER['HTTP_USER_AGENT']
variable instead.
Much confusion stems from the existence of at least three major libraries named bootstrap-datepicker:
If you're starting a new project - or heck, even if you're taking over an old project using the eyecon version - I recommend that you use eternicode's version, not eyecon's. The original eyecon version is outright inferior in terms of both functionality and documentation, and this is unlikely to change - it has not been updated since March 2013.
You can see most of the capabilities of the eternicode datepicker on the demo page which lets you play with the datepicker's configuration and observe the results. For more detail, see the succinct but comprehensive documentation, which you can probably consume in its entirety in under an hour.
In case you're impatient, though, here's a very short step-by-step guide to the simplest and most common use case for the datepicker.
Put an input
element on your page somewhere, e.g.
<input id="my-date-input">
With jQuery, select your input and call the .datepicker()
method:
jQuery('#my-date-input').datepicker();
Load your page and click on or tab into your input
element. A datepicker will appear:
One other option would be to use something like this
SELECT *
FROM table t INNER JOIN
(
SELECT 'Text%' Col
UNION SELECT 'Link%'
UNION SELECT 'Hello%'
UNION SELECT '%World%'
) List ON t.COLUMN LIKE List.Col
angle = Math.toDegrees(Math.atan2(target.x - x, target.y - y));
now for orientation of circular values to keep angle between 0 and 359 can be:
angle = angle + Math.ceil( -angle / 360 ) * 360
You can use following code which generate pdf file in background as like on button click and then would popup in brwoser with SaveAs and cancel option.
Warning[] warnings;
string[] streamIds;
string mimeType = string.Empty;
string encoding = string.Empty;`enter code here`
string extension = string.Empty;
DataSet dsGrpSum, dsActPlan, dsProfitDetails,
dsProfitSum, dsSumHeader, dsDetailsHeader, dsBudCom = null;
enter code here
//This is optional if you have parameter then you can add parameters as much as you want
ReportParameter[] param = new ReportParameter[5];
param[0] = new ReportParameter("Report_Parameter_0", "1st Para", true);
param[1] = new ReportParameter("Report_Parameter_1", "2nd Para", true);
param[2] = new ReportParameter("Report_Parameter_2", "3rd Para", true);
param[3] = new ReportParameter("Report_Parameter_3", "4th Para", true);
param[4] = new ReportParameter("Report_Parameter_4", "5th Para");
DataSet dsData= "Fill this dataset with your data";
ReportDataSource rdsAct = new ReportDataSource("RptActDataSet_usp_GroupAccntDetails", dsActPlan.Tables[0]);
ReportViewer viewer = new ReportViewer();
viewer.LocalReport.Refresh();
viewer.LocalReport.ReportPath = "Reports/AcctPlan.rdlc"; //This is your rdlc name.
viewer.LocalReport.SetParameters(param);
viewer.LocalReport.DataSources.Add(rdsAct); // Add datasource here
byte[] bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
// byte[] bytes = viewer.LocalReport.Render("Excel", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
// Now that you have all the bytes representing the PDF report, buffer it and send it to the client.
// System.Web.HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Buffer = true;
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "attachment; filename= filename" + "." + extension);
Response.OutputStream.Write(bytes, 0, bytes.Length); // create the file
Response.Flush(); // send it to the client to download
Response.End();
/***Your Code***/
public void paintComponent(Graphics g){
/***Your Code***/
g.setColor(Color.RED);
g.fillOval(50,50,20,20);
}
g.fillOval(x-axis,y-axis,width,height);
You can start with a custom number and increment from there, for example you want to add a cheque number for each payment you can do:
select @StartChequeNumber = 3446;
SELECT
((ROW_NUMBER() OVER(ORDER BY AnyColumn)) + @StartChequeNumber ) AS 'ChequeNumber'
,* FROM YourTable
will give the correct cheque number for each row.
This should do it for you.
<div id="nav-wrap">
<ul id="nav">
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
</ul>
</div>
#nav-wrap {
float: left;
height: 87px;
width: 900px;
}
#nav {
display: inline;
height: 87px;
width: 100%;
}
.nav-item {
float: left;
height: 87px;
line-height: 87px;
text-align: center;
text-decoration: none;
width: 150px;
}
The newest camera2 apis work fine w/ an emulator that has camera support enabled.
Example for using the newer API:
Emacs has comment-dwim (Do What I Mean) - just select the block and do a:
M-;
It's a toggle - use it to comment AND uncomment blocks.
If you don't have yaml-mode installed you will need to tell Emacs to use the hash character (#).
auto-alignment shortcut key Ctrl
+Shift
+F
to change the shortcut keys Goto Window > Preferences > Java > Editor > Save Actions
My understanding is that a primary key and a unique index with a not-null constraint, are the same (*); and I suppose one choose one or the other depending on what the specification explicitly states or implies (a matter of what you want to express and explicitly enforce). If it requires uniqueness and not-null, then make it a primary key. If it just happens all parts of a unique index are not-null without any requirement for that, then just make it a unique index.
The sole remaining difference is, you may have multiple not-null unique indexes, while you can't have multiple primary keys.
(*) Excepting a practical difference: a primary key can be the default unique key for some operations, like defining a foreign key. Ex. if one define a foreign key referencing a table and does not provide the column name, if the referenced table has a primary key, then the primary key will be the referenced column. Otherwise, the the referenced column will have to be named explicitly.
Others here have mentioned DB replication, but I don't know about it.
netstat -ano|grep 443|grep LISTEN
will tell you whether a process is listening on port 443 (you might have to replace LISTEN with a string in your language, though, depending on your system settings).
User interactive approach:
git clean -i -fd
Remove .classpath [y/N]? N
Remove .gitignore [y/N]? N
Remove .project [y/N]? N
Remove .settings/ [y/N]? N
Remove src/com/amazon/arsdumpgenerator/inspector/ [y/N]? y
Remove src/com/amazon/arsdumpgenerator/manifest/ [y/N]? y
Remove src/com/amazon/arsdumpgenerator/s3/ [y/N]? y
Remove tst/com/amazon/arsdumpgenerator/manifest/ [y/N]? y
Remove tst/com/amazon/arsdumpgenerator/s3/ [y/N]? y
-i for interactive
-f for force
-d for directory
-x for ignored files(add if required)
Note: Add -n or --dry-run to just check what it will do.
alter user username superuser;
Put your code in a string, iterate, eval, setTimeout and recursion to continue with the remaining lines. No doubt I'll refine this or just throw it out if it doesn't hit the mark. My intention is to use it to simulate really, really basic user testing.
The recursion and setTimeout make it sequential.
Thoughts?
var line_pos = 0;
var string =`
console.log('123');
console.log('line pos is '+ line_pos);
SLEEP
console.log('waited');
console.log('line pos is '+ line_pos);
SLEEP
SLEEP
console.log('Did i finish?');
`;
var lines = string.split("\n");
var r = function(line_pos){
for (i = p; i < lines.length; i++) {
if(lines[i] == 'SLEEP'){
setTimeout(function(){r(line_pos+1)},1500);
return;
}
eval (lines[line_pos]);
}
console.log('COMPLETED READING LINES');
return;
}
console.log('STARTED READING LINES');
r.call(this,line_pos);
OUTPUT
STARTED READING LINES
123
124
1 p is 0
undefined
waited
p is 5
125
Did i finish?
COMPLETED READING LINES
cross_validation was deprecated some time ago, try switching it out with model_selection
It prevents JSON hijacking, a major JSON security issue that is formally fixed in all major browsers since 2011 with ECMAScript 5.
Contrived example: say Google has a URL like mail.google.com/json?action=inbox
which returns the first 50 messages of your inbox in JSON format. Evil websites on other domains can't make AJAX requests to get this data due to the same-origin policy, but they can include the URL via a <script>
tag. The URL is visited with your cookies, and by overriding the global array constructor or accessor methods they can have a method called whenever an object (array or hash) attribute is set, allowing them to read the JSON content.
The while(1);
or &&&BLAH&&&
prevents this: an AJAX request at mail.google.com
will have full access to the text content, and can strip it away. But a <script>
tag insertion blindly executes the JavaScript without any processing, resulting in either an infinite loop or a syntax error.
This does not address the issue of cross-site request forgery.
Some of the core differences between C# and Javascript script syntax in Unity.
http://unity3d.com/learn/tutorials/modules/beginner/scripting/c-sharp-vs-javascript-syntax
but keep in mind C# is the best one to develop in unity
Can I use pip to install iPython?
Sure, both (first approach on page)
pip install ipython
and (third approach, second is conda
)
You can manually download IPython from GitHub or PyPI. To install one of these versions, unpack it and run the following from the top-level source directory using the Terminal:
pip install .
are officially recommended ways to install.
Why should I use conda as another python package manager when I already have pip?
As said here:
If you need a specific package, maybe only for one project, or if you need to share the project with someone else, conda seems more appropriate.
Conda surpasses pip in (YMMV)
What is the difference between pip and conda?
That is extensively answered by everyone else.
SELECT DISTINCT (t1.ProdId), t1.Quantity FROM Dummy t1 INNER JOIN
(SELECT ProdId, MAX(Quantity) as MaxQuantity FROM Dummy GROUP BY ProdId) t2
ON t1.ProdId = t2.ProdId
AND t1.Quantity = t2.MaxQuantity
ORDER BY t1.ProdId
this will give you the idea.
This (mysql_connect, mysql_...) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.
(ref: http://php.net/manual/en/function.mysql-connect.php)
Object Oriented:
$mysqli = new mysqli("host", "user", "password");
$mysqli->select_db("db");
Procedural:
$link = mysqli_connect("host","user","password") or die(mysqli_error($link));
mysqli_select_db($link, "db");
Finally solved it:
var zoomIntensity = 0.2;_x000D_
_x000D_
var canvas = document.getElementById("canvas");_x000D_
var context = canvas.getContext("2d");_x000D_
var width = 600;_x000D_
var height = 200;_x000D_
_x000D_
var scale = 1;_x000D_
var originx = 0;_x000D_
var originy = 0;_x000D_
var visibleWidth = width;_x000D_
var visibleHeight = height;_x000D_
_x000D_
_x000D_
function draw(){_x000D_
// Clear screen to white._x000D_
context.fillStyle = "white";_x000D_
context.fillRect(originx,originy,800/scale,600/scale);_x000D_
// Draw the black square._x000D_
context.fillStyle = "black";_x000D_
context.fillRect(50,50,100,100);_x000D_
}_x000D_
// Draw loop at 60FPS._x000D_
setInterval(draw, 1000/60);_x000D_
_x000D_
canvas.onwheel = function (event){_x000D_
event.preventDefault();_x000D_
// Get mouse offset._x000D_
var mousex = event.clientX - canvas.offsetLeft;_x000D_
var mousey = event.clientY - canvas.offsetTop;_x000D_
// Normalize wheel to +1 or -1._x000D_
var wheel = event.deltaY < 0 ? 1 : -1;_x000D_
_x000D_
// Compute zoom factor._x000D_
var zoom = Math.exp(wheel*zoomIntensity);_x000D_
_x000D_
// Translate so the visible origin is at the context's origin._x000D_
context.translate(originx, originy);_x000D_
_x000D_
// Compute the new visible origin. Originally the mouse is at a_x000D_
// distance mouse/scale from the corner, we want the point under_x000D_
// the mouse to remain in the same place after the zoom, but this_x000D_
// is at mouse/new_scale away from the corner. Therefore we need to_x000D_
// shift the origin (coordinates of the corner) to account for this._x000D_
originx -= mousex/(scale*zoom) - mousex/scale;_x000D_
originy -= mousey/(scale*zoom) - mousey/scale;_x000D_
_x000D_
// Scale it (centered around the origin due to the trasnslate above)._x000D_
context.scale(zoom, zoom);_x000D_
// Offset the visible origin to it's proper position._x000D_
context.translate(-originx, -originy);_x000D_
_x000D_
// Update scale and others._x000D_
scale *= zoom;_x000D_
visibleWidth = width / scale;_x000D_
visibleHeight = height / scale;_x000D_
}
_x000D_
<canvas id="canvas" width="600" height="200"></canvas>
_x000D_
The key, as @Tatarize pointed out, is to compute the axis position such that the zoom point (mouse pointer) remains in the same place after the zoom.
Originally the mouse is at a distance mouse/scale
from the corner, we want the point under the mouse to remain in the same place after the zoom, but this is at mouse/new_scale
away from the corner. Therefore we need to shift the origin
(coordinates of the corner) to account for this.
originx -= mousex/(scale*zoom) - mousex/scale;
originy -= mousey/(scale*zoom) - mousey/scale;
scale *= zoom
The remaining code then needs to apply the scaling and translate to the draw context so it's origin coincides with the canvas corner.
Once you have connected your UITableView delegate
and datasource
to your controller, you could do something like this:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSString *sectionName;
switch (section) {
case 0:
sectionName = NSLocalizedString(@"mySectionName", @"mySectionName");
break;
case 1:
sectionName = NSLocalizedString(@"myOtherSectionName", @"myOtherSectionName");
break;
// ...
default:
sectionName = @"";
break;
}
return sectionName;
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let sectionName: String
switch section {
case 0:
sectionName = NSLocalizedString("mySectionName", comment: "mySectionName")
case 1:
sectionName = NSLocalizedString("myOtherSectionName", comment: "myOtherSectionName")
// ...
default:
sectionName = ""
}
return sectionName
}
N 1.1's answer is correct. In addition, I've written a small JavaScript function to extract the current link from a list, which will save you the trouble of modifying each page to know its current link.
<script type="text/javascript">
function getCurrentLinkFrom(links){
var curPage = document.URL;
curPage = curPage.substr(curPage.lastIndexOf("/")) ;
links.each(function(){
var linkPage = $(this).attr("href");
linkPage = linkPage.substr(linkPage.lastIndexOf("/"));
if (curPage == linkPage){
return $(this);
}
});
};
$(document).ready(function(){
var currentLink = getCurrentLinkFrom($("navbar a"));
currentLink.addClass("current_link") ;
});
</script>
In most of the modern single page applications, we indeed have to store the token somewhere on the client side (most common use case - to keep the user logged in after a page refresh).
There are a total of 2 options available: Web Storage (session storage, local storage) and a client side cookie. Both options are widely used, but this doesn't mean they are very secure.
Tom Abbott summarizes well the JWT sessionStorage and localStorage security:
Web Storage (localStorage/sessionStorage) is accessible through JavaScript on the same domain. This means that any JavaScript running on your site will have access to web storage, and because of this can be vulnerable to cross-site scripting (XSS) attacks. XSS, in a nutshell, is a type of vulnerability where an attacker can inject JavaScript that will run on your page. Basic XSS attacks attempt to inject JavaScript through form inputs, where the attacker puts
<script>alert('You are Hacked');</script>
into a form to see if it is run by the browser and can be viewed by other users.
To prevent XSS, the common response is to escape and encode all untrusted data. React (mostly) does that for you! Here's a great discussion about how much XSS vulnerability protection is React responsible for.
But that doesn't cover all possible vulnerabilities! Another potential threat is the usage of JavaScript hosted on CDNs or outside infrastructure.
Here's Tom again:
Modern web apps include 3rd party JavaScript libraries for A/B testing, funnel/market analysis, and ads. We use package managers like Bower to import other peoples’ code into our apps.
What if only one of the scripts you use is compromised? Malicious JavaScript can be embedded on the page, and Web Storage is compromised. These types of XSS attacks can get everyone’s Web Storage that visits your site, without their knowledge. This is probably why a bunch of organizations advise not to store anything of value or trust any information in web storage. This includes session identifiers and tokens.
Therefore, my conclusion is that as a storage mechanism, Web Storage does not enforce any secure standards during transfer. Whoever reads Web Storage and uses it must do their due diligence to ensure they always send the JWT over HTTPS and never HTTP.
hifarrer's full solution is very helpful to me.
but, I met many other problems - supporting other mime type, listing capture devices(camera, video, audio recoder), opening capture device immediately(ex: <input accept="image/*;capture"> )...
So, I made a solution that works exactly same as default web browser app.
I used android-4.4.3_r1/src/com/android/browser/UploadHandler.java. (thanks to Rupert Rawnsley )
package org.mospi.agatenativewebview;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebSettings.PluginState;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = (WebView) findViewById(R.id.webView1);
initWebView(webView);
webView.loadUrl("http://google.com"); // TODO input your url
}
private final static Object methodInvoke(Object obj, String method, Class<?>[] parameterTypes, Object[] args) {
try {
Method m = obj.getClass().getMethod(method, new Class[] { boolean.class });
m.invoke(obj, args);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private void initWebView(WebView webView) {
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setAllowFileAccess(true);
settings.setDomStorageEnabled(true);
settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
settings.setLoadWithOverviewMode(true);
settings.setUseWideViewPort(true);
settings.setSupportZoom(true);
// settings.setPluginsEnabled(true);
methodInvoke(settings, "setPluginsEnabled", new Class[] { boolean.class }, new Object[] { true });
// settings.setPluginState(PluginState.ON);
methodInvoke(settings, "setPluginState", new Class[] { PluginState.class }, new Object[] { PluginState.ON });
// settings.setPluginsEnabled(true);
methodInvoke(settings, "setPluginsEnabled", new Class[] { boolean.class }, new Object[] { true });
// settings.setAllowUniversalAccessFromFileURLs(true);
methodInvoke(settings, "setAllowUniversalAccessFromFileURLs", new Class[] { boolean.class }, new Object[] { true });
// settings.setAllowFileAccessFromFileURLs(true);
methodInvoke(settings, "setAllowFileAccessFromFileURLs", new Class[] { boolean.class }, new Object[] { true });
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.clearHistory();
webView.clearFormData();
webView.clearCache(true);
webView.setWebChromeClient(new MyWebChromeClient());
// webView.setDownloadListener(downloadListener);
}
UploadHandler mUploadHandler;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == Controller.FILE_SELECTED) {
// Chose a file from the file picker.
if (mUploadHandler != null) {
mUploadHandler.onResult(resultCode, intent);
}
}
super.onActivityResult(requestCode, resultCode, intent);
}
class MyWebChromeClient extends WebChromeClient {
public MyWebChromeClient() {
}
private String getTitleFromUrl(String url) {
String title = url;
try {
URL urlObj = new URL(url);
String host = urlObj.getHost();
if (host != null && !host.isEmpty()) {
return urlObj.getProtocol() + "://" + host;
}
if (url.startsWith("file:")) {
String fileName = urlObj.getFile();
if (fileName != null && !fileName.isEmpty()) {
return fileName;
}
}
} catch (Exception e) {
// ignore
}
return title;
}
@Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
String newTitle = getTitleFromUrl(url);
new AlertDialog.Builder(MainActivity.this).setTitle(newTitle).setMessage(message).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
}).setCancelable(false).create().show();
return true;
// return super.onJsAlert(view, url, message, result);
}
@Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
String newTitle = getTitleFromUrl(url);
new AlertDialog.Builder(MainActivity.this).setTitle(newTitle).setMessage(message).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
}).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
}).setCancelable(false).create().show();
return true;
// return super.onJsConfirm(view, url, message, result);
}
// Android 2.x
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
openFileChooser(uploadMsg, "");
}
// Android 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
openFileChooser(uploadMsg, "", "filesystem");
}
// Android 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
mUploadHandler = new UploadHandler(new Controller());
mUploadHandler.openFileChooser(uploadMsg, acceptType, capture);
}
// Android 4.4, 4.4.1, 4.4.2
// openFileChooser function is not called on Android 4.4, 4.4.1, 4.4.2,
// you may use your own java script interface or other hybrid framework.
// Android 5.0.1
public boolean onShowFileChooser(
WebView webView, ValueCallback<Uri[]> filePathCallback,
FileChooserParams fileChooserParams) {
String acceptTypes[] = fileChooserParams.getAcceptTypes();
String acceptType = "";
for (int i = 0; i < acceptTypes.length; ++ i) {
if (acceptTypes[i] != null && acceptTypes[i].length() != 0)
acceptType += acceptTypes[i] + ";";
}
if (acceptType.length() == 0)
acceptType = "*/*";
final ValueCallback<Uri[]> finalFilePathCallback = filePathCallback;
ValueCallback<Uri> vc = new ValueCallback<Uri>() {
@Override
public void onReceiveValue(Uri value) {
Uri[] result;
if (value != null)
result = new Uri[]{value};
else
result = null;
finalFilePathCallback.onReceiveValue(result);
}
};
openFileChooser(vc, acceptType, "filesystem");
return true;
}
};
class Controller {
final static int FILE_SELECTED = 4;
Activity getActivity() {
return MainActivity.this;
}
}
// copied from android-4.4.3_r1/src/com/android/browser/UploadHandler.java
//////////////////////////////////////////////////////////////////////
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// package com.android.browser;
//
// import android.app.Activity;
// import android.content.ActivityNotFoundException;
// import android.content.Intent;
// import android.net.Uri;
// import android.os.Environment;
// import android.provider.MediaStore;
// import android.webkit.ValueCallback;
// import android.widget.Toast;
//
// import java.io.File;
// import java.util.Vector;
//
// /**
// * Handle the file upload callbacks from WebView here
// */
// public class UploadHandler {
class UploadHandler {
/*
* The Object used to inform the WebView of the file to upload.
*/
private ValueCallback<Uri> mUploadMessage;
private String mCameraFilePath;
private boolean mHandled;
private boolean mCaughtActivityNotFoundException;
private Controller mController;
public UploadHandler(Controller controller) {
mController = controller;
}
String getFilePath() {
return mCameraFilePath;
}
boolean handled() {
return mHandled;
}
void onResult(int resultCode, Intent intent) {
if (resultCode == Activity.RESULT_CANCELED && mCaughtActivityNotFoundException) {
// Couldn't resolve an activity, we are going to try again so skip
// this result.
mCaughtActivityNotFoundException = false;
return;
}
Uri result = intent == null || resultCode != Activity.RESULT_OK ? null
: intent.getData();
// As we ask the camera to save the result of the user taking
// a picture, the camera application does not return anything other
// than RESULT_OK. So we need to check whether the file we expected
// was written to disk in the in the case that we
// did not get an intent returned but did get a RESULT_OK. If it was,
// we assume that this result has came back from the camera.
if (result == null && intent == null && resultCode == Activity.RESULT_OK) {
File cameraFile = new File(mCameraFilePath);
if (cameraFile.exists()) {
result = Uri.fromFile(cameraFile);
// Broadcast to the media scanner that we have a new photo
// so it will be added into the gallery for the user.
mController.getActivity().sendBroadcast(
new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
}
}
mUploadMessage.onReceiveValue(result);
mHandled = true;
mCaughtActivityNotFoundException = false;
}
void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
final String imageMimeType = "image/*";
final String videoMimeType = "video/*";
final String audioMimeType = "audio/*";
final String mediaSourceKey = "capture";
final String mediaSourceValueCamera = "camera";
final String mediaSourceValueFileSystem = "filesystem";
final String mediaSourceValueCamcorder = "camcorder";
final String mediaSourceValueMicrophone = "microphone";
// According to the spec, media source can be 'filesystem' or 'camera' or 'camcorder'
// or 'microphone' and the default value should be 'filesystem'.
String mediaSource = mediaSourceValueFileSystem;
if (mUploadMessage != null) {
// Already a file picker operation in progress.
return;
}
mUploadMessage = uploadMsg;
// Parse the accept type.
String params[] = acceptType.split(";");
String mimeType = params[0];
if (capture.length() > 0) {
mediaSource = capture;
}
if (capture.equals(mediaSourceValueFileSystem)) {
// To maintain backwards compatibility with the previous implementation
// of the media capture API, if the value of the 'capture' attribute is
// "filesystem", we should examine the accept-type for a MIME type that
// may specify a different capture value.
for (String p : params) {
String[] keyValue = p.split("=");
if (keyValue.length == 2) {
// Process key=value parameters.
if (mediaSourceKey.equals(keyValue[0])) {
mediaSource = keyValue[1];
}
}
}
}
//Ensure it is not still set from a previous upload.
mCameraFilePath = null;
if (mimeType.equals(imageMimeType)) {
if (mediaSource.equals(mediaSourceValueCamera)) {
// Specified 'image/*' and requested the camera, so go ahead and launch the
// camera directly.
startActivity(createCameraIntent());
return;
} else {
// Specified just 'image/*', capture=filesystem, or an invalid capture parameter.
// In all these cases we show a traditional picker filetered on accept type
// so launch an intent for both the Camera and image/* OPENABLE.
Intent chooser = createChooserIntent(createCameraIntent());
chooser.putExtra(Intent.EXTRA_INTENT, createOpenableIntent(imageMimeType));
startActivity(chooser);
return;
}
} else if (mimeType.equals(videoMimeType)) {
if (mediaSource.equals(mediaSourceValueCamcorder)) {
// Specified 'video/*' and requested the camcorder, so go ahead and launch the
// camcorder directly.
startActivity(createCamcorderIntent());
return;
} else {
// Specified just 'video/*', capture=filesystem or an invalid capture parameter.
// In all these cases we show an intent for the traditional file picker, filtered
// on accept type so launch an intent for both camcorder and video/* OPENABLE.
Intent chooser = createChooserIntent(createCamcorderIntent());
chooser.putExtra(Intent.EXTRA_INTENT, createOpenableIntent(videoMimeType));
startActivity(chooser);
return;
}
} else if (mimeType.equals(audioMimeType)) {
if (mediaSource.equals(mediaSourceValueMicrophone)) {
// Specified 'audio/*' and requested microphone, so go ahead and launch the sound
// recorder.
startActivity(createSoundRecorderIntent());
return;
} else {
// Specified just 'audio/*', capture=filesystem of an invalid capture parameter.
// In all these cases so go ahead and launch an intent for both the sound
// recorder and audio/* OPENABLE.
Intent chooser = createChooserIntent(createSoundRecorderIntent());
chooser.putExtra(Intent.EXTRA_INTENT, createOpenableIntent(audioMimeType));
startActivity(chooser);
return;
}
}
// No special handling based on the accept type was necessary, so trigger the default
// file upload chooser.
startActivity(createDefaultOpenableIntent());
}
private void startActivity(Intent intent) {
try {
mController.getActivity().startActivityForResult(intent, Controller.FILE_SELECTED);
} catch (ActivityNotFoundException e) {
// No installed app was able to handle the intent that
// we sent, so fallback to the default file upload control.
try {
mCaughtActivityNotFoundException = true;
mController.getActivity().startActivityForResult(createDefaultOpenableIntent(),
Controller.FILE_SELECTED);
} catch (ActivityNotFoundException e2) {
// Nothing can return us a file, so file upload is effectively disabled.
Toast.makeText(mController.getActivity(), R.string.uploads_disabled,
Toast.LENGTH_LONG).show();
}
}
}
private Intent createDefaultOpenableIntent() {
// Create and return a chooser with the default OPENABLE
// actions including the camera, camcorder and sound
// recorder where available.
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
Intent chooser = createChooserIntent(createCameraIntent(), createCamcorderIntent(),
createSoundRecorderIntent());
chooser.putExtra(Intent.EXTRA_INTENT, i);
return chooser;
}
private Intent createChooserIntent(Intent... intents) {
Intent chooser = new Intent(Intent.ACTION_CHOOSER);
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);
chooser.putExtra(Intent.EXTRA_TITLE,
mController.getActivity().getResources()
.getString(R.string.choose_upload));
return chooser;
}
private Intent createOpenableIntent(String type) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType(type);
return i;
}
private Intent createCameraIntent() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File externalDataDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM);
File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
File.separator + "browser-photos");
cameraDataDir.mkdirs();
mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
System.currentTimeMillis() + ".jpg";
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
return cameraIntent;
}
private Intent createCamcorderIntent() {
return new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
}
private Intent createSoundRecorderIntent() {
return new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
}
}
}
additional string resoruce of res/values/string.xml :
<string name="uploads_disabled">File uploads are disabled.</string>
<string name="choose_upload">Choose file for upload</string>
If you are using proguard, you may need below option in proguard-project.txt :
-keepclassmembers class * extends android.webkit.WebChromeClient {
public void openFileChooser(...);
}
UPDATE #1 (2015.09.09)
adds code for Android 5.0.1 compatability.
The Developer Toolbar GCLI and Shift+F2 shortcut were removed in Firefox version 60. To take a screenshot in 60 or newer:
:screenshot
or :screenshot --fullpage
Find out more regarding screenshots and other features
For Firefox versions < 60:
Press Shift+F2 or go to Tools > Web Developer > Developer Toolbar to open a command line. Write:
screenshot
and press Enter in order to take a screenshot.
To fully answer the question, you can even save the whole page, not only the visible part of it:
screenshot --fullpage
And to copy the screenshot to clipboard, use --clipboard
option:
screenshot --clipboard --fullpage
Firefox 18 changes the way arguments are passed to commands, you have to add "--" before them.
You can find some documentation and the full list of commands here.
PS. The screenshots are saved into the downloads directory by default.
Maybe this is going a bit too far back but…
Also, I’d like to suggest that multiline text fields have a different type (e.g. “textarea") than single-line fields ("text"), as they really are different types of things, and imply different issues (semantics) for client-side handling.
If you want a smaller table (e.g. if your table extends beyond the area that can be displayed) you can simply change:
\usepackage[paper=a4paper]{geometry}
to \usepackage[paper=a3paper]{geometry}
.
Note that this only helps if you don't plan on printing your table out, as it will appear way too small, then.
The best way is to create a variable of type Worksheet
, assign the worksheet and use it every time the VBA would implicitly use the ActiveSheet
.
This will help you avoid bugs that will eventually show up when your program grows in size.
For example something like Range("A1:C10").Sort Key1:=Range("A2")
is good when the macro works only on one sheet. But you will eventually expand your macro to work with several sheets, find out that this doesn't work, adjust it to ShTest1.Range("A1:C10").Sort Key1:=Range("A2")
... and find out that it still doesn't work.
Here is the correct way:
Dim ShTest1 As Worksheet
Set ShTest1 = Sheets("Test1")
ShTest1.Range("A1:C10").Sort Key1:=ShTest1.Range("A2")
Quote: I would like to know how to display the div in the middle of the screen, whether user has scrolled up/down.
Change
position: absolute;
To
position: fixed;
W3C specifications for position: absolute
and for position: fixed
.