Using the Firefox Web Developer Toolbar (https://addons.mozilla.org/en-US/firefox/addon/60)
Just go to View Source -> View Generated Source
I use it all the time for the exact same thing.
I know this is not an answer, but I'd like to contribute to this matter for what it's worth. It would be great if they could release justify-self
for flexbox to make it truly flexible.
It's my belief that when there are multiple items on the axis, the most logical way for justify-self
to behave is to align itself to its nearest neighbours (or edge) as demonstrated below.
I truly hope, W3C takes notice of this and will at least consider it. =)
This way you can have an item that is truly centered regardless of the size of the left and right box. When one of the boxes reaches the point of the center box it will simply push it until there is no more space to distribute.
The ease of making awesome layouts are endless, take a look at this "complex" example.
Whoa there!
There's a potentially serious problem with this code, because it ignores the character encoding specified in the String
(which is UTF-8 by default). When you call String.getBytes()
the platform default encoding is used to encode Unicode characters to bytes. So, the parser may think it's getting UTF-8 data when in fact it's getting EBCDIC or something… not pretty!
Instead, use the parse method that takes an InputSource, which can be constructed with a Reader, like this:
import java.io.StringReader;
import org.xml.sax.InputSource;
…
return builder.parse(new InputSource(new StringReader(xml)));
It may not seem like a big deal, but ignorance of character encoding issues leads to insidious code rot akin to y2k.
I used a combination of the above solutions and some trial and error to come to this solution. Took me an annoying amount of time so I hope this can help someone else in the future. I also noticed that the date picker input is not at all supported by Safari...
I am using styled-components to render a transparent date picker input as shown in the image below:
const StyledInput = styled.input`
appearance: none;
box-sizing: border-box;
border: 1px solid black;
background: transparent;
font-size: 1.5rem;
padding: 8px;
::-webkit-datetime-edit-text { padding: 0 2rem; }
::-webkit-datetime-edit-month-field { text-transform: uppercase; }
::-webkit-datetime-edit-day-field { text-transform: uppercase; }
::-webkit-datetime-edit-year-field { text-transform: uppercase; }
::-webkit-inner-spin-button { display: none; }
::-webkit-calendar-picker-indicator { background: transparent;}
`
No, but browser auto-complete is often triggered by the field having the same name
attribute as fields that were previously filled out. If you could rig up a clever way to have a randomized field name, autocomplete wouldn't be able to pull any previously entered values for the field.
If you were to give an input field a name like "email_<?= randomNumber() ?>
", and then have the script that receives this data loop through the POST or GET variables looking for something matching the pattern "email_[some number]
", you could pull this off, and this would have (practically) guaranteed success, regardless of browser.
attr("dominant-baseline", "central")
There are no values that will cause the checkbox to be unchecked. If the checked
attribute exists, the checkbox will be checked regardless of what value you set it to.
<input type="checkbox" checked />_x000D_
<input type="checkbox" checked="" />_x000D_
<input type="checkbox" checked="checked" />_x000D_
<input type="checkbox" checked="unchecked" />_x000D_
<input type="checkbox" checked="true" />_x000D_
<input type="checkbox" checked="false" />_x000D_
<input type="checkbox" checked="on" />_x000D_
<input type="checkbox" checked="off" />_x000D_
<input type="checkbox" checked="1" />_x000D_
<input type="checkbox" checked="0" />_x000D_
<input type="checkbox" checked="yes" />_x000D_
<input type="checkbox" checked="no" />_x000D_
<input type="checkbox" checked="y" />_x000D_
<input type="checkbox" checked="n" />
_x000D_
Renders everything checked in all modern browsers (FF3.6, Chrome 10, IE8).
<input type='submit' />
doesn't support HTML inside of it, since it's a single self-closing tag. <button>
, on the other hand, supports HTML, images, etc. inside because it's a tag pair: <button><img src='myimage.gif' /></button>
. <button>
is also more flexible when it comes to CSS styling.
The disadvantage of <button>
is that it's not fully supported by older browsers. IE6/7, for example, don't display it correctly.
Unless you have some specific reason, it's probably best to stick to <input type='submit' />
.
I found many answers but not one is simple... I hope this will help you...
try{
Intent intent = new Intent(CurrentActivity.this, NewActivity.class);
startActivity(intent);
} finally {
finish();
}
so, Very simple logic is here, as we know that in java we write code that has some chances of exception in a try block and handle that exception in catch block but in finally block we write code that has to be executed in any cost (Either the exception comes or not).
You could also use FilenameUtils from Apache. It provides you at least the following features for the example C:\dev\project\file.txt:
If I understand your question right:
To add a .net 2.0 Web Service Reference instead of a WCF Service Reference, right-click on your project and click 'Add Service Reference.'
Then click "Advanced.." at the bottom left of the dialog.
Then click "Add Web Reference.." on the bottom left of the next dialog.
Now you can add a regular SOAP web reference like you are looking for.
You may find my MSDN article on the subject helpful; I took a lot of space in that article describing when you should use async
on ASP.NET, not just how to use async
on ASP.NET.
I have some concerns using async actions in ASP.NET MVC. When it improves performance of my apps, and when - not.
First, understand that async
/await
is all about freeing up threads. On GUI applications, it's mainly about freeing up the GUI thread so the user experience is better. On server applications (including ASP.NET MVC), it's mainly about freeing up the request thread so the server can scale.
In particular, it won't:
await
. await
only "yields" to the ASP.NET thread pool, not to the browser.First question is - is it good to use async action everywhere in ASP.NET MVC?
I'd say it's good to use it everywhere you're doing I/O. It may not necessarily be beneficial, though (see below).
However, it's bad to use it for CPU-bound methods. Sometimes devs think they can get the benefits of async
by just calling Task.Run
in their controllers, and this is a horrible idea. Because that code ends up freeing up the request thread by taking up another thread, so there's no benefit at all (and in fact, they're taking the penalty of extra thread switches)!
Shall I use async/await keywords when I want to query database (via EF/NHibernate/other ORM)?
You could use whatever awaitable methods you have available. Right now most of the major players support async
, but there are a few that don't. If your ORM doesn't support async
, then don't try to wrap it in Task.Run
or anything like that (see above).
Note that I said "you could use". If you're talking about ASP.NET MVC with a single database backend, then you're (almost certainly) not going to get any scalability benefit from async
. This is because IIS can handle far more concurrent requests than a single instance of SQL server (or other classic RDBMS). However, if your backend is more modern - a SQL server cluster, Azure SQL, NoSQL, etc - and your backend can scale, and your scalability bottleneck is IIS, then you can get a scalability benefit from async
.
Third question - How many times I can use await keywords to query database asynchronously in ONE single action method?
As many as you like. However, note that many ORMs have a one-operation-per-connection rule. In particular, EF only allows a single operation per DbContext; this is true whether the operation is synchronous or asynchronous.
Also, keep in mind the scalability of your backend again. If you're hitting a single instance of SQL Server, and your IIS is already capable of keeping SQLServer at full capacity, then doubling or tripling the pressure on SQLServer is not going to help you at all.
Swift Version
The easiest method is to set the tableFooterView property:
override func viewDidLoad() {
super.viewDidLoad()
// This will remove extra separators from tableview
self.tableView.tableFooterView = UIView(frame: CGRectZero)
}
Using JSON.decode
for this comes with significant drawbacks that you must be aware of:
JSON.decode
(after wrapping them in double quotes) will error even though these are all valid: \\n
, \n
, \\0
, a"a
\\x45
\\u{045}
There are other caveats as well. Essentially, using JSON.decode
for this purpose is a hack and doesn't work the way you might always expect. You should stick with using the JSON
library to handle JSON, not for string operations.
I recently ran into this issue myself and wanted a robust decoder, so I ended up writing one myself. It's complete and thoroughly tested and is available here: https://github.com/iansan5653/unraw. It mimics the JavaScript standard as closely as possible.
The source is about 250 lines so I won't include it all here, but essentially it uses the following Regex to find all escape sequences and then parses them using parseInt(string, 16)
to decode the base-16 numbers and then String.fromCodePoint(number)
to get the corresponding character:
/\\(?:(\\)|x([\s\S]{0,2})|u(\{[^}]*\}?)|u([\s\S]{4})\\u([^{][\s\S]{0,3})|u([\s\S]{0,4})|([0-3]?[0-7]{1,2})|([\s\S])|$)/g
Commented (NOTE: This regex matches all escape sequences, including invalid ones. If the string would throw an error in JS, it throws an error in my library [ie, '\x!!'
will error]):
/
\\ # All escape sequences start with a backslash
(?: # Starts a group of 'or' statements
(\\) # If a second backslash is encountered, stop there (it's an escaped slash)
| # or
x([\s\S]{0,2}) # Match valid hexadecimal sequences
| # or
u(\{[^}]*\}?) # Match valid code point sequences
| # or
u([\s\S]{4})\\u([^{][\s\S]{0,3}) # Match surrogate code points which get parsed together
| # or
u([\s\S]{0,4}) # Match non-surrogate Unicode sequences
| # or
([0-3]?[0-7]{1,2}) # Match deprecated octal sequences
| # or
([\s\S]) # Match anything else ('.' doesn't match newlines)
| # or
$ # Match the end of the string
) # End the group of 'or' statements
/g # Match as many instances as there are
Using that library:
import unraw from "unraw";
let step1 = unraw('http\\u00253A\\u00252F\\u00252Fexample.com');
// yields "http%3A%2F%2Fexample.com"
// Then you can use decodeURIComponent to further decode it:
let step2 = decodeURIComponent(step1);
// yields http://example.com
For me, after I've removed Xcode, I have to switch active developer path as follows:
sudo xcode-select -s /
Twitter's bootstrap .span
classes are floated to the left so they won't center by usual means. So, if you want it to center your span
simply add float:none
to your #main
rule.
CSS
#main {
margin:0 auto;
float:none;
}
How about something like
git log --pretty=oneline master > 1
git log --pretty=oneline branch_A > 2
git rev-parse `diff 1 2 | tail -1 | cut -c 3-42`^
Following this procedure worked for me.
To create gpg key.
gpg --gen-key --homedir /etc/salt/gpgkeys
export the public key, secret key, and secret subkey.
gpg --homedir /etc/salt/gpgkeys --export test-key > pub.key
gpg --homedir /etc/salt/gpgkeys --export-secret-keys test-key > sec.key
gpg --homedir /etc/salt/gpgkeys --export-secret-subkeys test-key > sub.key
Now import the keys using the following command.
gpg --import pub.key
gpg --import sec.key
gpg --import sub.key
Verify if the keys are imported.
gpg --list-keys
gpg --list-secret-keys
Create a sample file.
echo "hahaha" > a.txt
Encrypt the file using the imported key
gpg --encrypt --sign --armor -r test-key a.txt
To decrypt the file, use the following command.
gpg --decrypt a.txt.asc
or alternatively you could not bother coding for it and use the 'conditional formatting' function in Excel which will set the background colour and font colour based on cell value.
There are only two variables here so set the default to yellow and then overwrite when the value is greater than or less than your threshold values.
Check your file: settings.gradle
for presence lines with included subprojects (for example:
include chapter1-bookstore
)
I came up with an absurd one-liner while writing a numeric base converter. Didn't see anything quite like it in the other answers, so here goes:
// This is cursed
function p(i,w,z){z=z||0;w=w||8;i+='';var o=i.length%w;return o?[...Array(w-o).fill(z),...i].join(''):i;}
console.log(p(8675309)); // Default: pad w/ 0 to 8 digits
console.log(p(525600, 10)); // Pad to 10 digits
console.log(p(69420, 10, 'X')); // Pad w/ X to 10 digits
console.log(p(8675309, 4)); // Pad to next 4 digits
console.log(p(12345678)); // Don't pad if you ain't gotta pad
_x000D_
Or, in a form that doesn't quite as readily betray that I've sold my soul to the Black Perl:
function pad(input, width, zero) {
zero = zero || 0; width = width || 8; // Defaults
input += ''; // Convert input to string first
var overflow = input.length % width // Do we overflow?
if (overflow) { // Yep! Let's pad it...
var needed = width - overflow; // ...to the next boundary...
var zeroes = Array(needed); // ...with an array...
zeroes = zeroes.fill(zero); // ...full of our zero character...
var output = [...zeroes,...input]; // ...and concat those zeroes to input...
output = output.join(''); // ...and finally stringify.
} else {
var output = input; // We don't overflow; no action needed :)
}
return output; // Done!
}
One thing that sets this apart from the other answers is that it takes a modulo of the number's length to the target width rather than a simple greater-than check. This is handy if you want to make sure the resulting length is some multiple of a target width (e.g. you need the output to be either 5 or 10 characters long).
No idea how well it performs, but hey, at least it's already minified!
You can use float on that particular div, e.g.
<div style="float:right;">
Float the div you want more space to have to the left as well:
<div style="float:left;">
If all else fails give the div on the right position:absolute and then move it as right as you want it to be.
<div style="position:absolute; left:-500px; top:30px;">
etc. Obviously put the style in a seperate stylesheet but this is just a quicker example.
Go to your db -> structure and do empty in required table. See here:
Or if none of the above works, type out the name of the outlet into the file first @IBOutlet weak var headerHeightConstraint: NSLayoutConstraint!
and then click and drag from the outlet in the nib to the variable you just programmatically created. It should work without any of the hassle of cleaning, building, and deleting anything.
You already got some good answers, but I guess you could see it like this: ENCRYPTION: Encryption has to be decryptable if you have the right key.
Example: Like when you send an e-mail. You might not want everyone in the world to know what you are writing to the person receiving the e-mail, but the person who receives the e-mail would probably want to be able to read it.
HASHES: hashes work similar like encryption, but it should not be able to reverse it at all.
Example: Like when you put a key in a locked door(the kinds that locks when you close them). You do not care how the lock works in detail, just as long as it unlocks itself when you use the key. If there is trouble you probably cannot fix it, instead get a new lock.(like forgetting passwords on every login, at least I do it all the time and it is a common area to use hashing).
... and I guess you could call that rainbow-algorithm a locksmith in this case.
Hope things clear up =)
I had a similar problem. It turned out, I was including an old header file of the same name from an old folder. I deleted the old file changed the #include directive to point to my new file and all was good.
Put export LD_LIBRARY_PATH=/usr/local/lib
in ~/.bashrc
[preferably towards end of script to avoid any overrides in between, Default ~/.bashrc
comes with many if-else
statements]
Post that whenever you open a new terminal/konsole, LD_LIBRARY_PATH
will be reflected
You will notice you have no value attr in the input
tags.
Also, although not shown, make sure the Javascript is run after the html is in place.
select name, count(*) from table group by name;
i think should do it
@Martin Konecny's answer provides the correct answer, but - as he mentions - it only works if the actual script is not invoked through a symlink residing in a different directory.
This answer covers that case: a solution that also works when the script is invoked through a symlink or even a chain of symlinks:
Linux / GNU readlink
solution:
If your script needs to run on Linux only or you know that GNU readlink
is in the $PATH
, use readlink -f
, which conveniently resolves a symlink to its ultimate target:
scriptDir=$(dirname -- "$(readlink -f -- "$BASH_SOURCE")")
Note that GNU readlink
has 3 related options for resolving a symlink to its ultimate target's full path: -f
(--canonicalize
), -e
(--canonicalize-existing
), and -m
(--canonicalize-missing
) - see man readlink
.
Since the target by definition exists in this scenario, any of the 3 options can be used; I've chosen -f
here, because it is the most well-known one.
Multi-(Unix-like-)platform solution (including platforms with a POSIX-only set of utilities):
If your script must run on any platform that:
has a readlink
utility, but lacks the -f
option (in the GNU sense of resolving a symlink to its ultimate target) - e.g., macOS.
readlink
; note that recent versions of FreeBSD/PC-BSD do support -f
.does not even have readlink
, but has POSIX-compatible utilities - e.g., HP-UX (thanks, @Charles Duffy).
The following solution, inspired by https://stackoverflow.com/a/1116890/45375,
defines helper shell function, rreadlink()
, which resolves a given symlink to its ultimate target in a loop - this function is in effect a POSIX-compliant implementation of GNU readlink
's -e
option, which is similar to the -f
option, except that the ultimate target must exist.
Note: The function is a bash
function, and is POSIX-compliant only in the sense that only POSIX utilities with POSIX-compliant options are used. For a version of this function that is itself written in POSIX-compliant shell code (for /bin/sh
), see here.
If readlink
is available, it is used (without options) - true on most modern platforms.
Otherwise, the output from ls -l
is parsed, which is the only POSIX-compliant way to determine a symlink's target.
Caveat: this will break if a filename or path contains the literal substring ->
- which is unlikely, however.
(Note that platforms that lack readlink
may still provide other, non-POSIX methods for resolving a symlink; e.g., @Charles Duffy mentions HP-UX's find
utility supporting the %l
format char. with its -printf
primary; in the interest of brevity the function does NOT try to detect such cases.)
An installable utility (script) form of the function below (with additional functionality) can be found as rreadlink
in the npm registry; on Linux and macOS, install it with [sudo] npm install -g rreadlink
; on other platforms (assuming they have bash
), follow the manual installation instructions.
If the argument is a symlink, the ultimate target's canonical path is returned; otherwise, the argument's own canonical path is returned.
#!/usr/bin/env bash
# Helper function.
rreadlink() ( # execute function in a *subshell* to localize the effect of `cd`, ...
local target=$1 fname targetDir readlinkexe=$(command -v readlink) CDPATH=
# Since we'll be using `command` below for a predictable execution
# environment, we make sure that it has its original meaning.
{ \unalias command; \unset -f command; } &>/dev/null
while :; do # Resolve potential symlinks until the ultimate target is found.
[[ -L $target || -e $target ]] || { command printf '%s\n' "$FUNCNAME: ERROR: '$target' does not exist." >&2; return 1; }
command cd "$(command dirname -- "$target")" # Change to target dir; necessary for correct resolution of target path.
fname=$(command basename -- "$target") # Extract filename.
[[ $fname == '/' ]] && fname='' # !! curiously, `basename /` returns '/'
if [[ -L $fname ]]; then
# Extract [next] target path, which is defined
# relative to the symlink's own directory.
if [[ -n $readlinkexe ]]; then # Use `readlink`.
target=$("$readlinkexe" -- "$fname")
else # `readlink` utility not available.
# Parse `ls -l` output, which, unfortunately, is the only POSIX-compliant
# way to determine a symlink's target. Hypothetically, this can break with
# filenames containig literal ' -> ' and embedded newlines.
target=$(command ls -l -- "$fname")
target=${target#* -> }
fi
continue # Resolve [next] symlink target.
fi
break # Ultimate target reached.
done
targetDir=$(command pwd -P) # Get canonical dir. path
# Output the ultimate target's canonical path.
# Note that we manually resolve paths ending in /. and /.. to make sure we
# have a normalized path.
if [[ $fname == '.' ]]; then
command printf '%s\n' "${targetDir%/}"
elif [[ $fname == '..' ]]; then
# Caveat: something like /var/.. will resolve to /private (assuming
# /var@ -> /private/var), i.e. the '..' is applied AFTER canonicalization.
command printf '%s\n' "$(command dirname -- "${targetDir}")"
else
command printf '%s\n' "${targetDir%/}/$fname"
fi
)
# Determine ultimate script dir. using the helper function.
# Note that the helper function returns a canonical path.
scriptDir=$(dirname -- "$(rreadlink "$BASH_SOURCE")")
Great answer from Anonymous. \ solved my problem when I tried to escape quotes in HTML strings.
So if you use sed to return some HTML templates (on a server), use double backslash instead of single:
var htmlTemplate = "<div style=\\"color:green;\\"></div>";
Since I never can remember that LINQ calls it Where
, Select
and Aggregate
instead of Filter
, Map
and Reduce
so I created a few extension methods you can use:
IEnumerable<string> myStrings = new List<string>() { "1", "2", "3", "4", "5" };
IEnumerable<int> convertedToInts = myStrings.Map(s => int.Parse(s));
IEnumerable<int> filteredInts = convertedToInts.Filter(i => i <= 3); // Keep 1,2,3
int sumOfAllInts = filteredInts.Reduce((sum, i) => sum + i); // Sum up all ints
Assert.Equal(6, sumOfAllInts); // 1+2+3 is 6
Here are the 3 methods (from https://github.com/cs-util-com/cscore/blob/master/CsCore/PlainNetClassLib/src/Plugins/CsCore/com/csutil/collections/IEnumerableExtensions.cs ):
public static IEnumerable<R> Map<T, R>(this IEnumerable<T> self, Func<T, R> selector) {
return self.Select(selector);
}
public static T Reduce<T>(this IEnumerable<T> self, Func<T, T, T> func) {
return self.Aggregate(func);
}
public static IEnumerable<T> Filter<T>(this IEnumerable<T> self, Func<T, bool> predicate) {
return self.Where(predicate);
}
Some more details from https://github.com/cs-util-com/cscore#ienumerable-extensions :
Because I just went through this - I wanted to give my solution even though this is a bit old.
I have several computers on a home router and I have been working on some projects for myself. Well, I wanted to see what it looked like on my mobil devices. But WAMP was set so I could only get on from the development system. So I began looking around and found this article as well as some others. The problem is - none of them worked for me. So I was left to figure this out on my own.
My solution:
First, in the HTTPD.CONF file you need to add one line to the end of the list of what devices are allowed to access your WAMP server. So instead of:
# Require all granted
# onlineoffline tag - don't remove
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
Allow from ::1
Allow from localhost
make it:
# Require all granted
# onlineoffline tag - don't remove
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
Allow from ::1
Allow from localhost
Allow from 192.168.78
The above says that any device that is on your router (the '78' is just an arbitrary number picked for this solution. It should be whatever your router is set up for. So it might be 192.168.1 or 192.168.0 or even 192.168.254 - you have to look it up on your router.) can now access your server.
The above did NOT do anything for me - at first. There is more you need to do. But first - what you do NOT need to do. You do NOT need to change the WAMP setting from Offline to Online. FOR ME - changing that setting doesn't do anything. Unknown why - it just doesn't. So change it if you want - but I don't think it needs to be changed.
So what else DOES need to be changed? You have to go all the way back to the beginning of the httpd.conf file for this next change and it is really simple. You have to add a new line after the
Listen Localhost:80
add
Listen 192.168.78.###:80
Where the "###" is what IP your server is on. So let's say your server is on IP number 234. Then the above command would become
Listen localhost:80
Listen 192.168.78.234:80
Again - the '78' is just an arbitrary number I picked. To get your real IP number you have to open a command window and type in
ipconfig/all
command. Look for what your TCP/IPv4 number is and set it to that number or TCP/IPv6 if that is all you have (although on internal router sets you usually have an IPv4 number).
Note: In case you do not know how to bring up a command window - you click on Start, select the "Run" option, and type "cmd.exe" in to the dialog box without the quotes. On newer systems (since they keep changing everything) it might be the white windows icon or the circle or Bill Gates jumping up and down. Whatever it is - click on it.
Once you have done the above - restart all services and everything should come up just fine.
Finally - why? Why do you have to change the Listen command? It has to do with localhost. 'localhost' is set to 127.0.0.1 and NOT your IP address by default. This can be found in your host file which is usually found in the system32 folder under Windows but probably has been moved by Microsoft to somewhere else. Look it up online for where it is and go look at it. If you see a lot of sex, porn, etc sites in your localhost host file - you need to get rid of them (unless that is your thing). I suggest RogueKiller (at AdLice.com) be used to take a look at your system because it can reset your host file for you.
If your host file is normal though - it should contain just one entry and that entry is to set localhost to 127.0.0.1. That is why using localhost in the httpd.conf file makes it so you only can work on everything and see everything from your server computer.
So if you feel adventurous - change your host file and leave the Listen command alone OR just change the Listen command to listen to port 80 on your server.
NEW (I forgot to put in this part)
You MAY have to change your TCP/IP address. (Mine is already set up so I didn't need to do this.) You will need to look up for your OS how to get to where your TCP/IP address is defined. Under Windows XP this was Control Panel->Network Connections. This has changed in later OSs so you have to look up how to get there. Anyway, once there you will see your Wireless Network Connection or Local Area Connection (Windows). Basically WIFI or Ethernet cable. Select the one that is active and in use. Under Windows you then right-click and select Properties. A dialog should pop-up and you should see a list of checkboxes with what they are to the side. Look for the one that is for TCP/IP. There should be one that says TCP/IP v4. Select it. (If there isn't one - you should proceed with caution.) Click the Properties button and you should get another dialog box. This one shows either "Obtain an IP address automatically" or "Use the following IP address" selected. If it is the first one then you have to change it to the second one. BUT BEFORE YOU DO THAT - bring up a command window and type in the ipcongfig/all command so you have, right there in front of you, what your default gateway is. Then change it from "Obtain..." to "Use...". Where it says "IP address" put in the IP address you want to always use. This is the IP address you put in on the Listen command above. The second line (Subnet mask) usually is 255.255.255.0 meaning only the last number (ie: 0) changes. Then, looking back at the command window put in your default gateway. Last, but not least, when you changed from "Obtain..." to "Use..." the DNS settings may have changed. If the section which deals with DNS settings has changed to "Use..." and it is blank - the answer is simple. Just look at that ipconfig/all output, find the DNS setting(s) there and put them in to the fields provided. Once done click the OK button and then click the second OK button. Once the dialog closes you may have to reboot your system for the changes to take effect. Try it out by going to Google or Stack Overflow. If you can still go places - then no reboot is required. Otherwise, reboot. Remember! If you can't get on the internet afterwards all you do is go back and reset everything to the "Obtain..." option. The most likely reason, after making the changes, that you can no longer get on the internet is because the TCP/IP address you chose to use is already in use by the router. The saying "There can be only one" goes for TCP/IP addresses too. This is why I always pick a high one-hundreds number or a low two-hundreds number. Because most DHCP set ups use numbers less than fifty. So in this way you don't collide with someone else's TCP/IP number.
This is how I fixed my problem.
Remove "SSLv2ClientHello" from the enabled protocols on the client SSLSocket or HttpsURLConnection.
Execute the same commands but replace the "-A" with "-D". For example:
iptables -A ...
becomes
iptables -D ...
If there is a package.json
, and in it there is lodash
configuration in it. then you should:
npm install
if in the package.json
there is no lodash
:
npm install --save-dev
In my case I had a class that had a method and a string property of the same name, I was trying to call the method but was getting the string property.
Faced the same problem running on Windows 10 and using the Windows cmd.
Solved it by running the following command in the Anaconda Prompt which comes with Anaconda3 (as administrator):
conda install -c menpo opencv3=3.1.0
Command found on the official website: https://anaconda.org/menpo/opencv3
Using modern javascript style:
const NUMBERS = "nul one two three four five six seven ocho nueve".split(" ")
const isOdd = n=> NUMBERS[n % 10].indexOf("e")!=-1
const isEven = n=> isOdd(+n+1)
I had the same problem. Debugging does not work with the stuff that comes with the OpenCV executable. you have to build your own binarys.
Then enable Microsoft Symbol Servers in Debug->options and settings->debug->symbols
An alternative to using keytool
, you can use the command
openssl x509 -in certificate.pem -text
This should work for any x509 .pem file provided you have openssl
installed.
I solved this error using the bellow i get it from here
ionic cordova run browser
will load those native plugins that support browser
platform.
It is solved by adding the following code in app.js file
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname);
app.get('/', function(req, res){
res.render("index");
});
From official reference
Full-text indexes can be used only with MyISAM tables. (In MySQL 5.6 and up, they can also be used with InnoDB tables.) Full-text indexes can be created only for CHAR, VARCHAR, or TEXT columns.
https://dev.mysql.com/doc/refman/5.5/en/fulltext-search.html
InnoDB with MySQL 5.5 does not support Full-text indexes.
Simplest way to read a file in Swift > 4.0
let path = Bundle.main.path(forResource: "data", ofType: "txt") // file path for file "data.txt"
do {
var text = try String(contentsOfFile: path!)
}
catch(_){print("error")}
}
In your Interface Builder click on your problem Table View
Then navigate to Attributes Inspector and change Style Plain to Grouped ;) Easy
As Paul stated, it's because 'a'
is an int
in C but a char
in C++.
I cover that specific difference between C and C++ in something I wrote a few years ago, at: http://david.tribble.com/text/cdiffs.htm
Use the :javascript
filter. This will generate a script tag and escape the script contents as CDATA:
!!! 5
html(lang="en")
head
title "Test"
:javascript
if (10 == 10) {
alert("working")
}
body
The PowerShell string evaluation is calling ToString() on the DataSet. In order to evaluate any properties (or method calls), you have to force evaluation by enclosing the expression in $()
for($i=0;$i -lt $ds.Tables[1].Rows.Count;$i++)
{
write-host "value is : $i $($ds.Tables[1].Rows[$i][0])"
}
Additionally foreach
allows you to iterate through a collection or array without needing to figure out the length.
Rewritten (and edited for compile) -
foreach ($Row in $ds.Tables[1].Rows)
{
write-host "value is : $($Row[0])"
}
I was able to solve this issue by doing the following...
You will likely want to uninstall any workbench packages already installed. GL!
Actually, using ZSH allows you to use special mapping of environment variables. So you can simply do:
# append
path+=('/home/david/pear/bin')
# or prepend
path=('/home/david/pear/bin' $path)
# export to sub-processes (make it inherited by child processes)
export PATH
For me that's a very neat feature which can be propagated to other variables. Example:
typeset -T LD_LIBRARY_PATH ld_library_path :
It can also be when you don't have a proper php extension loaded. I would double check that you have all of the required php extensions loaded on your system if it isn't the memory limit issue.
Best way in my opinion.
$.fn.findByContentText = function (text) {
return $(this).contents().filter(function () {
return $(this).text().trim() == text.trim();
});
};
I'm probably late but this worked for me:
<target name="build" />
If the gem you are trying to install requires xml libraries, then try this:
sudo gem install -n /usr/local/bin <gem_name> -- --use-system-libraries --with-xml2-include=/usr/include/libxml2 --with-xml2-lib=/usr/lib/
Specifically, I ran into a problem while installing the nokogiri gem v 1.6.8 on OS X El Capitan
and this finally worked for me:
sudo gem install -n /usr/local/bin nokogiri -- --use-system-libraries --with-xml2-include=/usr/include/libxml2 --with-xml2-lib=/usr/lib/
To make sure you have libxml2 and libxslt installed, you can do:
brew install libxml2 libxslt
brew install libiconv
and then check to make sure you have xcode command line tools installed:
xcode-select --install
should return this error:
xcode-select: error: command line tools are already installed, use "Software Update" to install updates
EITHER try this library: http://github.com/erica/uidevice-extension/ (by Erica Sadun). (The library is 7-8 years old, and hence is obsolete)
(Sample Code):
[[UIDevice currentDevice] platformType] // ex: UIDevice4GiPhone
[[UIDevice currentDevice] platformString] // ex: @"iPhone 4G"
OR You can use this method:
You can get the device model number using uname from sys/utsname.h. For example:
Objective-C
#import <sys/utsname.h> // import it in your header or implementation file.
NSString* deviceName()
{
struct utsname systemInfo;
uname(&systemInfo);
return [NSString stringWithCString:systemInfo.machine
encoding:NSUTF8StringEncoding];
}
Swift 3
extension UIDevice {
var modelName: String {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
return identifier
}
}
print(UIDevice.current.modelName)
The result should be:
// Output on a simulator
@"i386" on 32-bit Simulator
@"x86_64" on 64-bit Simulator
// Output on an iPhone
@"iPhone1,1" on iPhone
@"iPhone1,2" on iPhone 3G
@"iPhone2,1" on iPhone 3GS
@"iPhone3,1" on iPhone 4 (GSM)
@"iPhone3,2" on iPhone 4 (GSM Rev A)
@"iPhone3,3" on iPhone 4 (CDMA/Verizon/Sprint)
@"iPhone4,1" on iPhone 4S
@"iPhone5,1" on iPhone 5 (model A1428, AT&T/Canada)
@"iPhone5,2" on iPhone 5 (model A1429, everything else)
@"iPhone5,3" on iPhone 5c (model A1456, A1532 | GSM)
@"iPhone5,4" on iPhone 5c (model A1507, A1516, A1526 (China), A1529 | Global)
@"iPhone6,1" on iPhone 5s (model A1433, A1533 | GSM)
@"iPhone6,2" on iPhone 5s (model A1457, A1518, A1528 (China), A1530 | Global)
@"iPhone7,1" on iPhone 6 Plus
@"iPhone7,2" on iPhone 6
@"iPhone8,1" on iPhone 6S
@"iPhone8,2" on iPhone 6S Plus
@"iPhone8,4" on iPhone SE
@"iPhone9,1" on iPhone 7 (CDMA)
@"iPhone9,3" on iPhone 7 (GSM)
@"iPhone9,2" on iPhone 7 Plus (CDMA)
@"iPhone9,4" on iPhone 7 Plus (GSM)
@"iPhone10,1" on iPhone 8 (CDMA)
@"iPhone10,4" on iPhone 8 (GSM)
@"iPhone10,2" on iPhone 8 Plus (CDMA)
@"iPhone10,5" on iPhone 8 Plus (GSM)
@"iPhone10,3" on iPhone X (CDMA)
@"iPhone10,6" on iPhone X (GSM)
@"iPhone11,2" on iPhone XS
@"iPhone11,4" on iPhone XS Max
@"iPhone11,6" on iPhone XS Max China
@"iPhone11,8" on iPhone XR
@"iPhone12,1" on iPhone 11
@"iPhone12,3" on iPhone 11 Pro
@"iPhone12,5" on iPhone 11 Pro Max
@"iPhone12,8" on iPhone SE (2nd Gen)
@"iPhone13,1" on iPhone 12 Mini
@"iPhone13,2" on iPhone 12
@"iPhone13,3" on iPhone 12 Pro
@"iPhone13,4" on iPhone 12 Pro Max
//iPad 1
@"iPad1,1" on iPad - Wifi (model A1219)
@"iPad1,2" on iPad - Wifi + Cellular (model A1337)
//iPad 2
@"iPad2,1" - Wifi (model A1395)
@"iPad2,2" - GSM (model A1396)
@"iPad2,3" - 3G (model A1397)
@"iPad2,4" - Wifi (model A1395)
// iPad Mini
@"iPad2,5" - Wifi (model A1432)
@"iPad2,6" - Wifi + Cellular (model A1454)
@"iPad2,7" - Wifi + Cellular (model A1455)
//iPad 3
@"iPad3,1" - Wifi (model A1416)
@"iPad3,2" - Wifi + Cellular (model A1403)
@"iPad3,3" - Wifi + Cellular (model A1430)
//iPad 4
@"iPad3,4" - Wifi (model A1458)
@"iPad3,5" - Wifi + Cellular (model A1459)
@"iPad3,6" - Wifi + Cellular (model A1460)
//iPad AIR
@"iPad4,1" - Wifi (model A1474)
@"iPad4,2" - Wifi + Cellular (model A1475)
@"iPad4,3" - Wifi + Cellular (model A1476)
// iPad Mini 2
@"iPad4,4" - Wifi (model A1489)
@"iPad4,5" - Wifi + Cellular (model A1490)
@"iPad4,6" - Wifi + Cellular (model A1491)
// iPad Mini 3
@"iPad4,7" - Wifi (model A1599)
@"iPad4,8" - Wifi + Cellular (model A1600)
@"iPad4,9" - Wifi + Cellular (model A1601)
// iPad Mini 4
@"iPad5,1" - Wifi (model A1538)
@"iPad5,2" - Wifi + Cellular (model A1550)
//iPad AIR 2
@"iPad5,3" - Wifi (model A1566)
@"iPad5,4" - Wifi + Cellular (model A1567)
// iPad PRO 9.7"
@"iPad6,3" - Wifi (model A1673)
@"iPad6,4" - Wifi + Cellular (model A1674)
@"iPad6,4" - Wifi + Cellular (model A1675)
//iPad PRO 12.9"
@"iPad6,7" - Wifi (model A1584)
@"iPad6,8" - Wifi + Cellular (model A1652)
//iPad (5th generation)
@"iPad6,11" - Wifi (model A1822)
@"iPad6,12" - Wifi + Cellular (model A1823)
//iPad PRO 12.9" (2nd Gen)
@"iPad7,1" - Wifi (model A1670)
@"iPad7,2" - Wifi + Cellular (model A1671)
@"iPad7,2" - Wifi + Cellular (model A1821)
//iPad PRO 10.5"
@"iPad7,3" - Wifi (model A1701)
@"iPad7,4" - Wifi + Cellular (model A1709)
// iPad (6th Gen)
@"iPad7,5" - WiFi
@"iPad7,6" - WiFi + Cellular
// iPad (7th Gen)
@"iPad7,11" - WiFi
@"iPad7,12" - WiFi + Cellular
//iPad PRO 11"
@"iPad8,1" - WiFi
@"iPad8,2" - 1TB, WiFi
@"iPad8,3" - WiFi + Cellular
@"iPad8,4" - 1TB, WiFi + Cellular
//iPad PRO 12.9" (3rd Gen)
@"iPad8,5" - WiFi
@"iPad8,6" - 1TB, WiFi
@"iPad8,7" - WiFi + Cellular
@"iPad8,8" - 1TB, WiFi + Cellular
//iPad PRO 11" (2nd Gen)
@"iPad8,9" - WiFi
@"iPad8,10" - 1TB, WiFi
//iPad PRO 12.9" (4th Gen)
@"iPad8,11" - (WiFi)
@"iPad8,12" - (WiFi+Cellular)
// iPad mini 5th Gen
@"iPad11,1" - WiFi
@"iPad11,2" - Wifi + Cellular
// iPad Air 3rd Gen
@"iPad11,3" - Wifi
@"iPad11,4" - Wifi + Cellular
// iPad (8th Gen)
@"iPad11,6" - iPad 8th Gen (WiFi)
@"iPad11,7" - iPad 8th Gen (WiFi+Cellular)
// iPad Air 4th Gen
@"iPad13,1" - iPad air 4th Gen (WiFi)
@"iPad13,2" - iPad air 4th Gen (WiFi+Cellular)
//iPod Touch
@"iPod1,1" on iPod Touch
@"iPod2,1" on iPod Touch Second Generation
@"iPod3,1" on iPod Touch Third Generation
@"iPod4,1" on iPod Touch Fourth Generation
@"iPod5,1" on iPod Touch 5th Generation
@"iPod7,1" on iPod Touch 6th Generation
@"iPod9,1" on iPod Touch 7th Generation
// Apple Watch
@"Watch1,1" on Apple Watch 38mm case
@"Watch1,2" on Apple Watch 38mm case
@"Watch2,6" on Apple Watch Series 1 38mm case
@"Watch2,7" on Apple Watch Series 1 42mm case
@"Watch2,3" on Apple Watch Series 2 38mm case
@"Watch2,4" on Apple Watch Series 2 42mm case
@"Watch3,1" on Apple Watch Series 3 38mm case (GPS+Cellular)
@"Watch3,2" on Apple Watch Series 3 42mm case (GPS+Cellular)
@"Watch3,3" on Apple Watch Series 3 38mm case (GPS)
@"Watch3,4" on Apple Watch Series 3 42mm case (GPS)
@"Watch4,1" on Apple Watch Series 4 40mm case (GPS)
@"Watch4,2" on Apple Watch Series 4 44mm case (GPS)
@"Watch4,3" on Apple Watch Series 4 40mm case (GPS+Cellular)
@"Watch4,4" on Apple Watch Series 4 44mm case (GPS+Cellular)
@"Watch5,1" on Apple Watch Series 5 40mm case (GPS)
@"Watch5,2" on Apple Watch Series 5 44mm case (GPS)
@"Watch5,3" on Apple Watch Series 5 40mm case (GPS+Cellular)
@"Watch5,4" on Apple Watch Series 5 44mm case (GPS+Cellular)
@"Watch5,9" on Apple Watch SE 40mm case (GPS)
@"Watch5,10" on Apple Watch SE 44mm case (GPS)
@"Watch5,11" on Apple Watch SE 40mm case (GPS+Cellular)
@"Watch5,12" on Apple Watch SE 44mm case (GPS+Cellular)
@"Watch6,1" on Apple Watch Series 6 40mm case (GPS)
@"Watch6,2" on Apple Watch Series 6 44mm case (GPS)
@"Watch6,3" on Apple Watch Series 6 40mm case (GPS+Cellular)
@"Watch6,4" on Apple Watch Series 6 44mm case (GPS+Cellular)
You can use TrimEnd
. It's efficient as well and looks clean.
"Name,".TrimEnd(',');
I think best method is to query pg_setting
view:
select s.name, s.setting, s.short_desc from pg_settings s where s.name='data_directory';
Output:
name | setting | short_desc
----------------+------------------------+-----------------------------------
data_directory | /var/lib/pgsql/10/data | Sets the server's data directory.
(1 row)
Using a nested .each()
means that your inner loop is doing one td at a time, so you can't set the productId
and product
and quantity
all in the inner loop.
Also using function(key, val)
and then val[key].innerHTML
isn't right: the .each()
method passes the index (an integer) and the actual element, so you'd use function(i, element)
and then element.innerHTML
. Though jQuery also sets this
to the element, so you can just say this.innerHTML
.
Anyway, here's a way to get it to work:
table.find('tr').each(function (i, el) {
var $tds = $(this).find('td'),
productId = $tds.eq(0).text(),
product = $tds.eq(1).text(),
Quantity = $tds.eq(2).text();
// do something with productId, product, Quantity
});
Since wdiff
accepts args specifying the string at the beginning and end of both insertions and deletions, you can use ANSI color sequences as those strings:
wdiff -n -w $'\033[30;41m' -x $'\033[0m' -y $'\033[30;42m' -z $'\033[0m' file1 file2
For example, this is the output of comparing two CSV files:
Example from https://www.gnu.org/software/wdiff/manual/html_node/wdiff-Examples.html
With str(x)
. However, every data type can define its own string conversion, so this might not be what you want.
If X inherits from Y, that has two somewhat orthogonal effects:
Although inheritance provides for both features, it is not hard to imagine circumstances where either could be of use without the other. No .net language I know of has a direct way of implementing the first without the second, though one could obtain such functionality by defining a base class which is never used directly, and having one or more classes that inherit directly from it without adding anything new (such classes could share all their code, but would not be substitutable for each other). Any CLR-compliant language, however, will allow the use of interfaces which provide the second feature of interfaces (substitutability) without the first (member reuse).
In order to create a backup using pg_dump
that is compatible with pg_restore
you must use the --format=custom
/ -Fc
when creating your dump.
From the docs:
Output a custom-format archive suitable for input into pg_restore.
So your pg_dump
command might look like:
pg_dump --file /tmp/db.dump --format=custom --host localhost --dbname my-source-database --username my-username --password
And your pg_restore
command:
pg_restore --verbose --clean --no-acl --no-owner --host localhost --dbname my-destination-database /tmp/db.dump
Woks fine for me on ubuntu 16.04. path: /etc/mysql/mysql.cnf
and paste that
[mysqld]
#
# * Basic Settings
#
sql_mode = "NO_ENGINE_SUBSTITUTION"
Looking at your Erlang implementation. The timing has included the start up of the entire virtual machine, running your program and halting the virtual machine. Am pretty sure that setting up and halting the erlang vm takes some time.
If the timing was done within the erlang virtual machine itself, results would be different as in that case we would have the actual time for only the program in question. Otherwise, i believe that the total time taken by the process of starting and loading of the Erlang Vm plus that of halting it (as you put it in your program) are all included in the total time which the method you are using to time the program is outputting. Consider using the erlang timing itself which we use when we want to time our programs within the virtual machine itself
timer:tc/1 or timer:tc/2 or timer:tc/3
. In this way, the results from erlang will exclude the time taken to start and stop/kill/halt the virtual machine. That is my reasoning there, think about it, and then try your bench mark again.
I actually suggest that we try to time the program (for languages that have a runtime), within the runtime of those languages in order to get a precise value. C for example has no overhead of starting and shutting down a runtime system as does Erlang, Python and Haskell (98% sure of this - i stand correction). So (based on this reasoning) i conclude by saying that this benchmark wasnot precise /fair enough for languages running on top of a runtime system. Lets do it again with these changes.
EDIT: besides even if all the languages had runtime systems, the overhead of starting each and halting it would differ. so i suggest we time from within the runtime systems (for the languages for which this applies). The Erlang VM is known to have considerable overhead at start up!
This helps for me to do IN condition Hope this will help you..
CREATE PROCEDURE `test`(IN Array_String VARCHAR(100))
BEGIN
SELECT * FROM Table_Name
WHERE FIND_IN_SET(field_name_to_search, Array_String);
END//;
Calling:
call test('3,2,1');
When you divide two integers, the result will be an integer, irrespective of the fact that you store it in a double.
You can check if the error is of type WebException
and then inspect the response code;
if (e.Error.GetType().Name == "WebException")
{
WebException we = (WebException)e.Error;
HttpWebResponse response = (System.Net.HttpWebResponse)we.Response;
if (response.StatusCode==HttpStatusCode.NotFound)
System.Diagnostics.Debug.WriteLine("Not found!");
}
or
try
{
// send request
}
catch (WebException e)
{
// check e.Status as above etc..
}
For sliding both activity (old and new) same direction:
left_in.xml
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="300"
android:fromXDelta="-100%"
android:toXDelta="0%"
android:interpolator="@android:anim/decelerate_interpolator"
/>
right_in.xml
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="300"
android:fromXDelta="100%"
android:toXDelta="0%"
android:interpolator="@android:anim/decelerate_interpolator"
/>
left_out.xml
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="300"
android:fromXDelta="0%"
android:interpolator="@android:anim/decelerate_interpolator"
android:toXDelta="-100%" />
right_out.xml
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="300"
android:fromXDelta="0%"
android:interpolator="@android:anim/decelerate_interpolator"
android:toXDelta="100%" />
startActivity transition:
overridePendingTransition(R.anim.right_in, R.anim.left_out);
onBackPressed transition:
overridePendingTransition(R.anim.left_in, R.anim.right_out);
Adding on to @Rob Hruska's sol, this setting in server.xml inside section works:
<Context path="" docBase="gateway" reloadable="true" override="true"> </Context>
Note: override="true" might be required in some cases.
You can use Nexmo to send SMS as well as receive SMS.
Sending SMS with the Nexmo Java Library is fairly straightforward. After creating a new account, renting a virtual number, and getting your API key & secret you can use the library to send SMS like so:
public class SendSMS {
public static void main(String[] args) throws Exception {
AuthMethod auth = new TokenAuthMethod(API_KEY, API_SECRET);
NexmoClient client = new NexmoClient(auth);
TextMessage message = new TextMessage(FROM_NUMBER, TO_NUMBER, "Hello from Nexmo!");
//There may be more than one response if the SMS sent is more than 160 characters.
SmsSubmissionResult[] responses = client.getSmsClient().submitMessage(message);
for (SmsSubmissionResult response : responses) {
System.out.println(response);
}
}
}
To receive SMS you'll need to set up a server that consumes a webhook. That's fairly simple as well. I recommend checking out our tutorial on receiving SMS with Java.
Disclosure: I work for Nexmo
HTML4 specification states that:
Inline elements may contain only data and other inline elements
Span is an inline element, therefore having span inside span is valid. There's a related question: Can <span> tags have any type of tags inside them? which makes it completely clear.
HTML5 specification (including the most current draft of HTML 5.3 dated November 16, 2017) changes terminology, but it's still perfectly valid to place span inside another span.
To select rows according to one 'cell_type' (e.g. 'hesc'), use ==
:
expr[expr$cell_type == "hesc", ]
To select rows according to two or more different 'cell_type', (e.g. either 'hesc' or 'bj fibroblast'), use %in%
:
expr[expr$cell_type %in% c("hesc", "bj fibroblast"), ]
UPDATE table1
SET
`ID` = (SELECT table2.id FROM table2 WHERE table1.`name`=table2.`name`)
You cannot directly copy a table into a destination server database from a different database if source db is not in your linked servers. But one way is possible that, generate scripts (schema with data) of the desired table into one table temporarily in the source server DB, then execute the script in the destination server DB to create a table with your data. Finally use INSERT INTO [DESTINATION_TABLE] select * from [TEMPORARY_SOURCE_TABLE]. After getting the data into your destination table drop the temporary one.
I found this solution when I faced the same situation. Hope this helps you too.
Use the C Standard Library function getchar()
instead as getch()
is not a standard function, being provided by Borland TURBO C for MS-DOS/Windows only.
printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
getchar();
Here, getchar()
expects you to press the return key so the printf
statement should be press ENTER to continue
. Even if you press another key, you still need to press ENTER:
printf("Let the Battle Begin!\n");
printf("Press ENTER key to Continue\n");
getchar();
If you are using Windows then you can use getch()
printf("Let the Battle Begin!\n");
printf("Press Any Key to Continue\n");
getch();
//if you press any character it will continue ,
//but this is not a standard c function.
char ch;
printf("Let the Battle Begin!\n");
printf("Press ENTER key to Continue\n");
//here also if you press any other key will wait till pressing ENTER
scanf("%c",&ch); //works as getchar() but here extra variable is required.
Try this to get an array of attribute name => attribute value(s):
global $product;
$formatted_attributes = array();
$attributes = $product->get_attributes();
foreach($attributes as $attr=>$attr_deets){
$attribute_label = wc_attribute_label($attr);
if ( isset( $attributes[ $attr ] ) || isset( $attributes[ 'pa_' . $attr ] ) ) {
$attribute = isset( $attributes[ $attr ] ) ? $attributes[ $attr ] : $attributes[ 'pa_' . $attr ];
if ( $attribute['is_taxonomy'] ) {
$formatted_attributes[$attribute_label] = implode( ', ', wc_get_product_terms( $product->id, $attribute['name'], array( 'fields' => 'names' ) ) );
} else {
$formatted_attributes[$attribute_label] = $attribute['value'];
}
}
}
//print_r($formatted_attributes);
return $formatted_attributes;
It's little inefficient but does the trick.
JavaScript doesn't have function overloading, including for methods or constructors.
If you want a function to behave differently depending on the number and types of parameters you pass to it, you'll have to sniff them manually. JavaScript will happily call a function with more or fewer than the declared number of arguments.
function foo(a, b) {
if (b===undefined) // parameter was omitted in call
b= 'some default value';
if (typeof(a)==='string')
this._constructInSomeWay(a, b);
else if (a instanceof MyType)
this._constructInSomeOtherWay(a, b);
}
You can also access arguments
as an array-like to get any further arguments passed in.
If you need more complex arguments, it can be a good idea to put some or all of them inside an object lookup:
function bar(argmap) {
if ('optionalparam' in argmap)
this._constructInSomeWay(argmap.param, argmap.optionalparam);
...
}
bar({param: 1, optionalparam: 2})
Python demonstrates how default and named arguments can be used to cover the most use cases in a more practical and graceful way than function overloading. JavaScript, not so much.
Another possible cause of the "Error inflating class" message could be misspelling the full package name where it's specified in XML:
<com.alpenglow.androcap.GhostSurfaceCameraView android:id="@+id/ghostview_cameraview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
Opening your layout XML file in the Eclipse XML editor should highlight this problem.
Simplify or break apart the function so that it doesn't require nine arguments (or ignore pylint, but dodges like the ones you're proposing defeat the purpose of a lint tool).
EDIT: if it's a temporary measure, disable the warning for the particular function in question using a comment as described here: http://lists.logilab.org/pipermail/python-projects/2006-April/000664.html
Later, you can grep for all of the disabled warnings.
A[A==NDV]=numpy.nan
A==NDV will produce a boolean array that can be used as an index for A
I found this resource that details the various methods: How to embed TIFF files in HTML documents
As mentioned, it will very much depend on browser support for the format. Viewing that page in Chrome on Windows didn't display any of the images.
It would also be helpful if you posted the code you've tried already.
You need to set the password for root@localhost
to be blank. There are two ways:
The MySQL SET PASSWORD
command:
SET PASSWORD FOR root@localhost=PASSWORD('');
Using the command-line mysqladmin
tool:
mysqladmin -u root -pCURRENTPASSWORD password ''
The short answer to print floating point numbers losslessly (such that they can be read back in to exactly the same number, except NaN and Infinity):
printf("%.9g", number)
.printf("%.17g", number)
.Do NOT use %f
, since that only specifies how many significant digits after the decimal and will truncate small numbers. For reference, the magic numbers 9 and 17 can be found in float.h
which defines FLT_DECIMAL_DIG
and DBL_DECIMAL_DIG
.
There is nothing you can do on your end (client side). You can not enable crossDomain calls yourself, the source (dailymotion.com) needs to have CORS enabled for this to work.
The only thing you can really do is to create a server side proxy script which does this for you. Are you using any server side scripts in your project? PHP, Python, ASP.NET etc? If so, you could create a server side "proxy" script which makes the HTTP call to dailymotion and returns the response. Then you call that script from your Javascript code, since that server side script is on the same domain as your script code, CORS will not be a problem.
If you look at the scope of the variable 'hoursWorked' you will see that it is a member of the class (declared as private int)
The two variables you are having trouble with are passed as parameters to the constructor.
The error message is because 'hours' is out of scope in the setter.
You first need to parse your string before following the other people's suggestion:
var dateString = "2010-09-11";
var myDate = new Date(dateString);
//add a day to the date
myDate.setDate(myDate.getDate() + 1);
If you want it back in the same format again you will have to do that "manually":
var y = myDate.getFullYear(),
m = myDate.getMonth() + 1, // january is month 0 in javascript
d = myDate.getDate();
var pad = function(val) { var str = val.toString(); return (str.length < 2) ? "0" + str : str};
dateString = [y, pad(m), pad(d)].join("-");
But I suggest getting Date.js as mentioned in other replies, that will help you alot.
He drinks rice (wrong semantic- meaningless, right syntax- grammar)
Hi drink water (right semantic- has meaning, wrong syntax- grammar)
I'm sorry to do this, but I couldn't use any of the other answers as-is and haven't time to duke it out in the comments.
Uses C# 6 syntax.
static class EnumExtensions
{
/// returns the localized Name, if a [Display(Name="Localised Name")] attribute is applied to the enum member
/// returns null if there isnt an attribute
public static string DisplayNameOrEnumName(this Enum value)
// => value.DisplayNameOrDefault() ?? value.ToString()
{
// More efficient form of ^ based on http://stackoverflow.com/a/17034624/11635
var enumType = value.GetType();
var enumMemberName = Enum.GetName(enumType, value);
return enumType
.GetEnumMemberAttribute<DisplayAttribute>(enumMemberName)
?.GetName() // Potentially localized
?? enumMemberName; // Or fall back to the enum name
}
/// returns the localized Name, if a [Display] attribute is applied to the enum member
/// returns null if there is no attribute
public static string DisplayNameOrDefault(this Enum value) =>
value.GetEnumMemberAttribute<DisplayAttribute>()?.GetName();
static TAttribute GetEnumMemberAttribute<TAttribute>(this Enum value) where TAttribute : Attribute =>
value.GetType().GetEnumMemberAttribute<TAttribute>(value.ToString());
static TAttribute GetEnumMemberAttribute<TAttribute>(this Type enumType, string enumMemberName) where TAttribute : Attribute =>
enumType.GetMember(enumMemberName).Single().GetCustomAttribute<TAttribute>();
}
I would prefer to use array_key_exists to search for keys in arrays like:
Array([0]=>'A',[1]=>'B',['key'=>'value'])
to find the specified effectively, since array_search and in_array() don't work here. And do removing stuff with unset().
I think it will help someone.
Try this:
SELECT ID, Email, ProductName, ProductModel FROM Products WHERE ID IN (SELECT MAX(ID) FROM Products GROUP BY Email)
For Loopback3 all the examples given did not work for me, or as fast as using REST API anyway. But it helped me to figure out the exact answer I needed.
{"where":{"arrayAttribute":{ "all" :[String]}}}
I have a mac but would assume all linux are the same for this part...
In my case I got this:
2018-12-03 11:13:27 - Start server:
2018-12-03 11:13:27 - Server start done.
2018-12-03 11:13:27 - Checking server status...
2018-12-03 11:13:27 - Trying to connect to MySQL...
2018-12-03 11:13:27 - Lost connection to MySQL server at 'reading authorization packet', system error: 0 (2013)
2018-12-03 11:13:27 - Assuming server is not running
I ran this:
sudo killall mysqld
And then started the mysql again through mysqlworkbench although in your case it might be like this:
mysql.server start
*sidenote: I tried running mysql.server stop
and got this Shutting down MySQL
.... SUCCESS!
but after running ps aux | grep mysql
I saw that it hasn't really shut down...
The best way that I usually use is very simple, I fully disable context menu in the whole page, pure html+javascript:
<body oncontextmenu="return false;">
That's it! I do that because you can always see the source by right click.
Ok, you say: "I can use directly the browser view source" and it's true but we start from the fact that you CAN'T stop downloading html5
videos.
DateTime d = DateTime.Today.Date;
Console.WriteLine(d.ToShortDateString()); // outputs just date
if you want to compare dates, ignoring the time part, make an use of DateTime.Year
and DateTime.DayOfYear
properties.
code snippet
DateTime d1 = DateTime.Today;
DateTime d2 = DateTime.Today.AddDays(3);
if (d1.Year < d2.Year)
Console.WriteLine("d1 < d2");
else
if (d1.DayOfYear < d2.DayOfYear)
Console.WriteLine("d1 < d2");
Put autocmd commands based on the file suffix in your ~/.vimrc
autocmd BufRead,BufNewFile *.c,*.h,*.java set noic cin noexpandtab
autocmd BufRead,BufNewFile *.pl syntax on
The commands you're looking for are probably ts= and sw=
A Window is always shown independently, A Page is intended to be shown inside a Frame or inside a NavigationWindow.
Restart MySQL, it works fine.
BUT beware that if such a query is stuck, there is a problem somewhere :
LIKE %...%
, etc.)As @syedrakib said, it works but this is no long-living solution for production.
Beware : doing the restart can affect your data with inconsistent state.
Also, you can check how MySQL handles your query with the EXPLAIN keyword and see if something is possible there to speed up the query (indexes, complex tests,...).
public class shuffleCards{
public static void main(String[] args) {
String[] cardsType ={"club","spade","heart","diamond"};
String [] cardValue = {"Ace","2","3","4","5","6","7","8","9","10","King", "Queen", "Jack" };
List<String> cards = new ArrayList<String>();
for(int i=0;i<=(cardsType.length)-1;i++){
for(int j=0;j<=(cardValue.length)-1;j++){
cards.add(cardsType[i] + " " + "of" + " " + cardValue[j]) ;
}
}
Collections.shuffle(cards);
System.out.print("Enter the number of cards within:" + cards.size() + " = ");
Scanner data = new Scanner(System.in);
Integer inputString = data.nextInt();
for(int l=0;l<= inputString -1;l++){
System.out.print( cards.get(l)) ;
}
}
}
DECLARE
tmp NUMBER(3,1);
BEGIN
SELECT COUNT(content_id) INTO tmp FROM contents WHERE (condition);
if tmp != 0 then
INSERT INTO contents VALUES (...);
else
INSERT INTO contents VALUES (...);
end if;
END;
I used the code above. It is long, but, simple and worked for me. Similar, to Micheal's code.
You're declaring a virtual
function and not defining it:
virtual void calculateCredits();
Either define it or declare it as:
virtual void calculateCredits() = 0;
Or simply:
virtual void calculateCredits() { };
Read more about vftable: http://en.wikipedia.org/wiki/Virtual_method_table
If you want to remove a specific Item or variable from the user's local storage, you can use
localStorage.removeItem("name of localStorage variable you want to remove");
To formalize some of the approaches laid out above:
Create a function that operates on the rows of your dataframe like so:
def f(row):
if row['A'] == row['B']:
val = 0
elif row['A'] > row['B']:
val = 1
else:
val = -1
return val
Then apply it to your dataframe passing in the axis=1
option:
In [1]: df['C'] = df.apply(f, axis=1)
In [2]: df
Out[2]:
A B C
a 2 2 0
b 3 1 1
c 1 3 -1
Of course, this is not vectorized so performance may not be as good when scaled to a large number of records. Still, I think it is much more readable. Especially coming from a SAS background.
Edit
Here is the vectorized version
df['C'] = np.where(
df['A'] == df['B'], 0, np.where(
df['A'] > df['B'], 1, -1))
I know this is an old question, but I'd like to offer one example of how the yield keyword can be creatively used. I have really benefited from this technique. Hopefully this will be of assistance to anyone else who stumbles upon this question.
Note: Don't think about the yield keyword as merely being another way to build a collection. A big part of the power of yield comes in the fact that execution is paused in your method or property until the calling code iterates over the next value. Here's my example:
Using the yield keyword (alongside Rob Eisenburg's Caliburn.Micro coroutines implementation) allows me to express an asynchronous call to a web service like this:
public IEnumerable<IResult> HandleButtonClick() {
yield return Show.Busy();
var loginCall = new LoginResult(wsClient, Username, Password);
yield return loginCall;
this.IsLoggedIn = loginCall.Success;
yield return Show.NotBusy();
}
What this will do is turn my BusyIndicator on, call the Login method on my web service, set my IsLoggedIn flag to the return value, and then turn the BusyIndicator back off.
Here's how this works: IResult has an Execute method and a Completed event. Caliburn.Micro grabs the IEnumerator from the call to HandleButtonClick() and passes it into a Coroutine.BeginExecute method. The BeginExecute method starts iterating through the IResults. When the first IResult is returned, execution is paused inside HandleButtonClick(), and BeginExecute() attaches an event handler to the Completed event and calls Execute(). IResult.Execute() can perform either a synchronous or an asynchronous task and fires the Completed event when it's done.
LoginResult looks something like this:
public LoginResult : IResult {
// Constructor to set private members...
public void Execute(ActionExecutionContext context) {
wsClient.LoginCompleted += (sender, e) => {
this.Success = e.Result;
Completed(this, new ResultCompletionEventArgs());
};
wsClient.Login(username, password);
}
public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
public bool Success { get; private set; }
}
It may help to set up something like this and step through the execution to watch what's going on.
Hope this helps someone out! I've really enjoyed exploring the different ways yield can be used.
Using this method you can fill in your div with the image varying ratio of divs and images.
jQuery:
$(window).load(function(){
$('body').find(.fillme).each(function(){
var fillmeval = $(this).width()/$(this).height();
var imgval = $this.children('img').width()/$this.children('img').height();
var imgClass;
if(imgval > fillmeval){
imgClass = "stretchy";
}else{
imgClass = "stretchx";
}
$(this).children('img').addClass(imgClass);
});
});
HTML:
<div class="fillme">
<img src="../images/myimg.jpg" />
</div>
CSS:
.fillme{
overflow:hidden;
}
.fillme img.stretchx{
height:auto;
width:100%;
}
.fillme img.stretchy{
height:100%;
width:auto;
}
Just a note that the constant
keyword use for safe-area margins has been updated to env
for 11.2 beta+
https://webkit.org/blog/7929/designing-websites-for-iphone-x/
Here are some main key differences between constructor and method in java
If you want an recent copy of npgsql, then go here
This can be installed via package manager console as
PM> Install-Package Npgsql
First, add it to .gitignore
, so it is not accidentally committed by you (or someone else) again:
.idea
Second, remove the directory only from the repository, but do not delete it locally. To achieve that, do what is listed here:
Remove a file from a Git repository without deleting it from the local filesystem
Third, commit the .gitignore
file and the removal of .idea
from the repository. After that push it to the remote(s).
The full process would look like this:
$ echo '.idea' >> .gitignore
$ git rm -r --cached .idea
$ git add .gitignore
$ git commit -m '(some message stating you added .idea to ignored entries)'
$ git push
(optionally you can replace last line with git push some_remote
, where some_remote
is the name of the remote you want to push to)
EDIT: My former answer (based on answers in this thread) was not the way to go for me. I wanted a sub-menu to expand on mouse enter or touch click and to collapse on mouse leave or another touch click. Since mouse events normally are being fired after touch events, it was kind of tricky to write event listeners that support both touchscreen and mouse input at the same time.
I ended up writing a jQuery plugin called "Touch Or Mouse" (897 bytes minified) that can detect whether an event was invoked by a touchscreen or mouse (without testing for touch support!). This enables the support of both touchscreen and mouse at the same time and completely separate their events.
This way the OP can use touchstart
or touchend
for quickly responding to touch clicks and click
for clicks invoked only by a mouse.
First one has to make ie. the body element track touch events:
$(document.body).touchOrMouse('init');
Mouse events our bound to elements in the default way and by calling $body.touchOrMouse('get', e)
we can find out whether the event was invoked by a touchscreen or mouse.
$('.link').click(function(e) {
var touchOrMouse = $(document.body).touchOrMouse('get', e);
if (touchOrMouse === 'touch') {
// Handle touch click.
}
else if (touchOrMouse === 'mouse') {
// Handle mouse click.
}
}
See the plugin at work at http://jsfiddle.net/lmeurs/uo4069nh.
touchstart
and touchend
events, this way the touchend
event does not have to be fired on the trigger element (ie. a link or button). Between these two touch events this plugin considers any mouse event to be invoked by touch.touchend
, when a mouse event is being fired within the ghostEventDelay
(option, 1000ms by default) after touchend
, this plugin considers the mouse event to be invoked by touch.:active
state. The mouseleave
event is only fired after the element loses this state by ie. clicking on another element. Since this could be seconds (or minutes!) after the mouseenter
event has been fired, this plugin keeps track of an element's last mouseenter
event: if the last mouseenter
event was invoked by touch, the following mouseleave
event is also considered to be invoked by touch.As this answer and @RichardOD suggested , you should do like this:
[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetDiskFreeSpaceEx(string lpDirectoryName,
out ulong lpFreeBytesAvailable,
out ulong lpTotalNumberOfBytes,
out ulong lpTotalNumberOfFreeBytes);
ulong FreeBytesAvailable;
ulong TotalNumberOfBytes;
ulong TotalNumberOfFreeBytes;
bool success = GetDiskFreeSpaceEx(@"\\mycomputer\myfolder",
out FreeBytesAvailable,
out TotalNumberOfBytes,
out TotalNumberOfFreeBytes);
if(!success)
throw new System.ComponentModel.Win32Exception();
Console.WriteLine("Free Bytes Available: {0,15:D}", FreeBytesAvailable);
Console.WriteLine("Total Number Of Bytes: {0,15:D}", TotalNumberOfBytes);
Console.WriteLine("Total Number Of FreeBytes: {0,15:D}", TotalNumberOfFreeBytes);
argc
is the number of command line arguments given to the program at runtime, and argv
is an array of arrays of characters (rather, an array of C-strings) containing these arguments. If you know you're not going to need the command line arguments, you can declare your main at taking a void
argument, instead:
int main(void) {
/* ... */
}
Those are the only two prototypes defined for main
as per the standards, but some compilers allow a return type of void
as well. More on this on Wikipedia.
I had a similar problem when trying to use boost unit testing in Visual Studio 2015 (Community Edition):
fatal error LNK1104: libboost_unit_test_framework-vc140-mt-1_57
so I thought I'd share my solution.
You can create a boost unit testing project in of of two ways (and this solution works for both):
Here are the steps I followed to get both projects to work:
First, download the desired boost version (for example, boost_1_57_0). You can either download boost with the correct binaries (compiled using msvc v140), or extract the binaries yourself by running the following commands from command line:
Where msvc-14.0 specifies that we require the Visual Studio 2015 version (VS 2015 = v14.0 = v140), and address-model=32 specifies that we require platform 32 (but the same can be done for 64 bit).
Once you have the binaries, go to Visual Studio, select the Boost Unit Testing project you have created. Go to Project properties > configuration (from the main menu) and make the following choices:
Set the "General > Platform Toolset" to Visual Studio 2015 (v140).
Include the path to the boost folder (e.g. C:\boost_1_57_0) and the path to the subfolder containing the binary files (e.g. C:\boost_1_57_0\stage\lib) in:
You can also get a 403 if when testing with dev server you are using integrated pipeline and then install as classic pipeline mode on your live IIS 7.5 web server, also I was missing my app_data folder which also was required
In case you want to utilize .then() which has a subtle difference in comparison with .done() :
return $.post(url, payload)
.then(
function (result, textStatus, jqXHR) {
return result;
},
function (jqXHR, textStatus, errorThrown) {
return console.error(errorThrown);
});
`
function checkPalindrome (str) {
var str = str.toLowerCase();
var original = str.split(' ').join('');
var reversed = original.split(' ').reverse().join('');
return (original === reversed);
}
`
The whole code if somebody need it.
void alarm(Context context, Calendar calendar) {
AlarmManager alarmManager = (AlarmManager)context.getSystemService(ALARM_SERVICE);
final String SOME_ACTION = "com.android.mytabs.MytabsActivity.AlarmReceiver";
IntentFilter intentFilter = new IntentFilter(SOME_ACTION);
AlarmReceiver mReceiver = new AlarmReceiver();
context.registerReceiver(mReceiver, intentFilter);
Intent anotherIntent = new Intent(SOME_ACTION);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, anotherIntent, 0);
alramManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(context, "Added", Toast.LENGTH_LONG).show();
}
class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent arg1) {
Toast.makeText(context, "Started", Toast.LENGTH_LONG).show();
}
}
Try this (demo):
.ui-autocomplete {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
display: none;
float: left;
min-width: 160px;
padding: 5px 0;
margin: 2px 0 0;
list-style: none;
font-size: 14px;
text-align: left;
background-color: #ffffff;
border: 1px solid #cccccc;
border: 1px solid rgba(0, 0, 0, 0.15);
border-radius: 4px;
-webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
background-clip: padding-box;
}
.ui-autocomplete > li > div {
display: block;
padding: 3px 20px;
clear: both;
font-weight: normal;
line-height: 1.42857143;
color: #333333;
white-space: nowrap;
}
.ui-state-hover,
.ui-state-active,
.ui-state-focus {
text-decoration: none;
color: #262626;
background-color: #f5f5f5;
cursor: pointer;
}
.ui-helper-hidden-accessible {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
}
Try this...
function urlChange(url) {
var site = url+'?toolbar=0&navpanes=0&scrollbar=0';
document.getElementById('iFrameName').src = site;
}
<a href="javascript:void(0);" onClick="urlChange('www.mypdf.com/test.pdf')">TEST </a>
The color of the buttons and other text can also be changed via theme:
values-21/styles.xml
<style name="AppTheme" parent="...">
...
<item name="android:timePickerDialogTheme">@style/AlertDialogCustom</item>
<item name="android:datePickerDialogTheme">@style/AlertDialogCustom</item>
<item name="android:alertDialogTheme">@style/AlertDialogCustom</item>
</style>
<style name="AlertDialogCustom" parent="android:Theme.Material.Light.Dialog.Alert">
<item name="android:colorPrimary">#00397F</item>
<item name="android:colorAccent">#0AAEEF</item>
</style>
The result:
var todayDate = moment().format('DD-MM-YYYY');//to get today date 06/03/2018 if you want to add extra day to your current date
then var dueDate = moment().add(15,'days').format('DD-MM-YYYY')// to add 15 days to current date..
point 2 and 3 are using in your jquery code...
The Accept Ranges
header (the bit in writeHead()
) is required for the HTML5 video controls to work.
I think instead of just blindly send the full file, you should first check the Accept Ranges
header in the REQUEST, then read in and send just that bit. fs.createReadStream
support start
, and end
option for that.
So I tried an example and it works. The code is not pretty but it is easy to understand. First we process the range header to get the start/end position. Then we use fs.stat
to get the size of the file without reading the whole file into memory. Finally, use fs.createReadStream
to send the requested part to the client.
var fs = require("fs"),
http = require("http"),
url = require("url"),
path = require("path");
http.createServer(function (req, res) {
if (req.url != "/movie.mp4") {
res.writeHead(200, { "Content-Type": "text/html" });
res.end('<video src="http://localhost:8888/movie.mp4" controls></video>');
} else {
var file = path.resolve(__dirname,"movie.mp4");
fs.stat(file, function(err, stats) {
if (err) {
if (err.code === 'ENOENT') {
// 404 Error if file not found
return res.sendStatus(404);
}
res.end(err);
}
var range = req.headers.range;
if (!range) {
// 416 Wrong range
return res.sendStatus(416);
}
var positions = range.replace(/bytes=/, "").split("-");
var start = parseInt(positions[0], 10);
var total = stats.size;
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;
res.writeHead(206, {
"Content-Range": "bytes " + start + "-" + end + "/" + total,
"Accept-Ranges": "bytes",
"Content-Length": chunksize,
"Content-Type": "video/mp4"
});
var stream = fs.createReadStream(file, { start: start, end: end })
.on("open", function() {
stream.pipe(res);
}).on("error", function(err) {
res.end(err);
});
});
}
}).listen(8888);
Using the second form gives you a variable (named based upon the as
clause, in your example e
) in the except
block scope with the exception object bound to it so you can use the infomration in the exception (type, message, stack trace, etc) to handle the exception in a more specially tailored manor.
You could use .apply and pd.value_counts to get a count the occurrence of all the names in the name column.
dataframe['name'].apply(pd.value_counts)
Commenting out this line worked for me: $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin'; But I found several config.inc.php files on my computer because I had a couple installations of MySQL and php haha. I changed it by finding the one under Xampp by just clicking on the config button under Apache for the Xampp control panel then commenting out the line. //
The ExecuteNonQuery
method is used for SQL statements that are not queries, such as INSERT
, UPDATE
, ... You want to use ExecuteScalar
or ExecuteReader
if you expect your statement to return results (i.e. a query).
Intelli iDEA causes these stupid troubles @ times. Simple goto pom.xml , right click and do -> Maven -> Reimport.
This should solve the problem.
A new look using Async/Await and callbacks. You only need one line of code if you keep the extension method in your project.
/// <summary>
/// A new way to use Tasks for Asynchronous calls
/// </summary>
public class Example
{
/// <summary>
/// No more delegates, background workers etc. just one line of code as shown below
/// Note it is dependent on the XTask class shown next.
/// </summary>
public async void ExampleMethod()
{
//Still on GUI/Original Thread here
//Do your updates before the next line of code
await XTask.RunAsync(() =>
{
//Running an asynchronous task here
//Cannot update GUI Thread here, but can do lots of work
});
//Can update GUI/Original thread on this line
}
}
/// <summary>
/// A class containing extension methods for the Task class
/// Put this file in folder named Extensions
/// Use prefix of X for the class it Extends
/// </summary>
public static class XTask
{
/// <summary>
/// RunAsync is an extension method that encapsulates the Task.Run using a callback
/// </summary>
/// <param name="Code">The caller is called back on the new Task (on a different thread)</param>
/// <returns></returns>
public async static Task RunAsync(Action Code)
{
await Task.Run(() =>
{
Code();
});
return;
}
}
You can add other things to the Extension method such as wrapping it in a Try/Catch statement, allowing caller to tell it what type to return after completion, an exception callback to caller:
Adding Try Catch, Auto Exception Logging and CallBack
/// <summary>
/// Run Async
/// </summary>
/// <typeparam name="T">The type to return</typeparam>
/// <param name="Code">The callback to the code</param>
/// <param name="Error">The handled and logged exception if one occurs</param>
/// <returns>The type expected as a competed task</returns>
public async static Task<T> RunAsync<T>(Func<string,T> Code, Action<Exception> Error)
{
var done = await Task<T>.Run(() =>
{
T result = default(T);
try
{
result = Code("Code Here");
}
catch (Exception ex)
{
Console.WriteLine("Unhandled Exception: " + ex.Message);
Console.WriteLine(ex.StackTrace);
Error(ex);
}
return result;
});
return done;
}
public async void HowToUse()
{
//We now inject the type we want the async routine to return!
var result = await RunAsync<bool>((code) => {
//write code here, all exceptions are logged via the wrapped try catch.
//return what is needed
return someBoolValue;
},
error => {
//exceptions are already handled but are sent back here for further processing
});
if (result)
{
//we can now process the result because the code above awaited for the completion before
//moving to this statement
}
}
Here is the simple ListView with different images. First of all you have to copy the different kinds of images and paste it to the res/drawable-hdpi in your project. Images should be (.png)file format. then copy this code.
In main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ListView
android:id="@+id/listview"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
create listview_layout.xml and paste this code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="@+id/flag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/hello"
android:paddingTop="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
android:text="TextView1" />
<TextView
android:id="@+id/cur"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10dp"
android:text="TextView2" />
</LinearLayout>
In your Activity
package com.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class SimpleListImageActivity extends Activity {
// Array of strings storing country names
String[] countries = new String[] {
"India",
"Pakistan",
"Sri Lanka",
"China",
"Bangladesh",
"Nepal",
"Afghanistan",
"North Korea",
"South Korea",
"Japan"
};
// Array of integers points to images stored in /res/drawable-hdpi/
//here you have to give image name which you already pasted it in /res/drawable-hdpi/
int[] flags = new int[]{
R.drawable.image1,
R.drawable.image2,
R.drawable.image3,
R.drawable.image4,
R.drawable.image5,
R.drawable.image6,
R.drawable.image7,
R.drawable.image8,
R.drawable.image9,
R.drawable.image10,
};
// Array of strings to store currencies
String[] currency = new String[]{
"Indian Rupee",
"Pakistani Rupee",
"Sri Lankan Rupee",
"Renminbi",
"Bangladeshi Taka",
"Nepalese Rupee",
"Afghani",
"North Korean Won",
"South Korean Won",
"Japanese Yen"
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Each row in the list stores country name, currency and flag
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<10;i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("txt", "Country : " + countries[i]);
hm.put("cur","Currency : " + currency[i]);
hm.put("flag", Integer.toString(flags[i]) );
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { "flag","txt","cur" };
// Ids of views in listview_layout
int[] to = { R.id.flag,R.id.txt,R.id.cur};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.listview_layout, from, to);
// Getting a reference to listview of main.xml layout file
ListView listView = ( ListView ) findViewById(R.id.listview);
// Setting the adapter to the listView
listView.setAdapter(adapter);
}
}
This is the full code.you can make changes to your need... Comments are welcome
Create a new custom object and add it to the object array that Import-Csv
creates.
$fileContent = Import-csv $file -header "Date", "Description"
$newRow = New-Object PsObject -Property @{ Date = 'Text4' ; Description = 'Text5' }
$fileContent += $newRow
To your first question:
I would go with Paul R's comment and terminate with '\0'
. But the value 0
itself works also fine. A matter of taste. But don't use the MACRO NULL
which is meant for pointers.
To your second question:
If your string is not terminated with\0
, it might still print the expected output because following your string is a non-printable character in your memory. This is a really nasty bug though, since it might blow up when you might not expect it. Always terminate a string with '\0'
.
onreadystatechange Stores a function (or the name of a function) to be called automatically each time the readyState property changes readyState Holds the status of the XMLHttpRequest. Changes from 0 to 4:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
status 200: "OK"
404: Page not found
In HTML, the selected option is represented by the presence of the selected
attribute on the <option>
element like so:
<option ... selected>...</option>
Or if you're HTML/XHTML strict:
<option ... selected="selected">...</option>
Thus, you just have to let JSP/EL print it conditionally. Provided that you've prepared the selected department as follows:
request.setAttribute("selectedDept", selectedDept);
then this should do:
<select name="department">
<c:forEach var="item" items="${dept}">
<option value="${item.key}" ${item.key == selectedDept ? 'selected="selected"' : ''}>${item.value}</option>
</c:forEach>
</select>
echo "Sending emails ..."
NOW=$(date +"%F %H:%M")
echo $NOW " Running service" >> open_files.log
header=`echo "Service Restarting: " $NOW`
mail -s "$header" [email protected], \
[email protected], \ < open_files.log
This is my working implementation
private void showMessage()
{
lblMessage.setText("");
List<String> messages = db.getAllGCMMessages();
for (int k = messages.size() - 1; k >= 0; --k)
{
String message = messages.get(k).toString();
lblMessage.append(message + "\n\n");
}
Linkify.addLinks(lblMessage, Linkify.ALL);
}
and to change color of hyperlinks , i editted my xml for textview -
android:textColorLink="#69463d"
This is how I use the Fail method.
There are three states that your test case can end up in
intended (Unlike negative test cases that expect a exception to occur).
If you are using eclipse there three states are indicated by a Green, Blue and red marker respectively.
I use the fail operation for the the third scenario.
e.g. : public Integer add(integer a, Integer b) { return new Integer(a.intValue() + b.intValue())}
With the release of Mercurial 2.2, you can use the --amend
option with hg commit
to update the last commit with the current working directory
From the command line reference:
The --amend flag can be used to amend the parent of the working directory with a new commit that contains the changes in the parent in addition to those currently reported by hg status, if there are any. The old commit is stored in a backup bundle in .hg/strip-backup (see hg help bundle and hg help unbundle on how to restore it).
Message, user and date are taken from the amended commit unless specified. When a message isn't specified on the command line, the editor will open with the message of the amended commit.
The great thing is that this mechanism is "safe", because it relies on the relatively new "Phases" feature to prevent updates that would change history that's already been made available outside of the local repository.
"Is there another good reason (other than the header problem) to skip the ending php tag?"
You don't want to inadvertently output extraneous whitepace characters when generating binary output, CSV data, or other non-HTML output.
I am able to sftp using PowerShell as below:
PS C:\Users\user\Desktop> sftp [email protected]
[email protected]'s password:
Connected to [email protected].
sftp> ls
testFolder
sftp> cd testFolder
sftp> ls
taj_mahal.jpeg
sftp> put taj_mahal_1.jpeg
Uploading taj_mahal_1.jpeg to /home/user/testFolder/taj_mahal_1.jpeg
taj_mahal_1.jpeg 100% 11KB 35.6KB/s 00:00
sftp> ls
taj_mahal.jpeg taj_mahal_1.jpeg
sftp>
I do not have installed Posh-SSH or anything like that. I am using Windows 10 Pro PowerShell. No additional modules installed.
As always, read Bootstrap's great documentation:
3.x Docs: https://getbootstrap.com/docs/3.3/css/#grid-nesting
Make sure the parent level row is inside of a .container
element. Whenever you'd like to nest rows, just open up a new .row
inside of your column.
Here's a simple layout to work from:
<div class="container">
<div class="row">
<div class="col-xs-6">
<div class="big-box">image</div>
</div>
<div class="col-xs-6">
<div class="row">
<div class="col-xs-6"><div class="mini-box">1</div></div>
<div class="col-xs-6"><div class="mini-box">2</div></div>
<div class="col-xs-6"><div class="mini-box">3</div></div>
<div class="col-xs-6"><div class="mini-box">4</div></div>
</div>
</div>
</div>
</div>
4.0 Docs: http://getbootstrap.com/docs/4.0/layout/grid/#nesting
Here's an updated version for 4.0, but you should really read the entire docs section on the grid so you understand how to leverage this powerful feature
<div class="container">
<div class="row">
<div class="col big-box">
image
</div>
<div class="col">
<div class="row">
<div class="col mini-box">1</div>
<div class="col mini-box">2</div>
</div>
<div class="row">
<div class="col mini-box">3</div>
<div class="col mini-box">4</div>
</div>
</div>
</div>
</div>
Which will look like this (with a little bit of added styling):
This answer does not address the Bash part of the question, but because I tried to use the answers in this question to implement this functionality in Emacs I'll throw it out there.
Emacs actually has a function for this out of the box:
ELISP> (file-relative-name "/a/b/c" "/a/b/c")
"."
ELISP> (file-relative-name "/a/b/c" "/a/b")
"c"
ELISP> (file-relative-name "/a/b/c" "/c/b")
"../../a/b/c"
for me it worked by adding
1) "You can run the mongodb instance without username and password first.---OK
2) "Then you can add the user to the system database of the mongodb which is default one using the query below".---OK
db.createUser({
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ],
mechanisms:[ "SCRAM-SHA-1" ] // I added this line
})
This answer got me 90% of the way there. I found the rest of my answer on the Microsoft site here.
The code below is what I'm using to target all ie by adding a .ie class to <html>
Use jQuery (which deprecated .browser in favor of user agents in 1.9+, see http://api.jquery.com/jQuery.browser/) to add an .ie class:
// ie identifier
$(document).ready(function () {
if (navigator.appName == 'Microsoft Internet Explorer') {
$("html").addClass("ie");
}
});
SYSDATE
and GETDATE
perform identically.
SYSDATE
is compatible with Oracle syntax, and GETDATE
is compatible with Microsoft SQL Server syntax.
In Rails 4 all I had to do was the def change
def change
rename_table :old_table_name, :new_table_name
end
And all of my indexes were taken care of for me. I did not need to manually update the indexes by removing the old ones and adding new ones.
And it works using the change for going up or down in regards to the indexes as well.
I strongly disagree with most answers previously mentioned.
Short answer:
Omit the "in" class and add it using jQuery to fade it in.
See this jsfiddle for an example that fades in alert after 3 seconds http://jsfiddle.net/QAz2U/3/
Long answer:
Although it is true bootstrap doesn't natively support fading in alerts, most answers here use the jQuery fade function, which uses JavaScript to animate (fade) the element. The big advantage of this is cross browser compatibility. The downside is performance (see also: jQuery to call CSS3 fade animation?).
Bootstrap uses CSS3 transitions, which have way better performance. Which is important for mobile devices:
Bootstraps CSS to fade the alert:
.fade {
opacity: 0;
-webkit-transition: opacity 0.15s linear;
-moz-transition: opacity 0.15s linear;
-o-transition: opacity 0.15s linear;
transition: opacity 0.15s linear;
}
.fade.in {
opacity: 1;
}
Why do I think this performance is so important? People using old browsers and hardware will potentially get a choppy transitions with jQuery.fade(). The same goes for old hardware with modern browsers. Using CSS3 transitions people using modern browsers will get a smooth animation even with older hardware, and people using older browsers that don't support CSS transitions will just instantly see the element pop in, which I think is a better user experience than choppy animations.
I came here looking for the same answer as the above: to fade in a bootstrap alert. After some digging in the code and CSS of Bootstrap the answer is rather straightforward. Don't add the "in" class to your alert. And add this using jQuery when you want to fade in your alert.
HTML (notice there is NO in class!)
<div id="myAlert" class="alert success fade" data-alert="alert">
<!-- rest of alert code goes here -->
</div>
Javascript:
function showAlert(){
$("#myAlert").addClass("in")
}
Calling the function above function adds the "in" class and fades in the alert using CSS3 transitions :-)
Also see this jsfiddle for an example using a timeout (thanks John Lehmann!): http://jsfiddle.net/QAz2U/3/
The error message is pretty self-explanatory: your application needs the Oracle Client installed on the machine it's running on. Your development PC already has it. Make sure your target PC has it, too.
Edit: The System.Data.OracleClient namespace is deprecated. Make sure you use the driver native to your database system, that would be ODP.NET from Oracle.
My Solution :
db.collection("name of collection").find({}, {limit: 1}).sort({$natural: -1})
To complement the existing helpful answers:
Using Bash's own regex-matching operator, =~
, is a faster alternative in this case, given that you're only matching a single value already stored in a variable:
set -- '12-34-5678' # set $1 to sample value
kREGEX_DATE='^[0-9]{2}[-/][0-9]{2}[-/][0-9]{4}$' # note use of [0-9] to avoid \d
[[ $1 =~ $kREGEX_DATE ]]
echo $? # 0 with the sample value, i.e., a successful match
Note, however, that the caveat re using flavor-specific regex constructs such as \d
equally applies:
While =~
supports EREs (extended regular expressions), it also supports the host platform's specific extension - it's a rare case of Bash's behavior being platform-dependent.
To remain portable (in the context of Bash), stick to the POSIX ERE specification.
Note that =~
even allows you to define capture groups (parenthesized subexpressions) whose matches you can later access through Bash's special ${BASH_REMATCH[@]}
array variable.
Further notes:
$kREGEX_DATE
is used unquoted, which is necessary for the regex to be recognized as such (quoted parts would be treated as literals).
While not always necessary, it is advisable to store the regex in a variable first, because Bash has trouble with regex literals containing \
.
\<
is supported to match word boundaries, [[ 3 =~ \<3 ]] && echo yes
doesn't work, but re='\<3'; [[ 3 =~ $re ]] && echo yes
does.I've changed variable name REGEX_DATE
to kREGEX_DATE
(k
signaling a (conceptual) constant), so as to ensure that the name isn't an all-uppercase name, because all-uppercase variable names should be avoided to prevent conflicts with special environment and shell variables.
Here's how I'd do it:
def distance(a,b):
return sqrt((a.x - b.x)**2 + (a.y - b.y)**2)
def is_between(a,c,b):
return distance(a,c) + distance(c,b) == distance(a,b)
"Note that you need to have image fully loaded first (otherwise ending up in having empty images), so in some cases you'd need to wrap handling into: bannerImage.addEventListener("load", function () {}); – yuga Nov 1 '17 at 13:04"
This is extremely IMPORTANT. One of the the options i'm exploring this afternoon is using javascript callback methods rather than addEventListeners since that doesn't seem to bind correctly either. Getting all the elements ready before page load WITHOUT a page refresh is critical.
If anyone can expand upon this please do - as in, did you use a settimeout, a wait, a callback, or an addEventListener method to get the desired result. Which one and why?
Cmd + Shift + 7 will comment the selected lines.
This worked for me.
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
try {
List<String> listing = getObjectNamesForBucket(bucket, s3Client);
Log.e(TAG, "listing "+ listing);
}
catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "Exception found while listing "+ e);
}
}
});
thread.start();
private List<String> getObjectNamesForBucket(String bucket, AmazonS3 s3Client) {
ObjectListing objects=s3Client.listObjects(bucket);
List<String> objectNames=new ArrayList<String>(objects.getObjectSummaries().size());
Iterator<S3ObjectSummary> oIter=objects.getObjectSummaries().iterator();
while (oIter.hasNext()) {
objectNames.add(oIter.next().getKey());
}
while (objects.isTruncated()) {
objects=s3Client.listNextBatchOfObjects(objects);
oIter=objects.getObjectSummaries().iterator();
while (oIter.hasNext()) {
objectNames.add(oIter.next().getKey());
}
}
return objectNames;
}
You can filter
the string by digits using str.isdigit
method,
>>> int(filter(str.isdigit, str1))
3158
Show Processlist fetches the information from another table. Here is how you can pull the data and look at 'INFO' column which contains the whole query :
select * from INFORMATION_SCHEMA.PROCESSLIST where db = 'somedb';
You can add any condition or ignore based on your requirement.
The output of the query is resulted as :
+-------+------+-----------------+--------+---------+------+-----------+----------------------------------------------------------+
| ID | USER | HOST | DB | COMMAND | TIME | STATE | INFO |
+-------+------+-----------------+--------+---------+------+-----------+----------------------------------------------------------+
| 5 | ssss | localhost:41060 | somedb | Sleep | 3 | | NULL |
| 58169 | root | localhost | somedb | Query | 0 | executing | select * from sometable where tblColumnName = 'someName' |
Emm... Why not to use something like this?
function displayArrayObjects(arrayObjects) {_x000D_
var len = arrayObjects.length, text = "";_x000D_
_x000D_
for (var i = 0; i < len; i++) {_x000D_
var myObject = arrayObjects[i];_x000D_
_x000D_
for (var x in myObject) {_x000D_
text += ( x + ": " + myObject[x] + " ");_x000D_
}_x000D_
text += "<br/>";_x000D_
}_x000D_
_x000D_
document.getElementById("message").innerHTML = text;_x000D_
}_x000D_
_x000D_
_x000D_
var lineChartData = [{_x000D_
date: new Date(2009, 10, 2),_x000D_
value: 5_x000D_
}, {_x000D_
date: new Date(2009, 10, 25),_x000D_
value: 30_x000D_
}, {_x000D_
date: new Date(2009, 10, 26),_x000D_
value: 72,_x000D_
customBullet: "images/redstar.png"_x000D_
}];_x000D_
_x000D_
displayArrayObjects(lineChartData);
_x000D_
<h4 id="message"></h4>
_x000D_
result:
date: Mon Nov 02 2009 00:00:00 GMT+0200 (FLE Standard Time) value: 5
date: Wed Nov 25 2009 00:00:00 GMT+0200 (FLE Standard Time) value: 30
date: Thu Nov 26 2009 00:00:00 GMT+0200 (FLE Standard Time) value: 72 customBullet: images/redstar.png
File pathBinary = new File("Firefox.exe location");
FirefoxBinary ffBinary = new FirefoxBinary(pathBinary);
FirefoxProfile firefoxProfile = new FirefoxProfile();
FirefoxDriver driver = new FirefoxDriver(ffBinary,firefoxProfile);
You need to add binary of the browser
or
Best and forever solution: Just add Firefox.exe location to environmental variables
This Proxy will expose the buffer as any of the TypedArrays, without any copy. :
https://www.npmjs.com/package/node-buffer-as-typedarray
It only works on LE, but can be easily ported to BE. Also, never got to actually test how efficient this is.
Single quotes won't interpolate anything, but double quotes will. For example: variables, backticks, certain \
escapes, etc.
Example:
$ echo "$(echo "upg")"
upg
$ echo '$(echo "upg")'
$(echo "upg")
The Bash manual has this to say:
Enclosing characters in single quotes (
'
) preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.Enclosing characters in double quotes (
"
) preserves the literal value of all characters within the quotes, with the exception of$
,`
,\
, and, when history expansion is enabled,!
. The characters$
and`
retain their special meaning within double quotes (see Shell Expansions). The backslash retains its special meaning only when followed by one of the following characters:$
,`
,"
,\
, or newline. Within double quotes, backslashes that are followed by one of these characters are removed. Backslashes preceding characters without a special meaning are left unmodified. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an!
appearing in double quotes is escaped using a backslash. The backslash preceding the!
is not removed.The special parameters
*
and@
have special meaning when in double quotes (see Shell Parameter Expansion).
If you are using a relatively recent version of JSHint, the generally preferred approach is to create a .jshintrc file in the root of your project, and put this config in it:
{
"globals": {
"$": false
}
}
This declares to JSHint that $ is a global variable, and the false indicates that it should not be overridden.
The .jshintrc file was not supported in really old versions of JSHint (such as v0.5.5 like the original question in 2012). If you cannot or do not want to use the .jshintrc file, you can add this at the top of the script file:
/*globals $:false */
There is also a shorthand "jquery" jshint option as seen on the JSHint options page..
DBContext.TestAddresses.Select(m => m.NAME).Distinct();
if you have multiple column do like this:
DBContext.TestAddresses.Select(m => new {m.NAME, m.ID}).Distinct();
In this example no duplicate CategoryId and no CategoryName i hope this will help you
There is a probably a better “command line” way to do this, and I know this is a hack, but I’ve never been able to find a good solution.
Using TortoiseGIT: If you have a GIT commit where some file move operations are showing up as load of adds/deletes rather than renames, even though the files only have small changes, then do this:
The new commit will now properly show the file renames… which will help maintain proper file history.
If you do not care about internet explorer\edge, then simplest way to achieve different color for strike-through would be to use CSS property: text-decoration-color in conjunction with text-decoration:line-through;
.yourClass {
text-decoration: line-through !important;
text-decoration-color: red !important;
}
-- Does not work with Edge\Internet Explorer
The following should work, but you may need to change the format:
echo date('l F jS, Y (m-d-Y)', strtotime('+3 months', strtotime($DateToAdjust)));
I have written a quick guide on how to install the latest versions of Python 2 and Python 3 on CentOS 6 and CentOS 7. It currently covers Python 2.7.13 and Python 3.6.0:
# Start by making sure your system is up-to-date:
yum update
# Compilers and related tools:
yum groupinstall -y "development tools"
# Libraries needed during compilation to enable all features of Python:
yum install -y zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel expat-devel
# If you are on a clean "minimal" install of CentOS you also need the wget tool:
yum install -y wget
The next steps depend on the version of Python you're installing.
For Python 2.7.14:
wget http://python.org/ftp/python/2.7.14/Python-2.7.14.tar.xz
tar xf Python-2.7.14.tar.xz
cd Python-2.7.14
./configure --prefix=/usr/local --enable-unicode=ucs4 --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"
make && make altinstall
# Strip the Python 2.7 binary:
strip /usr/local/lib/libpython2.7.so.1.0
For Python 3.6.3:
wget http://python.org/ftp/python/3.6.3/Python-3.6.3.tar.xz
tar xf Python-3.6.3.tar.xz
cd Python-3.6.3
./configure --prefix=/usr/local --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"
make && make altinstall
# Strip the Python 3.6 binary:
strip /usr/local/lib/libpython3.6m.so.1.0
To install Pip:
# First get the script:
wget https://bootstrap.pypa.io/get-pip.py
# Then execute it using Python 2.7 and/or Python 3.6:
python2.7 get-pip.py
python3.6 get-pip.py
# With pip installed you can now do things like this:
pip2.7 install [packagename]
pip2.7 install --upgrade [packagename]
pip2.7 uninstall [packagename]
You are not supposed to change the system version of Python because it will break the system (as you found out). Installing other versions works fine as long as you leave the original system version alone. This can be accomplished by using a custom prefix (for example /usr/local
) when running configure, and using make altinstall
(instead of the normal make install
) when installing your build of Python.
Having multiple versions of Python available is usually not a big problem as long as you remember to type the full name including the version number (for example "python2.7" or "pip2.7"). If you do all your Python work from a virtualenv the versioning is handled for you, so make sure you install and use virtualenv!
Try doing this :
recipients="[email protected],[email protected],[email protected]"
And another approach, using shell here-doc :
/usr/sbin/sendmail "$recipients" <<EOF
subject:$subject
from:$from
Example Message
EOF
Be sure to separate the headers from the body with a blank line as per RFC 822.
Use this code.
driver.FindElement(By.XPath(".//[@id='header']/div/div[3]/div/form/input[1]")).SendKeys("25025");
DateTime.Now.Date.ToShortDateString()
is culture specific.
It is best to stick with:
DateTime.Now.ToString("d/MM/yyyy");
i supposed you uploaded your photo in your drive all what you need to do is while you are opening your google drive just open your dev tools in chrome and head to your img tag and copy the link beside the src attribute and use it
I attempted
pod install --repo-update
and all of these still did not fix the problem.
In the project file is folder "bin/debug/your_appliacion_name.exe". This is final executable program file.
SELECT
CASE WHEN LastName IS NULL THEN FirstName
WHEN LastName IS NOT NULL THEN LastName + ', ' + FirstName
END AS 'FullName'
FROM customers GROUP BY 1`
There is no replaceAt
function in JavaScript. You can use the following code to replace any character in any string at specified position:
function rep() {
var str = 'Hello World';
str = setCharAt(str,4,'a');
alert(str);
}
function setCharAt(str,index,chr) {
if(index > str.length-1) return str;
return str.substring(0,index) + chr + str.substring(index+1);
}
_x000D_
<button onclick="rep();">click</button>
_x000D_
For an updated answer see this SO question:
calling web service using VBA code in excel 2010
Both threads should be merged though.
the mime type might not be text/csv
some systems can read/save them different. (for example sometimes IE sends .csv files as application/vnd.ms-excel
) so you best bet would be to build an array of allowed values and test against that, then find all possible values to test against.
$mimes = array('application/vnd.ms-excel','text/plain','text/csv','text/tsv');
if(in_array($_FILES['file']['type'],$mimes)){
// do something
} else {
die("Sorry, mime type not allowed");
}
if you wished you could add a further check if mime is returned as text/plain you could run a preg_match
to make sure it has enough commas in it to be a csv.
Example: index = False
import pandas as pd
writer = pd.ExcelWriter("dataframe.xlsx", engine='xlsxwriter')
dataframe.to_excel(writer,sheet_name = dataframe, index=False)
writer.save()
One of the ways to use git diff is:
git diff <commit> <path>
And a common way to refer one commit of the last commit is as a relative path to the actual HEAD. You can reference previous commits as HEAD^ (in your example this will be 123abc) or HEAD^^ (456def in your example), etc ...
So the answer to your question is:
git diff HEAD^^ myfile
I had the same issue today.While searching here for solution,I have did silly mistake that is instead of importing
import org.springframework.transaction.annotation.Transactional;
unknowingly i have imported
import javax.transaction.Transactional;
Afer changing it everything worked fine.
So thought of sharing,If somebody does same mistake .
I found a way that works if I use JavaScript combined with TypeScript.
logging.d.ts:
declare var log: log4javascript.Logger;
log-declaration.js:
log = null;
initalize-app.ts
import './log-declaration.js';
// Call stuff to actually setup log.
// Similar to this:
log = functionToSetupLog();
This puts it in the global scope and TypeScript knows about it. So I can use it in all my files.
NOTE: I think this only works because I have the allowJs
TypeScript option set to true.
If someone posts an pure TypeScript solution, I will accept that.
Example with mysql_fetch_assoc()
:
while ($row = mysql_fetch_assoc($result))
{
/* ... your stuff ...*/
}
In your case with foreach
, with the $result
array you get from select()
:
foreach ($result as $row)
{
/* ... your stuff ...*/
}
It's much like the same, with proper iteration.
du -k /var/lib/postgresql/ |sort -n |tail
To fix this install the specific typescript version 3.1.6
npm i [email protected] --save-dev --save-exact
My Windows 10 machine was automagically updated today. Looks like the "Windows 10 Anniversary update" When I restarted Virtualbox my server with a bridged adapter showed same as OP. I tried rerunning the VirtualBox installer (it did a Repair) - that did not fix the issue. I tried running the installer again as Admin (it did a Repair) - that did not fix. I ran the installer and selected UnInstall, then ran it again to Install. And the Network adapter settings looked good. Server started and connected to my network as usual. Whew. Hope this helps someone.
Example of CSS Text Gradient
background-image: -moz-linear-gradient(top,#E605C1 0%,#3B113B 100%);
background-image: -webkit-linear-gradient(top,#E605C1 0%,#3B113B 100%);
background-image: -o-linear-gradient(top,#E605C1 0%,#3B113B 100%);
background-image: -ms-linear-gradient(top,#E605C1 0%,#3B113B 100%);
background-image: linear-gradient(top,#E605C1 0%,#3B113B 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
position:relative;
display:inline-block; /*required*/
Online generator textgradient.com
I had the same problem, found this thread, tried all but nogo.
Then I spend another 4 hours wasted time.
Then I found that the compilation settings had changed from 64bits to x86. When I changed it back to 64bits it worked. Don't know exactly why but could be that the IIS application pool was not set to allow 32 bit applications.
It means if "OperationURL[1]" evaluates to "GET" then return "GetRequestSignature()" else return "". I'm guessing "GetRequestSignature()" here returns a string. The syntax CONDITION ? A : B basically stands for an if-else where A is returned when CONDITION is true and B is returned when CONDITION is false.
I got it:
string clean = Regex.Replace(q, @"[^a-zA-Z0-9\s]", string.Empty);
Didn't know you could put \s in the brackets
With the release of RecyclerView library, now you can align a list of images bind with text easily. You can use LinearLayoutManager to specify the direction in which you would like to orient your list, either vertical or horizontal as shown below.
You can download a full working demo from this post
Pandas 0.24.0+ solution
In Pandas 0.24.0 a new feature was introduced specifically designed for fast writes to Postgres. You can learn more about it here: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#io-sql-method
import csv
from io import StringIO
from sqlalchemy import create_engine
def psql_insert_copy(table, conn, keys, data_iter):
# gets a DBAPI connection that can provide a cursor
dbapi_conn = conn.connection
with dbapi_conn.cursor() as cur:
s_buf = StringIO()
writer = csv.writer(s_buf)
writer.writerows(data_iter)
s_buf.seek(0)
columns = ', '.join('"{}"'.format(k) for k in keys)
if table.schema:
table_name = '{}.{}'.format(table.schema, table.name)
else:
table_name = table.name
sql = 'COPY {} ({}) FROM STDIN WITH CSV'.format(
table_name, columns)
cur.copy_expert(sql=sql, file=s_buf)
engine = create_engine('postgresql://myusername:mypassword@myhost:5432/mydatabase')
df.to_sql('table_name', engine, method=psql_insert_copy)
you have to put this in web.config :
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000" />
</webServices>
</scripting>
</system.web.extensions>
While only a few lines are required to plot multiple/overlapping histograms in ggplot2, the results are't always satisfactory. There needs to be proper use of borders and coloring to ensure the eye can differentiate between histograms.
The following functions balance border colors, opacities, and superimposed density plots to enable the viewer to differentiate among distributions.
Single histogram:
plot_histogram <- function(df, feature) {
plt <- ggplot(df, aes(x=eval(parse(text=feature)))) +
geom_histogram(aes(y = ..density..), alpha=0.7, fill="#33AADE", color="black") +
geom_density(alpha=0.3, fill="red") +
geom_vline(aes(xintercept=mean(eval(parse(text=feature)))), color="black", linetype="dashed", size=1) +
labs(x=feature, y = "Density")
print(plt)
}
Multiple histogram:
plot_multi_histogram <- function(df, feature, label_column) {
plt <- ggplot(df, aes(x=eval(parse(text=feature)), fill=eval(parse(text=label_column)))) +
geom_histogram(alpha=0.7, position="identity", aes(y = ..density..), color="black") +
geom_density(alpha=0.7) +
geom_vline(aes(xintercept=mean(eval(parse(text=feature)))), color="black", linetype="dashed", size=1) +
labs(x=feature, y = "Density")
plt + guides(fill=guide_legend(title=label_column))
}
Usage:
Simply pass your data frame into the above functions along with desired arguments:
plot_histogram(iris, 'Sepal.Width')
plot_multi_histogram(iris, 'Sepal.Width', 'Species')
The extra parameter in plot_multi_histogram is the name of the column containing the category labels.
We can see this more dramatically by creating a dataframe with many different distribution means:
a <-data.frame(n=rnorm(1000, mean = 1), category=rep('A', 1000))
b <-data.frame(n=rnorm(1000, mean = 2), category=rep('B', 1000))
c <-data.frame(n=rnorm(1000, mean = 3), category=rep('C', 1000))
d <-data.frame(n=rnorm(1000, mean = 4), category=rep('D', 1000))
e <-data.frame(n=rnorm(1000, mean = 5), category=rep('E', 1000))
f <-data.frame(n=rnorm(1000, mean = 6), category=rep('F', 1000))
many_distros <- do.call('rbind', list(a,b,c,d,e,f))
Passing data frame in as before (and widening chart using options):
options(repr.plot.width = 20, repr.plot.height = 8)
plot_multi_histogram(many_distros, 'n', 'category')
Have you tried :
driver.manage().window().maximize()
You should close your Scanner when you're done with it:
in.close();
Similarities:
DTDs and Schemas both perform the same basic functions:
Differences:
DTDs are better for text-intensive applications, while schemas have several advantages for data-intensive workflows.
Schemas are written in XML and thusly follow the same rules, while DTDs are written in a completely different language.
Examples:
DTD:
<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT employees (Efirstname, Elastname, Etitle, Ephone, Eemail)>
<!ELEMENT Efirstname (#PCDATA)>
<!ELEMENT Elastname (#PCDATA)>
<!ELEMENT Etitle (#PCDATA)>
<!ELEMENT Ephone (#PCDATA)>
<!ELEMENT Eemail (#PCDATA)>
XSD:
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:od="urn:schemas-microsoft-com:officedata">
<xsd:element name="dataroot">
<xsd:complexType>
<xsd:sequence>
<xsd:element ref="employees" minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
<xsd:attribute name="generated" type="xsd:dateTime"/>
</xsd:complexType>
</xsd:element>
<xsd:element name="employees">
<xsd:annotation>
<xsd:appinfo>
<od:index index-name="PrimaryKey" index-key="Employeeid " primary="yes"
unique="yes" clustered="no"/>
<od:index index-name="Employeeid" index-key="Employeeid " primary="no" unique="no"
clustered="no"/>
</xsd:appinfo>
</xsd:annotation>
<xsd:complexType>
<xsd:sequence>
<xsd:element name="Elastname" minOccurs="0" od:jetType="text"
od:sqlSType="nvarchar">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:maxLength value="50"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="Etitle" minOccurs="0" od:jetType="text" od:sqlSType="nvarchar">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:maxLength value="50"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="Ephone" minOccurs="0" od:jetType="text"
od:sqlSType="nvarchar">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:maxLength value="50"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="Eemail" minOccurs="0" od:jetType="text"
od:sqlSType="nvarchar">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:maxLength value="50"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="Ephoto" minOccurs="0" od:jetType="text"
od:sqlSType="nvarchar">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:maxLength value="50"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
I had the same problem with commandline php even when ini_set("memory_limit", "-1");
was set, so the limit is in php not from apache.
You should check if you are using the 64bit version of php.
Look at this question about Checking if code is running on 64-bit PHP to find out what php you are using.
I think your php is compiled in 32 bit.
On linux you can use simple shell script https://github.com/dfsq/compressJS.sh to combine multiple javascript files into the single one. It makes use of the Closure Compiler online service so the resulting script is also effectively compressed.
$ ./compressJS.sh some-script.js another-sctipt.js onemore.js
The best way is to create special source folder named resources
and use it for all resource including log4j.properties. So, just put it there.
On the Java Resources folder that was automatically created by the Dynamic Web Project, right click and add a new Source Folder and name it 'resources'. Files here will then be exported to the war file to the classes directory
As we've already figured out in the question and the posted answers, there is an anti Web-scraping and a Bot detection service called "Distil Networks" in play here. And, according to the company CEO's interview:
Even though they can create new bots, we figured out a way to identify Selenium the a tool they’re using, so we’re blocking Selenium no matter how many times they iterate on that bot. We’re doing that now with Python and a lot of different technologies. Once we see a pattern emerge from one type of bot, then we work to reverse engineer the technology they use and identify it as malicious.
It'll take time and additional challenges to understand how exactly they are detecting Selenium, but what can we say for sure at the moment:
Decided to post it as an answer, since clearly:
Can a website detect when you are using selenium with chromedriver?
Yes.
Also, what I haven't experimented with is older selenium and older browser versions - in theory, there could be something implemented/added to selenium at a certain point that Distil Networks bot detector currently relies on. Then, if this is the case, we might detect (yeah, let's detect the detector) at what point/version a relevant change was made, look into changelog and changesets and, may be, this could give us more information on where to look and what is it they use to detect a webdriver-powered browser. It's just a theory that needs to be tested.
cursor.fetchall()
and list(cursor)
are essentially the same. The different option is to not retrieve a list, and instead just loop over the bare cursor object:
for result in cursor:
This can be more efficient if the result set is large, as it doesn't have to fetch the entire result set and keep it all in memory; it can just incrementally get each item (or batch them in smaller batches).
You can use the ng-class
tag. Have a look http://jsfiddle.net/4WK7R/3/
Some good answers here, but like the OP I found myself wanting, in a scripting context, all of:
curl
exit status codeThis is difficult to achieve with a single curl
invocation and I was looking for a complete solution/example, since the required processing is complex.
I combined some other bash recipes on multiplexing stdout/stderr/return-code with some of the ideas here to arrive at the following example:
{
IFS= read -rd '' out
IFS= read -rd '' http_code
IFS= read -rd '' status
} < <({ out=$(curl -sSL -o /dev/stderr -w "%{http_code}" 'https://httpbin.org/json'); } 2>&1; printf '\0%s' "$out" "$?")
Then the results can be found in variables:
echo out $out
echo http_code $http_code
echo status $status
Results:
out { "slideshow": { "author": "Yours Truly", "date": "date of publication", "slides": [ { "title": "Wake up to WonderWidgets!", "type": "all" }, { "items": [ "Why <em>WonderWidgets</em> are great", "Who <em>buys</em> WonderWidgets" ], "title": "Overview", "type": "all" } ], "title": "Sample Slide Show" } }
http_code 200
status 0
The script works by multiplexing the output, HTTP response code and curl
exit status separated by null characters, then reading these back into the current shell/script. It can be tested with curl
requests that would return a >=400 response code but also produce output.
Note that without the -f
flag, curl
won't return non-zero error codes when the server returns an abnormal HTTP response code i.e. >=400, and with the -f
flag, server output is suppresses on error, making use of this flag for error-detection and processing unattractive.
Credits for the generic read
with IFS processing go to this answer: https://unix.stackexchange.com/a/430182/45479 .
When the form is submitted:
document.activeElement
will give you the submit button that was clicked.
document.activeElement.getAttribute('value')
will give you that button's value.
Note that if the form is submitted by hitting the Enter key, then document.activeElement
will be whichever form input
that was focused at the time. If this wasn't a submit button then in this case it may be that there is no "button that was clicked."
If you want an inbuilt function to dump your data into some github markdown, you now have one. Take a look at to_markdown
:
df = pd.DataFrame({"A": [1, 2, 3], "B": [1, 2, 3]}, index=['a', 'a', 'b'])
print(df.to_markdown())
| | A | B |
|:---|----:|----:|
| a | 1 | 1 |
| a | 2 | 2 |
| b | 3 | 3 |
Here's what that looks like on github:
Note that you will still need to have the tabulate
package installed.
Firstly install ffmpeg-php
project (http://ffmpeg-php.sourceforge.net/)
And then you can use of this simple code:
<?php
$frame = 10;
$movie = 'test.mp4';
$thumbnail = 'thumbnail.png';
$mov = new ffmpeg_movie($movie);
$frame = $mov->getFrame($frame);
if ($frame) {
$gd_image = $frame->toGDImage();
if ($gd_image) {
imagepng($gd_image, $thumbnail);
imagedestroy($gd_image);
echo '<img src="'.$thumbnail.'">';
}
}
?>
Description: This project use binary extension .so
file, It's very old and last update was for 2008. So, maybe don't works with newer version of FFMpeg
or PHP
.
Firstly install PHP-FFMpeg
project (https://github.com/PHP-FFMpeg/PHP-FFMpeg)
(just run for install: composer require php-ffmpeg/php-ffmpeg
)
And then you can use of this simple code:
<?php
require 'vendor/autoload.php';
$sec = 10;
$movie = 'test.mp4';
$thumbnail = 'thumbnail.png';
$ffmpeg = FFMpeg\FFMpeg::create();
$video = $ffmpeg->open($movie);
$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds($sec));
$frame->save($thumbnail);
echo '<img src="'.$thumbnail.'">';
Description: It's newer and more modern project and works with latest version of FFMpeg
and PHP
. Note that it's required to proc_open()
PHP function.