The answers are fine, but with Swift 4 you could simplify your code a bit:
let text = "Test string"
let substring = "string"
let substringRange = text.range(of: substring)!
let nsRange = NSRange(substringRange, in: text)
Be cautious, as the result of range
function has to be unwrapped.
An easy, efficient solution is to configure the view to use a Core Animation layer as its backing store. Then you can use -[CALayer setBackgroundColor:]
to set the background color of the layer.
- (void)awakeFromNib {
self.wantsLayer = YES; // NSView will create a CALayer automatically
}
- (BOOL)wantsUpdateLayer {
return YES; // Tells NSView to call `updateLayer` instead of `drawRect:`
}
- (void)updateLayer {
self.layer.backgroundColor = [NSColor colorWithCalibratedRed:0.227f
green:0.251f
blue:0.337
alpha:0.8].CGColor;
}
That’s it!
The accepted answer has the drawback that it doesn't take into consideration that a database can be locked by a connection that is executing a query that involves tables in a database other than the one connected to.
This can be the case if the server instance has more than one database and the query directly or indirectly (for example through synonyms) use tables in more than one database etc.
I therefore find that it sometimes is better to use syslockinfo to find the connections to kill.
My suggestion would therefore be to use the below variation of the accepted answer from AlexK:
USE [master];
DECLARE @kill varchar(8000) = '';
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), req_spid) + ';'
FROM master.dbo.syslockinfo
WHERE rsc_type = 2
AND rsc_dbid = db_id('MyDB')
EXEC(@kill);
Cookie-Based Authentication
Cookies based Authentication works normally in these 4 steps-
Browser will submit this session Id on each subsequent requests, the session ID is verified against the database, based on this session id website will identify the session belonging to which client and then give access the request.
Once a user logs out of the app, the session is destroyed both client-side and server-side.
The algorithm (HS256
) used to sign the JWT means that the secret is a symmetric key that is known by both the sender and the receiver. It is negotiated and distributed out of band. Hence, if you're the intended recipient of the token, the sender should have provided you with the secret out of band.
If you're the sender, you can use an arbitrary string of bytes as the secret, it can be generated or purposely chosen. You have to make sure that you provide the secret to the intended recipient out of band.
For the record, the 3 elements in the JWT are not base64-encoded but base64url-encoded, which is a variant of base64 encoding that results in a URL-safe value.
Edit: Seven years later, this answer still gets occasional upvotes. It's fine if you are looking for runtime checking, but I would now recommend compile-time type checking using Typescript, or possibly Flow. See https://stackoverflow.com/a/31420719/610585 above for more.
Original answer:
It's not built into the language, but you can do it yourself quite easily. Vibhu's answer is what I would consider the typical way of type checking in Javascript. If you want something more generalized, try something like this: (just an example to get you started)
typedFunction = function(paramsList, f){
//optionally, ensure that typedFunction is being called properly -- here's a start:
if (!(paramsList instanceof Array)) throw Error('invalid argument: paramsList must be an array');
//the type-checked function
return function(){
for(var i=0,p,arg;p=paramsList[i],arg=arguments[i],i<paramsList.length; i++){
if (typeof p === 'string'){
if (typeof arg !== p) throw new Error('expected type ' + p + ', got ' + typeof arg);
}
else { //function
if (!(arg instanceof p)) throw new Error('expected type ' + String(p).replace(/\s*\{.*/, '') + ', got ' + typeof arg);
}
}
//type checking passed; call the function itself
return f.apply(this, arguments);
}
}
//usage:
var ds = typedFunction([Date, 'string'], function(d, s){
console.log(d.toDateString(), s.substr(0));
});
ds('notadate', 'test');
//Error: expected type function Date(), got string
ds();
//Error: expected type function Date(), got undefined
ds(new Date(), 42);
//Error: expected type string, got number
ds(new Date(), 'success');
//Fri Jun 14 2013 success
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$parts = explode("\r\n\r\nHTTP/", $response);
$parts = (count($parts) > 1 ? 'HTTP/' : '').array_pop($parts);
list($headers, $body) = explode("\r\n\r\n", $parts, 2);
Works with HTTP/1.1 100 Continue
before other headers.
If you need work with buggy servers which sends only LF instead of CRLF as line breaks you can use preg_split
as follows:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$parts = preg_split("@\r?\n\r?\nHTTP/@u", $response);
$parts = (count($parts) > 1 ? 'HTTP/' : '').array_pop($parts);
list($headers, $body) = preg_split("@\r?\n\r?\n@u", $parts, 2);
Show time in form 24 hours
Right("0" & hour(now),2) & ":" & Right("0" & minute(now),2) = 01:35
Right("0" & hour(now),2) = 01
Right("0" & minute(now),2) = 35
Open the hosts file located at : **C:\windows\system32\drivers\etc**.
Add the following at end of this file :
YourServerIP YourDNS
Example:
198.168.1.1 maps.google.com
To open a PDF at page 100 the follow works
<path to Adobe Reader> /A "page=100" "<Path To PDF file>"
If you require more than one argument separate them with &
I use the following in a batch file to open the book I'm reading to the page I was up to.
C:\Program Files\Adobe\Reader 10.0\Reader\AcroRd32.exe /A "page=149&pagemode=none" "D:\books\MCTS(70-562) ASP.Net 3.5 Development.pdf"
The best list of command line args for Adobe Reader I have found is here.
http://partners.adobe.com/public/developer/en/acrobat/PDFOpenParameters.pdf
It's for version 7 but all the arguments I tried worked.
As for closing the file, I think you will need to use the SDK, or if you are opening the file from code you could close the file from code once you have finished with it.
You don't need a FK, you can join arbitrary columns.
But having a foreign key ensures that the join will actually succeed in finding something.
Foreign key give you certain guarantees that would be extremely difficult and error prone to implement otherwise.
For example, if you don't have a foreign key, you might insert a detail record in the system and just after you checked that the matching master record is present somebody else deletes it. So in order to prevent this you need to lock the master table, when ever you modify the detail table (and vice versa). If you don't need/want that guarantee, screw the FKs.
Depending on your RDBMS a foreign key also might improve performance of select (but also degrades performance of updates, inserts and deletes)
The OData protocol is built on top of the AtomPub protocol. The AtomPub protocol is one of the best examples of REST API design. So, in a sense you are right - the OData is just another REST API and each OData implementation is a REST-ful web service.
The difference is that OData is a specific protocol; REST is architecture style and design pattern.
try this
Select * From Table
Where field like '%' + ltrValue1 + '%'
And field like '%' + ltrValue2 + '%'
... etc.
and be prepared for a table scan as this functionality cannot use any existing indices
Most of the answers here are more or less correct, but all of them with some issues (for me). So, finally, googleing I found the correct procedure, as stated in the dedicated bootstrap doc: https://getbootstrap.com/docs/4.0/getting-started/theming/.
Let's assume bootstrap is installed in node_modules/bootstrap
.
A. Create your your_bootstrap.scss
file:
@import "your_variables_theme"; // here your variables
// mandatory imports from bootstrap src
@import "../node_modules/bootstrap/scss/functions";
@import "../node_modules/bootstrap/scss/variables"; // here bootstrap variables
@import "../node_modules/bootstrap/scss/mixins";
// optional imports from bootstrap (do not import 'bootstrap.scss'!)
@import "../node_modules/bootstrap/scss/root";
@import "../node_modules/bootstrap/scss/reboot";
@import "../node_modules/bootstrap/scss/type";
etc...
B. In the same folder, create the _your_variables_theme.scss
file.
C. Customize the bootstrap variables in _your_variables_theme.scss
file following this rules:
Copy and paste variables from
_variables.scss
as needed, modify their values, and remove the !default flag. If a variable has already been assigned, then it won’t be re-assigned by the default values in Bootstrap.Variable overrides within the same Sass file can come before or after the default variables. However, when overriding across Sass files, your overrides must come before you import Bootstrap’s Sass files.
Default variables are available in node_modules/bootstrap/scss/variables.scss
.
Want to center an image? Very easy, Bootstrap comes with two classes, .center-block
and text-center
.
Use the former in the case of your image being a BLOCK
element, for example, adding img-responsive
class to your img
makes the img
a block element. You should know this if you know how to navigate in the web console and see applied styles to an element.
Don't want to use a class? No problem, here is the CSS bootstrap uses. You can make a custom class or write a CSS rule for the element to match the Bootstrap class.
// In case you're dealing with a block element apply this to the element itself
.center-block {
margin-left:auto;
margin-right:auto;
display:block;
}
// In case you're dealing with a inline element apply this to the parent
.text-center {
text-align:center
}
Expanding a little bit on the previous answer, you can make the footnote links clickable here as well. First define the footnote at the bottom like this
<a name="myfootnote1">1</a>: Footnote content goes here
Then reference it at some other place in the document like this
<sup>[1](#myfootnote1)</sup>
if you're looking for the equivalent of "adb run myapp.apk"
you can use the script shown in this answer
(linux and mac only - maybe with cygwin on windows)
linux/mac users can also create a script to run an apk with something like the following:
create a file named "adb-run.sh" with these 3 lines:
pkg=$(aapt dump badging $1|awk -F" " '/package/ {print $2}'|awk -F"'" '/name=/ {print $2}')
act=$(aapt dump badging $1|awk -F" " '/launchable-activity/ {print $2}'|awk -F"'" '/name=/ {print $2}')
adb shell am start -n $pkg/$act
then "chmod +x adb-run.sh" to make it executable.
now you can simply:
adb-run.sh myapp.apk
The benefit here is that you don't need to know the package name or launchable activity name. Similarly, you can create "adb-uninstall.sh myapp.apk"
Note: This requires that you have aapt in your path. You can find it under the new build tools folder in the SDK
The evaluated value for settext was integer so it went to see a resource attached to it but it was not found, you wanted to set text so it should be string so convert integer into string by attaching .toStringe
or String.valueOf(int)
will solve your problem!
cballou's solution will work if you are using an old version of jquery. In newer versions you can also try:
$.ajax({
type: 'POST',
url:'url.do',
data: formData,
success: function(data, textStatus, request){
alert(request.getResponseHeader('some_header'));
},
error: function (request, textStatus, errorThrown) {
alert(request.getResponseHeader('some_header'));
}
});
According to docs the XMLHttpRequest object is available as of jQuery 1.4.
It turns out that, out of the four possible permutations of including or excluding trailing or leading forward slashes on the BaseAddress
and the relative URI passed to the GetAsync
method -- or whichever other method of HttpClient
-- only one permutation works. You must place a slash at the end of the BaseAddress
, and you must not place a slash at the beginning of your relative URI, as in the following example.
using (var handler = new HttpClientHandler())
using (var client = new HttpClient(handler))
{
client.BaseAddress = new Uri("http://something.com/api/");
var response = await client.GetAsync("resource/7");
}
Even though I answered my own question, I figured I'd contribute the solution here since, again, this unfriendly behavior is undocumented. My colleague and I spent most of the day trying to fix a problem that was ultimately caused by this oddity of HttpClient
.
As was stated in the comments to the original post, this seemed to be an issue with the python interpreter I was using for whatever reason, and not something wrong with the python scripts. I switched over from the WinPython bundle to the official python 3.6 from python.org and it worked just fine. thanks for the help everyone :)
Use event delegation for dynamically created elements:
$(document).on("click", '.mylink', function(event) {
alert("new link clicked!");
});
This does actually work, here's an example where I appended an anchor with the class .mylink
instead of data
- http://jsfiddle.net/EFjzG/
Since we are talking about having every element exactly once, a "set" makes more sense to me.
Example with classes and IEqualityComparer implemented:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public Product(int x, string y)
{
Id = x;
Name = y;
}
}
public class ProductCompare : IEqualityComparer<Product>
{
public bool Equals(Product x, Product y)
{ //Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
//Check whether the products' properties are equal.
return x.Id == y.Id && x.Name == y.Name;
}
public int GetHashCode(Product product)
{
//Check whether the object is null
if (Object.ReferenceEquals(product, null)) return 0;
//Get hash code for the Name field if it is not null.
int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode();
//Get hash code for the Code field.
int hashProductCode = product.Id.GetHashCode();
//Calculate the hash code for the product.
return hashProductName ^ hashProductCode;
}
}
Now
List<Product> originalList = new List<Product> {new Product(1, "ad"), new Product(1, "ad")};
var setList = new HashSet<Product>(originalList, new ProductCompare()).ToList();
setList
will have unique elements
I thought of this while dealing with .Except()
which returns a set-difference
The easiest solution working fine for me is this:
export CFLAGS=-ggdb
export CXXFLAGS=-ggdb
CMake will append them to all configurations' flags. Just make sure to clear CMake cache.
Everyone is talking about how to escape '
in a '
-quoted string literal. There's a much bigger issue here: single-quoted string literals aren't valid JSON. JSON is based on JavaScript, but it's not the same thing. If you're writing an object literal inside JavaScript code, fine; if you actually need JSON, you need to use "
.
With double-quoted strings, you won't need to escape the '
. (And if you did want a literal "
in the string, you'd use \"
.)
I had the same on Android. This is how i fixed it:
including ONLY the file:
slf4j-api-1.7.6.jar
in my libs/ folder
Having any additional slf4j* file, caused the NoClassDefFoundError.
Obviously, the rest of the libs can be there (android-support-v4, etc)
Versions: Eclipse Kepler 2013 06 14 - 02 29 ADT 22.3 Android SDK: 4.4.2
Hope someone saves the time i wasted thanks to this!
This would be the simplest solution!
std::vector<double> v (5);
for(auto itr = v.begin();itr != v.end();++itr){
auto current_loop_index = itr - v.begin();
std::cout << current_loop_index << std::endl;
}
Tested on gcc-9 with -std=c++11
flag
Output:
0
1
2
3
4
If treating strings as bytes is more your thing, you can use the following functions
function u_atob(ascii) {
return Uint8Array.from(atob(ascii), c => c.charCodeAt(0));
}
function u_btoa(buffer) {
var binary = [];
var bytes = new Uint8Array(buffer);
for (var i = 0, il = bytes.byteLength; i < il; i++) {
binary.push(String.fromCharCode(bytes[i]));
}
return btoa(binary.join(''));
}
// example, it works also with astral plane characters such as ''
var encodedString = new TextEncoder().encode('?');
var base64String = u_btoa(encodedString);
console.log('?' === new TextDecoder().decode(u_atob(base64String)))
You can try this also:
private void Page_Loaded_1(object sender, RoutedEventArgs e)
{
Uri iconUri = new Uri(@"C:\Apps\R&D\WPFNavigation\WPFNavigation\Images\airport.ico", UriKind.RelativeOrAbsolute);
(this.Parent as Window).Icon = BitmapFrame.Create(iconUri);
}
You need something like this:
foreach(DataColumn c in dr.Table.Columns)
{
MessageBox.Show(c.ColumnName);
}
I got this error when I used a where clause which looked at a nvarchar field but didn't use single quotes.
My invalid SQL query looked like this:
SELECT * FROM RandomTable WHERE Id IN (SELECT Id FROM RandomTable WHERE [Number] = 13028533)
This didn't work since the Number column had the data type nvarchar. It wasn't an int as I first thought.
I changed it to:
SELECT * FROM RandomTable WHERE Id IN (SELECT Id FROM RandomTable WHERE [Number] = '13028533')
And it worked.
Gradle (build.gradle):
implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310")
Entity (User.class):
LocalDate dateOfBirth;
Code:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
User user = mapper.readValue(json, User.class);
To convert your time value (float or int) to a formatted string, use:
time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1347517370))
I guess it's just because the onblur event is called as a result of the input losing focus, there isn't a blur action associated with an input, like there is a click action associated with a button
Just running the SELECT
statement will have no effect on the data. You have to use an UPDATE
statement with the REPLACE
to make the change occur:
UPDATE photos
SET caption = REPLACE(caption,'"','\'')
Here is a working sample: http://sqlize.com/7FjtEyeLAh
model.find({Branch:branch},function (err, docs){
if (err) res.send(err)
res.send(JSON.parse(JSON.stringify(docs)))
});
Ok, most answers are valid but not quite right. The idea of JWT is that you can validate the token without the need to contact the issuer everytime. You must check the id and verify the signature of the token with the known public key of the certificate google used to sign the token.
See the next post why and how to do this.
http://ncona.com/2015/02/consuming-a-google-id-token-from-a-server/
You could follow these steps to revert the incorrect commit(s) or to reset your remote branch back to correct HEAD/state.
git checkout development
copy the commit hash (i.e. id of the commit immediately before the wrong commit) from git log
git log -n5
output:
commit 7cd42475d6f95f5896b6f02e902efab0b70e8038 "Merge branch 'wrong-commit' into 'development'"
commit f9a734f8f44b0b37ccea769b9a2fd774c0f0c012 "this is a wrong commit"
commit 3779ab50e72908da92d2cfcd72256d7a09f446ba "this is the correct commit"
reset the branch to the commit hash copied in the previous step
git reset <commit-hash> (i.e. 3779ab50e72908da92d2cfcd72256d7a09f446ba)
git status
to show all the changes that were part of the wrong commit.git reset --hard
to revert all those changes.git push -f origin development
Similar Question Here
Finalizers in Java are bad. They add a lot of overhead to garbage collection. Avoid them whenever possible.
The shutdownHook will only get called when the VM is shutting down. I think it very well may do what you want.
You could loop through the list and keep the tuple in a variable and then you can see both values from the same variable...
num=(0, 0)
for item in tuplelist:
if item[1]>num[1]:
num=item #num has the whole tuple with the highest y value and its x value
I believe that Python 3.1 will print them nicer by default, without any code changing. But that is useless if you use any extensions that haven't been updated to work with Python 3.1
I'm late to this party but I'd like to add one bit to user756519's thorough, excellent answer. I don't believe the "RetainSameConnection on the Connection Manager" property is relevant in this instance based on my recent experience. In my case, the relevant point was their advice to set "ValidateExternalMetadata" to False.
I'm using a temp table to facilitate copying data from one database (and server) to another, hence the reason "RetainSameConnection" was not relevant in my particular case. And I don't believe it is important to accomplish what is happening in this example either, as thorough as it is.
Each object's lock is little different from Mutex/Semaphore design. For example there is no way to correctly implement traversing linked nodes with releasing previous node's lock and capturing next one. But with mutex it is easy to implement:
Node p = getHead();
if (p == null || x == null) return false;
p.lock.acquire(); // Prime loop by acquiring first lock.
// If above acquire fails due to interrupt, the method will
// throw InterruptedException now, so there is no need for
// further cleanup.
for (;;) {
Node nextp = null;
boolean found;
try {
found = x.equals(p.item);
if (!found) {
nextp = p.next;
if (nextp != null) {
try { // Acquire next lock
// while still holding current
nextp.lock.acquire();
}
catch (InterruptedException ie) {
throw ie; // Note that finally clause will
// execute before the throw
}
}
}
}finally { // release old lock regardless of outcome
p.lock.release();
}
Currently, there is no such class in java.util.concurrent
, but you can find Mutext implementation here Mutex.java. As for standard libraries, Semaphore provides all this functionality and much more.
There are two operators in Python for the "not equal" condition -
a.) != If values of the two operands are not equal, then the condition becomes true. (a != b) is true.
b.) <> If values of the two operands are not equal, then the condition becomes true. (a <> b) is true. This is similar to the != operator.
The same problem exists in Visual Studio, here's how to fix it there:
Go to:
Tools > Options > SQL Server Tools > Transact-SQL Editor > Query Results > Results To Grid
Now click the check box to true: "Include column headers when copying or saving the results"
try
git reflog
this gives you a history of how your HEAD and branch pointers where moved in the past.
e.g. :
88ea06b HEAD@{0}: checkout: moving from DEVELOPMENT to remotes/origin/SomeNiceFeature e47bf80 HEAD@{1}: pull origin DEVELOPMENT: Fast-forward
the top of this list is one reasone one might encounter a DETACHED HEAD state ... checking out a remote tracking branch.
$.each(top_brands, function(index, el) {
for (var key in el) {
if (el.hasOwnProperty(key)) {
brand_options.append($("<option />").val(key).text(key+ " " + el[key]));
}
}
});
But if your data structure is var top_brands = {'Adidas': 100, 'Nike': 50};
, then thing will be much more simple.
for (var key in top_brands) {
if (top_brands.hasOwnProperty(key)) {
brand_options.append($("<option />").val(key).text(key+ " " + el[key]));
}
}
Or use the jquery each:
$.each(top_brands, function(key, value) {
brand_options.append($("<option />").val(key).text(key + " " + value));
});
I see in your Update 2 that you have use sAutoWidth
, but I think you mistyped bAutoWidth
. Try to change this.
You can also add a CSS rule to .table
if the problem persists.
You should also be careful when the width of the content is greater than the header of the column.
So something like the combination of the 1 & 2:
$('.table').dataTable({
bAutoWidth: false,
aoColumns : [
{ sWidth: '15%' },
{ sWidth: '15%' },
{ sWidth: '15%' },
{ sWidth: '15%' },
{ sWidth: '15%' },
{ sWidth: '15%' },
{ sWidth: '10%' }
]
});
Try with:
#! /bin/bash
i=0
while read line
do
array[ $i ]="$line"
(( i++ ))
done < <(ls -ls)
echo ${array[1]}
In your version, the while
runs in a subshell, the environment variables you modify in the loop are not visible outside it.
(Do keep in mind that parsing the output of ls
is generally not a good idea at all.)
I just want to explain one more scenario like List<Documents>
, this list contains a few more lists of other documents like List<Excel>
, List<Word>
, List<PowerPoint>
. So the structure is
class A {
List<Documents> documentList;
}
class Documents {
List<Excel> excels;
List<Word> words;
List<PowerPoint> ppt;
}
Now if you want to iterate Excel only from documents then do something like below..
So the code would be
List<Documents> documentList = new A().getDocumentList();
//check documentList as not null
Optional<Excel> excelOptional = documentList.stream()
.map(doc -> doc.getExcel())
.flatMap(List::stream).findFirst();
if(excelOptional.isPresent()){
Excel exl = optionalExcel.get();
// now get the value what you want.
}
I hope this can solve someone's issue while coding...
You don't need to change the delimiter to display the right part of the string with cut
.
The -f
switch of the cut
command is the n-TH element separated by your delimiter : :
, so you can just type :
grep puddle2_1557936 | cut -d ":" -f2
Another solutions (adapt it a bit) if you want fun :
Using grep :
grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or still with look around regex
grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with perl :
perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or using ruby (thanks to glenn jackman)
ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with awk :
awk -F'puddle2_1557936:' '{print $2}' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or with python :
python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
or using only bash :
IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2
js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2
php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2
wget is capable of doing what you are asking. Just try the following:
wget -p -k http://www.example.com/
The -p
will get you all the required elements to view the site correctly (css, images, etc).
The -k
will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.
From the Wget docs:
‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.
Each link will be changed in one of the two ways:
The links to files that have been downloaded by Wget will be changed to refer
to the file they point to as a relative link.
Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
downloaded, then the link in doc.html will be modified to point to
‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
combinations of directories.
The links to files that have not been downloaded by Wget will be changed to
include host name and absolute path of the location they point to.
Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
../bar/img.gif), then the link in doc.html will be modified to point to
http://hostname/bar/img.gif.
Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.
Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads.
Original answer:
I too tried to change the support library to "23". When I changed the targetSdkVersion
to 23, Android Studio reported the following error:
This support library should not use a lower version (22) than the
targetSdkVersion
(23)
I simply changed:
compile 'com.android.support:appcompat-v7:23.0.0'
to
compile 'com.android.support:appcompat-v7:+'
Although this fixed my issue, you should not use dynamic versions. After a few hours the new support repository was available and it is currently 23.0.1
.
Pro tip:
You can use double quotes and create a ${supportLibVersion}
variable for simplicity. Example:
ext {
supportLibVersion = '23.1.1'
}
compile "com.android.support:appcompat-v7:${supportLibVersion}"
compile "com.android.support:design:${supportLibVersion}"
compile "com.android.support:palette-v7:${supportLibVersion}"
compile "com.android.support:customtabs:${supportLibVersion}"
compile "com.android.support:gridlayout-v7:${supportLibVersion}"
source: https://twitter.com/manidesto/status/669195097947377664
I've had this problem. See The Python "Connection Reset By Peer" Problem.
You have (most likely) run afoul of small timing issues based on the Python Global Interpreter Lock.
You can (sometimes) correct this with a time.sleep(0.01)
placed strategically.
"Where?" you ask. Beats me. The idea is to provide some better thread concurrency in and around the client requests. Try putting it just before you make the request so that the GIL is reset and the Python interpreter can clear out any pending threads.
If you have a handle to an existing fragment you can just replace it with the fragment's ID.
Example in Kotlin:
fun aTestFuction() {
val existingFragment = MyExistingFragment() //Get it from somewhere, this is a dirty example
val newFragment = MyNewFragment()
replaceFragment(existingFragment, newFragment, "myTag")
}
fun replaceFragment(existing: Fragment, new: Fragment, tag: String? = null) {
supportFragmentManager.beginTransaction().replace(existing.id, new, tag).commit()
}
You can do that in PL/SQL Developer v10.
1. Click on Table that you want to generate script for.
2. Click Export data.
3. Check if table is selected that you want to export data for.
4. Click on SQL inserts tab.
5. Add where clause if you don't need the whole table.
6. Select file where you will find your SQL script.
7. Click export.
Additional to the above - the QEMU website has good documentation about setting up an ARM based emulator: http://qemu.weilnetz.de/qemu-doc.html#ARM-System-emulator
It's not possible.
And yes, I think MS made a mistake here.
Their decision does not make sense and forces programmers to write (as described above) a pointless wrapper class.
Here is a good example: Trying to extend static MS Unit testing class Assert: I want 1 more Assert method AreEqual(x1,x2)
.
The only way to do this is to point to different classes or write a wrapper around 100s of different Assert methods. Why!?
If the decision was being made to allow extensions of instances, I see no logical reason to not allow static extensions. The arguments about sectioning libraries does not stand up once instances can be extended.
Hope this will help someone:
import React from 'react';
import * as History from 'history';
import { withRouter } from 'react-router-dom';
interface Props {
history: History;
}
@withRouter
export default class YourComponent extends React.PureComponent<Props> {
private onBackClick = (event: React.MouseEvent): void => {
const { history } = this.props;
history.goBack();
};
...
This works for me. Are you sure you're indenting with tabs?
CC = gcc
CFLAGS = -g -pedantic -O0 -std=gnu99 -m32 -Wall
PROGRAMS = digitreversal
all : $(PROGRAMS)
digitreversal : digitreversal.o
[tab]$(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)
.PHONY: clean
clean:
[tab]@rm -f $(PROGRAMS) *.o core
Am I the only one who read this and realized that none of the answers addressed the "integer" part of the question?
var myInteger = 6;
var myFloat = 6.2;
if( myInteger > 0 )
// Cool, we correctly identified this as a positive integer
if( myFloat > 0 )
// Oh, no! That's not an integer!
To guarantee that you're dealing with an integer, you want to cast your value to an integer then compare it with itself.
if( parseInt( myInteger ) == myInteger && myInteger > 0 )
// myInteger is an integer AND it's positive
if( parseInt( myFloat ) == myFloat && myFloat > 0 )
// myFloat is NOT an integer, so parseInt(myFloat) != myFloat
As a bonus, there are some shortcuts for converting from a float to an integer in JavaScript. In JavaScript, all bitwise operators (|
, ^
, &
, etc) will cast your number to an integer before operating. I assume this is because 99% of developers don't know the IEEE floating point standard and would get horribly confused when "200 | 2" evaluated to 400(ish). These shortcuts tend to run faster than Math.floor
or parseInt
, and they take up fewer bytes if you're trying to eke out the smallest possible code:
if( myInteger | 0 == myInteger && myInteger > 0 )
// Woot!
if( myFloat | 0 == myFloat && myFloat > 0 )
// Woot, again!
But wait, there's more!
These bitwise operators are working on 32-bit signed integers. This means the highest bit is the sign bit. By forcing the sign bit to zero your number will remain unchanged only if it was positive. You can use this to check for positiveness AND integerness in a single blow:
// Where 2147483647 = 01111111111111111111111111111111 in binary
if( (myInteger & 2147483647) == myInteger )
// myInteger is BOTH positive and an integer
if( (myFloat & 2147483647) == myFloat )
// Won't happen
* note bit AND operation is wrapped with parenthesis to make it work in chrome (console)
If you have trouble remembering this convoluted number, you can also calculate it before-hand as such:
var specialNumber = ~(1 << 31);
Per @Reinsbrain's comment, a similar bitwise hack can be used to check for a negative integer. In a negative number, we do want the left-most bit to be a 1, so by forcing this bit to 1 the number will only remain unchanged if it was negative to begin with:
// Where -2147483648 = 10000000000000000000000000000000 in binary
if( (myInteger | -2147483648) == myInteger )
// myInteger is BOTH negative and an integer
if( (myFloat | -2147483648) == myFloat )
// Won't happen
This special number is even easier to calculate:
var specialNumber = 1 << 31;
As mentioned earlier, since JavaScript bitwise operators convert to 32-bit integers, numbers which don't fit in 32 bits (greater than ~2 billion) will fail
You can fall back to the longer solution for these:
if( parseInt(123456789000) == 123456789000 && 123456789000 > 0 )
However even this solution fails at some point, because parseInt
is limited in its accuracy for large numbers. Try the following and see what happens:
parseInt(123123123123123123123); // That's 7 "123"s
On my computer, in Chrome console, this outputs: 123123123123123130000
The reason for this is that parseInt treats the input like a 64-bit IEEE float. This provides only 52 bits for the mantissa, meaning a maximum value of ~4.5e15 before it starts rounding
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.
Taking all of the proposed answers and applying them to my situation - trying to check or uncheck a checkbox based on a retrieved value of true (should check the box) or false (should not check the box) - I tried all of the above and found that using .prop("checked", true) and .prop("checked", false) were the correct solution.
I can't add comments or up answers yet, but I felt this was important enough to add to the conversation.
Here is the longhand code for a fullcalendar modification that says if the retrieved value "allDay" is true, then check the checkbox with ID "even_allday_yn":
if (allDay)
{
$( "#even_allday_yn").prop('checked', true);
}
else
{
$( "#even_allday_yn").prop('checked', false);
}
As MusiGenesis put so nicely, in most databases:
schema : database : table :: floor plan : house : room
But, in Oracle it may be easier to think of:
schema : database : table :: owner : house : room
Displaying content saved in PDF/DOC/DOCX file format is ideal for displaying the pdf/doc/docx file on your web page
Try AddDate:
package main
import (
"fmt"
"time"
)
func main() {
now := time.Now()
fmt.Println("now:", now)
then := now.AddDate(0, -1, 0)
fmt.Println("then:", then)
}
Produces:
now: 2009-11-10 23:00:00 +0000 UTC
then: 2009-10-10 23:00:00 +0000 UTC
Playground: http://play.golang.org/p/QChq02kisT
To get the script, that currently loaded the script you can use
var thisScript = document.currentScript;
You need to keep a reference at the beginning of your script, so you can call later
var url = thisScript.src
Recent Debian have Python package androguard
:
Description-en: full Python tool to play with Android files
Androguard is a full Python tool to play with Android files.
* DEX, ODEX
* APK
* Android's binary xml
* Android resources
* Disassemble DEX/ODEX bytecodes
* Decompiler for DEX/ODEX files
Install corresponding packages:
sudo apt-get install androguard python-networkx
Decompile DEX file:
$ androdd -i classes.dex -o ./dir-for-output
Extract classes.dex
from Apk + Decompile:
$ androdd -i app.apk -o ./dir-for-output
Apk file is nothing more that Java archive (JAR), you may extract files from archive via:
$ unzip app.apk -d ./dir-for-output
Give your radiobutton a custom style:
<style name="MyRadioButtonStyle" parent="@android:style/Widget.CompoundButton.RadioButton">
<item name="android:button">@drawable/custom_btn_radio</item>
</style>
custom_btn_radio.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:state_window_focused="false"
android:drawable="@drawable/btn_radio_on" />
<item android:state_checked="false" android:state_window_focused="false"
android:drawable="@drawable/btn_radio_off" />
<item android:state_checked="true" android:state_pressed="true"
android:drawable="@drawable/btn_radio_on_pressed" />
<item android:state_checked="false" android:state_pressed="true"
android:drawable="@drawable/btn_radio_off_pressed" />
<item android:state_checked="true" android:state_focused="true"
android:drawable="@drawable/btn_radio_on_selected" />
<item android:state_checked="false" android:state_focused="true"
android:drawable="@drawable/btn_radio_off_selected" />
<item android:state_checked="false" android:drawable="@drawable/btn_radio_off" />
<item android:state_checked="true" android:drawable="@drawable/btn_radio_on" />
</selector>
Replace the drawables with your own.
try this one :),
Get-LocalGroup | %{ $groups = "$(Get-LocalGroupMember -Group $_.Name | %{ $_.Name } | Out-String)"; Write-Output "$($_.Name)>`r`n$($groups)`r`n" }
Your javascript is executed before the HTML is generated, so it doesn't "see" the ungenerated INPUT elements. For jQuery, you would either stick the Javascript at the end of the HTML or wrap it like this:
<script type="text/javascript"> $(function() { //jQuery trick to say after all the HTML is parsed. $("input[type=radio]").click(function() { var total = 0; $("input[type=radio]:checked").each(function() { total += parseFloat($(this).val()); }); $("#totalSum").val(total); }); }); </script>
EDIT: This code works for me
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <strong>Choose a base package:</strong> <input id="item_0" type="radio" name="pkg" value="1942" />Base Package 1 - $1942 <input id="item_1" type="radio" name="pkg" value="2313" />Base Package 2 - $2313 <input id="item_2" type="radio" name="pkg" value="2829" />Base Package 3 - $2829 <strong>Choose an add on:</strong> <input id="item_10" type="radio" name="ext" value="0" />No add-on - +$0 <input id="item_12" type="radio" name="ext" value="2146" />Add-on 1 - (+$2146) <input id="item_13" type="radio" name="ext" value="2455" />Add-on 2 - (+$2455) <input id="item_14" type="radio" name="ext" value="2764" />Add-on 3 - (+$2764) <input id="item_15" type="radio" name="ext" value="3073" />Add-on 4 - (+$3073) <input id="item_16" type="radio" name="ext" value="3382" />Add-on 5 - (+$3382) <input id="item_17" type="radio" name="ext" value="3691" />Add-on 6 - (+$3691) <strong>Your total is:</strong> <input id="totalSum" type="text" name="totalSum" readonly="readonly" size="5" value="" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $("input[type=radio]").click(function() { var total = 0; $("input[type=radio]:checked").each(function() { total += parseFloat($(this).val()); }); $("#totalSum").val(total); }); </script> </body> </html>
You can also manually change the time part of date and format in "dd/mm/yyyy" pattern according to your requirement.
public static Date getZeroTimeDate(Date changeDate){
Date returnDate=new Date(changeDate.getTime()-(24*60*60*1000));
return returnDate;
}
If the return value is not working then check for the context parameter in web.xml. eg.
<context-param>
<param-name>javax.faces.DATETIMECONVERTER_DEFAULT_TIMEZONE_IS_SYSTEM_TIMEZONE</param-name>
<param-value>true</param-value>
</context-param>
To answer your extra question
:
You can set which rows should be repeated on every page using:
$objPHPExcel->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 5);
Now, row 1, 2, 3, 4 and 5 will be repeated.
Always, always, always put disposable objects inside of using statements. I can't see how you've instantiated your DataReader but you should do it like this:
using (Connection c = ...)
{
using (DataReader dr = ...)
{
//Work with dr in here.
}
}
//Now the connection and reader have been closed and disposed.
Now, to answer your question, the reader is using the same connection as the command you're trying to ExecuteNonQuery
on. You need to use a separate connection since the DataReader keeps the connection open and reads data as you need it.
In PHP, strings are bytestreams. What exactly are you trying to do?
Re: edit
Ps. Why do I need this at all!? Well I need to send via fputs() bytearray to server written in java...
fputs
takes a string as argument. Most likely, you just need to pass your string to it. On the Java side of things, you should decode the data in whatever encoding, you're using in php (the default is iso-8859-1).
I had this issue with code that I copied from a blog. I got rid of the issue on PyCharm by Shift+Tab'ing(unindenting) the last error-throwing code-block all the way to the left, and then Tab'ing it back to where it was. I suppose is somehow indirectly working the same as the 'reformat code' comment above.
In my case the problem was the JAVA_HOME variable was set an installed jre.
An alternative to setting the AS_JAVA variable is to set JAVA_HOME environment variable to the jdk (i.e. /usr/local/jdk1.7.0.51).
I realize this is an old question, but it took me several hours to find a good solution and thought I'd pass on what I learned here and save someone else the trouble. Try, for example,
SELECT * FROM some_table WHERE id_column = ANY(@id_list)
where @id_list is bound to an int[] parameter by way of
command.Parameters.Add("@id_list", NpgsqlDbType.Array | NpgsqlDbType.Integer).Value = my_id_list;
where command is a NpgsqlCommand (using C# and Npgsql in Visual Studio).
Try setting a Windows System Environment variable called _JAVA_OPTIONS
with the heap size you want. Java should be able to find it and act accordingly.
It's weird that I haven't encountered a solution that compares the object's values as opposed to the existence of any entry (maybe I missed it among the many given solutions).
I would like to cover the case where an object is considered empty if all its values are undefined:
const isObjectEmpty = obj => Object.values(obj).every(val => typeof val === "undefined")
console.log(isObjectEmpty({})) // true
console.log(isObjectEmpty({ foo: undefined, bar: undefined })) // true
console.log(isObjectEmpty({ foo: false, bar: null })) // false
_x000D_
Let's say, for the sake of example, you have a function (paintOnCanvas
) that destructs values from its argument (x
, y
and size
). If all of them are undefined, they are to be left out of the resulting set of options. If not they are not, all of them are included.
function paintOnCanvas ({ brush, x, y, size }) {
const baseOptions = { brush }
const areaOptions = { x, y, size }
const options = isObjectEmpty(areaOptions) ? baseOptions : { ...baseOptions, areaOptions }
// ...
}
I have used the attribute "layout_alignRight" in my case, in text its :
android:layout_alignRight="@+id/myComponentId"
If you want to add some right margin, just set the attribute "Layout_Margin Right" to "20dp" for exemple, in text its :
android:layout_marginRight="20dp"
Other answers have suggested netrc to specify username and password, based on what I've read, I agree. Here are some syntax details:
https://ec.haxx.se/usingcurl-netrc.html
Like other answers, I would like to stress the need to pay attention to security regarding this question.
Although I am not an expert, I found these links insightful:
https://ec.haxx.se/cmdline-passwords.html
To summarize:
Using the encrypted versions of the protocols (HTTPS vs HTTP) (FTPS vs FTP) can help avoid Network Leakage.
Using netrc can help avoid Command Line Leakage.
To go a step further, it seems you can also encrypt the netrc files using gpg
https://brandur.org/fragments/gpg-curl
With this your credentials are not "at rest" (stored) as plain text.
If you want to trim and print one dimensional Array or the deepest dimension of multi-dimensional Array you should use:
foreach($array as $key => $value)
{
$array[$key] = trim($value);
print("-");
print($array[$key]);
print("-");
print("<br>");
}
If you want to trim but do not want to print one dimensional Array or the deepest dimension of multi-dimensional Array you should use:
$array = array_map('trim', $array);
You only need to write
seamless
in your code. There is not need for:
seamless ="seamless"
I just found this out myself.
EDIT - this does not remove scrollbars. Strangely
scrolling="no" still seems to work in html5. I have tried using the overflow function with an inline style as recommended by html5 but this doesn't work for me.
There's generally nothing particularly inefficient about it. It doesn't generally matter to the JVM that you've made a subclass and added a constructor to it-- that's a normal, everyday thing to do in an object-oriented language. I can think of quite contrived cases where you could cause an inefficiency by doing this (e.g. you have a repeatedly-called method that ends up taking a mixture of different classes because of this subclass, whereas ordinary the class passed in would be totally predictable-- in the latter case, the JIT compiler could make optimisations that are not feasible in the first). But really, I think the cases where it'll matter are very contrived.
I'd see the issue more from the point of view of whether you want to "clutter things up" with lots of anonymous classes. As a rough guide, consider using the idiom no more than you'd use, say, anonymous classes for event handlers.
In (2), you're inside the constructor of an object, so "this" refers to the object you're constructing. That's no different to any other constructor.
As for (3), that really depends on who's maintaining your code, I guess. If you don't know this in advance, then a benchmark that I would suggest using is "do you see this in the source code to the JDK?" (in this case, I don't recall seeing many anonymous initialisers, and certainly not in cases where that's the only content of the anonymous class). In most moderately sized projects, I'd argue you're really going to need your programmers to understand the JDK source at some point or other, so any syntax or idiom used there is "fair game". Beyond that, I'd say, train people on that syntax if you have control of who's maintaining the code, else comment or avoid.
You can add your URLs to VerifyCsrfToken.php middleware. The URLs will be excluded from CSRF verification.
protected $except = [
"your url",
"your url/abc"
];
The table normally contains multiple rows. Use a loop and use row.Field<string>(0)
to access the value of each row.
foreach(DataRow row in dt.Rows)
{
string file = row.Field<string>("File");
}
You can also access it via index:
foreach(DataRow row in dt.Rows)
{
string file = row.Field<string>(0);
}
If you expect only one row, you can also use the indexer of DataRowCollection
:
string file = dt.Rows[0].Field<string>(0);
Since this fails if the table is empty, use dt.Rows.Count
to check if there is a row:
if(dt.Rows.Count > 0)
file = dt.Rows[0].Field<string>(0);
I hope this will be helpful.. If I understood the problem
html{
background-color:green;
}
body {
position:relative;
left:200px;
background-color:red;
}
div{
position:relative;
left:100px;
width:100px;
height:100px;
background-color:blue;
}
This is inherently the wrong thing to do. If you are running a Python script from another Python script, you should communicate through Python instead of through the OS:
import script1
In an ideal world, you will be able to call a function inside script1
directly:
for i in range(whatever):
script1.some_function(i)
If necessary, you can hack sys.argv
. There's a neat way of doing this using a context manager to ensure that you don't make any permanent changes.
import contextlib
@contextlib.contextmanager
def redirect_argv(num):
sys._argv = sys.argv[:]
sys.argv=[str(num)]
yield
sys.argv = sys._argv
with redirect_argv(1):
print(sys.argv)
I think this is preferable to passing all your data to the OS and back; that's just silly.
For future reference to anyone here having difficulty, if you are adding the checkboxes dynamically, the correct accepted answer above will not work. You'll need to leverage event delegation which allows a parent node to capture bubbled events from a specific descendant and issue a callback.
// $(<parent>).on('<event>', '<child>', callback);
$(document).on('change', '.checkbox', function() {
if(this.checked) {
// checkbox is checked
}
});
Note that it's almost always unnecessary to use document
for the parent selector. Instead choose a more specific parent node to prevent propagating the event up too many levels.
The example below displays how the events of dynamically added dom nodes do not trigger previously defined listeners.
$postList = $('#post-list');_x000D_
_x000D_
$postList.find('h1').on('click', onH1Clicked);_x000D_
_x000D_
function onH1Clicked() {_x000D_
alert($(this).text());_x000D_
}_x000D_
_x000D_
// simulate added content_x000D_
var title = 2;_x000D_
_x000D_
function generateRandomArticle(title) {_x000D_
$postList.append('<article class="post"><h1>Title ' + title + '</h1></article>');_x000D_
}_x000D_
_x000D_
setTimeout(generateRandomArticle.bind(null, ++title), 1000);_x000D_
setTimeout(generateRandomArticle.bind(null, ++title), 5000);_x000D_
setTimeout(generateRandomArticle.bind(null, ++title), 10000);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<section id="post-list" class="list post-list">_x000D_
<article class="post">_x000D_
<h1>Title 1</h1>_x000D_
</article>_x000D_
<article class="post">_x000D_
<h1>Title 2</h1>_x000D_
</article>_x000D_
</section>
_x000D_
While this example displays the usage of event delegation to capture events for a specific node (h1
in this case), and issue a callback for such events.
$postList = $('#post-list');_x000D_
_x000D_
$postList.on('click', 'h1', onH1Clicked);_x000D_
_x000D_
function onH1Clicked() {_x000D_
alert($(this).text());_x000D_
}_x000D_
_x000D_
// simulate added content_x000D_
var title = 2;_x000D_
_x000D_
function generateRandomArticle(title) {_x000D_
$postList.append('<article class="post"><h1>Title ' + title + '</h1></article>');_x000D_
}_x000D_
_x000D_
setTimeout(generateRandomArticle.bind(null, ++title), 1000); setTimeout(generateRandomArticle.bind(null, ++title), 5000); setTimeout(generateRandomArticle.bind(null, ++title), 10000);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<section id="post-list" class="list post-list">_x000D_
<article class="post">_x000D_
<h1>Title 1</h1>_x000D_
</article>_x000D_
<article class="post">_x000D_
<h1>Title 2</h1>_x000D_
</article>_x000D_
</section>
_x000D_
Q1.) Assuming process B tries to take ownership of the same mutex you locked in process A (you left that out of your pseudocode) then no, process B cannot access sharedResource while the mutex is locked since it will sit waiting to lock the mutex until it is released by process A. It will return from the mutex_lock() function when the mutex is locked (or when an error occurs!)
Q2.) In Process B, ensure you always lock the mutex, access the shared resource, and then unlock the mutex. Also, check the return code from the mutex_lock( pMutex ) routine to ensure that you actually own the mutex, and ONLY unlock the mutex if you have locked it. Do the same from process A.
Both processes should basically do the same thing when accessing the mutex.
lock()
If the lock succeeds, then {
access sharedResource
unlock()
}
Q3.) Yes, there are lots of diagrams: =) https://www.google.se/search?q=mutex+thread+process&rlz=1C1AFAB_enSE487SE487&um=1&ie=UTF-8&hl=en&tbm=isch&source=og&sa=N&tab=wi&ei=ErodUcSmKqf54QS6nYDoAw&biw=1200&bih=1730&sei=FbodUbPbB6mF4ATarIBQ
Another way to do this without revert (traces of undo):
Don't do it if someone else has pushed other commits
Create a backup of your branch, being in your branch my-branch
. So in case something goes wrong, you can restart the process without losing any work done.
git checkout -b my-branch-temp
Go back to your branch.
git checkout my-branch
Reset, to discard your last commit (to undo it):
git reset --hard HEAD^
Remove the branch on remote (ex. origin
remote).
git push origin :my-branch
Repush your branch (without the unwanted commit) to the remote.
git push origin my-branch
Done!
I hope that helps! ;)
For me, the perfect example for threading is monitoring asynchronous events. Look at this code.
# thread_test.py
import threading
import time
class Monitor(threading.Thread):
def __init__(self, mon):
threading.Thread.__init__(self)
self.mon = mon
def run(self):
while True:
if self.mon[0] == 2:
print "Mon = 2"
self.mon[0] = 3;
You can play with this code by opening an IPython session and doing something like:
>>> from thread_test import Monitor
>>> a = [0]
>>> mon = Monitor(a)
>>> mon.start()
>>> a[0] = 2
Mon = 2
>>>a[0] = 2
Mon = 2
Wait a few minutes
>>> a[0] = 2
Mon = 2
expand "Java Resources" and then 'Libraries' (in eclipse project). make sure that "Apache Tomcat" present.
if not follow- right click on project -> "Build Path" -> "Java Build Path" -> "Add Library" -> select "Server Runtime" -> next -> select "Apache Tomcat -> click finish
XmlDocument doc = new XmlDocument();
doc.LoadXml(str);
Where str
is your XML string. See the MSDN article for more info.
import datetime
def diff_times_in_seconds(t1, t2):
# caveat emptor - assumes t1 & t2 are python times, on the same day and t2 is after t1
h1, m1, s1 = t1.hour, t1.minute, t1.second
h2, m2, s2 = t2.hour, t2.minute, t2.second
t1_secs = s1 + 60 * (m1 + 60*h1)
t2_secs = s2 + 60 * (m2 + 60*h2)
return( t2_secs - t1_secs)
# using it
diff_times_in_seconds( datetime.datetime.strptime( "13:23:34", '%H:%M:%S').time(),datetime.datetime.strptime( "14:02:39", '%H:%M:%S').time())
Yet another solution:
I got inside objects.mk file
################################################################################
# Automatically-generated file. Do not edit!
################################################################################
USER_OBJS := /home/../mylib.so
LIBS := -lstdc++fs -lGL -lGLU -lGLEW -lglut -lm -lmylib
then didn't read first line. Then altered next line. It was another projects' folder because I copied this using "copy/clone project" feature and this was causing the error for me. I changed myLib.so into /proper_address/reallyMyLib.so and it worked.
Warning: It may harm some unknown places! Backup whole project before doing this. Because it says "do not edit".
the $("body").append(r)
statement should be within the test
function, also there was misplaced "
in the test
method
function test() {
var r=$('<input/>').attr({
type: "button",
id: "field",
value: 'new'
});
$("body").append(r);
}
Demo: Fiddle
Update
In that case try a more jQuery-ish solution
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function($){
$('#mybutton').one('click', function(){
var r=$('<input/>').attr({
type: "button",
id: "field",
value: 'new'
});
$("body").append(r);
})
})
</script>
</head>
<body>
<button id="mybutton">Insert after</button>
</body>
</html>
Demo: Plunker
function printResult() {
var DocumentContainer = document.getElementById('your_div_id');
var WindowObject = window.open('', "PrintWindow", "width=750,height=650,top=50,left=50,toolbars=no,scrollbars=yes,status=no,resizable=yes");
WindowObject.document.writeln(DocumentContainer.innerHTML);
WindowObject.document.close();
WindowObject.focus();
WindowObject.print();
WindowObject.close();
}
You can change the font size in R Markdown with HTML code tags <font size="1"> your text </font>
. This code is added to the R Markdown document and will alter the output of the HTML output.
For example:
<font size="1"> This is my text number1</font> _x000D_
_x000D_
<font size="2"> This is my text number 2 </font>_x000D_
_x000D_
<font size="3"> This is my text number 3</font> _x000D_
_x000D_
<font size="4"> This is my text number 4</font> _x000D_
_x000D_
<font size="5"> This is my text number 5</font> _x000D_
_x000D_
<font size="6"> This is my text number 6</font>
_x000D_
It is possible that you have multiple versions of the dll(s) on your system. You can search your system to find out. The issue may be solved by simply changing the order of the directories in your path. This was my issue. (Cannot run Qt Creator GUI outside of Qt. "The application was unable to start correctly (0xc000007b)" error)
foreach (ListItem item in CBLGold.Items)
{
if (item.Selected)
{
string selectedValue = item.Value;
}
}
$(function () {
$('input[type=checkbox]').click(function () {
var chks = document.getElementById('<%= chkRoleInTransaction.ClientID %>').getElementsByTagName('INPUT');
for (i = 0; i < chks.length; i++) {
chks[i].checked = false;
}
if (chks.length > 1)
$(this)[0].checked = true;
});
});
Create an Android app using Eclipse.
Create a layout that has a <WebView>
control.
Move your HTML code to /assets
folder.
Load webview with your file:///android_asset/ file.
And you have an android app!
With bash you may use read
like tis:
#!/usr/bin/env bash
{ IFS= read -rd '' value <config.txt;} 2>/dev/null
printf '%s' "$value"
Notice that:
The last newline is preserved.
The stderr
is silenced to /dev/null
by redirecting the whole commands block, but the return status of the read command is preserved, if one needed to handle read error conditions.
You need to add a name
attribute to your dropdown list, then you need to add a required
attribute, and then you can reference the error using myForm.[input name].$error.required
:
HTML:
<form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
<input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
<select name="service_id" class="Sitedropdown" style="width: 220px;"
ng-model="ServiceID"
ng-options="service.ServiceID as service.ServiceName for service in services"
required>
<option value="">Select Service</option>
</select>
<span ng-show="myForm.service_id.$error.required">Select service</span>
</form>
Controller:
function Ctrl($scope) {
$scope.services = [
{ServiceID: 1, ServiceName: 'Service1'},
{ServiceID: 2, ServiceName: 'Service2'},
{ServiceID: 3, ServiceName: 'Service3'}
];
$scope.save = function(myForm) {
console.log('Selected Value: '+ myForm.service_id.$modelValue);
alert('Data Saved! without validate');
};
}
Here's a working plunker.
As mentioned above, edit the application host.config. An easy way to find this is run your site in VS using IIS Express. Right click the systray icon, show all applications. Choose your site, and then click on the config link at the bottom to open it.
I'd suggest adding another binding entry, and leave the initial localhost one there. This additional binding will appear in the IIS Express systray as a separate application under the site.
To avoid having to run VS as admin (lots of good reasons not to run as admin), add a netsh rule as follows (obviously replacing the IP and port with your values) - you'll need an admin cmd.exe for this, it only needs to be run once:
netsh http add urlacl url=http://192.168.1.121:51652/ user=\Everyone
netsh can add rules like url=http://+:51652/ but I failed to get this to place nicely with IIS Express. You can use netsh http show urlacl
to list existing rules, and they can be deleted with netsh http delete urlacl url=blah
.
Further info: http://msdn.microsoft.com/en-us/library/ms733768.aspx
There are many ways for doing that (you might want to obfuscate the source code, you can compress it, ...). Some of these methods need additional code to transform your program in an executable form (compression, for example).
But the thing all methods cannot do, is keeping the source code secret. The other party gets your binary code, which can always be transformed (reverse-engineered) into a human-readable form again, because the binary code contains all functionality information that is provided in your source code.
There is no inherent reason that a simple batch file would run in XP but not Windows 10. It is possible you are referencing a command or a 3rd party utility that no longer exists. To know more about what is actually happening, you will need to do one of the following:
pause
to the batch file so that you can see what is happening before it exits.
.bat
files and select "edit". This will open the file in notepad.pause
.- OR -
.bat
files are located, hold down the "shift" key and right click in the white space.Once you have done this, I recommend creating a new question with the output you see after using one of the methods above.
You should simply install request
locally within your project.
Just cd
to the folder containing your js file and run
npm install request
I have tried this then i fixed my issue. It will calculate all media-breakpoint automatically by given rate (base-size/rate-size)
$base-size: 16;
$rate-size-xl: 24;
// set default size for all cases;
:root {
--size: #{$base-size};
}
// if it's smaller then LG it will set size rate to 16/16;
// example: if size set to 14px, it will be 14px * 16 / 16 = 14px
@include media-breakpoint-down(lg) {
:root {
--size: #{$base-size};
}
}
// if it is bigger then XL it will set size rate to 24/16;
// example: if size set to 14px, it will be 14px * 24 / 16 = 21px
@include media-breakpoint-up(xl) {
:root {
--size: #{$rate-size-xl};
}
}
@function size($px) {
@return calc(#{$px} / $base-size * var(--size));
}
div {
font-size: size(14px);
width: size(150px);
}
Function In function python
def Greater(a,b):
if a>b:
return a
return b
def Greater_new(a,b,c,d):
return Greater(Greater(a,b),Greater(c,d))
print("Greater Number is :-",Greater_new(212,33,11,999))
Variation of Aaron's answer. Using sed without temporary files
#!/bin/bash
VERSION=1.0.0
IMAGE=company/image
ID=$(docker build -t ${IMAGE} . | tail -1 | sed 's/.*Successfully built \(.*\)$/\1/')
docker tag ${ID} ${IMAGE}:${VERSION}
docker tag -f ${ID} ${IMAGE}:latest
Note that COLUMNS
is:
SIGWINCH
signal.That second point usually means that your COLUMNS
variable will only be set in your interactive shell, not in a bash script.
If your script's stdin
is connected to your terminal you can manually look up the width of your terminal by asking your terminal:
tput cols
And to use this in your SVN command:
svn diff "$@" --diff-cmd /usr/bin/diff -x "-y -w -p -W $(tput cols)"
(Note: you should quote "$@"
and stay away from eval
;-))
I checked the runtime value of the ResultSet interface and found out it was pretty much a ResultSetImpl all the time. ResultSetImpl has a method called getUpdateCount()
which returns the value you are looking for.
This code sample should suffice:
ResultSet resultSet = executeQuery(sqlQuery);
double rowCount = ((ResultSetImpl)resultSet).getUpdateCount()
I realize that downcasting is generally an unsafe procedure but this method hasn't yet failed me.
You can change the name of the column, therefore instead of "COUNT(*)" you would have something meaningful. You will have to update your "RowCount.sql" script for that.
For example:
SQL> select count(*) as RecordCountFromTableOne from TableOne;
Will be displayed as:
RecordCountFromTableOne
-----------------------
0
If you want to have space in the title, you need to enclose it in double quotes
SQL> select count(*) as "Record Count From Table One" from TableOne;
Will be displayed as:
Record Count From Table One
---------------------------
0
For disable trigger
ALTER TABLE table_name DISABLE TRIGGER trigger_name
For enable trigger
ALTER TABLE table_name ENABLE TRIGGER trigger_name
In this example, nothing really. The exact
param comes into play when you have multiple paths that have similar names:
For example, imagine we had a Users
component that displayed a list of users. We also have a CreateUser
component that is used to create users. The url for CreateUsers
should be nested under Users
. So our setup could look something like this:
<Switch>
<Route path="/users" component={Users} />
<Route path="/users/create" component={CreateUser} />
</Switch>
Now the problem here, when we go to http://app.com/users
the router will go through all of our defined routes and return the FIRST match it finds. So in this case, it would find the Users
route first and then return it. All good.
But, if we went to http://app.com/users/create
, it would again go through all of our defined routes and return the FIRST match it finds. React router does partial matching, so /users
partially matches /users/create
, so it would incorrectly return the Users
route again!
The exact
param disables the partial matching for a route and makes sure that it only returns the route if the path is an EXACT match to the current url.
So in this case, we should add exact
to our Users
route so that it will only match on /users
:
<Switch>
<Route exact path="/users" component={Users} />
<Route path="/users/create" component={CreateUser} />
</Switch>
It looks like you're having more trouble with Validation than errors/exceptions so I'll say a bit about both.
Validation
Controller actions should generally take Input Models where the validation is declared directly on the model.
public class Customer
{
[Require]
public string Name { get; set; }
}
Then you can use an ActionFilter
that automatically sends validation messages back to the client.
public class ValidationActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var modelState = actionContext.ModelState;
if (!modelState.IsValid) {
actionContext.Response = actionContext.Request
.CreateErrorResponse(HttpStatusCode.BadRequest, modelState);
}
}
}
For more information about this check out http://ben.onfabrik.com/posts/automatic-modelstate-validation-in-aspnet-mvc
Error handling
It's best to return a message back to the client that represents the exception that happened (with relevant status code).
Out of the box you have to use Request.CreateErrorResponse(HttpStatusCode, message)
if you want to specify a message. However, this ties the code to the Request
object, which you shouldn't need to do.
I usually create my own type of "safe" exception that I expect the client would know how to handle and wrap all others with a generic 500 error.
Using an action filter to handle the exceptions would look like this:
public class ApiExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
var exception = context.Exception as ApiException;
if (exception != null) {
context.Response = context.Request.CreateErrorResponse(exception.StatusCode, exception.Message);
}
}
}
Then you can register it globally.
GlobalConfiguration.Configuration.Filters.Add(new ApiExceptionFilterAttribute());
This is my custom exception type.
using System;
using System.Net;
namespace WebApi
{
public class ApiException : Exception
{
private readonly HttpStatusCode statusCode;
public ApiException (HttpStatusCode statusCode, string message, Exception ex)
: base(message, ex)
{
this.statusCode = statusCode;
}
public ApiException (HttpStatusCode statusCode, string message)
: base(message)
{
this.statusCode = statusCode;
}
public ApiException (HttpStatusCode statusCode)
{
this.statusCode = statusCode;
}
public HttpStatusCode StatusCode
{
get { return this.statusCode; }
}
}
}
An example exception that my API can throw.
public class NotAuthenticatedException : ApiException
{
public NotAuthenticatedException()
: base(HttpStatusCode.Forbidden)
{
}
}
This while else statement should only execute the else code when the condition is false, this means it will always execute it. But, there is a catch, when you use the break keyword within the while loop, the else statement should not execute.
The code that satisfies does condition is only:
boolean entered = false;
while (condition) {
entered = true; // Set it to true stright away
// While loop code
// If you want to break out of this loop
if (condition) {
entered = false;
break;
}
} if (!entered) {
// else code
}
getting logged in username: System.Web.HttpContext.Current.User.Identity.Name
I needed a simple formatting library without the bells and whistles of locale and language support. So I modified
http://www.mattkruse.com/javascript/date/date.js
and used it. See https://github.com/adgang/atom-time/blob/master/lib/dateformat.js
The documentation is pretty clear.
The best way is NOT converting to FLOAT or MONEY before converting because of chance of loss of precision. So the secure ways can be something like this :
CREATE FUNCTION [dbo].[fn_ConvertToString]
(
@value sql_variant
)
RETURNS varchar(max)
AS
BEGIN
declare @x varchar(max)
set @x= reverse(replace(ltrim(reverse(replace(convert(varchar(max) , @value),'0',' '))),' ',0))
--remove "unneeded "dot" if any
set @x = Replace(RTRIM(Replace(@x,'.',' ')),' ' ,'.')
return @x
END
where @value can be any decimal(x,y)
How can I display these open transactions and commit or cancel them?
There is no open transaction, MySQL will rollback the transaction upon disconnect.
You cannot commit the transaction (IFAIK).
You display threads using
SHOW FULL PROCESSLIST
See: http://dev.mysql.com/doc/refman/5.1/en/thread-information.html
It will not help you, because you cannot commit a transaction from a broken connection.
What happens when a connection breaks
From the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/mysql-tips.html
4.5.1.6.3. Disabling mysql Auto-Reconnect
If the mysql client loses its connection to the server while sending a statement, it immediately and automatically tries to reconnect once to the server and send the statement again. However, even if mysql succeeds in reconnecting, your first connection has ended and all your previous session objects and settings are lost: temporary tables, the autocommit mode, and user-defined and session variables. Also, any current transaction rolls back.
This behavior may be dangerous for you, as in the following example where the server was shut down and restarted between the first and second statements without you knowing it:
Also see: http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html
How to diagnose and fix this
To check for auto-reconnection:
If an automatic reconnection does occur (for example, as a result of calling mysql_ping()), there is no explicit indication of it. To check for reconnection, call
mysql_thread_id()
to get the original connection identifier before callingmysql_ping()
, then callmysql_thread_id()
again to see whether the identifier has changed.
Make sure you keep your last query (transaction) in the client so that you can resubmit it if need be.
And disable auto-reconnect mode, because that is dangerous, implement your own reconnect instead, so that you know when a drop occurs and you can resubmit that query.
If anybody is still interest Eclipse Labs Rest Client tool is an excellent choice. I'm trying it in Windows in an EXE version and works smoothly.
I've worked also with Rest Client previously and its great too.
Try making the whole sheet font size smaller. Then zoom and save. Make a practice sheet first because it really screws everything up.
there is a limited alternative you can use
header:
class std_int_vector;
class A{
std_int_vector* vector;
public:
A();
virtual ~A();
};
cpp:
#include "header.h"
#include <vector>
class std_int_vector: public std::vectror<int> {}
A::A() : vector(new std_int_vector()) {}
[...]
not tested in real programs, so expect it to be non-perfect.
It looks like psexec -h
is the way to do this:
-h If the target system is Windows Vista or higher, has the process
run with the account's elevated token, if available.
Which... doesn't seem to be listed in the online documentation in Sysinternals - PsExec.
But it works on my machine.
If the first column is always the same size (including the spaces), then you can just take those characters (via LEFT
) and clean up the spaces (with RTRIM
):
SELECT RTRIM(LEFT(YourColumn, YourColumnSize))
Alternatively, you can extract the second (or third, etc.) column (using SUBSTRING
):
SELECT RTRIM(SUBSTRING(YourColumn, PreviousColumnSizes, YourColumnSize))
One benefit of this approach (especially if YourColumn
is the result of a computation) is that YourColumn
is only specified once.
Perhaps unintentional, but moving my docker file to the solution folder instead of the project eliminated the error. This was helpful when I still wanted to run the solution independently of docker
This shows how to run the playbooks on the target server itself.
This is a bit trickier if you want to use a local connection. But this should be OK if you use a variable for the hosts setting and in the hosts file create a special entry for localhost.
In (all) playbooks have the hosts: line set to:
- hosts: "{{ target | default('no_hosts')}}"
In the inventory hosts file add an entry for the localhost which sets the connection to be local:
[localhost]
127.0.0.1 ansible_connection=local
Then on the command line run commands explicitly setting the target - for example:
$ ansible-playbook --extra-vars "target=localhost" test.yml
This will also work when using ansible-pull:
$ ansible-pull -U <git-repo-here> -d ~/ansible --extra-vars "target=localhost" test.yml
If you forget to set the variable on the command line the command will error safely (as long as you've not created a hosts group called 'no_hosts'!) with a warning of:
skipping: no hosts matched
And as mentioned above you can target a single machine (as long as it is in your hosts file) with:
$ ansible-playbook --extra-vars "target=server.domain" test.yml
or a group with something like:
$ ansible-playbook --extra-vars "target=web-servers" test.yml
In case you have some parameters to pass to a function and want a value in return. Here I am passing "12345" as an argument to a function and after processing returning variable XYZ which will be assigned to VALUE
#!/bin/bash
getValue()
{
ABC=$1
XYZ="something"$ABC
echo $XYZ
}
VALUE=$( getValue "12345" )
echo $VALUE
Output:
something12345
This comes down to browser image support; it looks like the only mainstream browser that supports tiff is Safari:
http://en.wikipedia.org/wiki/Comparison_of_web_browsers#Image_format_support
Where are you getting the tiff images from? Is it possible for them to be generated in a different format?
If you have a static set of images then I'd recommend using something like PaintShop Pro to batch convert them, changing the format.
If this isn't an option then there might be some mileage in looking for a pre-written Java applet (or another browser plugin) that can display the images in the browser.
lsof +f -- /mountpoint
(as lists the processes using files on the mount mounted at /mountpoint. Particularly useful for finding which process(es) are using a mounted USB stick or CD/DVD.
Your Window is not implementing the necessary data binding notifications that the grid requires to use it as a data source, namely the INotifyPropertyChanged interface.
Your "Name2" string needs also to be a property and not a public variable, as data binding is for use with properties.
Implementing the necessary interfaces for using an object as a data source can be found here.
Are you sure the page you are redirecting too doesn't have a redirection within that if no session data is found? That could be your problem
Also yes always add whitespace like @Peter O suggested.
Cern's ROOT produces some pretty nice stuff, I use it to display Neural Network data a lot.
I know I am quite late to post this, but I share similar experience when I learned the ropes of IAP model.
In-app purchase is one of the most comprehensive workflow in iOS implemented by Storekit framework. The entire documentation is quite clear if you patience to read it, but is somewhat advanced in nature of technicality.
To summarize:
1 - Request the products - use SKProductRequest & SKProductRequestDelegate classes to issue request for Product IDs and receive them back from your own itunesconnect store.
These SKProducts should be used to populate your store UI which the user can use to buy a specific product.
2 - Issue payment request - use SKPayment & SKPaymentQueue to add payment to the transaction queue.
3 - Monitor transaction queue for status update - use SKPaymentTransactionObserver Protocol's updatedTransactions method to monitor status:
SKPaymentTransactionStatePurchasing - don't do anything
SKPaymentTransactionStatePurchased - unlock product, finish the transaction
SKPaymentTransactionStateFailed - show error, finish the transaction
SKPaymentTransactionStateRestored - unlock product, finish the transaction
4 - Restore button flow - use SKPaymentQueue's restoreCompletedTransactions to accomplish this - step 3 will take care of the rest, along with SKPaymentTransactionObserver's following methods:
paymentQueueRestoreCompletedTransactionsFinished
restoreCompletedTransactionsFailedWithError
Here is a step by step tutorial (authored by me as a result of my own attempts to understand it) that explains it. At the end it also provides code sample that you can directly use.
Here is another one I created to explain certain things that only text could describe in better manner.
I'm using Python 3.4.0
In Python 3 we have some problems with data types transformation.
So... here I'll tell a tip for those (like me) that works a lot with hex strings.
I'll take an hex data and make an complement it:
a = b'acad0109'
compl = int(a,16)-pow(2,32)
result=hex(compl)
print(result)
print(int(result,16))
print(bin(int(result,16)))
result = -1397948151 or -0x5352fef7 or '-0b1010011010100101111111011110111'
Here is the method using ex
editor (part of Vim):
Join all lines and print to the standard output:
$ ex +%j +%p -scq! file
Join all lines in-place (in the file):
$ ex +%j -scwq file
Note: This will concatenate all lines inside the file it-self!
The methods are identical when an object or array is passed, but res.json()
will also convert non-objects, such as null
and undefined
, which are not valid JSON.
The method also uses the json replacer
and json spaces
application settings, so you can format JSON with more options. Those options are set like so:
app.set('json spaces', 2);
app.set('json replacer', replacer);
And passed to a JSON.stringify()
like so:
JSON.stringify(value, replacer, spacing);
// value: object to format
// replacer: rules for transforming properties encountered during stringifying
// spacing: the number of spaces for indentation
This is the code in the res.json()
method that the send method doesn't have:
var app = this.app;
var replacer = app.get('json replacer');
var spaces = app.get('json spaces');
var body = JSON.stringify(obj, replacer, spaces);
The method ends up as a res.send()
in the end:
this.charset = this.charset || 'utf-8';
this.get('Content-Type') || this.set('Content-Type', 'application/json');
return this.send(body);
You may find such kind of errors when you did not define the complete path of your XML file. Try this one if you are using opencv3.1.0 in raspberrypi 3: "faceCascade = cv2.CascadeClassifier('/home/pi/opencv-3.1.0/data/haarcascades/haarcascade_frontalface_default.xml')"
Here is a time performance comparison between using np.where
vs list_comprehension
. Seems like np.where
is faster on average.
# np.where
start_times = []
end_times = []
for i in range(10000):
start = time.time()
start_times.append(start)
temp_list = np.array([1,2,3,3,5])
ixs = np.where(temp_list==3)[0].tolist()
end = time.time()
end_times.append(end)
print("Took on average {} seconds".format(
np.mean(end_times)-np.mean(start_times)))
Took on average 3.81469726562e-06 seconds
# list_comprehension
start_times = []
end_times = []
for i in range(10000):
start = time.time()
start_times.append(start)
temp_list = np.array([1,2,3,3,5])
ixs = [i for i in range(len(temp_list)) if temp_list[i]==3]
end = time.time()
end_times.append(end)
print("Took on average {} seconds".format(
np.mean(end_times)-np.mean(start_times)))
Took on average 4.05311584473e-06 seconds
try this function :-
function msToTime(ms) {_x000D_
var d = new Date(null)_x000D_
d.setMilliseconds(ms)_x000D_
return d.toLocaleTimeString("en-US")_x000D_
}_x000D_
_x000D_
var ms = 4000000_x000D_
alert(msToTime(ms))
_x000D_
In my case this error was happening in a Gitlab CI pipeline when I was passing multiple Gitlab env variables to docker build
with --build-arg
flags.
Turns out that one of the variables had a space in it which was causing the error. It was difficult to find since the pipeline logs just showed the $VARIABLE_NAME
.
Make sure to quote the environment variables so that spaces get handled correctly.
Change from:
--build-arg VARIABLE_NAME=$VARIABLE_NAME
to:
--build-arg VARIABLE_NAME="$VARIABLE_NAME"
CDATA is Obsolete.
Note that CDATA sections should not be used within HTML; they only work in XML.
So do not use it in HTML 5.
https://developer.mozilla.org/en-US/docs/Web/API/CDATASection#Specifications
Disclaimer: The following answer assumes that you are using the JavaScript environment of a web browser.
JavaScript handles XML with 'XML DOM objects'. You can obtain such an object in three ways:
1. Creating a new XML DOM object
var xmlDoc = document.implementation.createDocument(null, "books");
The first argument can contain the namespace URI of the document to be created, if the document belongs to one.
Source: https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument
2. Fetching an XML file with XMLHttpRequest
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var xmlDoc = xhttp.responseXML; //important to use responseXML here
}
xhttp.open("GET", "books.xml", true);
xhttp.send();
3. Parsing a string containing serialized XML
var xmlString = "<root></root>";
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(xmlString, "text/xml"); //important to use "text/xml"
When you have obtained an XML DOM object, you can use methods to manipulate it like
var node = xmlDoc.createElement("heyHo");
var elements = xmlDoc.getElementsByTagName("root");
elements[0].appendChild(node);
For a full reference, see http://www.w3schools.com/xml/dom_intro.asp
Note: It is important, that you don't use the methods provided by the document namespace, i. e.
var node = document.createElement("Item");
This will create HTML nodes instead of XML nodes and will result in a node with lower-case tag names. XML tag names are case-sensitive in contrast to HTML tag names.
You can serialize XML DOM objects like this:
var serializer = new XMLSerializer();
var xmlString = serializer.serializeToString(xmlDoc);
Use cbind
e.g.
df <- data.frame(b = runif(6), c = rnorm(6))
cbind(a = 0, df)
giving:
> cbind(a = 0, df)
a b c
1 0 0.5437436 -0.1374967
2 0 0.5634469 -1.0777253
3 0 0.9018029 -0.8749269
4 0 0.1649184 -0.4720979
5 0 0.6992595 0.6219001
6 0 0.6907937 -1.7416569
WARNING: You should understand the security risks of this method before you consider it. John's summary of the risk:
By giving the container access to
/var/run/docker.sock
, it is [trivially easy] to break out of the containment provided by docker and gain access to the host machine. Obviously this is potentially dangerous.
Inside the container, the dockerId is your hostname. So, you could:
--volume
/var/run/docker.sock:/var/run/docker.sock --privileged
docker inspect $(hostname)
inside the containerAvoid this. Only do it if you understand the risks and have a clear mitigation for the risks.
Write it like this:
string[] files = Directory.GetFiles(@".\Archive", "*.zip");
. is for relative to the folder where you started your exe, and @ to allow \ in the name.
When using filters, you pass it as a second parameter. You can also add a third parameter to specify if you want to search recursively for the pattern.
In order to get the folder where your .exe actually resides, use:
var executingPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
you can use plt.matshow()
instead of plt.imshow()
or you can use seaborn module's heatmap
(see documentation) to plot the confusion matrix
import seaborn as sn
import pandas as pd
import matplotlib.pyplot as plt
array = [[33,2,0,0,0,0,0,0,0,1,3],
[3,31,0,0,0,0,0,0,0,0,0],
[0,4,41,0,0,0,0,0,0,0,1],
[0,1,0,30,0,6,0,0,0,0,1],
[0,0,0,0,38,10,0,0,0,0,0],
[0,0,0,3,1,39,0,0,0,0,4],
[0,2,2,0,4,1,31,0,0,0,2],
[0,1,0,0,0,0,0,36,0,2,0],
[0,0,0,0,0,0,1,5,37,5,1],
[3,0,0,0,0,0,0,0,0,39,0],
[0,0,0,0,0,0,0,0,0,0,38]]
df_cm = pd.DataFrame(array, index = [i for i in "ABCDEFGHIJK"],
columns = [i for i in "ABCDEFGHIJK"])
plt.figure(figsize = (10,7))
sn.heatmap(df_cm, annot=True)
If you want to center one view, use this one. In this case TextView must be the lowermost view in your XML because it's layout_height is match_parent.
<TextView
android:id="@+id/tv_to_be_centered"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:gravity="center"
android:text="Some text"
/>
It's really a 6 of one, a half-dozen of the other situation.
The only possible argument against your approach is $_SERVER['REQUEST_METHOD'] == 'POST' may not be populated on certain web-servers/configuration, whereas the $_POST array will always exist in PHP4/PHP5 (and if it doesn't exist, you have bigger problems (-:)
curl_exec
is necessary. Try CURLOPT_NOBODY
to not download the body. That might be faster.
This is something that worked for me, although it smells a bit wrong:
var iframe = ...
var doc = iframe.contentDocument;
var i = doc.createElement('input');
i.style.display = 'none';
doc.body.appendChild(i);
i.focus();
doc.body.removeChild(i);
hmmm. it also scrolls to the bottom of the content. Guess I should be inserting the dummy textbox at the top.
Well the correct answer for the default Json formater based on Json.net is to set ReferenceLoopHandling
to Ignore
.
Just add this to the Application_Start
in Global.asax:
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter
.SerializerSettings
.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
This is the correct way. It will ignore the reference pointing back to the object.
Other responses focused in changing the list being returned by excluding data or by making a facade object and sometimes that is not an option.
Using the JsonIgnore
attribute to restrict the references can be time consuming and if you want to serialize the tree starting from another point that will be a problem.
I was using a virtual environment on Ubuntu 18.04, and since I only wanted to install it as a client, I only had to do:
sudo apt install libpq-dev
pip install psycopg2
And installed without problems. Of course, you can use the binary as other answers said, but I preferred this solution since it was stated in a requirements.txt file.
Seems like one of your values, with a property key of 'value' is undefined. Test that i1
, i2
and __i
are defined before executing the if statements:
var i1 = document.getElementById('i1');
var i2 = document.getElementById('i2');
var __i = {'user' : document.getElementsByName("username")[0], 'pass' : document.getElementsByName("password")[0] };
if(i1 && i2 && __i.user && __i.pass)
{
if( __i.user.value.length >= 1 ) { i1.value = ''; } else { i1.value = 'Acc'; }
if( __i.pass.value.length >= 1 ) { i2.value = ''; } else { i2.value = 'Pwd'; }
}
Given worked for me.
document.querySelectorAll(".widget.hover").forEach(obj=>obj.classList.remove("hover"));
To get a footer that sticks to the bottom of your viewport, give it a fixed position like this:
footer {
position: fixed;
height: 100px;
bottom: 0;
width: 100%;
}
Bootstrap includes this CSS in the Navbar > Placement section with the class fixed-bottom
. Just add this class to your footer element:
<footer class="fixed-bottom">
Bootstrap docs: https://getbootstrap.com/docs/4.4/utilities/position/#fixed-bottom
This is easy one:
foreach( $_POST['field'] as $num => $val ) {
print ' '.$num.' -> '.$val.' ';
}
The function you need is CInt
.
ie CInt(PrinterLabel)
See Type Conversion Functions (Visual Basic) on MSDN
Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!
WebClient is a higher-level abstraction built on top of HttpWebRequest to simplify the most common tasks. For instance, if you want to get the content out of an HttpWebResponse, you have to read from the response stream:
var http = (HttpWebRequest)WebRequest.Create("http://example.com");
var response = http.GetResponse();
var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();
With WebClient, you just do DownloadString
:
var client = new WebClient();
var content = client.DownloadString("http://example.com");
Note: I left out the using
statements from both examples for brevity. You should definitely take care to dispose your web request objects properly.
In general, WebClient is good for quick and dirty simple requests and HttpWebRequest is good for when you need more control over the entire request.
It's simple, use $.getJSON()
function and in your URL just include
callback=?
as a parameter. That will convert the call to JSONP which is necessary to make cross-domain calls. More info: http://api.jquery.com/jQuery.getJSON/
For the same issue on Windows7
You will see an error like this if your environment variables/ system variables are incorrectly set:
Fatal Python error: Py_Initialize: unable to load the file system codec
ImportError: No module named 'encodings'
Current thread 0x00001db4 (most recent call first):
Fixing this is really simple:
When you download Python3.x version, and run the .exe file, it gives you an option to customize where in your system you want to install Python. For example, I chose this location: C:\Program Files\Python36
Then open system properties and go to "Advanced" tab (Or you can simply do this: Go to Start > Search for "environment variables" > Click on "Edit the system environment variables".) Under the "Advanced" tab, look for "Environment Variables" and click it. Another window with name "Environment Variables" will pop up.
Now make sure your user variables have the correct Python path listed in "Path Variable". In my example here, you should see C:\Program Files\Python36. If you do not find it there, add it, by selecting Path Variable field and clicking Edit.
Last step is to double-check PYTHONHOME and PYTHONPATH fields under System Variables in the same window. You should see the same path as described above. If not add it there too.
Then click OK and go back to CMD terminal, and try checking for python. The issue should now be resolved. It worked for me.
inline-block
is of no use in this scenarioSOLUTION
word-break: normal|break-all|keep-all|break-word|initial|inherit;
white-space: nowrap
nowhere used.NOTE FOR BETTER UNDERSTANDING:
word-wrap
/overflow-wrap
is used to break words that overflow their container
word-break
property breaks all words at the end of a line, even those that would normally wrap onto another line and wouldn’t overflow their container.
word-wrap
is the historic and nonstandard property. It has been renamed to overflow-wrap
but remains an alias, browsers must support in future. Many browsers (especially the old ones) don’t support overflow-wrap
and require word-wrap
as a fallback (which is supported by all).
If you want to please the W3C you should consider associate both in your CSS. If you don’t, using word-wrap
alone is just fine.
It worked for me, when I set error_reporting in two places at same time
somewhere in PHP code
ini_set('error_reporting', 30711);
and in .htaccess file
php_value error_reporting 30711
For the current Spring-Boot Version 1.5.3 the parameter is
spring.resources.static-locations
Update I configured
`spring.resources.static-locations=file:/opt/x/y/z/static``
and expected to get my index.html living in this folder when calling
http://<host>/index.html
This did not work. I had to include the folder name in the URL:
http://<host>/static/index.html
On Unix time.clock() measures the amount of CPU time that has been used by the current process, so it's no good for measuring elapsed time from some point in the past. On Windows it will measure wall-clock seconds elapsed since the first call to the function. On either system time.time() will return seconds passed since the epoch.
If you're writing code that's meant only for Windows, either will work (though you'll use the two differently - no subtraction is necessary for time.clock()). If this is going to run on a Unix system or you want code that is guaranteed to be portable, you will want to use time.time().
You may run into such problem while dealing with scraped data stored as Pandas DataFrame.
This solution works like charm if the list of values is present as text.
def textToList(hashtags):
return hashtags.strip('[]').replace('\'', '').replace(' ', '').split(',')
hashtags = "[ 'A','B','C' , ' D']"
hashtags = textToList(hashtags)
Output: ['A', 'B', 'C', 'D']
No external library required.
According to Listening For and Broadcasting Global Messages, and Setting Alarms in Common Tasks and How to Do Them in Android:
If the receiving class is not registered using in its manifest, you can dynamically instantiate and register a receiver by calling Context.registerReceiver().
Take a look at registerReceiver (BroadcastReceiver receiver, IntentFilter filter) for more info.
You can append to your PATH
in a minimal fashion. No need for
parentheses unless you're appending more than one element. It also
usually doesn't need quotes. So the simple, short way to append is:
path+=/some/new/bin/dir
This lower-case syntax is using path
as an array, yet also
affects its upper-case partner equivalent, PATH
(to which it is
"bound" via typeset
).
(Notice that no :
is needed/wanted as a separator.)
Then the common pattern for testing a new script/executable becomes:
path+=$PWD/.
# or
path+=$PWD/bin
You can sprinkle path settings around your .zshrc
(as above) and it will naturally lead to the earlier listed settings taking precedence (though you may occasionally still want to use the "prepend" form path=(/some/new/bin/dir $path)
).
Treating path
this way (as an array) also means: no need to do a
rehash
to get the newly pathed commands to be found.
Also take a look at vared path
as a dynamic way to edit path
(and other things).
You may only be interested in path
for this question, but since
we're talking about exports and arrays, note that
arrays generally cannot be exported.
You can even prevent PATH
from taking on duplicate entries
(refer to
this
and this):
typeset -U path
try pcregrep
instead of regular grep
:
pcregrep -M "pattern1.*\n.*pattern2" filename
the -M
option allows it to match across multiple lines, so you can search for newlines as \n
.
Can't import all at once but can use following combination:
ALT
+ Enter
--> Show intention actions and quick-fixes.
F2
--> Next highlighted error.
$(document).ready(function(){_x000D_
$(window).scroll(function() {_x000D_
if ($(document).scrollTop() >1290 ) { _x000D_
$(".navbar-fixed-top").css("background-color", "rgb(255, 160, 160)"); _x000D_
}else if ($(document).scrollTop() >850) { _x000D_
$(".navbar-fixed-top").css("background-color", "black"); _x000D_
}else if ($(document).scrollTop() >350) { _x000D_
$(".navbar-fixed-top").css("background-color", "rgba(47, 73, 158, 0.514)"); _x000D_
}_x000D_
else {_x000D_
$(".navbar-fixed-top").css("background-color", "red"); _x000D_
}_x000D_
});_x000D_
});
_x000D_
@import url(https://fonts.googleapis.com/css?family=Roboto+Slab:400,700|Open+Sans);_x000D_
body {_x000D_
font-family: "Roboto Slab", sans-serif;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
h1,_x000D_
h2,_x000D_
h3,_x000D_
h4 {_x000D_
font-family: "Open Sans", sans-serif;_x000D_
}_x000D_
_x000D_
.main {_x000D_
padding-top: 50px;_x000D_
}_x000D_
_x000D_
#home {_x000D_
padding-top: 20%;_x000D_
background-image: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://s31.postimg.org/l5q32ptln/coffee_cup_mug_apple.jpg');_x000D_
background-attachment: fixed;_x000D_
background-repeat: no-repeat;_x000D_
background-position: center center;_x000D_
position: relative;_x000D_
height: 100vh;_x000D_
}_x000D_
_x000D_
#home h2 {_x000D_
color: white;_x000D_
font-size: 4em;_x000D_
}_x000D_
_x000D_
#home h4 {_x000D_
color: white;_x000D_
font-size: 2em;_x000D_
}_x000D_
_x000D_
#home ul {_x000D_
list-style-type: none;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
#home li {_x000D_
padding-bottom: 12px;_x000D_
padding-right: 12px;_x000D_
display: inline;_x000D_
}_x000D_
_x000D_
#home li:last-child {_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
@media (max-width: 710px) {_x000D_
#home li {_x000D_
display: block;_x000D_
}_x000D_
}_x000D_
_x000D_
.img-style {_x000D_
height: 200px;_x000D_
width: 200px;_x000D_
margin-top: 50px;_x000D_
}_x000D_
_x000D_
#about {_x000D_
height: 100vh;_x000D_
padding-top: 10%;_x000D_
background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('https://s32.postimg.org/sm6o6617p/photo_1432821596592_e2c18b78144f.jpg');_x000D_
background-attachment: fixed;_x000D_
background-repeat: no-repeat;_x000D_
background-position: center center;_x000D_
position: relative;_x000D_
color: white;_x000D_
}_x000D_
_x000D_
#about p,_x000D_
li {_x000D_
font-size: 17px;_x000D_
}_x000D_
_x000D_
.navbar.color-yellow {_x000D_
background-color: yellow;_x000D_
height: 50px;_x000D_
color: yellow;_x000D_
}_x000D_
_x000D_
.navbar.color-change {_x000D_
background-color: #f45b69;_x000D_
height: 50px;_x000D_
color: rgba(255, 254, 255, 0.8);_x000D_
}_x000D_
_x000D_
#portfolio {_x000D_
padding-top: 30px;_x000D_
rgba(226,_x000D_
226,_x000D_
226,_x000D_
1);_x000D_
background: linear-gradient(to bottom, rgba(226, 226, 226, 1) 0%, rgba(209, 209, 209, 1) 25%, rgba(219, 219, 219, 1) 57%, rgba(254, 254, 254, 1) 100%);_x000D_
height: 100vh;_x000D_
}_x000D_
_x000D_
#portfolio .block .portfolio-contant ul li {_x000D_
float: left;_x000D_
width: 32.22%;_x000D_
overflow: hidden;_x000D_
margin: 6px;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
#portfolio .block .portfolio-contant ul li:hover .overly {_x000D_
opacity: 1;_x000D_
}_x000D_
_x000D_
#portfolio .block .portfolio-contant ul li:hover .position-center {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
-webkit-transform: translate(0%, -50%);_x000D_
-moz-transform: translate(0%, -50%);_x000D_
-ms-transform: translate(0%, -50%);_x000D_
transform: translate(0%, -50%);_x000D_
}_x000D_
_x000D_
#portfolio .block .portfolio-contant ul li a {_x000D_
display: block;_x000D_
color: #fff;_x000D_
}_x000D_
_x000D_
#portfolio .block .portfolio-contant ul li a h2 {_x000D_
font-size: 22px;_x000D_
text-transform: uppercase;_x000D_
letter-spacing: 1px;_x000D_
}_x000D_
_x000D_
#portfolio .block .portfolio-contant ul li a p {_x000D_
font-size: 15px;_x000D_
}_x000D_
_x000D_
#portfolio .block .portfolio-contant ul li a span {_x000D_
font-style: italic;_x000D_
font-size: 13px;_x000D_
color: #655E7A;_x000D_
}_x000D_
_x000D_
#portfolio .block .portfolio-contant ul img {_x000D_
width: 100%;_x000D_
height: auto;_x000D_
}_x000D_
_x000D_
#portfolio .block .portfolio-contant .overly {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
right: 0;_x000D_
left: 0;_x000D_
background: rgba(0, 0, 0, 0.9);_x000D_
opacity: 0;_x000D_
-webkit-transition: .3s all;_x000D_
-o-transition: .3s all;_x000D_
transition: .3s all;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
#portfolio .block .portfolio-contant .position-center {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
left: 10%;_x000D_
-webkit-transform: translate(0%, 50%);_x000D_
-moz-transform: translate(0%, 50%);_x000D_
-ms-transform: translate(0%, 50%);_x000D_
transform: translate(0%, 50%);_x000D_
-webkit-transition: .5s all;_x000D_
-o-transition: .5s all;_x000D_
transition: .5s all;_x000D_
}_x000D_
_x000D_
#contact {_x000D_
height: 100vh;_x000D_
padding-top: 10%;_x000D_
background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url("https://s32.postimg.org/ex6q1qxkl/pexels_photo.jpg");_x000D_
background-attachment: fixed;_x000D_
background-size: cover;_x000D_
background-repeat: no-repeat;_x000D_
background-position: center center;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
#contact h3 {_x000D_
color: white;_x000D_
}_x000D_
_x000D_
footer ul {_x000D_
list-style-type: none;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
footer li {_x000D_
display: inline;_x000D_
padding-right: 10px;_x000D_
}_x000D_
_x000D_
footer li:last-child {_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
footer p {_x000D_
color: grey;_x000D_
font-size: 11px;_x000D_
}
_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
<meta http-equiv="X-UA-Compatible" content="ie=edge">_x000D_
<title>Document</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<header>_x000D_
<nav class="navbar navbar-default navbar-fixed-top" role="navigation">_x000D_
<div class="container">_x000D_
<div class="navbar-header">_x000D_
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#collapse" aria-expanded="false">_x000D_
<span class="sr-only">Toggle navigation</span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
<span class="icon-bar"></span>_x000D_
</button>_x000D_
<a class="navbar-brand" href="#featured">Portfolio</a>_x000D_
</div>_x000D_
<!-- navbar-header -->_x000D_
<div class="collapse navbar-collapse" id="collapse">_x000D_
<ul class="nav navbar-nav navbar-right">_x000D_
<li class="active"><a href="#home">Home</a></li>_x000D_
<li><a href="#about">About</a></li>_x000D_
<li><a href="#portfolio">Portfolio</a></li>_x000D_
<li><a href="#contact">Contact</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
<!-- collapse navbar-collapse -->_x000D_
_x000D_
</div>_x000D_
<!-- container -->_x000D_
</nav>_x000D_
</header>_x000D_
_x000D_
<div class="main">_x000D_
<div class="row " id="home" data-speed="2" data-type="background">_x000D_
<div class="container">_x000D_
<h2 class="text-center">Welcome to my portfolio</h2>_x000D_
<h4 class="text-center">Where awesomeness is crafted</h4>_x000D_
<hr>_x000D_
<ul>_x000D_
<li><a href="https://github.com/vamshi121" class="btn btn-primary"><i class="fa fa-github"></i> GitHub</a></li>_x000D_
<li><a href="https://tn.linkedin.com/in/mannemvamshi" class="btn btn-primary"><i class="fa fa-linkedin"></i> LinkedIn</a></li>_x000D_
<li><a href="https://freecodecamp.com/" class="btn btn-primary"><i class="fa fa-fire"></i> FreeCodeCamp</a></li>_x000D_
_x000D_
</ul>_x000D_
</div>_x000D_
<!--container-->_x000D_
_x000D_
</div>_x000D_
<!--home-->_x000D_
<div class="row" id="about" data-speed="2" data-type="background">_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col-md-5 col-md-offset-1">_x000D_
<h2>About me</h2>_x000D_
<p>Courteous and Enthusiastic,I'm interested in IT and around in its globe. I began to be fascinated by web programming i.e, building websites and developing cross-platform apps.I'm always looking for new ventures where i can learn evolve and_x000D_
expertise._x000D_
</marquee>_x000D_
</div>_x000D_
</p>_x000D_
<p>My skills are:_x000D_
<ul>_x000D_
<li> Front-end : HTML5, CSS3 , jQuery, Bootstrap, AngularJS</li>_x000D_
<li>Back-end: Ruby on Rails</li>_x000D_
<li>Methodology: Agile, TDD</li>_x000D_
</ul>_x000D_
</p>_x000D_
</div>_x000D_
<!--col-md-5-->_x000D_
<div class="col-md-4 col-md-offset-1">_x000D_
<img class="img-circle img-style hidden-xs" src="https://www.triketech.site/images/log.png" />_x000D_
</div>_x000D_
</div>_x000D_
<!--row-->_x000D_
</div>_x000D_
<!--container-->_x000D_
</div>_x000D_
<!--about-->_x000D_
<div class="row" id="portfolio" data-speed="2" data-type="background">_x000D_
<div class="container">_x000D_
<h2 class="text-center">Portfolio projects</h2>_x000D_
<div class="row">_x000D_
<div class="col-md-12">_x000D_
<div class="block">_x000D_
<div class="portfolio-contant">_x000D_
<ul id="portfolio-contant-active">_x000D_
<li class="mix Branding">_x000D_
<a href="#">_x000D_
<img src="#" alt="">_x000D_
<div class="overly">_x000D_
<div class="position-center">_x000D_
<h2>Local Support</h2>_x000D_
_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
<!--overly-->_x000D_
</a>_x000D_
</li>_x000D_
</ul>_x000D_
</div>_x000D_
<!--portfolio-contant-->_x000D_
</div>_x000D_
<!--block-->_x000D_
</div>_x000D_
<!--col-->_x000D_
</div>_x000D_
<!--row-->_x000D_
</div>_x000D_
<!--container-->_x000D_
</div>_x000D_
<!--portfolio-->_x000D_
<div class="row" id="contact" data-speed="2" data-type="background">_x000D_
<div class="container">_x000D_
<div class="col-md-4 col-md-offset-1">_x000D_
<h3>Contact me at:</h3>_x000D_
<h3>[email protected]</h3>_x000D_
</div>_x000D_
<!--col-md-4-->_x000D_
</div>_x000D_
<!--container-->_x000D_
</div>_x000D_
<!--contact-->_x000D_
</div>_x000D_
<!--main-->_x000D_
<footer>_x000D_
<ul>_x000D_
<li><a href="#home">Home</a> </li>_x000D_
<li><a href="#about">About</a> </li>_x000D_
<li><a href="#portfolio">Portfolio</a> </li>_x000D_
<li><a href="#contact">Contact</a> </li>_x000D_
</ul>_x000D_
<p class="text-center">Copyright © - All Rights Reserved. </p>_x000D_
</footer>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
<script>
$(document).ready(function(){
$(window).scroll(function() {
if ($(document).scrollTop() >1920 ) {
$(".navbar-fixed-top").css("background-color", "rgb(255, 160, 160)");
} else if ($(document).scrollTop() >1580) {
$(".navbar-fixed-top").css("background-color", "black");
} else if ($(document).scrollTop() >620) {
$(".navbar-fixed-top").css("background-color", "rgba(47, 73, 158, 0.514)");
} else {
$(".navbar-fixed-top").css("background-color", "transparent");
}
});
});
</script>
For me the easiest way was to read the last versions of the project with a combination of curl, grep, sort and tail.
My format: service-(version: 1.9.23)-(buildnumber)156.tar.gz
versionToDownload=$(curl -u$user:$password 'https://$artifactory/artifactory/$project/' | grep -o 'service-[^"]*.tar.gz' | sort | tail -1)
Not knowing in what context this will appear, but I believe the CSS-style property float
either left
or right
will have this effect. On the other hand, it'll have other side effects as well, such as allowing text to float around it.
Please correct me if I'm wrong though, I'm not 100% sure, and currently can't test it myself.
if you want to change color by hovering in the element, try this:
path:hover{
fill:red;
}
As Luiggi mentioned you need to change your main to:
import java.util.Arrays;
public class trial1{
public static void main(String[] args){
int[] A = numbers();
System.out.println(Arrays.toString(A)); //Might require import of util.Arrays
}
public static int[] numbers(){
int[] A = {1,2,3};
return A;
}
}
Unfortunately, the old xkcd comic isn't completely up to date anymore.
Since Python 3.0 you have to write:
print("Hello, World!")
And someone has still to write that antigravity
library :(
see if you are placing the client section in the correct web.config file. SharePoint has around 6 to 7 config files. http://msdn.microsoft.com/en-us/library/office/ms460914(v=office.14).aspx (http://msdn.microsoft.com/en-us/library/office/ms460914%28v=office.14%29.aspx)
Post this you can simply try
ServiceClient client = new ServiceClient("ServiceSOAP");
The {glue} package offers string interpolation. In the example, {wd}
is substituted with the contents of the variable. Complex expressions are also supported.
library(glue)
wd <- getwd()
glue("Current working dir: {wd}")
#> Current working dir: /tmp/RtmpteMv88/reprex46156826ee8c
Created on 2019-05-13 by the reprex package (v0.2.1)
Note how the printed output doesn't contain the [1]
artifacts and the "
quotes, for which other answers use cat()
.
Possible alternative from the source code of Integer.compare
method which requires API Version 19
is :
public int compareTo(Animal other) {
return Integer.valueOf(this.year_discovered).compareTo(other.year_discovered);
}
This alternative does not require you to use API version 19
.
To enable use bind()
method
$("#id").bind("click",eventhandler);
call this handler
function eventhandler(){
alert("Bind click")
}
To disable click useunbind()
$("#id").unbind("click");
/
and ..
in the user provided file name can be harmful. So you should get rid of these by something like:
$fname = str_replace('..', '', $fname);
$fname = str_replace('/', '', $fname);
try this
var value = iterate('tr.item span.value');
var quantity = iterate('tr.item span.quantity');
function iterate(selector)
{
var result = '';
if ($(selector))
{
$(selector).each(function ()
{
if (result == '')
{
result = $(this).html();
}
else
{
result = result + "," + $(this).html();
}
});
}
}
It is not quite as baked-in in Java, so you don't get this for free. It is done with convention rather than language constructs. In all data transfer classes (and maybe even in all classes you write...), you should implement a sensible toString
method. So here you need to override toString()
in your Person
class and return the desired state.
There are utilities available that help with writing a good toString method, or most IDEs have an automatic toString()
writing shortcut.
we have two way to concatenate columns in MySql
select concat(hobbies) as `Hobbies` from people_hobbies where 1
Or
select group_concat(hobbies) as `Hobbies` from people_hobbies where 1
You could use preg_split
instead of explode
and split on [ ]+
(one or more spaces). But I think in this case you could go with preg_match_all
and capturing:
preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];
The pattern matches a space, php
, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php
as part of a user name but really only as a command.
An alternative to capturing is the "keep" feature of PCRE. If you use \K
in the pattern, everything before it is discarded in the match:
preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];
I would use preg_match()
. I do something similar for many of my system management scripts. Here is an example:
$test = "user 12052 0.2 0.1 137184 13056 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user 12054 0.2 0.1 137184 13064 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user 12055 0.6 0.1 137844 14220 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user 12057 0.2 0.1 137184 13052 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user 12058 0.2 0.1 137184 13052 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user 12059 0.3 0.1 135112 13000 ? Ss 10:00 0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root 12068 0.0 0.0 106088 1164 pts/1 S+ 10:00 0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root 12070 0.0 0.0 103240 828 pts/1 R+ 10:00 0:00 grep utilities";
$lines = explode("\n", $test);
foreach($lines as $line){
if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
print_r($matches);
}
}
The above prints:
Array
(
[0] => .php cust1 cron
[1] => cust1
)
Array
(
[0] => .php cust3 cron
[1] => cust3
)
Array
(
[0] => .php cust4 cron
[1] => cust4
)
Array
(
[0] => .php cust89 cron
[1] => cust89
)
Array
(
[0] => .php cust435 cron
[1] => cust435
)
Array
(
[0] => .php cust16 cron
[1] => cust16
)
You can set $test
to equal the output from exec. the values you are looking for would be in the if
statement under the foreach
. $matches[1]
will have the custx value.
You can use this
<div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel" data-interval="4000">
Just add data-interval="1000"
where next picture will be after 1 sec.
TEXT is a data-type for text based input. On the other hand, you have BLOB and CLOB which are more suitable for data storage (images, etc) due to their larger capacity limits (4GB for example).
As for the difference between BLOB and CLOB, I believe CLOB has character encoding associated with it, which implies it can be suited well for very large amounts of text.
BLOB and CLOB data can take a long time to retrieve, relative to how quick data from a TEXT field can be retrieved. So, use only what you need.
You could try this:
#include <stdio.h>
int main()
{
int i,j;
int my_array[3][3] ={10, 23, 42, 1, 654, 0, 40652, 22, 0};
for(i = 0; i < 3; i++)
{
for(j = 0; j < 3; j++)
{
printf("%d ", my_array[i][j]);
}
printf("\n");
}
return 0;
}
Not native in Javascript, but plenty of libraries have this method.
Underscore.js's _.uniq(array)
(link) works quite well (source).
late in the game , but this worked for me:
$("#container>table>tbody>tr:first").trigger('click');
All answers are old, I recommend and I am a big fan of requests
From homepage:
Python’s standard urllib2 module provides most of the HTTP capabilities you need, but the API is thoroughly broken. It was built for a different time — and a different web. It requires an enormous amount of work (even method overrides) to perform the simplest of tasks.
Things shouldn't be this way. Not in Python.
Ok we all know the answer involves DATEDIFF()
. But that gives you only half the result you may be after. What if you want to get the results in human-readable format, in terms of Minutes and Seconds between two DATETIME
values?
The CONVERT()
, DATEADD()
and of course DATEDIFF()
functions are perfect for a more easily readable result that your clients can use, instead of a number.
i.e.
CONVERT(varchar(5), DATEADD(minute, DATEDIFF(MINUTE, date1, date2), 0), 114)
This will give you something like:
HH:MM
If you want more precision, just increase the VARCHAR()
.
CONVERT(varchar(12), DATEADD(minute, DATEDIFF(MINUTE, date1, date2), 0), 114)
HH:MM.SS.MS
Each ng-repeat creates a child scope with the passed data, and also adds an additional $index
variable in that scope.
So what you need to do is reach up to the parent scope, and use that $index
.
See http://plnkr.co/edit/FvVhirpoOF8TYnIVygE6?p=preview
<li class="tutorial_title {{tutorial.active}}" ng-click="loadFromMenu($parent.$index)" ng-repeat="tutorial in section.tutorials">
{{tutorial.name}}
</li>
Change this.foo()
to module.exports.foo()
So your myscript
output 3 lines, could look like:
myscript() { echo $'abc\ndef\nghi'; }
or
myscript() { local i; for i in abc def ghi ;do echo $i; done ;}
Ok this is a function, not a script (no need of path ./
), but output is same
myscript
abc
def
ghi
To check for result code, test function will become:
myscript() { local i;for i in abc def ghi ;do echo $i;done;return $((RANDOM%128));}
Your operation is correct:
RESULT=$(myscript)
About result code, you could add:
RCODE=$?
even in same line:
RESULT=$(myscript) RCODE=$?
Then
echo $RESULT
abc def ghi
echo "$RESULT"
abc
def
ghi
echo ${RESULT@Q}
$'abc\ndef\nghi'
printf "%q\n" "$RESULT"
$'abc\ndef\nghi'
but for showing variable definition, use declare -p
:
declare -p RESULT
declare -- RESULT="abc
def
ghi"
mapfile
Storing answer into myvar
variable:
mapfile -t myvar < <(myscript)
echo ${myvar[2]}
ghi
Showing $myvar
:
declare -p myvar
declare -a myvar=([0]="abc" [1]="def" [2]="ghi")
In case you have to check for result code, you could:
RESULT=$(myscript) RCODE=$?
mapfile -t myvar <<<"$RESULT"
read
in command group{ read firstline; read secondline; read thirdline;} < <(myscript)
echo $secondline
def
Showing variables:
declare -p firstline secondline thirdline
declare -- firstline="abc"
declare -- secondline="def"
declare -- thirdline="ghi"
I often use:
{ read foo;read foo total use free foo ;} < <(df -k /)
Then
declare -p use free total
declare -- use="843476"
declare -- free="582128"
declare -- total="1515376"
Same prepended step:
RESULT=$(myscript) RCODE=$?
{ read firstline; read secondline; read thirdline;} <<<"$RESULT"
declare -p firstline secondline thirdline RCODE
declare -- firstline="abc"
declare -- secondline="def"
declare -- thirdline="ghi"
declare -- RCODE="50"
All of the answers here are helpful, Thanks to everyone who offered help.
However as i see that that the safe area topic is a little bit confused which won’t appear to be well documented.
So i will summarize it here as mush as possible to make it easy to understand safeAreaInsets
, safeAreaLayoutGuide
and LayoutGuide
.
In iOS 7, Apple introduced the topLayoutGuide
and bottomLayoutGuide
properties in UIViewController
,
They allowed you to create constraints to keep your content from being hidden by UIKit bars like the status, navigation or tab bar
It was possible with these layout guides to specify constraints on content,
avoiding it to be hidden by top or bottom navigation elements (UIKit bars, status bar, nav or tab bar…).
So for example if you wanna make a tableView starts from the top screen you have done something like that:
self.tableView.contentInset = UIEdgeInsets(top: -self.topLayoutGuide.length, left: 0, bottom: 0, right: 0)
In iOS 11 Apple has deprecated these properties replacing them with a single safe area layout guide
Safe area according to Apple
Safe areas help you place your views within the visible portion of the overall interface. UIKit-defined view controllers may position special views on top of your content. For example, a navigation controller displays a navigation bar on top of the underlying view controller’s content. Even when such views are partially transparent, they still occlude the content that is underneath them. In tvOS, the safe area also includes the screen’s overscan insets, which represent the area covered by the screen’s bezel.
Below, a safe area highlighted in iPhone 8 and iPhone X-series:
The safeAreaLayoutGuide
is a property of UIView
To get the height of safeAreaLayoutGuide
:
extension UIView {
var safeAreaHeight: CGFloat {
if #available(iOS 11, *) {
return safeAreaLayoutGuide.layoutFrame.size.height
}
return bounds.height
}
}
That will return the height of the Arrow in your picture.
Now, what about getting the top "notch" and bottom home screen indicator heights?
Here we will use the safeAreaInsets
The safe area of a view reflects the area not covered by navigation bars, tab bars, toolbars, and other ancestors that obscure a view controller's view. (In tvOS, the safe area reflects the area not covered by the screen's bezel.) You obtain the safe area for a view by applying the insets in this property to the view's bounds rectangle. If the view is not currently installed in a view hierarchy, or is not yet visible onscreen, the edge insets in this property are 0.
The following will show the unsafe area and there distance from edges on iPhone 8 and one of iPhone X-Series.
Now, if navigation bar added
So, now how to get the unsafe area height? we will use the safeAreaInset
Here are to solutions however they differ in an important thing,
First One:
self.view.safeAreaInsets
That will return the EdgeInsets, you can now access the top and the bottom to know the insets,
Second One:
UIApplication.shared.windows.first{$0.isKeyWindow }?.safeAreaInsets
The first one you are taking the view insets, so if there a navigation bar it will be considered , however the second one you are accessing the window's safeAreaInsets so the navigation bar will not be considered