In order to create a java.util.Date from a java.time.LocalDate, you have to
The code might look as follows:
LocalDate localDate = LocalDate.now();
Date date = new Date(localDate.atStartOfDay(ZoneId.of("America/New_York")).toEpochSecond() * 1000);
Because default parameters are resolved at compile time, not runtime. So the default values does not belong to the object being called, but to the reference type that it is being called through.
You shouldn't need a $watch. Just bind to resize event on window:
'use strict';
var app = angular.module('plunker', []);
app.directive('myDirective', ['$window', function ($window) {
return {
link: link,
restrict: 'E',
template: '<div>window size: {{width}}px</div>'
};
function link(scope, element, attrs){
scope.width = $window.innerWidth;
angular.element($window).bind('resize', function(){
scope.width = $window.innerWidth;
// manuall $digest required as resize event
// is outside of angular
scope.$digest();
});
}
}]);
You CAN include a modal within a form. In the Bootstrap documentation it recommends the modal to be a "top level" element, but it still works within a form.
You create a form, and then the modal "save" button will be a button of type="submit" to submit the form from within the modal.
<form asp-action="AddUsersToRole" method="POST" class="mb-3">
@await Html.PartialAsync("~/Views/Users/_SelectList.cshtml", Model.Users)
<div class="modal fade" id="role-select-modal" tabindex="-1" role="dialog" aria-labelledby="role-select-modal" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Select a Role</h5>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Add Users to Role</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
</form>
You can post (or GET) your form data to any URL. By default it is the serving page URL, but you can change it by setting the form action
. You do not have to use ajax.
deploy:
resources:
limits:
cpus: '0.001'
memory: 50M
reservations:
cpus: '0.0001'
memory: 20M
More: https://docs.docker.com/compose/compose-file/compose-file-v3/#resources
In you specific case:
version: "3"
services:
node:
image: USER/Your-Pre-Built-Image
environment:
- VIRTUAL_HOST=localhost
volumes:
- logs:/app/out/
command: ["npm","start"]
cap_drop:
- NET_ADMIN
- SYS_ADMIN
deploy:
resources:
limits:
cpus: '0.001'
memory: 50M
reservations:
cpus: '0.0001'
memory: 20M
volumes:
- logs
networks:
default:
driver: overlay
Note:
Also Note: Networks in Swarm mode do not bridge. If you would like to connect internally only, you have to attach to the network. You can 1) specify an external network within an other compose file, or have to create the network with --attachable parameter (docker network create -d overlay My-Network --attachable) Otherwise you have to publish the port like this:
ports:
- 80:80
Faster way of doing this:
WHERE interests LIKE '%sports%' OR interests LIKE '%pub%'
is this:
WHERE interests REGEXP 'sports|pub'
Found this solution here: http://forums.mysql.com/read.php?10,392332,392950#msg-392950
More about REGEXP here: http://www.tutorialspoint.com/mysql/mysql-regexps.htm
The method GetFileNameWithoutExtension
, as the name implies, does not return the extension on the file. In your case, it would only return "a". You want to append your ".Jpeg" to that result. However, at a different level, this seems strange, as image files have different metadata and cannot be converted so easily.
If you use that forumla in the name manager you are creating a dynamic range which uses "this sheet" in place of a specific sheet.
As Jerry says, Sheet1!A1 refers to cell A1 on Sheet1. If you create a named range and omit the Sheet1 part you will reference cell A1 on the currently active sheet. (omitting the sheet reference and using it in a cell formula will error).
edit: my bad, I was using $A$1 which will lock it to the A1 cell as above, thanks pnuts :p
All these commands are called automatically at the appropriate times by iOS when you load/present/hide the view controller. It's important to note that these methods are attached to UIViewController
and not to UIView
s themselves. You won't get any of these features just using a UIView
.
There's great documentation on Apple's site here. Putting in simply though:
ViewDidLoad
- Called when you create the class and load from xib. Great for initial setup and one-time-only work.
ViewWillAppear
- Called right before your view appears, good for hiding/showing fields or any operations that you want to happen every time before the view is visible. Because you might be going back and forth between views, this will be called every time your view is about to appear on the screen.
ViewDidAppear
- Called after the view appears - great place to start an animations or the loading of external data from an API.
ViewWillDisappear
/DidDisappear
- Same idea as ViewWillAppear
/ViewDidAppear
.
ViewDidUnload
/ViewDidDispose
- In Objective-C, this is where you do your clean-up and release of stuff, but this is handled automatically so not much you really need to do here.
found this and it worked for me.
strSQL = "SELECT * FROM DataTable"
'Where DataTable is the Named range
How can I run SQL statements on a named range within an excel sheet?
According to Harry's linear-gradient solution (answered Oct 14 '15 at 9:55), it says that opacity background isn't possible, I tried it and yep, it isn't.
But! I found a workaround. No it's not super optimised, but it worked. So here's my solution. Since Harry doesn't use pseudo element, we can achieve this by creating one.
Set position relative to the container and create a pseudo element with the same linear-gradient properties. In other words, just clone it. Then put a transparent background for the container, and lets say a black background for the clone. Put a position absolute on it, a z-index of -1 and an opacity value (ie. 50%). It will do the job. Again it's a workaround and it's not perfect but it works just fine.
.cut-corner {_x000D_
position: relative;_x000D_
color: white;_x000D_
background-repeat: no-repeat;_x000D_
background-image: linear-gradient(white, white), linear-gradient(white, white), linear-gradient(white, white), linear-gradient(white, white), linear-gradient(to bottom left, transparent calc(50% - 1px), white calc(50% - 1px), white calc(50% + 1px), transparent calc(50% + 1px)), linear-gradient(transparent, transparent), linear-gradient(transparent, transparent);_x000D_
background-size: 2px 100%, 2px 100%, 100% 2px, 100% 2px, 25px 25px, 100% 100%, 100% 100%;_x000D_
background-position: 0% 0%, 100% 25px, -25px 0%, 0px 100%, 100% 0%, -25px 0%, 100% 25px;_x000D_
}_x000D_
.cut-corner:after {_x000D_
content: "";_x000D_
position: absolute;_x000D_
left: 0;_x000D_
bottom: 0;_x000D_
right: 0;_x000D_
top: 0;_x000D_
z-index: -1;_x000D_
opacity: 0.5;_x000D_
background-repeat: no-repeat;_x000D_
background-image: linear-gradient(white, white), linear-gradient(white, white), linear-gradient(white, white), linear-gradient(white, white), linear-gradient(to bottom left, transparent calc(50% - 1px), white calc(50% - 1px), white calc(50% + 1px), black calc(50% + 1px)), linear-gradient(black, black), linear-gradient(black, black);_x000D_
background-size: 2px 100%, 2px 100%, 100% 2px, 100% 2px, 25px 25px, 100% 100%, 100% 100%;_x000D_
background-position: 0% 0%, 100% 25px, -25px 0%, 0px 100%, 100% 0%, -25px 0%, 100% 25px;_x000D_
}_x000D_
_x000D_
/* Just for demo */_x000D_
_x000D_
div {_x000D_
padding: 10px;_x000D_
}_x000D_
body{_x000D_
background-image: radial-gradient(circle, #3F9CBA 0%, #153346 100%);_x000D_
}
_x000D_
<div class="cut-corner">_x000D_
Some content<br>_x000D_
Some content<br>_x000D_
Some content<br>_x000D_
Some content _x000D_
</div>
_x000D_
What you have is correct, but this is more consice:
^[A-Z]{3}$
Go to http://dev.mysql.com/downloads/connector/j and with in the dropdown select "Platform Independent" then it will show you the options to download tar.gz file or zip file.
Download zip file and extract it, with in that you will find mysql-connector-XXX.jar
file
If you are using maven then you can add the dependency from the link http://mvnrepository.com/artifact/mysql/mysql-connector-java
Select the version you want to use and add the dependency in your pom.xml
file
You need to analyze the JSON calls using Wireshark, so you will see if you include the charset in the formation of the JSON page or not, for example:
0000 48 54 54 50 2f 31 2e 31 20 32 30 30 20 4f 4b 0d HTTP/1.1 200 OK. 0010 0a 43 6f 6e 74 65 6e 74 2d 54 79 70 65 3a 20 74 .Content -Type: t 0020 65 78 74 2f 68 74 6d 6c 0d 0a 43 61 63 68 65 2d ext/html ..Cache- 0030 43 6f 6e 74 72 6f 6c 3a 20 6e 6f 2d 63 61 63 68 Control: no-cach
0000 48 54 54 50 2f 31 2e 31 20 32 30 30 20 4f 4b 0d HTTP/1.1 200 OK. 0010 0a 43 61 63 68 65 2d 43 6f 6e 74 72 6f 6c 3a 20 .Cache-C ontrol: 0020 6e 6f 2d 63 61 63 68 65 0d 0a 43 6f 6e 74 65 6e no-cache ..Conten 0030 74 2d 54 79 70 65 3a 20 74 65 78 74 2f 68 74 6d t-Type: text/htm 0040 6c 3b 20 63 68 61 72 73 65 74 3d 49 53 4f 2d 38 l; chars et=ISO-8 0050 38 35 39 2d 31 0d 0a 43 6f 6e 6e 65 63 74 69 6f 859-1..C onnectio
Why is that? because we can not put on the page of JSON a goal like this:
In my case I use the manufacturer Connect Me 9210 Digi:
It worked for me without having to convert the data passed by JSON for UTF-8 and then redo the conversion on the page ...
Most answers suggest to just add ServerName localhost
to /etc/apache2/apache2.conf
.
But quoting Apache documentation :
The presence of this error message also indicates that Apache httpd was unable to obtain a fully-qualified hostname by doing a reverse lookup on your server's IP address. While the above instructions will get rid of the warning in any case, it is also a good idea to fix your name resolution so that this reverse mapping works.
Therefore adding such a line to /etc/hosts
is probably a more robust solution :
192.0.2.0 foobar.example.com foobar
where 192.0.2.0 is the static IP address of the server named foobar
within the example.com
domain.
One can check the FQDN e.g. with
hostname -A
(shortcut for hostname --all-fqdn
).
I had a navigation controllers integrated in a TabbarController. This worked
self.navigationItem.title=@"title";
The number
type has a step
value controlling which numbers are valid (along with max
and min
), which defaults to 1
. This value is also used by implementations for the stepper buttons (i.e. pressing up increases by step
).
Simply change this value to whatever is appropriate. For money, two decimal places are probably expected:
<input type="number" step="0.01">
(I'd also set min=0
if it can only be positive)
If you'd prefer to allow any number of decimal places, you can use step="any"
(though for currencies, I'd recommend sticking to 0.01
). In Chrome & Firefox, the stepper buttons will increment / decrement by 1 when using any
. (thanks to Michal Stefanow's answer for pointing out any
, and see the relevant spec here)
Here's a playground showing how various steps affect various input types:
<form>_x000D_
<input type=number step=1 /> Step 1 (default)<br />_x000D_
<input type=number step=0.01 /> Step 0.01<br />_x000D_
<input type=number step=any /> Step any<br />_x000D_
<input type=range step=20 /> Step 20<br />_x000D_
<input type=datetime-local step=60 /> Step 60 (default)<br />_x000D_
<input type=datetime-local step=1 /> Step 1<br />_x000D_
<input type=datetime-local step=any /> Step any<br />_x000D_
<input type=datetime-local step=0.001 /> Step 0.001<br />_x000D_
<input type=datetime-local step=3600 /> Step 3600 (1 hour)<br />_x000D_
<input type=datetime-local step=86400 /> Step 86400 (1 day)<br />_x000D_
<input type=datetime-local step=70 /> Step 70 (1 min, 10 sec)<br />_x000D_
</form>
_x000D_
As usual, I'll add a quick note: remember that client-side validation is just a convenience to the user. You must also validate on the server-side!
// assuming driver is a healthy WebDriver instance
WebElement fileInput = driver.findElement(By.name("uploadfile"));
fileInput.sendKeys("C:/path/to/file.jpg");
Hey, that's mine from somewhere :).
In case of the Zamzar web, it should work perfectly. You don't click the element. You just type the path into it. To be concrete, this should be absolutely ok:
driver.findElement(By.id("inputFile")).sendKeys("C:/path/to/file.jpg");
In the case of the Uploadify web, you're in a pickle, since the upload thing is no input
, but a Flash object. There's no API for WebDriver that would allow you to work with browser dialogs (or Flash objects).
So after you click the Flash element, there'll be a window popping up that you'll have no control over. In the browsers and operating systems I know, you can pretty much assume that after the window has been opened, the cursor is in the File name
input. Please, make sure this assumption is true in your case, too.
If not, you could try to jump to it by pressing Alt + N, at least on Windows...
If yes, you can "blindly" type the path into it using the Robot
class. In your case, that would be something in the way of:
driver.findElement(By.id("SWFUpload_0")).click();
Robot r = new Robot();
r.keyPress(KeyEvent.VK_C); // C
r.keyRelease(KeyEvent.VK_C);
r.keyPress(KeyEvent.VK_COLON); // : (colon)
r.keyRelease(KeyEvent.VK_COLON);
r.keyPress(KeyEvent.VK_SLASH); // / (slash)
r.keyRelease(KeyEvent.VK_SLASH);
// etc. for the whole file path
r.keyPress(KeyEvent.VK_ENTER); // confirm by pressing Enter in the end
r.keyRelease(KeyEvent.VK_ENTER);
It sucks, but it should work. Note that you might need these: How can I make Robot type a `:`? and Convert String to KeyEvents (plus there is the new and shiny KeyEvent#getExtendedKeyCodeForChar()
which does similar work, but is available only from JDK7).
For Flash, the only alternative I know (from this discussion) is to use the dark technique:
First, you modify the source code of you the flash application, exposing internal methods using the ActionScript's ExternalInterface API. Once exposed, these methods will be callable by JavaScript in the browser.
Second, now that JavaScript can call internal methods in your flash app, you use WebDriver to make a JavaScript call in the web page, which will then call into your flash app.
This technique is explained further in the docs of the flash-selenium project. (http://code.google.com/p/flash-selenium/), but the idea behind the technique applies just as well to WebDriver.
You can bind the menu items to a site map and use the roles attribute. You will need to enable Security Trimming in your Web.Config to do this. This is the simplest way.
Site Navigation Overview: http://msdn.microsoft.com/en-us/library/e468hxky.aspx
Security Trimming Info: http://msdn.microsoft.com/en-us/library/ms178428.aspx
SiteMap Binding Info: http://www.w3schools.com/aspnet/aspnet_navigation.asp
Good Tutorial/Overview here: http://weblogs.asp.net/jgalloway/archive/2008/01/26/asp-net-menu-and-sitemap-security-trimming-plus-a-trick-for-when-your-menu-and-security-don-t-match-up.aspx
Another option that works, but is less ideal is to use the loginview control which can display controls based on role. This might be the quickest (but least flexible/performant) option. You can find a guide here: http://weblogs.asp.net/sukumarraju/archive/2010/07/28/role-based-authorization-using-loginview-control.aspx
A root-relative URL starts with a /
character, to look something like <a href="/directoryInRoot/fileName.html">link text</a>
.
The link you posted: <a href="fruits/index.html">Back to Fruits List</a>
is linking to an html file located in a directory named fruits
, the directory being in the same directory as the html page in which this link appears.
To make it a root-relative URL, change it to:
<a href="/fruits/index.html">Back to Fruits List</a>
Edited in response to question, in comments, from OP:
So doing / will make it relative to www.example.com, is there a way to specify what the root is, e.g what if i want the root to be www.example.com/fruits in www.example.com/fruits/apples/apple.html?
Yes, prefacing the URL, in the href
or src
attributes, with a /
will make the path relative to the root directory. For example, given the html page at www.example.com/fruits/apples.html
, the a
of href="/vegetables/carrots.html"
will link to the page www.example.com/vegetables/carrots.html
.
The base
tag element allows you to specify the base-uri for that page (though the base
tag would have to be added to every page in which it was necessary for to use a specific base, for this I'll simply cite the W3's example:
For example, given the following BASE declaration and A declaration:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>Our Products</TITLE>
<BASE href="http://www.aviary.com/products/intro.html">
</HEAD>
<BODY>
<P>Have you seen our <A href="../cages/birds.gif">Bird Cages</A>?
</BODY>
</HTML>
the relative URI "../cages/birds.gif" would resolve to:
http://www.aviary.com/cages/birds.gif
Example quoted from: http://www.w3.org/TR/html401/struct/links.html#h-12.4.
Suggested reading:
This should work, I just tested it out and it worked as expected: no expansion, substitution, or what-have-you took place.
cat <<< '
#!/bin/bash
curr=`cat /sys/class/backlight/intel_backlight/actual_brightness`
if [ $curr -lt 4477 ]; then
curr=$((curr+406));
echo $curr > /sys/class/backlight/intel_backlight/brightness;
fi' > file # use overwrite mode so that you don't keep on appending the same script to that file over and over again, unless that's what you want.
Using the following also works.
cat <<< ' > file
... code ...'
Also, it's worth noting that when using heredocs, such as << EOF
, substitution and variable expansion and the like takes place. So doing something like this:
cat << EOF > file
cd "$HOME"
echo "$PWD" # echo the current path
EOF
will always result in the expansion of the variables $HOME
and $PWD
. So if your home directory is /home/foobar
and the current path is /home/foobar/bin
, file
will look like this:
cd "/home/foobar"
echo "/home/foobar/bin"
instead of the expected:
cd "$HOME"
echo "$PWD"
using List Comprehension:
>>> L = [1]*5
>>> [x+1 for x in L]
[2, 2, 2, 2, 2]
>>>
which roughly translates to using a for loop:
>>> newL = []
>>> for x in L:
... newL+=[x+1]
...
>>> newL
[2, 2, 2, 2, 2]
or using map:
>>> map(lambda x:x+1, L)
[2, 2, 2, 2, 2]
>>>
You must make sure that the input string has enough space to hold all the padding characters. Try this:
char hello[11] = "Hello";
StringPadRight(hello, 10, "0");
Note that I allocated 11 bytes for the hello
string to account for the null terminator at the end.
If you don't want to have a dependency like Flurl, you can use its source code:
/// <summary>
/// Basically a Path.Combine for URLs. Ensures exactly one '/' separates each segment,
/// and exactly on '&' separates each query parameter.
/// URL-encodes illegal characters but not reserved characters.
/// </summary>
/// <param name="parts">URL parts to combine.</param>
public static string Combine(params string[] parts) {
if (parts == null)
throw new ArgumentNullException(nameof(parts));
string result = "";
bool inQuery = false, inFragment = false;
string CombineEnsureSingleSeparator(string a, string b, char separator) {
if (string.IsNullOrEmpty(a)) return b;
if (string.IsNullOrEmpty(b)) return a;
return a.TrimEnd(separator) + separator + b.TrimStart(separator);
}
foreach (var part in parts) {
if (string.IsNullOrEmpty(part))
continue;
if (result.EndsWith("?") || part.StartsWith("?"))
result = CombineEnsureSingleSeparator(result, part, '?');
else if (result.EndsWith("#") || part.StartsWith("#"))
result = CombineEnsureSingleSeparator(result, part, '#');
else if (inFragment)
result += part;
else if (inQuery)
result = CombineEnsureSingleSeparator(result, part, '&');
else
result = CombineEnsureSingleSeparator(result, part, '/');
if (part.Contains("#")) {
inQuery = false;
inFragment = true;
}
else if (!inFragment && part.Contains("?")) {
inQuery = true;
}
}
return EncodeIllegalCharacters(result);
}
/// <summary>
/// URL-encodes characters in a string that are neither reserved nor unreserved. Avoids encoding reserved characters such as '/' and '?'. Avoids encoding '%' if it begins a %-hex-hex sequence (i.e. avoids double-encoding).
/// </summary>
/// <param name="s">The string to encode.</param>
/// <param name="encodeSpaceAsPlus">If true, spaces will be encoded as + signs. Otherwise, they'll be encoded as %20.</param>
/// <returns>The encoded URL.</returns>
public static string EncodeIllegalCharacters(string s, bool encodeSpaceAsPlus = false) {
if (string.IsNullOrEmpty(s))
return s;
if (encodeSpaceAsPlus)
s = s.Replace(" ", "+");
// Uri.EscapeUriString mostly does what we want - encodes illegal characters only - but it has a quirk
// in that % isn't illegal if it's the start of a %-encoded sequence https://stackoverflow.com/a/47636037/62600
// no % characters, so avoid the regex overhead
if (!s.Contains("%"))
return Uri.EscapeUriString(s);
// pick out all %-hex-hex matches and avoid double-encoding
return Regex.Replace(s, "(.*?)((%[0-9A-Fa-f]{2})|$)", c => {
var a = c.Groups[1].Value; // group 1 is a sequence with no %-encoding - encode illegal characters
var b = c.Groups[2].Value; // group 2 is a valid 3-character %-encoded sequence - leave it alone!
return Uri.EscapeUriString(a) + b;
});
}
For the benefit of Swift 3 beginners:
Here is a code sample to verify if a file named "database.sqlite" exists in application document directory:
func findIfSqliteDBExists(){
let docsDir : URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let dbPath : URL = docsDir.appendingPathComponent("database.sqlite")
let strDBPath : String = dbPath.path
let fileManager : FileManager = FileManager.default
if fileManager.fileExists(atPath:strDBPath){
print("An sqlite database exists at this path :: \(strDBPath)")
}else{
print("SQLite NOT Found at :: \(strDBPath)")
}
}
For a popup javascript is required. Put this in your header:
<script>
function myFunction()
{
alert("I am an alert box!"); // this is the message in ""
}
</script>
And this in your body:
<input type="button" onclick="myFunction()" value="Show alert box">
When the button is pressed a box pops up with the message set in the header.
This can be put in any html or php file without the php tags.
-----EDIT-----
To display it using php try this:
<?php echo '<script>myfunction()</script>'; ?>
It may not be 100% correct but the principle is the same.
To display different messages you can either create lots of functions or you can pass a variable in to the function when you call it.
You can pass in the element to the controller, just like the scope:
function someControllerFunc($scope, $element){
}
I just came accross the answer from Lizard which is extremely helpful - especially when you do some sorting. Isn't is beautiful how many chars we need to say mostly the same ;)
If anyone else if looking for a all-in solution (as far as the comments above tell), here's the copy&paste:
/**
* Replace language-specific characters by ASCII-equivalents.
* @param string $s
* @return string
*/
public static function normalizeChars($s) {
$replace = array(
'?'=>'-', '?'=>'-', '?'=>'-', '?'=>'-',
'A'=>'A', 'A'=>'A', 'À'=>'A', 'Ã'=>'A', 'Á'=>'A', 'Æ'=>'A', 'Â'=>'A', 'Å'=>'A', 'Ä'=>'Ae',
'Þ'=>'B',
'C'=>'C', '?'=>'C', 'Ç'=>'C',
'È'=>'E', 'E'=>'E', 'É'=>'E', 'Ë'=>'E', 'Ê'=>'E',
'G'=>'G',
'I'=>'I', 'Ï'=>'I', 'Î'=>'I', 'Í'=>'I', 'Ì'=>'I',
'L'=>'L',
'Ñ'=>'N', 'N'=>'N',
'Ø'=>'O', 'Ó'=>'O', 'Ò'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'Oe',
'S'=>'S', 'S'=>'S', '?'=>'S', 'Š'=>'S',
'?'=>'T',
'Ù'=>'U', 'Û'=>'U', 'Ú'=>'U', 'Ü'=>'Ue',
'Ý'=>'Y',
'Z'=>'Z', 'Ž'=>'Z', 'Z'=>'Z',
'â'=>'a', 'a'=>'a', 'a'=>'a', 'á'=>'a', 'a'=>'a', 'ã'=>'a', 'A'=>'a', '?'=>'a', '?'=>'a', 'å'=>'a', 'à'=>'a', '?'=>'a', '?'=>'a', 'A'=>'a', '?'=>'a', 'a'=>'a', 'ä'=>'ae', 'æ'=>'ae', '?'=>'ae', '?'=>'ae',
'?'=>'b', '?'=>'b', '?'=>'b', 'þ'=>'b',
'c'=>'c', 'C'=>'c', 'C'=>'c', 'c'=>'c', 'ç'=>'c', '?'=>'c', '?'=>'c', 'c'=>'c', '?'=>'c', 'C'=>'c', 'c'=>'c', '?'=>'ch', '?'=>'ch',
'?'=>'d', 'd'=>'d', 'Ð'=>'d', 'D'=>'d', 'd'=>'d', '?'=>'d', '?'=>'D', 'ð'=>'d',
'?'=>'e', '?'=>'e', '?'=>'e', '?'=>'e', '?'=>'e', 'e'=>'e', 'e'=>'e', 'e'=>'e', 'E'=>'e', 'E'=>'e', 'e'=>'e', 'e'=>'e', 'E'=>'e', '?'=>'e', 'E'=>'e', 'ê'=>'e', '?'=>'e', 'è'=>'e', 'ë'=>'e', 'é'=>'e',
'?'=>'f', 'ƒ'=>'f', '?'=>'f',
'g'=>'g', 'G'=>'g', 'G'=>'g', 'G'=>'g', '?'=>'g', '?'=>'g', 'g'=>'g', 'g'=>'g', '?'=>'g', '?'=>'g', '?'=>'g', 'g'=>'g',
'?'=>'h', 'h'=>'h', '?'=>'h', 'H'=>'h', 'H'=>'h', 'h'=>'h', '?'=>'h', '?'=>'h',
'î'=>'i', 'ï'=>'i', 'í'=>'i', 'ì'=>'i', 'i'=>'i', 'i'=>'i', 'i'=>'i', 'I'=>'i', '?'=>'i', 'i'=>'i', 'i'=>'i', 'I'=>'i', 'I'=>'i', '?'=>'i', 'I'=>'i', '?'=>'i', '?'=>'i', 'I'=>'i', '?'=>'i', '?'=>'i', '?'=>'i', 'i'=>'i', '?'=>'ij', '?'=>'ij',
'?'=>'j', '?'=>'j', 'J'=>'j', 'j'=>'j', '?'=>'ja', '?'=>'ja', '?'=>'je', '?'=>'je', '?'=>'jo', '?'=>'jo', '?'=>'ju', '?'=>'ju',
'?'=>'k', '?'=>'k', 'K'=>'k', '?'=>'k', '?'=>'k', 'k'=>'k', '?'=>'k',
'?'=>'l', '?'=>'l', '?'=>'l', 'l'=>'l', 'l'=>'l', 'l'=>'l', 'L'=>'l', 'L'=>'l', '?'=>'l', 'L'=>'l', 'l'=>'l', '?'=>'l',
'?'=>'m', '?'=>'m', '?'=>'m', '?'=>'m',
'ñ'=>'n', '?'=>'n', 'N'=>'n', '?'=>'n', '?'=>'n', '?'=>'n', '?'=>'n', 'n'=>'n', '?'=>'n', 'n'=>'n', '?'=>'n', 'N'=>'n', 'n'=>'n',
'?'=>'o', '?'=>'o', 'o'=>'o', 'õ'=>'o', 'ô'=>'o', 'O'=>'o', 'o'=>'o', 'O'=>'o', 'O'=>'o', 'o'=>'o', 'ø'=>'o', '?'=>'o', 'o'=>'o', 'ò'=>'o', '?'=>'o', 'O'=>'o', 'o'=>'o', 'ó'=>'o', 'O'=>'o', 'œ'=>'oe', 'Œ'=>'oe', 'ö'=>'oe',
'?'=>'p', '?'=>'p', '?'=>'p', '?'=>'p',
'?'=>'q',
'r'=>'r', 'r'=>'r', 'R'=>'r', 'r'=>'r', 'R'=>'r', '?'=>'r', 'R'=>'r', '?'=>'r', '?'=>'r',
'?'=>'s', '?'=>'s', 'S'=>'s', 'š'=>'s', 's'=>'s', '?'=>'s', 's'=>'s', '?'=>'s', 's'=>'s', '?'=>'sch', '?'=>'sch', '?'=>'sh', '?'=>'sh', 'ß'=>'ss',
'?'=>'t', '?'=>'t', 't'=>'t', '?'=>'t', 't'=>'t', 't'=>'t', 'T'=>'t', '?'=>'t', '?'=>'t', 'T'=>'t', 'T'=>'t', '™'=>'tm',
'u'=>'u', '?'=>'u', 'U'=>'u', 'u'=>'u', 'U'=>'u', 'u'=>'u', 'U'=>'u', 'U'=>'u', 'u'=>'u', 'U'=>'u', 'u'=>'u', 'U'=>'u', 'U'=>'u', 'u'=>'u', 'u'=>'u', 'U'=>'u', 'U'=>'u', 'u'=>'u', 'U'=>'u', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', '?'=>'u', 'u'=>'u', 'u'=>'u', 'U'=>'u', 'U'=>'u', 'u'=>'u', 'u'=>'u', 'ü'=>'ue',
'?'=>'v', '?'=>'v', '?'=>'v',
'?'=>'w', 'w'=>'w', 'W'=>'w',
'?'=>'y', 'y'=>'y', 'ý'=>'y', 'ÿ'=>'y', 'Ÿ'=>'y', 'Y'=>'y',
'?'=>'y', 'ž'=>'z', '?'=>'z', '?'=>'z', 'z'=>'z', '?'=>'z', 'z'=>'z', '?'=>'z', '?'=>'zh', '?'=>'zh'
);
return strtr($s, $replace);
}
Note some slight changes regarding the German umlauts (ä => ae)
Edit: Included more characters based on the posting from user3682119 (except for the copyright symbol) and the comment from daker.
According to the answer here, quotes in values need to be escaped. You can do that with \"
So just repalce the quote in your values
msget = msget.replace("\"", "\\\"");
I think no one has given the correct answer to the question. My working solution is : 1. Just declare another class along with container-fluid class example(.maxx):
<div class="container-fluid maxx">_x000D_
<div class="row">_x000D_
<div class="col-sm-12">_x000D_
<p>Hello</p>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
.container-fluid.maxx {_x000D_
padding-left: 0px;_x000D_
padding-right: 0px; }
_x000D_
This will work 100% and will remove the padding from left and right. I hope this helps.
Simply unregister the default StringHttpMessageConverter
instance:
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
/**
* Unregister the default {@link StringHttpMessageConverter} as we want Strings
* to be handled by the JSON converter.
*
* @param converters List of already configured converters
* @see WebMvcConfigurationSupport#addDefaultHttpMessageConverters(List)
*/
@Override
protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.stream()
.filter(c -> c instanceof StringHttpMessageConverter)
.findFirst().ifPresent(converters::remove);
}
}
Tested with both controller action handler methods and controller exception handlers:
@RequestMapping("/foo")
public String produceFoo() {
return "foo";
}
@ExceptionHandler(FooApiException.class)
public String fooException(HttpServletRequest request, Throwable e) {
return e.getMessage();
}
Final notes:
extendMessageConverters
is available since Spring 4.1.3, if are running on a previous version you can implement the same technique using configureMessageConverters
, it just takes a little bit more work.Not exactly what the OP was asking for, but a simple way to disable all axes lines, ticks and labels is to simply call:
plt.axis('off')
set <ORACLE_HOME> path variable
example
path ORACLE_HOME
value is C:\oraclexe\app\oracle\product\10.2.0\server
insertRow2 <- function(existingDF, newrow, r) {
existingDF <- rbind(existingDF,newrow)
existingDF <- existingDF[order(c(1:(nrow(existingDF)-1),r-0.5)),]
row.names(existingDF) <- 1:nrow(existingDF)
return(existingDF)
}
insertRow2(existingDF,newrow,r)
V1 V2 V3 V4
1 1 6 11 16
2 2 7 12 17
3 1 2 3 4
4 3 8 13 18
5 4 9 14 19
6 5 10 15 20
microbenchmark(
+ rbind(existingDF[1:r,],newrow,existingDF[-(1:r),]),
+ insertRow(existingDF,newrow,r),
+ insertRow2(existingDF,newrow,r)
+ )
Unit: microseconds
expr min lq median uq max
1 insertRow(existingDF, newrow, r) 513.157 525.6730 531.8715 544.4575 1409.553
2 insertRow2(existingDF, newrow, r) 430.664 443.9010 450.0570 461.3415 499.988
3 rbind(existingDF[1:r, ], newrow, existingDF[-(1:r), ]) 606.822 625.2485 633.3710 653.1500 1489.216
echo "12|23|11" | awk '{split($0,a,"|"); print a[3] a[2] a[1]}'
Try this:
ls -l | awk -F : '{sum+=$5} END {print "AVG=",sum/NR}'
NR is an AWK builtin variable to count the no. of records
Note: Using Android Support Library v22.1.0 and targeting API level 11 and up? Scroll down to the last update.
My application style is set to Theme.Holo which is dark and I would like the check boxes on my list view to be of style Theme.Holo.Light. I am not trying to create a custom style. The code below doesn't seem to work, nothing happens at all.
At first it may not be apparent why the system exhibits this behaviour, but when you actually look into the mechanics you can easily deduce it. Let me take you through it step by step.
First, let's take a look what the Widget.Holo.Light.CompoundButton.CheckBox
style defines. To make things more clear, I've also added the 'regular' (non-light) style definition.
<style name="Widget.Holo.Light.CompoundButton.CheckBox" parent="Widget.CompoundButton.CheckBox" />
<style name="Widget.Holo.CompoundButton.CheckBox" parent="Widget.CompoundButton.CheckBox" />
As you can see, both are empty declarations that simply wrap Widget.CompoundButton.CheckBox
in a different name. So let's look at that parent style.
<style name="Widget.CompoundButton.CheckBox">
<item name="android:background">@android:drawable/btn_check_label_background</item>
<item name="android:button">?android:attr/listChoiceIndicatorMultiple</item>
</style>
This style references both a background and button drawable. btn_check_label_background
is simply a 9-patch and hence not very interesting with respect to this matter. However, ?android:attr/listChoiceIndicatorMultiple
indicates that some attribute based on the current theme (this is important to realise) will determine the actual look of the CheckBox
.
As listChoiceIndicatorMultiple
is a theme attribute, you will find multiple declarations for it - one for each theme (or none if it gets inherited from a parent theme). This will look as follows (with other attributes omitted for clarity):
<style name="Theme">
<item name="listChoiceIndicatorMultiple">@android:drawable/btn_check</item>
...
</style>
<style name="Theme.Holo">
<item name="listChoiceIndicatorMultiple">@android:drawable/btn_check_holo_dark</item>
...
</style>
<style name="Theme.Holo.Light" parent="Theme.Light">
<item name="listChoiceIndicatorMultiple">@android:drawable/btn_check_holo_light</item>
...
</style>
So this where the real magic happens: based on the theme's listChoiceIndicatorMultiple
attribute, the actual appearance of the CheckBox
is determined. The phenomenon you're seeing is now easily explained: since the appearance is theme-based (and not style-based, because that is merely an empty definition) and you're inheriting from Theme.Holo
, you will always get the CheckBox
appearance matching the theme.
Now, if you want to change your CheckBox
's appearance to the Holo.Light version, you will need to take a copy of those resources, add them to your local assets and use a custom style to apply them.
As for your second question:
Also can you set styles to individual widgets if you set a style to the application?
Absolutely, and they will override any activity- or application-set styles.
Is there any way to set a theme(style with images) to the checkbox widget. (...) Is there anyway to use this selector: link?
Update:
Let me start with saying again that you're not supposed to rely on Android's internal resources. There's a reason you can't just access the internal namespace as you please.
However, a way to access system resources after all is by doing an id lookup by name. Consider the following code snippet:
int id = Resources.getSystem().getIdentifier("btn_check_holo_light", "drawable", "android");
((CheckBox) findViewById(R.id.checkbox)).setButtonDrawable(id);
The first line will actually return the resource id of the btn_check_holo_light
drawable resource. Since we established earlier that this is the button selector that determines the look of the CheckBox
, we can set it as 'button drawable' on the widget. The result is a CheckBox
with the appearance of the Holo.Light
version, no matter what theme/style you set on the application, activity or widget in xml. Since this sets only the button drawable, you will need to manually change other styling; e.g. with respect to the text appearance.
Below a screenshot showing the result. The top checkbox uses the method described above (I manually set the text colour to black in xml), while the second uses the default theme-based Holo
styling (non-light, that is).
Update2:
With the introduction of Support Library v22.1.0, things have just gotten a lot easier! A quote from the release notes (my emphasis):
Lollipop added the ability to overwrite the theme at a view by view level by using the
android:theme
XML attribute - incredibly useful for things such as dark action bars on light activities. Now, AppCompat allows you to useandroid:theme
for Toolbars (deprecating theapp:theme
used previously) and, even better, bringsandroid:theme
support to all views on API 11+ devices.
In other words: you can now apply a theme on a per-view basis, which makes solving the original problem a lot easier: just specify the theme you'd like to apply for the relevant view. I.e. in the context of the original question, compare the results of below:
<CheckBox
...
android:theme="@android:style/Theme.Holo" />
<CheckBox
...
android:theme="@android:style/Theme.Holo.Light" />
The first CheckBox
is styled as if used in a dark theme, the second as if in a light theme, regardless of the actual theme set to your activity or application.
Of course you should no longer be using the Holo theme, but instead use Material.
I think TrungTN and anon's answer is okay, but MartinStettner's way of implementing the hex() function is not really simple, and too dark, considering hex << (int)mychar is already a workaround.
here is my solution to make "<<" operator easier:
#include <sstream>
#include <iomanip>
string uchar2hex(unsigned char inchar)
{
ostringstream oss (ostringstream::out);
oss << setw(2) << setfill('0') << hex << (int)(inchar);
return oss.str();
}
int main()
{
unsigned char a = 131;
std::cout << uchar2hex(a) << std::endl;
}
It's just not worthy implementing a stream operator :-)
To enable use bind()
method
$("#id").bind("click",eventhandler);
call this handler
function eventhandler(){
alert("Bind click")
}
To disable click useunbind()
$("#id").unbind("click");
The lookup module of ansible works fine for me. The yml is:
- hosts: test
vars:
time: "{{ lookup('pipe', 'date -d \"1 day ago\" +\"%Y%m%d\"') }}"
You can replace any command with date to get result of the command.
On MVC 5 is quite similar
@Html.ActionLink("LinkText", "ActionName", new { id = "id" })
If you are explicitly calling time.sleep()
as part of your thread (say polling some external service), an improvement upon Phillipe's method is to use the timeout in the event
's wait()
method wherever you sleep()
For example:
import threading
class KillableThread(threading.Thread):
def __init__(self, sleep_interval=1):
super().__init__()
self._kill = threading.Event()
self._interval = sleep_interval
def run(self):
while True:
print("Do Something")
# If no kill signal is set, sleep for the interval,
# If kill signal comes in while sleeping, immediately
# wake up and handle
is_killed = self._kill.wait(self._interval)
if is_killed:
break
print("Killing Thread")
def kill(self):
self._kill.set()
Then to run it
t = KillableThread(sleep_interval=5)
t.start()
# Every 5 seconds it prints:
#: Do Something
t.kill()
#: Killing Thread
The advantage of using wait()
instead of sleep()
ing and regularly checking the event is that you can program in longer intervals of sleep, the thread is stopped almost immediately (when you would otherwise be sleep()
ing) and in my opinion, the code for handling exit is significantly simpler.
You can't selectively escape %
, as %
always has a special meaning depending on the following character.
In the documentation of Python, at the bottem of the second table in that section, it states:
'%' No argument is converted, results in a '%' character in the result.
Therefore you should use:
selectiveEscape = "Print percent %% in sentence and not %s" % (test, )
(please note the expicit change to tuple as argument to %
)
Without knowing about the above, I would have done:
selectiveEscape = "Print percent %s in sentence and not %s" % ('%', test)
with the knowledge you obviously already had.
Ruby is v2.0 now. Programs like Jekyll (and I am sure many others) require it. I just ran:
sudo apt-get install ruby2.0
check version
ruby --version
Hope that helps
try
{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(c.getContentResolver() , Uri.parse(paths));
}
catch (Exception e)
{
//handle exception
}
and yes path must be in a format of like this
file:///mnt/sdcard/filename.jpg
Or by using DBI
s sqlRownamesToColumn
library(DBI)
sqlRownamesToColumn(df)
You can use [weak self] or [unowned self] in the capture list prior to your parameters of the block. The capture list is optional syntax.
[unowned self]
works good here because the cell will never be nil. Otherwise you can use [weak self]
As others said, class variables are shared between a given class and its subclasses. Class instance variables belong to exactly one class; its subclasses are separate.
Why does this behavior exist? Well, everything in Ruby is an object—even classes. That means that each class has an object of the class Class
(or rather, a subclass of Class
) corresponding to it. (When you say class Foo
, you're really declaring a constant Foo
and assigning a class object to it.) And every Ruby object can have instance variables, so class objects can have instance variables, too.
The trouble is, instance variables on class objects don't really behave the way you usually want class variables to behave. You usually want a class variable defined in a superclass to be shared with its subclasses, but that's not how instance variables work—the subclass has its own class object, and that class object has its own instance variables. So they introduced separate class variables with the behavior you're more likely to want.
In other words, class instance variables are sort of an accident of Ruby's design. You probably shouldn't use them unless you specifically know they're what you're looking for.
None of the above was my solution: in my case the issue is that [ApiController] was not added to the controller so it is giving Null value
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController] // This was my problem, make sure that it is there!
public class OrderController : Controller
...
Another option is
Private Sub Worksheet_Change(ByVal Target As Range)
IF Target.Address = "$D$2" Then
MsgBox("Cell D2 Has Changed.")
End If
End Sub
I believe this uses fewer resources than Intersect
, which will be helpful if your worksheet changes a lot.
var yearStart = 2000;
var yearEnd = 2040;
var arr = [];
for (var i = yearStart; i <= yearEnd; i++) {
arr.push(i);
}
I had the same issue and I resolved it with MySQL workbench, as shown in the attached screenshot:
Hope that helps!
Antti Sykäri's algorithm is nice and short. I initially made a variation that replaced JavaScript's Math.random
when you call Math.seed(s)
, but then Jason commented that returning the function would be better:
Math.seed = function(s) {
return function() {
s = Math.sin(s) * 10000; return s - Math.floor(s);
};
};
// usage:
var random1 = Math.seed(42);
var random2 = Math.seed(random1());
Math.random = Math.seed(random2());
This gives you another functionality that JavaScript doesn't have: multiple independent random generators. That is especially important if you want to have multiple repeatable simulations running at the same time.
Some time has passed since this question was asked (and answered) but another option is to override the Accept header on the server during request processing using a MessageHandler as below:
public class ForceableContentTypeDelegationHandler : DelegatingHandler
{
protected async override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
var someOtherCondition = false;
var accHeader = request.Headers.GetValues("Accept").FirstOrDefault();
if (someOtherCondition && accHeader.Contains("application/xml"))
{
request.Headers.Remove("Accept");
request.Headers.Add("Accept", "application/json");
}
return await base.SendAsync(request, cancellationToken);
}
}
Where someOtherCondition
can be anything including browser type, etc. This would be for conditional cases where only sometimes do we want to override the default content negotiation. Otherwise as per other answers, you would simply remove an unnecessary formatter from the configuration.
You'll need to register it of course. You can either do this globally:
public static void Register(HttpConfiguration config) {
config.MessageHandlers.Add(new ForceableContentTypeDelegationHandler());
}
or on a route by route basis:
config.Routes.MapHttpRoute(
name: "SpecialContentRoute",
routeTemplate: "api/someUrlThatNeedsSpecialTreatment/{id}",
defaults: new { controller = "SpecialTreatment" id = RouteParameter.Optional },
constraints: null,
handler: new ForceableContentTypeDelegationHandler()
);
And since this is a message handler it will run on both the request and response ends of the pipeline much like an HttpModule
. So you could easily acknowledge the override with a custom header:
public class ForceableContentTypeDelegationHandler : DelegatingHandler
{
protected async override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
var wasForced = false;
var someOtherCondition = false;
var accHeader = request.Headers.GetValues("Accept").FirstOrDefault();
if (someOtherCondition && accHeader.Contains("application/xml"))
{
request.Headers.Remove("Accept");
request.Headers.Add("Accept", "application/json");
wasForced = true;
}
var response = await base.SendAsync(request, cancellationToken);
if (wasForced){
response.Headers.Add("X-ForcedContent", "We overrode your content prefs, sorry");
}
return response;
}
}
@Stephen Paul continuation...
ngOnDestroy
(ed) when the modal is exited.Why?
In some cases you might not want to modal to retain its status after having been closed, but rather restored to the initial state.
Original modal issue
Passing the content straightforward into the view actually generates initializes it even before the modal gets it. The modal doesn't have a way to kill such content even if using a *ngIf
wrapper.
Solution
ng-template
. ng-template
doesn't render until ordered to do so.
my-component.module.ts
...
imports: [
...
ModalModule
]
my-component.ts
<button (click)="reuseModal.open()">Open</button>
<app-modal #reuseModal>
<ng-template #header></ng-template>
<ng-template #body>
<app-my-body-component>
<!-- This component will be created only when modal is visible and will be destroyed when it's not. -->
</app-my-body-content>
<ng-template #footer></ng-template>
</app-modal>
modal.component.ts
export class ModalComponent ... {
@ContentChild('header') header: TemplateRef<any>;
@ContentChild('body') body: TemplateRef<any>;
@ContentChild('footer') footer: TemplateRef<any>;
...
}
modal.component.html
<div ... *ngIf="visible">
...
<div class="modal-body">
ng-container *ngTemplateOutlet="body"></ng-container>
</div>
References
I have to say that it wouldn't have been possible without the excellent official and community documentation around the net. It might help some of you too to understand better how ng-template
, *ngTemplateOutlet
and @ContentChild
work.
https://angular.io/api/common/NgTemplateOutlet
https://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/
https://medium.com/claritydesignsystem/ng-content-the-hidden-docs-96a29d70d11b
https://netbasal.com/understanding-viewchildren-contentchildren-and-querylist-in-angular-896b0c689f6e
https://netbasal.com/understanding-viewchildren-contentchildren-and-querylist-in-angular-896b0c689f6e
modal.component.html
<div
(click)="onContainerClicked($event)"
class="modal fade"
tabindex="-1"
[ngClass]="{'in': visibleAnimate}"
[ngStyle]="{'display': visible ? 'block' : 'none', 'opacity': visibleAnimate ? 1 : 0}"
*ngIf="visible">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<ng-container *ngTemplateOutlet="header"></ng-container>
<button class="close" data-dismiss="modal" type="button" aria-label="Close" (click)="close()">×</button>
</div>
<div class="modal-body">
<ng-container *ngTemplateOutlet="body"></ng-container>
</div>
<div class="modal-footer">
<ng-container *ngTemplateOutlet="footer"></ng-container>
</div>
</div>
</div>
</div>
modal.component.ts
/**
* @Stephen Paul https://stackoverflow.com/a/40144809/2013580
* @zurfyx https://stackoverflow.com/a/46949848/2013580
*/
import { Component, OnDestroy, ContentChild, TemplateRef } from '@angular/core';
@Component({
selector: 'app-modal',
templateUrl: 'modal.component.html',
styleUrls: ['modal.component.scss'],
})
export class ModalComponent implements OnDestroy {
@ContentChild('header') header: TemplateRef<any>;
@ContentChild('body') body: TemplateRef<any>;
@ContentChild('footer') footer: TemplateRef<any>;
public visible = false;
public visibleAnimate = false;
ngOnDestroy() {
// Prevent modal from not executing its closing actions if the user navigated away (for example,
// through a link).
this.close();
}
open(): void {
document.body.style.overflow = 'hidden';
this.visible = true;
setTimeout(() => this.visibleAnimate = true, 200);
}
close(): void {
document.body.style.overflow = 'auto';
this.visibleAnimate = false;
setTimeout(() => this.visible = false, 100);
}
onContainerClicked(event: MouseEvent): void {
if ((<HTMLElement>event.target).classList.contains('modal')) {
this.close();
}
}
}
modal.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ModalComponent } from './modal.component';
@NgModule({
imports: [
CommonModule,
],
exports: [ModalComponent],
declarations: [ModalComponent],
providers: [],
})
export class ModalModule { }
Use either
&dquo; <div>&dquo;"+ title +@"&dquo;</div>
or escape the double quote:
\" <div>\""+ title +@"\"</div>
//Javascript file 1
localStorage.setItem('Data',10);
//Javascript file 2
var number=localStorage.getItem('Data');
Don't forget to link your JS files in html :)
The __init__.py
file makes Python treat directories containing it as modules.
Furthermore, this is the first file to be loaded in a module, so you can use it to execute code that you want to run each time a module is loaded, or specify the submodules to be exported.
You can download the wheel corresponding to your configuration here ("Pillow-4.1.1-cp36-cp36m-win_amd64.whl" in your case) and install it with:
pip install some-package.whl
If you have problem to install the wheel read this answer
This is another way to do it. I think maybe a little more general:
df.ix[:,-1]
If you log in a web application using tomcat add:
-Djava.util.logging.ConsoleHandler.formatter = org.apache.juli.OneLineFormatter
On VM arguments
To check on elasticsearch cluster health you need to use
curl localhost:9200/_cat/health
More on the cat APIs here.
I usually use elasticsearch-head plugin to visualize that.
You can find it's github project here.
It's easy to install sudo $ES_HOME/bin/plugin -i mobz/elasticsearch-head
and then you can open localhost:9200/_plugin/head/
in your web brower.
You should have something that looks like this :
Yes... The first parameter of the RAISERROR function needs an NVARCHAR variable. So try the following;
-- Replace PRINT function
DECLARE @strMsg NVARCHAR(100)
SELECT @strMsg = 'Here''s your message...'
RAISERROR (@strMsg, 0, 1) WITH NOWAIT
OR
RAISERROR (n'Here''s your message...', 0, 1) WITH NOWAIT
Late resurrection.
Your query seems very similar to the one at page 259 of the book Pro JPA 2: Mastering the Java Persistence API, which in JPQL reads:
SELECT e
FROM Employee e
WHERE e IN (SELECT emp
FROM Project p JOIN p.employees emp
WHERE p.name = :project)
Using EclipseLink + H2 database, I couldn't get neither the book's JPQL nor the respective criteria working. For this particular problem I have found that if you reference the id directly instead of letting the persistence provider figure it out everything works as expected:
SELECT e
FROM Employee e
WHERE e.id IN (SELECT emp.id
FROM Project p JOIN p.employees emp
WHERE p.name = :project)
Finally, in order to address your question, here is an equivalent strongly typed criteria query that works:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Employee> c = cb.createQuery(Employee.class);
Root<Employee> emp = c.from(Employee.class);
Subquery<Integer> sq = c.subquery(Integer.class);
Root<Project> project = sq.from(Project.class);
Join<Project, Employee> sqEmp = project.join(Project_.employees);
sq.select(sqEmp.get(Employee_.id)).where(
cb.equal(project.get(Project_.name),
cb.parameter(String.class, "project")));
c.select(emp).where(
cb.in(emp.get(Employee_.id)).value(sq));
TypedQuery<Employee> q = em.createQuery(c);
q.setParameter("project", projectName); // projectName is a String
List<Employee> employees = q.getResultList();
You have to rely on '#' but to make the task easier in vi you can perform the following (press escape first):
:10,20 s/^/#
with 10 and 20 being the start and end line numbers of the lines you want to comment out
and to undo when you are complete:
:10,20 s/^#//
The []-operator is resolved to the access property this[sometype index]
, with implementation depending upon the Element-Collection.
An Enumerable-Interface declares a blueprint of what a Collection should look like in the first place.
Take this example to demonstrate the usefulness of clean Interface separation:
var ienu = "13;37".Split(';').Select(int.Parse);
//provides an WhereSelectArrayIterator
var inta = "13;37".Split(';').Select(int.Parse).ToArray()[0];
//>13
//inta.GetType(): System.Int32
Also look at the syntax of the []-operator:
//example
public class SomeCollection{
public SomeCollection(){}
private bool[] bools;
public bool this[int index] {
get {
if ( index < 0 || index >= bools.Length ){
//... Out of range index Exception
}
return bools[index];
}
set {
bools[index] = value;
}
}
//...
}
It is clear that tvi.header
is not a String
. The ==
is an operator that is overloaded by String
class, which means it will be working only if compiler knows that both side of the operator are String
.
Here's some code from Excel 2010 that may work. It has a couple specifics (like filtering bad-encode characters from titles) but it was designed to create multiple multi-series graphs from 4-dimensional data having both absolute and percentage-based data. Modify it how you like:
Sub createAllGraphs()
Const chartWidth As Integer = 260
Const chartHeight As Integer = 200
If Sheets.Count = 1 Then
Sheets.Add , Sheets(1)
Sheets(2).Name = "AllCharts"
ElseIf Sheets("AllCharts").ChartObjects.Count > 0 Then
Sheets("AllCharts").ChartObjects.Delete
End If
Dim c As Variant
Dim c2 As Variant
Dim cs As Object
Set cs = Sheets("AllCharts")
Dim s As Object
Set s = Sheets(1)
Dim i As Integer
Dim chartX As Integer
Dim chartY As Integer
Dim r As Integer
r = 2
Dim curA As String
curA = s.Range("A" & r)
Dim curB As String
Dim curC As String
Dim startR As Integer
startR = 2
Dim lastTime As Boolean
lastTime = False
Do While s.Range("A" & r) <> ""
If curC <> s.Range("C" & r) Then
If r <> 2 Then
seriesAdd:
c.SeriesCollection.Add s.Range("D" & startR & ":E" & (r - 1)), , False, True
c.SeriesCollection(c.SeriesCollection.Count).Name = Replace(s.Range("C" & startR), "Â", "")
c.SeriesCollection(c.SeriesCollection.Count).XValues = "='" & s.Name & "'!$D$" & startR & ":$D$" & (r - 1)
c.SeriesCollection(c.SeriesCollection.Count).Values = "='" & s.Name & "'!$E$" & startR & ":$E$" & (r - 1)
c.SeriesCollection(c.SeriesCollection.Count).HasErrorBars = True
c.SeriesCollection(c.SeriesCollection.Count).ErrorBars.Select
c.SeriesCollection(c.SeriesCollection.Count).ErrorBar Direction:=xlY, Include:=xlBoth, Type:=xlCustom, Amount:="='" & s.Name & "'!$F$" & startR & ":$F$" & (r - 1), minusvalues:="='" & s.Name & "'!$F$" & startR & ":$F$" & (r - 1)
c.SeriesCollection(c.SeriesCollection.Count).ErrorBar Direction:=xlX, Include:=xlBoth, Type:=xlFixedValue, Amount:=0
c2.SeriesCollection.Add s.Range("D" & startR & ":D" & (r - 1) & ",G" & startR & ":G" & (r - 1)), , False, True
c2.SeriesCollection(c2.SeriesCollection.Count).Name = Replace(s.Range("C" & startR), "Â", "")
c2.SeriesCollection(c2.SeriesCollection.Count).XValues = "='" & s.Name & "'!$D$" & startR & ":$D$" & (r - 1)
c2.SeriesCollection(c2.SeriesCollection.Count).Values = "='" & s.Name & "'!$G$" & startR & ":$G$" & (r - 1)
c2.SeriesCollection(c2.SeriesCollection.Count).HasErrorBars = True
c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBars.Select
c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBar Direction:=xlY, Include:=xlBoth, Type:=xlCustom, Amount:="='" & s.Name & "'!$H$" & startR & ":$H$" & (r - 1), minusvalues:="='" & s.Name & "'!$H$" & startR & ":$H$" & (r - 1)
c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBar Direction:=xlX, Include:=xlBoth, Type:=xlFixedValue, Amount:=0
If lastTime = True Then GoTo postLoop
End If
If curB <> s.Range("B" & r).Value Then
If curA <> s.Range("A" & r).Value Then
chartX = chartX + chartWidth * 2
chartY = 0
curA = s.Range("A" & r)
End If
Set c = cs.ChartObjects.Add(chartX, chartY, chartWidth, chartHeight)
Set c = c.Chart
c.ChartWizard , xlXYScatterSmooth, , , , , True, Replace(s.Range("B" & r), "Â", "") & " " & s.Range("A" & r), s.Range("D1"), s.Range("E1")
Set c2 = cs.ChartObjects.Add(chartX + chartWidth, chartY, chartWidth, chartHeight)
Set c2 = c2.Chart
c2.ChartWizard , xlXYScatterSmooth, , , , , True, Replace(s.Range("B" & r), "Â", "") & " " & s.Range("A" & r) & " (%)", s.Range("D1"), s.Range("G1")
chartY = chartY + chartHeight
curB = s.Range("B" & r)
curC = s.Range("C" & r)
End If
curC = s.Range("C" & r)
startR = r
End If
If s.Range("A" & r) <> "" Then oneMoreTime = False ' end the loop for real this time
r = r + 1
Loop
lastTime = True
GoTo seriesAdd
postLoop:
cs.Activate
End Sub
You might be using a windows or linux computer where you have not logged into git hub so the certificate is not verified. From the sytem where you are getting error login to github with the credential then try to use the command it will work . Good Luck
Could use sprintf
to accomplish this:
awk '{str = sprintf("%s %s", $1, $2)} END {print str}' file
the "problem view" mentioned in previous answers was helpful, but i saw it didn't catch all the errors in project. After running application, it began populating other classes that had issues but didn't appear at first in that problems view.
The accepted answer by @kevinsa5 is correct, but you might be thinking "I swear this code used to work and now it doesn't," and you would be right.
There was an API change in the MySQLdb library between 1.2.3 and 1.2.5. The 1.2.3 versions supported
cursor.execute("SELECT * FROM foo WHERE bar = %s", 'baz')
but the 1.2.5 versions require
cursor.execute("SELECT * FROM foo WHERE bar = %s", ['baz'])
as the other answers state. I can't find the change in the changelogs, and it's possible the earlier behavior was considered a bug.
The Ubuntu 14.04 repository has python-mysqldb 1.2.3, but Ubuntu 16.04 and later have python-mysqldb 1.3.7+.
If you're dealing with a legacy codebase that requires the old behavior but your platform is a newish Ubuntu, install MySQLdb from PyPI instead:
$ pip install MySQL-python==1.2.3
I think you are putting one too many curly brackets. Try this
@if($user->status=='waiting')
<td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{!! $user->travel_id !!}" data-toggle="modal" data-target="#myModal">Approve/Reject</a> </td>
@else
<td>{!! $user->status !!}</td>
@endif
The simplest is using the OpenCV Mat class:
img=cv::Scalar(blue_value, green_value, red_value);
where img
was defined as a cv::Mat
.
Do you mean that the date range of the selected rows should not lie fully within the specified date range? In which case:
select *
from test_table
where start_date < date '2009-12-15'
or end_date > date '2010-01-02';
(Syntax above is for Oracle, yours may differ slightly).
Even though this is much later than the request, it might help others. Docmosis provides a Java API for creating documents in doc,pdf,odt format using documents as templates. It uses OpenOffice as the engine to perform the format conversions. Document manipulation and population is performed by Docmosis itself.
If you mean the screen where you have that interpreter prompt >>>
you can do CTRL+L on Bash shell can help. Windows does not have equivalent. You can do
import os
os.system('cls') # on windows
or
os.system('clear') # on linux / os x
Semantically, you use <p>
tags to indicate paragraphs. <span>
is used to apply CSS style and/or class(es) to an arbitrary section of text and inline elements.
You can set protocol versions in system property as :
overcome ssl handshake error
System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
I use Eclipse Indigo, and this is how I do it:
Window > Preferences > Startup and Shutdown > Workspaces
check box at the top of the window: "Prompt for workspace on startup"
class() exactly works like Javascript's typeof operator.
To get more details about variables you can use whos command or whos() function.
Here is the example code executed on MATLAB R2017a's Command Window.
>> % Define a number
>> num = 67
num =
67
>> % Get type of variable num
>> class(num)
ans =
'double'
>> % Define character vector
>> myName = 'Rishikesh Agrawani'
myName =
'Rishikesh Agrwani'
>> % Check type of myName
>> class(myName)
ans =
'char'
>> % Define a cell array
>> cellArr = {'This ', 'is ', 'a ', 'big chance to learn ', 'MATLAB.'}; % Cell array
>>
>> class(cellArr)
ans =
'cell'
>> % Get more details including type
>> whos num
Name Size Bytes Class Attributes
num 1x1 8 double
>> whos myName
Name Size Bytes Class Attributes
myName 1x17 34 char
>> whos cellArr
Name Size Bytes Class Attributes
cellArr 1x5 634 cell
>> % Another way to use whos i.e using whos(char_vector)
>> whos('cellArr')
Name Size Bytes Class Attributes
cellArr 1x5 634 cell
>> whos('num')
Name Size Bytes Class Attributes
num 1x1 8 double
>> whos('myName')
Name Size Bytes Class Attributes
myName 1x17 34 char
>>
No need to go to external links, everything you need is located on your computer already:
Android\android-sdk\platforms\android-x\data\res\layout.
Source code for all android layouts are located here.
i set the fields to not null and problem solved, it updates when an information is commanded to store in it, no more showing msqli message that the field was empty cus you didnt insert value to it, well application of this solution can work on some projects depends on your project structure.
You can use title
attribute.
<img src="smiley.gif" title="Smiley face"/>
You can change the source of image as you want.
And as @Gray commented:
You can also use the title
on other things like <a ...
anchors, <p>
, <div>
, <input>
, etc.
See: this
Sadly I found the vim plugin mentioned not to be working with iTerm2 3.0.15 (to be fair I don't know if this broke on older versions) - but I found this hack instead.
Map command-p to do the paste and using iTerm2 vim keys. Obviously this only works for iTerm2.
How it works. I use "jk" to enter escape mode so you will also need:
:inoremap jk
in your .vimrc.
Then it just invokes P to enter paste mode, "+p to paste from the clipboard and then P to disable paste mode. hth.
A solution for the stripped white space in SET /P:
the trick is that backspace char which you can summon in the text editor EDIT for DOS. To create it in EDIT press ctrlP+ctrlH. I would paste it here but this webpage can't display it. It's visible on Notepad though (it's werid, like a small black rectangle with a white circle in the center)
So you write this:
<nul set /p=.9 Hello everyone
The dot can be any char, it's only there to tell SET /P that the text starts there, before the spaces, and not at the "Hello". The "9" is a representation of the backspace char that I can't display here. You have to put it instead of the 9, and it will delete the "." , after which you'll get this:
Hello Everyone
instead of:
Hello Everyone
I hope it helps
I would instead write a helper bash script that runs svn commit
on all the files you need to and none of the ones you don't. This way you have much more control.
For example, with one line, you can commit all files with extension .h
and .cpp
to which you made changes (and which wouldn't cause a conflict):
svn commit -m "" `svn status | grep "^M.*[h|cpp]$" | awk '{print $2}' | tr "\\n" " "`
Change / add extensions to the [h|cpp]
part. Add a log message in between the quotes of -m ""
if needed.
<div class="post_category">
<?php $category = get_the_category();
$allcategory = get_the_category();
foreach ($allcategory as $category) {
?>
<a class="btn"><?php echo $category->cat_name;; ?></a>
<?php
}
?>
</div>
I assume you want the PDF to display in the browser, rather than forcing a download. If that is the case, try setting the Content-Disposition
header with a value of inline
.
Also remember that this will also be affected by browser settings - some browsers may be configured to always download PDF files or open them in a different application (e.g. Adobe Reader)
You can use the transpose
function from the data.table
library. Simple and fast solution that keeps numeric
values as numeric
.
library(data.table)
# get data
data("mtcars")
# transpose
t_mtcars <- transpose(mtcars)
# get row and colnames in order
colnames(t_mtcars) <- rownames(mtcars)
rownames(t_mtcars) <- colnames(mtcars)
Using round
:
>>> numvar = 135.12345678910
>>> str(round(numvar, 9))
'135.123456789'
In Visual Studio 2012, open the Options dialog (Tools -> Options). Under Environment -> General, the first setting is "Color theme." You can use this to switch between Light and Dark.
The shell theme is distinct from the editor theme--you can use any editor fonts and colors settings with either shell theme.
There is also a Color Theme Editor extension that can be used to create new themes.
You have a recent presentation "Monadologie -- professional help on type anxiety" by Christopher League (July 12th, 2010), which is quite interesting on topics of continuation and monad.
The video going with this (slideshare) presentation is actually available at vimeo.
The Monad part start around 37 minutes in, on this one hour video, and starts with slide 42 of its 58 slide presentation.
It is presented as "the leading design pattern for functional programming", but the language used in the examples is Scala, which is both OOP and functional.
You can read more on Monad in Scala in the blog post "Monads - Another way to abstract computations in Scala", from Debasish Ghosh (March 27, 2008).
A type constructor M is a monad if it supports these operations:
# the return function
def unit[A] (x: A): M[A]
# called "bind" in Haskell
def flatMap[A,B] (m: M[A]) (f: A => M[B]): M[B]
# Other two can be written in term of the first two:
def map[A,B] (m: M[A]) (f: A => B): M[B] =
flatMap(m){ x => unit(f(x)) }
def andThen[A,B] (ma: M[A]) (mb: M[B]): M[B] =
flatMap(ma){ x => mb }
So for instance (in Scala):
Option
is a monaddef unit[A] (x: A): Option[A] = Some(x) def flatMap[A,B](m:Option[A])(f:A =>Option[B]): Option[B] = m match { case None => None case Some(x) => f(x) }
List
is Monaddef unit[A] (x: A): List[A] = List(x) def flatMap[A,B](m:List[A])(f:A =>List[B]): List[B] = m match { case Nil => Nil case x::xs => f(x) ::: flatMap(xs)(f) }
Monad are a big deal in Scala because of convenient syntax built to take advantage of Monad structures:
for
comprehension in Scala:
for {
i <- 1 to 4
j <- 1 to i
k <- 1 to j
} yield i*j*k
is translated by the compiler to:
(1 to 4).flatMap { i =>
(1 to i).flatMap { j =>
(1 to j).map { k =>
i*j*k }}}
The key abstraction is the flatMap
, which binds the computation through chaining.
Each invocation of flatMap
returns the same data structure type (but of different value), that serves as the input to the next command in chain.
In the above snippet, flatMap takes as input a closure (SomeType) => List[AnotherType]
and returns a List[AnotherType]
. The important point to note is that all flatMaps take the same closure type as input and return the same type as output.
This is what "binds" the computation thread - every item of the sequence in the for-comprehension has to honor this same type constraint.
If you take two operations (that may fail) and pass the result to the third, like:
lookupVenue: String => Option[Venue]
getLoggedInUser: SessionID => Option[User]
reserveTable: (Venue, User) => Option[ConfNo]
but without taking advantage of Monad, you get convoluted OOP-code like:
val user = getLoggedInUser(session)
val confirm =
if(!user.isDefined) None
else lookupVenue(name) match {
case None => None
case Some(venue) =>
val confno = reserveTable(venue, user.get)
if(confno.isDefined)
mailTo(confno.get, user.get)
confno
}
whereas with Monad, you can work with the actual types (Venue
, User
) like all the operations work, and keep the Option verification stuff hidden, all because of the flatmaps of the for syntax:
val confirm = for {
venue <- lookupVenue(name)
user <- getLoggedInUser(session)
confno <- reserveTable(venue, user)
} yield {
mailTo(confno, user)
confno
}
The yield part will only be executed if all three functions have Some[X]
; any None
would directly be returned to confirm
.
So:
Monads allow ordered computation within Functional Programing, that allows us to model sequencing of actions in a nice structured form, somewhat like a DSL.
And the greatest power comes with the ability to compose monads that serve different purposes, into extensible abstractions within an application.
This sequencing and threading of actions by a monad is done by the language compiler that does the transformation through the magic of closures.
By the way, Monad is not only model of computation used in FP:
Category theory proposes many models of computation. Among them
- the Arrow model of computations
- the Monad model of computations
- the Applicative model of computations
The concept of POD and the type trait std::is_pod
will be deprecated in C++20. See this question for further information.
It is confirmed that Windows 7 and newer versions (at least 64bit or both) do not use system speaker and instead they route the call to the default sound device.
So, using system.beep()
in win7/8/10 will not produce sound using internal system speaker. Instead, you'll get a beep sound from external speakers if they are available.
you can use ClearContents. ex,
Range("X").Cells.ClearContents
Use @Kristian Antonsen's answer, or you can use:
$('button').click(function() {
preventDefault();
captureForm();
});
try this method
$("your id or class name").css({ 'margin-top': '18px' });
The problem for me turned out to be pretty obscure. My class looked like this:
//-----------------------------------------
// libbase.h
class base {
public:
base() { }
virtual ~base() { }
virtual int foo() { return 0; }
};
//-----------------------------------------
//-----------------------------------------
// libbase.cpp
#include "libbase.h"
//-----------------------------------------
//-----------------------------------------
// main.h
class derived : public base {
public:
virtual int foo() ;
};
//-----------------------------------------
//-----------------------------------------
// main.cpp
int main () {
derived d;
}
//-----------------------------------------
The problem is in the linker. My header file went in a library somewhere, but all the virtual functions were declared 'inline' in the class declaration. Since there was no code using the virtual functions (yet), the compiler or linker neglected to put actual function bodies in place. It also failed to create the vtable.
In my main code where I derived from this class, the linker tried to connect my class to the base class and his vtable. But the vtable had been discarded.
The solution was to declare at least one of the virtual functions' bodies outside the class declaration, like this:
//-----------------------------------------
// libbase.h
class base {
public:
base() { }
virtual ~base() ; //-- No longer declared 'inline'
virtual int foo() { return 0; }
};
//-----------------------------------------
//-----------------------------------------
// libbase.cpp
#include "libbase.h"
base::~base()
{
}
//-----------------------------------------
The Excel number for a modern date is most easily calculated as the number of days since 12/30/1899 on the Gregorian calendar.
Excel treats the mythical date 01/00/1900 (i.e., 12/31/1899) as corresponding to 0, and incorrectly treats year 1900 as a leap year. So for dates before 03/01/1900, the Excel number is effectively the number of days after 12/31/1899.
However, Excel will not format any number below 0 (-1 gives you ##########) and so this only matters for "01/00/1900" to 02/28/1900, making it easier to just use the 12/30/1899 date as a base.
A complete function in DB2 SQL that accounts for the leap year 1900 error:
SELECT
DAYS(INPUT_DATE)
- DAYS(DATE('1899-12-30'))
- CASE
WHEN INPUT_DATE < DATE('1900-03-01')
THEN 1
ELSE 0
END
Sorry, the short answer is no. CSS (2.1) will only mark up the elements of a DOM, not their attributes. You'd have to apply a specific class to each input.
Bummer I know, because that would be incredibly useful.
I know you've said you'd prefer CSS over JavaScript, but you should still consider using jQuery. It provides a very clean and elegant way of adding styles to DOM elements based on attributes.
I will add a StackBlitz example and a comment to the answer from @tahiche.
The return value is a function to remove the event listener after you have added it. It is considered good practice to remove event listeners when you don't need them anymore. So you can store this return value and call it inside your ngOnDestroy
method.
I admit that it might seem confusing at first, but it is actually a very useful feature. How else can you clean up after yourself?
export class MyComponent implements OnInit, OnDestroy {
public removeEventListener: () => void;
constructor(
private renderer: Renderer2,
private elementRef: ElementRef
) {
}
public ngOnInit() {
this.removeEventListener = this.renderer.listen(this.elementRef.nativeElement, 'click', (event) => {
if (event.target instanceof HTMLAnchorElement) {
// Prevent opening anchors the default way
event.preventDefault();
// Your custom anchor click event handler
this.handleAnchorClick(event);
}
});
}
public ngOnDestroy() {
this.removeEventListener();
}
}
You can find a StackBlitz here to show how this could work for catching clicking on anchor elements.
I added a body with an image as follows:
<img src="x" onerror="alert(1)"></div>
to show that the sanitizer is doing its job.
Here in this fiddle you find the same body attached to an innerHTML
without sanitizing it and it will demonstrate the issue.
The last update for "windows git" did move the git.exe file from the /bin folder to the /cmd folder. So, to use git with IDEs such as webStorm or Android Studio you can use the path :
C:\Users\<user>\AppData\Local\GitHub\PortableGit_<..numbers..>\cmd\git.exe
But if you want to have linux-like commands such as git, ssh, ls, cp under windows powerShell or cmd add to your windows PATH variables :
C:\Users\<user>\AppData\Local\GitHub\PortableGit_<...numbers...>\usr\bin
change <user> and <...numbers...> to your values and reboot!
Also, you will have to update this everytime git updates since it might change the portable folder name. If folder structure changes I will update this post.
Thx @dennisschagt for the comment above! ;)
I'm using below excel file url: https://github.com/inventorbala/Sample-Excel-files/blob/master/sample-excel-files.xlsx
Output:
Array
(
[0] => Array
(
[store_id] => 3716
[employee_uid] => 664368
[opus_id] => zh901j
[item_description] => PRE ATT $75 PNLS 90EXP
[opus_transaction_date] => 2019-10-18
[opus_transaction_num] => X2MBV1DJKSLQW
[opus_invoice_num] => O3716IN3409
[customer_name] => BILL PHILLIPS
[mobile_num] => 4052380136
[opus_amount] => 75
[rq4_amount] => 0
[difference] => -75
[ocomment] => Re-Upload: We need RQ4 transaction for October. If you're unable to provide the October invoice, it will be counted as EPin shortage.
[mark_delete] => 0
[upload_date] => 2019-10-20
)
[1] => Array
(
[store_id] => 2710
[employee_uid] => 75899
[opus_id] => dc288t
[item_description] => PRE ATT $50 PNLS 90EXP
[opus_transaction_date] => 2019-10-18
[opus_transaction_num] => XJ90419JKT9R9
[opus_invoice_num] => M2710IN868
[customer_name] => CALEB MENDEZ
[mobile_num] => 6517672079
[opus_amount] => 50
[rq4_amount] => 0
[difference] => -50
[ocomment] => No Response. Re-Upload
[mark_delete] => 0
[upload_date] => 2019-10-20
)
[2] => Array
(
[store_id] => 0136
[employee_uid] => 70167
[opus_id] => fv766x
[item_description] => PRE ATT $50 PNLS 90EXP
[opus_transaction_date] => 2019-10-18
[opus_transaction_num] => XQ57316JKST1V
[opus_invoice_num] => GONZABP25622
[customer_name] => FAUSTINA CASTILLO
[mobile_num] => 8302638628
[opus_amount] => 100
[rq4_amount] => 50
[difference] => -50
[ocomment] => Re-Upload: We have been charged in opus for $100. Provide RQ4 invoice number for remaining amount
[mark_delete] => 0
[upload_date] => 2019-10-20
)
[3] => Array
(
[store_id] => 3264
[employee_uid] => 23723
[opus_id] => aa297h
[item_description] => PRE ATT $25 PNLS 90EXP
[opus_transaction_date] => 2019-10-19
[opus_transaction_num] => XR1181HJKW9MP
[opus_invoice_num] => C3264IN1588
[customer_name] => SOPHAT VANN
[mobile_num] => 9494668372
[opus_amount] => 70
[rq4_amount] => 25
[difference] => -45
[ocomment] => No Response. Re-Upload
[mark_delete] => 0
[upload_date] => 2019-10-20
)
[4] => Array
(
[store_id] => 4166
[employee_uid] => 568494
[opus_id] => ab7598
[item_description] => PRE ATT $40 RTR
[opus_transaction_date] => 2019-10-20
[opus_transaction_num] => X8F58P3JL2RFU
[opus_invoice_num] => I4166IN2481
[customer_name] => KELLY MC GUIRE
[mobile_num] => 6189468180
[opus_amount] => 40
[rq4_amount] => 0
[difference] => -40
[ocomment] => Re-Upload: The invoice number that you provided (I4166IN2481) belongs to September transaction. We need RQ4 transaction for October. If you're unable to provide the October invoice, it will be counted as EPin shortage.
[mark_delete] => 0
[upload_date] => 2019-10-21
)
[5] => Array
(
[store_id] => 4508
[employee_uid] => 552502
[opus_id] => ec850x
[item_description] => $30 RTR
[opus_transaction_date] => 2019-10-20
[opus_transaction_num] => XPL7M1BJL1W5D
[opus_invoice_num] => M4508IN6024
[customer_name] => PREPAID CUSTOMER
[mobile_num] => 6019109730
[opus_amount] => 30
[rq4_amount] => 0
[difference] => -30
[ocomment] => Re-Upload: The invoice number you provided (M4508IN7217) belongs to a different phone number. We need RQ4 transaction for the phone number in question. If you're unable to provide the RQ4 invoice for this transaction, it will be counted as EPin shortage.
[mark_delete] => 0
[upload_date] => 2019-10-21
)
[6] => Array
(
[store_id] => 3904
[employee_uid] => 35818
[opus_id] => tj539j
[item_description] => PRE $45 PAYG PINLESS REFILL
[opus_transaction_date] => 2019-10-20
[opus_transaction_num] => XM1PZQSJL215F
[opus_invoice_num] => N3904IN1410
[customer_name] => DORTHY JONES
[mobile_num] => 3365982631
[opus_amount] => 90
[rq4_amount] => 45
[difference] => -45
[ocomment] => Re-Upload: Please email the details to Treasury and confirm
[mark_delete] => 0
[upload_date] => 2019-10-21
)
[7] => Array
(
[store_id] => 1820
[employee_uid] => 59883
[opus_id] => cb9406
[item_description] => PRE ATT $25 PNLS 90EXP
[opus_transaction_date] => 2019-10-20
[opus_transaction_num] => XTBJO14JL25OE
[opus_invoice_num] => SEVIEIN19013
[customer_name] => RON NELSON
[mobile_num] => 8653821076
[opus_amount] => 25
[rq4_amount] => 5
[difference] => -20
[ocomment] => Re-Upload: We have been charged in opus for $25. Provide RQ4 invoice number for remaining amount
[mark_delete] => 0
[upload_date] => 2019-10-21
)
[8] => Array
(
[store_id] => 0178
[employee_uid] => 572547
[opus_id] => ms5674
[item_description] => PRE $45 PAYG PINLESS REFILL
[opus_transaction_date] => 2019-10-21
[opus_transaction_num] => XT29916JL4S69
[opus_invoice_num] => T0178BP1590
[customer_name] => GABRIEL LONGORIA JR
[mobile_num] => 4322133450
[opus_amount] => 45
[rq4_amount] => 0
[difference] => -45
[ocomment] => Re-Upload: Please email the details to Treasury and confirm
[mark_delete] => 0
[upload_date] => 2019-10-22
)
[9] => Array
(
[store_id] => 2180
[employee_uid] => 7842
[opus_id] => lm854y
[item_description] => $30 RTR
[opus_transaction_date] => 2019-10-21
[opus_transaction_num] => XC9U712JL4LA4
[opus_invoice_num] => KETERIN1836
[customer_name] => PETE JABLONSKI
[mobile_num] => 9374092680
[opus_amount] => 30
[rq4_amount] => 40
[difference] => 10
[ocomment] => Re-Upload: Credit the remaining balance to customers account in OPUS and email confirmation to Treasury
[mark_delete] => 0
[upload_date] => 2019-10-22
)
.
.
.
[63] => Array
(
[store_id] => 0175
[employee_uid] => 33738
[opus_id] => ph5953
[item_description] => PRE ATT $40 RTR
[opus_transaction_date] => 2019-10-21
[opus_transaction_num] => XE5N31DJL51RA
[opus_invoice_num] => T0175IN4563
[customer_name] => WILLIE TAYLOR
[mobile_num] => 6822701188
[opus_amount] => 40
[rq4_amount] => 50
[difference] => 10
[ocomment] => Re-Upload: Credit the remaining balance to customers account in OPUS and email confirmation to Treasury
[mark_delete] => 0
[upload_date] => 2019-10-22
)
)
There's a pretty good write up in the Adobe KB's on 'wmode' and other attributes with regards to their effect on presentation and performance.
From bytes docs:
Accordingly, constructor arguments are interpreted as for bytearray().
Then, from bytearray docs:
The optional source parameter can be used to initialize the array in a few different ways:
- If it is an integer, the array will have that size and will be initialized with null bytes.
Note, that differs from 2.x (where x >= 6) behavior, where bytes
is simply str
:
>>> bytes is str
True
The 2.6 str differs from 3.0’s bytes type in various ways; most notably, the constructor is completely different.
The way to do this is via the bracket notation.
var test = {_x000D_
"id": "109",_x000D_
"No. of interfaces": "4"_x000D_
}_x000D_
alert(test["No. of interfaces"]);
_x000D_
For more info read out here:
You can get param from request.
@ResponseBody
public ResponseEntity<Boolean> saveData(HttpServletRequest request,
HttpServletResponse response, Model model){
String jsonString = request.getParameter("json");
}
Today (2.5 years after this answer) you can safely use Array.forEach
. As @ricosrealm suggests, decodeURIComponent
was used in this function.
function getJsonFromUrl(url) {
if(!url) url = location.search;
var query = url.substr(1);
var result = {};
query.split("&").forEach(function(part) {
var item = part.split("=");
result[item[0]] = decodeURIComponent(item[1]);
});
return result;
}
actually it's not that simple, see the peer-review in the comments, especially:
=
(@AndrewF)+
(added by me)For further details, see MDN article and RFC 3986.
Maybe this should go to codereview SE, but here is safer and regexp-free code:
function getJsonFromUrl(url) {
if(!url) url = location.href;
var question = url.indexOf("?");
var hash = url.indexOf("#");
if(hash==-1 && question==-1) return {};
if(hash==-1) hash = url.length;
var query = question==-1 || hash==question+1 ? url.substring(hash) :
url.substring(question+1,hash);
var result = {};
query.split("&").forEach(function(part) {
if(!part) return;
part = part.split("+").join(" "); // replace every + with space, regexp-free version
var eq = part.indexOf("=");
var key = eq>-1 ? part.substr(0,eq) : part;
var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
var from = key.indexOf("[");
if(from==-1) result[decodeURIComponent(key)] = val;
else {
var to = key.indexOf("]",from);
var index = decodeURIComponent(key.substring(from+1,to));
key = decodeURIComponent(key.substring(0,from));
if(!result[key]) result[key] = [];
if(!index) result[key].push(val);
else result[key][index] = val;
}
});
return result;
}
This function can parse even URLs like
var url = "?foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c";
// {"foo e": ["a a", "c", "[x]":"b"]}
var obj = getJsonFromUrl(url)["foo e"];
for(var key in obj) { // Array.forEach would skip string keys here
console.log(key,":",obj[key]);
}
/*
0 : a a
1 : c
[x] : b
*/
If your HTML is well-formed, you can easily employ an XML parser to do the job for you... If you're only reading, SAX would be ideal.
You are just creating your array incorrectly. You could use http_build_query:
$fields = array(
'username' => "annonymous",
'api_key' => urlencode("1234"),
'images' => array(
urlencode(base64_encode('image1')),
urlencode(base64_encode('image2'))
)
);
$fields_string = http_build_query($fields);
So, the entire code that you could use would be:
<?php
//extract data from the post
extract($_POST);
//set POST variables
$url = 'http://api.example.com/api';
$fields = array(
'username' => "annonymous",
'api_key' => urlencode("1234"),
'images' => array(
urlencode(base64_encode('image1')),
urlencode(base64_encode('image2'))
)
);
//url-ify the data for the POST
$fields_string = http_build_query($fields);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
echo $result;
//close connection
curl_close($ch);
?>
Open a new worksheet on the related instance (Alt-F10)
and run the following query
SELECT view_name, owner
FROM sys.all_views
ORDER BY owner, view_name
A bit more universal <select name="env" style="width: 200px; position:absolute;" onchange="this.nextElementSibling.value=this.value">_x000D_
<option></option>_x000D_
<option>1</option>_x000D_
<option>2</option>_x000D_
<option>3</option> _x000D_
</select>_x000D_
<input style="width: 178px; margin-top: 1px; border: none; position:relative; left:1px; margin-right: 25px;" value="123456789012345678901234"/>layout ...
_x000D_
In your Component you can add .class to your host element if you would have some general styles that you want to apply.
export class MyComponent{
@HostBinding('class') classes = 'classA classB';
CompressFormat is too slow...
Try ByteBuffer.
???Bitmap to byte???
width = bitmap.getWidth();
height = bitmap.getHeight();
int size = bitmap.getRowBytes() * bitmap.getHeight();
ByteBuffer byteBuffer = ByteBuffer.allocate(size);
bitmap.copyPixelsToBuffer(byteBuffer);
byteArray = byteBuffer.array();
???byte to bitmap???
Bitmap.Config configBmp = Bitmap.Config.valueOf(bitmap.getConfig().name());
Bitmap bitmap_tmp = Bitmap.createBitmap(width, height, configBmp);
ByteBuffer buffer = ByteBuffer.wrap(byteArray);
bitmap_tmp.copyPixelsFromBuffer(buffer);
You can use the onChange property. Something like:
<select onChange="window.location.href=this.value">
<option value="www.google.com">A</option>
<option value="www.aol.com">B</option>
</select>
there's a better way
# Larger example
rows = [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
('2006-04-06', 'SELL', 'IBM', 500, 53.00)]
c.executemany('insert into stocks values (?,?,?,?,?)', rows)
connection.commit()
It you can live with a fixed size, arrays will will be faster and need less memory.
If you need the flexibility of the List interface with adding and removing elements, the question remains which implementation you should choose. Often ArrayList is recommended and used for any case, but also ArrayList has its performance problems if elements at the beginning or in the middle of the list must be removed or inserted.
You therefore may want to have a look at http://java.dzone.com/articles/gaplist-%E2%80%93-lightning-fast-list which introduces GapList. This new list implementation combines the strengths of both ArrayList and LinkedList resulting in very good performance for nearly all operations.
Here's another way:
Option Explicit
' Just a little test stub.
Sub Tester()
Dim pList(500) As Integer
Dim i As Integer
For i = 0 To UBound(pList)
pList(i) = 500 - i
Next i
MsgBox "Value 18 is at array position " & FindInArray(pList, 18) & "."
MsgBox "Value 217 is at array position " & FindInArray(pList, 217) & "."
MsgBox "Value 1001 is at array position " & FindInArray(pList, 1001) & "."
End Sub
Function FindInArray(pList() As Integer, value As Integer)
Dim i As Integer
Dim FoundValueLocation As Integer
FoundValueLocation = -1
For i = 0 To UBound(pList)
If pList(i) = value Then
FoundValueLocation = i
Exit For
End If
Next i
FindInArray = FoundValueLocation
End Function
The 2020 answer: it probably doesn't matter
The best answer here was from 2012, so I decided to test for myself. On Chrome for Android, the JS and CSS resources are downloaded in parallel and I could not detect a difference in page rendering speed.
I included a more detailed writeup on my blog
Simplest way to find used view or stored procedure for the tableName using below query -
exec dbo.dbsearch 'Your_Table_Name'
/Using the Internal Regex used in creating the "new EmailAddressAttribute();" component in .Net4.5 >>> using System.ComponentModel.DataAnnotations; //To Validate an Email Address......Tested and Working.
public bool IsEmail(string email)
{
if (String.IsNullOrEmpty(email))
{ return false; }
try
{
Regex _regex = new Regex("^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])" +
"+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)" +
"((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|" +
"[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\u" +
"FDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|" +
"(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|" +
"[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900" +
"-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFF" +
"EF])))\\.?$", RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture | RegexOptions.Compiled);
return _regex.IsMatch(email);
}
catch (RegexMatchTimeoutException)
{
return false;
}
}
Also, You can use this:
http://msdn.microsoft.com/en-us/library/01escwtf(v=vs.110).aspx
Is Nothing requires an object that has been assigned to the value Nothing. IsNothing() can take any variable that has not been initialized, including of numeric type. This is useful for example when testing if an optional parameter has been passed.
I use this with good results:
border-style:hidden;
It also works for:
border-right-style:hidden; /*if you want to hide just a border on a cell*/
Example:
<style type="text/css">_x000D_
table, th, td {_x000D_
border: 2px solid green;_x000D_
}_x000D_
tr.hide_right > td, td.hide_right{_x000D_
border-right-style:hidden;_x000D_
}_x000D_
tr.hide_all > td, td.hide_all{_x000D_
border-style:hidden;_x000D_
}_x000D_
}_x000D_
</style>_x000D_
<table>_x000D_
<tr>_x000D_
<td class="hide_right">11</td>_x000D_
<td>12</td>_x000D_
<td class="hide_all">13</td>_x000D_
</tr>_x000D_
<tr class="hide_right">_x000D_
<td>21</td>_x000D_
<td>22</td>_x000D_
<td>23</td>_x000D_
</tr>_x000D_
<tr class="hide_all">_x000D_
<td>31</td>_x000D_
<td>32</td>_x000D_
<td>33</td>_x000D_
</tr>_x000D_
</table>
_x000D_
HTML
<table cellspacing="0">
<tr class="top bottom row">
<td>one one</td>
<td>one two</td>
</tr>
<tr class="top bottom row">
<td>two one</td>
<td>two two</td>
</tr>
<tr class="top bottom row">
<td>three one</td>
<td>three two</td>
</tr>
</table>?
CSS:
tr.top td { border-top: thin solid black; }
tr.bottom td { border-bottom: thin solid black; }
tr.row td:first-child { border-left: thin solid black; }
tr.row td:last-child { border-right: thin solid black; }?
There is a lack of answers for windows users. Here is how I solved this issue.
First add the PostgreSQL bin folder into the path variable like this
set PATH=%PATH%;C:\Program Files\PostgreSQL\11\bin
Substitute \11\
with your version of Postgres
next run
pip install pyscopg2
this at least got me to a compiling error.
Update: it looks to be an issue with the psycopg2 library and it’s dependencies not playing nice with python 3.8. https://github.com/psycopg/psycopg2/issues/990
SO thread 'Multiply two arrays element wise, where one of the arrays has arrays as elements' has an example of constructing an array from arrays. If the subarrays are the same size, numpy makes a 2d array. But if they differ in length, it makes an array with dtype=object
, and the subarrays retain their identity.
Following that, you could do something like this:
In [5]: result=np.array([np.zeros((1)),np.zeros((2))])
In [6]: result
Out[6]: array([array([ 0.]), array([ 0., 0.])], dtype=object)
In [7]: np.append([result[0]],[1,2])
Out[7]: array([ 0., 1., 2.])
In [8]: result[0]
Out[8]: array([ 0.])
In [9]: result[0]=np.append([result[0]],[1,2])
In [10]: result
Out[10]: array([array([ 0., 1., 2.]), array([ 0., 0.])], dtype=object)
However, I don't offhand see what advantages this has over a pure Python list or lists. It does not work like a 2d array. For example I have to use result[0][1]
, not result[0,1]
. If the subarrays are all the same length, I have to use np.array(result.tolist())
to produce a 2d array.
This can also help you by showing full details of the error on a client's browser.
<system.web>
<customErrors mode="Off"/>
</system.web>
<system.webServer>
<httpErrors errorMode="Detailed" />
</system.webServer>
Here are categories for NSArray and NSDictionary to make this super-easy. I've added an option for pretty-print (newlines and tabs to make easier to read).
@interface NSDictionary (BVJSONString)
-(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint;
@end
.
@implementation NSDictionary (BVJSONString)
-(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self
options:(NSJSONWritingOptions) (prettyPrint ? NSJSONWritingPrettyPrinted : 0)
error:&error];
if (! jsonData) {
NSLog(@"%s: error: %@", __func__, error.localizedDescription);
return @"{}";
} else {
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
}
@end
.
@interface NSArray (BVJSONString)
- (NSString *)bv_jsonStringWithPrettyPrint:(BOOL)prettyPrint;
@end
.
@implementation NSArray (BVJSONString)
-(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self
options:(NSJSONWritingOptions) (prettyPrint ? NSJSONWritingPrettyPrinted : 0)
error:&error];
if (! jsonData) {
NSLog(@"%s: error: %@", __func__, error.localizedDescription);
return @"[]";
} else {
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
}
@end
@RequestBody : Annotation indicating a method parameter should be bound to the body of the HTTP request.
For example:
@RequestMapping(path = "/something", method = RequestMethod.PUT)
public void handle(@RequestBody String body, Writer writer) throws IOException {
writer.write(body);
}
@ResponseBody annotation can be put on a method and indicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpreted as a view name).
For example:
@RequestMapping(path = "/something", method = RequestMethod.PUT)
public @ResponseBody String helloWorld() {
return "Hello World";
}
Alternatively, we can use @RestController annotation in place of @Controller
annotation. This will remove the need to using @ResponseBody
.
You can create multiple workspaces in Eclipse. You have to just specify the path of the workspace during Eclipse startup. You can even switch workspaces via File?Switch workspace.
You can then import project to your workspace, copy paste project to your new workspace folder, then
File?Import?Existing project in to workspace?select project.
QFile file("bigimage.jpg");
if (file.open(QIODevice::ReadOnly))
{
QByteArray fileData = file.readAll();
QByteArray hashData = QCryptographicHash::hash(fileData,QCryptographicHash::Md5); // or QCryptographicHash::Sha1
qDebug() << hashData.toHex(); // 0e0c2180dfd784dd84423b00af86e2fc
}
You should pass @item.email
in quotes then it will be treated as string argument
<td><a href ="#" onclick="Getinfo('@item.email');" >6/16/2016 2:02:29 AM</a> </td>
Otherwise, it is treated as variable thus error is generated.
select one.*, two.meal
from table1 as one
left join table2 as two
on (one.weddingtable = two.weddingtable and one.tableseat = two.tableseat)
Nirsoft's NirCMD can create shortcuts from a command line, too. (Along with a pile of other functions.) Free and available here:
http://www.nirsoft.net/utils/nircmd.html
Full instructions here: http://www.nirsoft.net/utils/nircmd2.html#using (Scroll down to the "shortcut" section.)
Yes, using nircmd does mean you are using another 3rd-party .exe, but it can do some functions not in (most of) the above solutions (e.g., pick a icon # in a dll with multiple icons, assign a hot-key, and set the shortcut target to be minimized or maximized).
Though it appears that the shortcutjs.bat solution above can do most of that, too, but you'll need to dig more to find how to properly assign those settings. Nircmd is probably simpler.
I am using lambda with Zappa; I am sending data with POST in json format:
My code for basic_lambda_pure.py is:
import time
import requests
import json
def my_handler(event, context):
print("Received event: " + json.dumps(event, indent=2))
print("Log stream name:", context.log_stream_name)
print("Log group name:", context.log_group_name)
print("Request ID:", context.aws_request_id)
print("Mem. limits(MB):", context.memory_limit_in_mb)
# Code will execute quickly, so we add a 1 second intentional delay so you can see that in time remaining value.
print("Time remaining (MS):", context.get_remaining_time_in_millis())
if event["httpMethod"] == "GET":
hub_mode = event["queryStringParameters"]["hub.mode"]
hub_challenge = event["queryStringParameters"]["hub.challenge"]
hub_verify_token = event["queryStringParameters"]["hub.verify_token"]
return {'statusCode': '200', 'body': hub_challenge, 'headers': 'Content-Type': 'application/json'}}
if event["httpMethod"] == "post":
token = "xxxx"
params = {
"access_token": token
}
headers = {
"Content-Type": "application/json"
}
_data = {"recipient": {"id": 1459299024159359}}
_data.update({"message": {"text": "text"}})
data = json.dumps(_data)
r = requests.post("https://graph.facebook.com/v2.9/me/messages",params=params, headers=headers, data=data, timeout=2)
return {'statusCode': '200', 'body': "ok", 'headers': {'Content-Type': 'application/json'}}
I got the next json response:
{
"resource": "/",
"path": "/",
"httpMethod": "POST",
"headers": {
"Accept": "*/*",
"Accept-Encoding": "deflate, gzip",
"CloudFront-Forwarded-Proto": "https",
"CloudFront-Is-Desktop-Viewer": "true",
"CloudFront-Is-Mobile-Viewer": "false",
"CloudFront-Is-SmartTV-Viewer": "false",
"CloudFront-Is-Tablet-Viewer": "false",
"CloudFront-Viewer-Country": "US",
"Content-Type": "application/json",
"Host": "ox53v9d8ug.execute-api.us-east-1.amazonaws.com",
"Via": "1.1 f1836a6a7245cc3f6e190d259a0d9273.cloudfront.net (CloudFront)",
"X-Amz-Cf-Id": "LVcBZU-YqklHty7Ii3NRFOqVXJJEr7xXQdxAtFP46tMewFpJsQlD2Q==",
"X-Amzn-Trace-Id": "Root=1-59ec25c6-1018575e4483a16666d6f5c5",
"X-Forwarded-For": "69.171.225.87, 52.46.17.84",
"X-Forwarded-Port": "443",
"X-Forwarded-Proto": "https",
"X-Hub-Signature": "sha1=10504e2878e56ea6776dfbeae807de263772e9f2"
},
"queryStringParameters": null,
"pathParameters": null,
"stageVariables": null,
"requestContext": {
"path": "/dev",
"accountId": "001513791584",
"resourceId": "i6d2tyihx7",
"stage": "dev",
"requestId": "d58c5804-b6e5-11e7-8761-a9efcf8a8121",
"identity": {
"cognitoIdentityPoolId": null,
"accountId": null,
"cognitoIdentityId": null,
"caller": null,
"apiKey": "",
"sourceIp": "69.171.225.87",
"accessKey": null,
"cognitoAuthenticationType": null,
"cognitoAuthenticationProvider": null,
"userArn": null,
"userAgent": null,
"user": null
},
"resourcePath": "/",
"httpMethod": "POST",
"apiId": "ox53v9d8ug"
},
"body": "eyJvYmplY3QiOiJwYWdlIiwiZW50cnkiOlt7ImlkIjoiMTA3OTk2NDk2NTUxMDM1IiwidGltZSI6MTUwODY0ODM5MDE5NCwibWVzc2FnaW5nIjpbeyJzZW5kZXIiOnsiaWQiOiIxNDAzMDY4MDI5ODExODY1In0sInJlY2lwaWVudCI6eyJpZCI6IjEwNzk5NjQ5NjU1MTAzNSJ9LCJ0aW1lc3RhbXAiOjE1MDg2NDgzODk1NTUsIm1lc3NhZ2UiOnsibWlkIjoibWlkLiRjQUFBNHo5RmFDckJsYzdqVHMxZlFuT1daNXFaQyIsInNlcSI6MTY0MDAsInRleHQiOiJob2xhIn19XX1dfQ==",
"isBase64Encoded": true
}
my data was on body key, but is code64 encoded, How can I know this? I saw the key isBase64Encoded
I copy the value for body key and decode with This tool and "eureka", I get the values.
I hope this help you. :)
So all in one line:
var checkedItemsAsString = $('[id*="checkbox"]:checked').map(function() { return $(this).val().toString(); } ).get().join(",");
..a note about the selector [id*="checkbox"]
, it will grab any item with the string "checkbox" in it. A bit clumsy here, but really good if you are trying to pull the selected values out of something like a .NET CheckBoxList. In that case "checkbox" would be the name that you gave the CheckBoxList control.
Adding my two cents here since I have not seen an answer that uses the option "Build with parameters" in Jenkins.
Here I am using Jenkins CI browser console for project starwars_api and I was able to build directly with "Build with parameters" with value refs/tags/tag-name
To analyze two arrays (array1 and array2) they need to meet the following two requirements:
1) They need to be a numpy.ndarray
Check with
type(array1)
# and
type(array2)
If that is not the case for at least one of them perform
array1 = numpy.ndarray(array1)
# or
array2 = numpy.ndarray(array2)
2) The dimensions need to be as follows:
array1.shape #shall give (N, 1)
array2.shape #shall give (N,)
N is the number of items that are in the array. To provide array1 with the right number of axes perform:
array1 = array1[:, numpy.newaxis]
Another easy way to do it so that it is referenced in the project folder you want, like "Frameworks", is to:
It will appear in both the project navigator where you want it, as well as in the "Link Binary With Libraries" area of the "Build Phases" pane of your target.
I'd use a static constructor on the class that sets the value of a static readonly array.
public class SomeClass
{
public readonly MyStruct[] myArray;
public static SomeClass()
{
myArray = { {"foo", "bar"},
{"boo", "far"}};
}
}
You can use a FileReader
object to read text file here is example code:
<div id="page-wrapper">
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
<script>
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}
</script>
Here is the codepen demo
If you have a fixed file to read every time your application load then you can use this code :
<script>
var fileDisplayArea = document.getElementById('fileDisplayArea');
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
fileDisplayArea.innerText = allText
}
}
}
rawFile.send(null);
}
readTextFile("file:///C:/your/path/to/file.txt");
</script>
You can Use Online Css link To set Style over existing content.
For That you have to load data in webview and enable JavaScript Support.
See Below Code:
WebSettings webSettings=web_desc.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDefaultTextEncodingName("utf-8");
webSettings.setTextZoom(55);
StringBuilder sb = new StringBuilder();
sb.append("<HTML><HEAD><LINK href=\" http://yourStyleshitDomain.com/css/mbl-view-content.css\" type=\"text/css\" rel=\"stylesheet\"/></HEAD><body>");
sb.append(currentHomeContent.getDescription());
sb.append("</body></HTML>");
currentWebView.loadDataWithBaseURL("file:///android_asset/", sb.toString(), "text/html", "utf-8", null);
Here Use StringBuilder to append String for Style.
sb.append("<HTML><HEAD><LINK href=\" http://yourStyleshitDomain.com/css/mbl-view-content.css\" type=\"text/css\" rel=\"stylesheet\"/></HEAD><body>");
sb.append(currentHomeContent.getDescription());
"Chrome violations" don't represent errors in either Chrome or your own web app. They are instead warnings to help you improve your app. In this case, Long running JavaScript
and took 83ms of runtime
are alerting you there's probably an opportunity to speed up your script.
("Violation" is not the best terminology; it's used here to imply the script "violates" a pre-defined guideline, but "warning" or similar would be clearer. These messages first appeared in Chrome in early 2017 and should ideally have a "More info" prompt to elaborate on the meaning and give suggested actions to the developer. Hopefully those will be added in the future.)
The C and C++ declaration syntax has repeatedly been described as a failed experiment, by the original designers.
Instead, let's name the type “pointer to Type
”; I’ll call it Ptr_
:
template< class Type >
using Ptr_ = Type*;
Now Ptr_<char>
is a pointer to char
.
Ptr_<const char>
is a pointer to const char
.
And const Ptr_<const char>
is a const
pointer to const char
.
There.
Don't fart around with inserting spaces. For one, older versions of IE won't know what you're talking about. Besides that, though, there are cleaner ways in general.
For colorless indents, use the text-indent
property.
p { text-indent: 1em; }
Edit:
If you want the space to be colored, you might consider adding a thick left border to the first letter. (I'd almost-but-not-quite say "instead", because the indent can be an issue if you use both. But it feels dirty to me to rely solely on the border to indent.) You can specify how far away, and how wide, the color is using the first letter's left margin/padding/border width.
p:first-letter { border-left: 1em solid red; }
Case where []
notation is helpful :
If your object is dynamic and there could be some random values in keys like number
and []
or any other special character, for example -
var a = { 1 : 3 };
Now if you try to access in like a.1
it will through an error, because it is expecting an string over there.
TL;DR ...and late to the party, but that short explanation might help future googlers..
In general that error message means that the replacement doesn't fit into the corresponding column of the dataframe.
A minimal example:
df <- data.frame(a = 1:2); df$a <- 1:3
throws the error
Error in
$<-.data.frame
(*tmp*
, a, value = 1:3) : replacement has 3 rows, data has 2
which is clear, because the vector a
of df
has 2 entries (rows) whilst the vector we try to replace it has 3 entries (rows).
Or you use the trick from PHP Debug to console.
First you need a little PHP helper function
function debug_to_console($data) {
$output = $data;
if (is_array($output))
$output = implode(',', $output);
echo "<script>console.log('Debug Objects: " . $output . "' );</script>";
}
Then you can use it like this:
debug_to_console("Test");
This will create an output like this:
Debug Objects: Test
Many ways this can be achieved.
Simple approach should be taking Substring
of an input string.
var result = input.Substring(input.Length - 3);
Another approach using Regular Expression
to extract last 3 characters.
var result = Regex.Match(input,@"(.{3})\s*$");
Working Demo
For mine I did it by setting the div's max width, hence for small widget won't get affected and the large widget is resized due to the max-width style.
// assuming your widget class is "widget"
.widget {
max-width: 100%;
height: auto;
}
We can use replace
to change the values in 'mpg' to NA
that corresponds to cyl==4
.
mtcars %>%
mutate(mpg=replace(mpg, cyl==4, NA)) %>%
as.data.frame()
Try this:
DateTime Date = DateTime.Now.AddHours(-DateTime.Now.Hour).AddMinutes(-DateTime.Now.Minute)
.AddSeconds(-DateTime.Now.Second);
Output will be like:
07/29/2015 00:00:00
public SmartSaverCals(Context context)
{
this.context= context;
}
add public to Your constructor.in my case problem solved
Do you mean that for a select element with an id of "next" you need to perform some specific script?
$("#next").change(function(){
//enter code here
});
I had the same problem and after a little research I decided the best would be to read MachineGuid
in registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography
, as @Agnus suggested. It is generated during OS installation and won't change unless you make another fresh OS install. Depending on the OS version it may contain the network adapter MAC address embedded (plus some other numbers, including random), or a pseudorandom number, the later for newer OS versions (after XP SP2, I believe, but not sure). If it's a pseudorandom theoretically it can be forged - if two machines have the same initial state, including real time clock. In practice, this will be rare, but be aware if you expect it to be a base for security that can be attacked by hardcore hackers.
Of course a registry entry can also be easily changed by anyone to forge a machine GUID, but what I found is that this would disrupt normal operation of so many components of Windows that in most cases no regular user would do it (again, watch out for hardcore hackers).
If you are using bootstrap (I am using version 4.0), feel free to try the following code.
<input data-toggle="tooltip" data-placement="top" title="This is the text of the tooltip" value="44"/>
data-placement
can be top, right, bottom or left
I'm using zeroMQ. I wanted a simple message passing system and I don't need the complication of a broker. I also don't want a huge Java oriented enterprise system.
If you want a fast, simple system and you need to support multiple languages (I use C and .net) then I'd recommend looking at 0MQ.
you can do it so simple:
First: For Example in Models you have User.cs with this implementation
public class User
{
public string username { get; set; }
public string age { get; set; }
}
We are passing the empty model to user – This model would be filled with user’s data when he submits the form like this
public ActionResult Add()
{
var model = new User();
return View(model);
}
When you return the View by empty User as model, it maps with the structure of the form that you implemented. We have this on HTML side:
@model MyApp.Models.Student
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Student</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.username, htmlAttributes: new {
@class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.username, new {
htmlAttributes = new { @class = "form-
control" } })
@Html.ValidationMessageFor(model => model.userame, "",
new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.age, htmlAttributes: new { @class
= "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.age, new { htmlAttributes =
new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.age, "", new {
@class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default"
/>
</div>
</div>
</div>
}
So on button submit you will use it like this
[HttpPost]
public ActionResult Add(User user)
{
// now user.username has the value that user entered on form
}
The below simple solution worked for me.
<input type="text" class="fa" placeholder=" Search">
Use this filter for implement search: https://www.npmjs.com/package/ng2-search-filter
Your static method should go from:
public static class SimpleUsing
{
public static void DoUsing(Action<MyDataContext> action)
{
using (MyDataContext db = new MyDataContext())
action(db);
}
}
To:
public static class SimpleUsing
{
public static TResult DoUsing<TResult>(Func<MyDataContext, TResult> action)
{
using (MyDataContext db = new MyDataContext())
return action(db);
}
}
This answer grew out of comments so I could provide code. For a complete elaboration, please see @sll's answer below.
Any reason you're not just using a simple for...in
loop?
var sample = { a: 1 , b: 2 , c:3 };
var summed = 0;
for (var key in sample) {
summed += sample[key];
};
remove class hideByDefault. Div will remain hidden itself till value of myvalue is false.
def querySet_to_list(qs):
"""
this will return python list<dict>
"""
return [dict(q) for q in qs]
def get_answer_by_something(request):
ss = Answer.objects.filter(something).values()
querySet_to_list(ss) # python list return.(json-able)
this code convert django queryset to python list
OAuth
Used for delegated authorization
only -- meaning you are authorizing a third-party service access to use personal data, without giving out a password. Also OAuth "sessions" generally live longer than user sessions. Meaning that OAuth is designed to allow authorization
i.e. Flickr uses OAuth to allow third-party services to post and edit a persons picture on their behalf, without them having to give out their flicker username and password.
OpenID
Used to authenticate
single sign-on identity. All OpenID is supposed to do is allow an OpenID provider to prove that you say you are. However many sites use identity authentication to provide authorization (however the two can be separated out)
i.e. One shows their passport at the airport to authenticate (or prove) the person's who's name is on the ticket they are using is them.
Make sure that the attribute is primary key and Auto Incrementable in the database. Then map it into the data class with the annotation with @GeneratedValue
annotation using IDENTITY.
@Entity
@Table(name = "client")
data class Client(
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private val id: Int? = null
)
GL
To show how much fun it is to create some functions that are fail fast I've written the following 3 functions.
One creates an AES key, one encodes it and one decodes it back. These three methods can be used with Java 8 (without dependence of internal classes or outside dependencies):
public static SecretKey generateAESKey(int keysize)
throws InvalidParameterException {
try {
if (Cipher.getMaxAllowedKeyLength("AES") < keysize) {
// this may be an issue if unlimited crypto is not installed
throw new InvalidParameterException("Key size of " + keysize
+ " not supported in this runtime");
}
final KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(keysize);
return keyGen.generateKey();
} catch (final NoSuchAlgorithmException e) {
// AES functionality is a requirement for any Java SE runtime
throw new IllegalStateException(
"AES should always be present in a Java SE runtime", e);
}
}
public static SecretKey decodeBase64ToAESKey(final String encodedKey)
throws IllegalArgumentException {
try {
// throws IllegalArgumentException - if src is not in valid Base64
// scheme
final byte[] keyData = Base64.getDecoder().decode(encodedKey);
final int keysize = keyData.length * Byte.SIZE;
// this should be checked by a SecretKeyFactory, but that doesn't exist for AES
switch (keysize) {
case 128:
case 192:
case 256:
break;
default:
throw new IllegalArgumentException("Invalid key size for AES: " + keysize);
}
if (Cipher.getMaxAllowedKeyLength("AES") < keysize) {
// this may be an issue if unlimited crypto is not installed
throw new IllegalArgumentException("Key size of " + keysize
+ " not supported in this runtime");
}
// throws IllegalArgumentException - if key is empty
final SecretKeySpec aesKey = new SecretKeySpec(keyData, "AES");
return aesKey;
} catch (final NoSuchAlgorithmException e) {
// AES functionality is a requirement for any Java SE runtime
throw new IllegalStateException(
"AES should always be present in a Java SE runtime", e);
}
}
public static String encodeAESKeyToBase64(final SecretKey aesKey)
throws IllegalArgumentException {
if (!aesKey.getAlgorithm().equalsIgnoreCase("AES")) {
throw new IllegalArgumentException("Not an AES key");
}
final byte[] keyData = aesKey.getEncoded();
final String encodedKey = Base64.getEncoder().encodeToString(keyData);
return encodedKey;
}
The primary flag seems to only work for vagrant ssh
for me.
In the past I have used the following method to hack around the issue.
# stage box intended for configuration closely matching production if ARGV[1] == 'stage' config.vm.define "stage" do |stage| box_setup stage, \ "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml" end end
I think the quickest/neatest way to do this:
For each class have string[] obj.ToListViewItem()
method and then do this:
foreach(var item in personList)
{
listView1.Items.Add(new ListViewItem(item.ToListViewItem()));
}
Here is an example definition
public class Person
{
public string Name { get; set; }
public string Address { get; set; }
public DateTime DOB { get; set; }
public uint ID { get; set; }
public string[] ToListViewItem()
{
return new string[] {
ID.ToString("000000"),
Name,
Address,
DOB.ToShortDateString()
};
}
}
As an added bonus you can have a static
method that returns ColumnHeader[]
list for setting up the listview columns with
listView1.Columns.AddRange(Person.ListViewHeaders());
For example we have some entity Group.
For this entity we create the repository GroupRepository.
public interface GroupRepository extends JpaRepository<Group, Long> {
}
Then we need to create a service layer with which we will use this repository.
public interface Service<T, ID> {
T save(T entity);
void deleteById(ID id);
List<T> findAll();
T getOne(ID id);
T editEntity(T entity);
Optional<T> findById(ID id);
}
public abstract class AbstractService<T, ID, R extends JpaRepository<T, ID>> implements Service<T, ID> {
private final R repository;
protected AbstractService(R repository) {
this.repository = repository;
}
@Override
public T save(T entity) {
return repository.save(entity);
}
@Override
public void deleteById(ID id) {
repository.deleteById(id);
}
@Override
public List<T> findAll() {
return repository.findAll();
}
@Override
public T getOne(ID id) {
return repository.getOne(id);
}
@Override
public Optional<T> findById(ID id) {
return repository.findById(id);
}
@Override
public T editEntity(T entity) {
return repository.saveAndFlush(entity);
}
}
@org.springframework.stereotype.Service
public class GroupServiceImpl extends AbstractService<Group, Long, GroupRepository> {
private final GroupRepository groupRepository;
@Autowired
protected GroupServiceImpl(GroupRepository repository) {
super(repository);
this.groupRepository = repository;
}
}
And in the controller we use this service.
@RestController
@RequestMapping("/api")
class GroupController {
private final Logger log = LoggerFactory.getLogger(GroupController.class);
private final GroupServiceImpl groupService;
@Autowired
public GroupController(GroupServiceImpl groupService) {
this.groupService = groupService;
}
@GetMapping("/groups")
Collection<Group> groups() {
return groupService.findAll();
}
@GetMapping("/group/{id}")
ResponseEntity<?> getGroup(@PathVariable Long id) {
Optional<Group> group = groupService.findById(id);
return group.map(response -> ResponseEntity.ok().body(response))
.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
@PostMapping("/group")
ResponseEntity<Group> createGroup(@Valid @RequestBody Group group) throws URISyntaxException {
log.info("Request to create group: {}", group);
Group result = groupService.save(group);
return ResponseEntity.created(new URI("/api/group/" + result.getId()))
.body(result);
}
@PutMapping("/group")
ResponseEntity<Group> updateGroup(@Valid @RequestBody Group group) {
log.info("Request to update group: {}", group);
Group result = groupService.save(group);
return ResponseEntity.ok().body(result);
}
@DeleteMapping("/group/{id}")
public ResponseEntity<?> deleteGroup(@PathVariable Long id) {
log.info("Request to delete group: {}", id);
groupService.deleteById(id);
return ResponseEntity.ok().build();
}
}
Well, I understand this question is Visual Studio GUI related, but maybe the asker can try this trick also. Just giving a different perspective in solving this problem.
I like to use terminal a lot for GIT, so here are the simple steps:
Pre-requisites...
Now,
Don't create any file inside the repository. Keep it empty. Copy its URL. It should be something like https://github.com/Username/ProjectName.git
Open up the terminal and redirect to your Visual Studio Project directory
Configure your credentials
git config --global user.name "your_git_username"
git config --global user.email "your_git_email"
Then type these commands
git init
git add .
git commit -m "First Migration Commit"
git remote add origin paste_your_URL_here
git push -u origin master
Done...Hope this helps
in your css :
#txtComputer {
font-size: 24px;
}
You can style an input entirely (background, color, etc.) and even use the hover event.
All that Add/Remove Programs is really doing is reading this Registry key:
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall
Working from @o-o's answer this will give you back the string of the date according to a format string. You can easily add a 2 digit year regex for the year & milliseconds and the such if you need them.
Date.prototype.getFromFormat = function(format) {
var yyyy = this.getFullYear().toString();
format = format.replace(/yyyy/g, yyyy)
var mm = (this.getMonth()+1).toString();
format = format.replace(/mm/g, (mm[1]?mm:"0"+mm[0]));
var dd = this.getDate().toString();
format = format.replace(/dd/g, (dd[1]?dd:"0"+dd[0]));
var hh = this.getHours().toString();
format = format.replace(/hh/g, (hh[1]?hh:"0"+hh[0]));
var ii = this.getMinutes().toString();
format = format.replace(/ii/g, (ii[1]?ii:"0"+ii[0]));
var ss = this.getSeconds().toString();
format = format.replace(/ss/g, (ss[1]?ss:"0"+ss[0]));
return format;
};
d = new Date();
var date = d.getFromFormat('yyyy-mm-dd hh:ii:ss');
alert(date);
I don't know how efficient that is however, especially perf wise because it uses a lot of regex. It could probably use some work I do not master pure js.
For what is worth:
the closest integer to any given input as shown in the following table can be calculated using Math.ceil or Math.floor depending of the distance between the input and the next integer
+-------+--------+
| input | output |
+-------+--------+
| 1 | 0 |
| 2 | 0 |
| 3 | 5 |
| 4 | 5 |
| 5 | 5 |
| 6 | 5 |
| 7 | 5 |
| 8 | 10 |
| 9 | 10 |
+-------+--------+
private int roundClosest(final int i, final int k) {
int deic = (i % k);
if (deic <= (k / 2.0)) {
return (int) (Math.floor(i / (double) k) * k);
} else {
return (int) (Math.ceil(i / (double) k) * k);
}
}
I don´t know how to do it using code, but for those who don't mind using a plugin. This is a great one that works for me:
If your detached HEAD is a fast forward of master and you just want the commits upstream, you can
git push origin HEAD:master
to push directly, or
git checkout master && git merge [ref of HEAD]
will merge it back into your local master.
Try width:inherit
to make the image take the width of it's container <div>
. It will stretch/shrink it's height to maintain proportion. Don't set the height in the <div>
, it will size to fit the image height.
img {
width:inherit;
}
.item {
border:1px solid pink;
width: 120px;
float: left;
margin: 3px;
padding: 3px;
}
Disclaimer: my answer is in the context of rx.js - a 'reactive programming' library for Javascript.
In functional programming, instead of iterating through each item of a collection, you apply higher order functions (HoFs) to the collection itself. So the idea behind FRP is that instead of processing each individual event, create a stream of events (implemented with an observable*) and apply HoFs to that instead. This way you can visualize the system as data pipelines connecting publishers to subscribers.
The major advantages of using an observable are:
i) it abstracts away state from your code, e.g., if you want the event handler to get fired only for every 'n'th event, or stop firing after the first 'n' events, or start firing only after the first 'n' events, you can just use the HoFs (filter, takeUntil, skip respectively) instead of setting, updating and checking counters.
ii) it improves code locality - if you have 5 different event handlers changing the state of a component, you can merge their observables and define a single event handler on the merged observable instead, effectively combining 5 event handlers into 1. This makes it very easy to reason about what events in your entire system can affect a component, since it's all present in a single handler.
An Iterable is a lazily consumed sequence - each item is pulled by the iterator whenever it wants to use it, and hence the enumeration is driven by the consumer.
An observable is a lazily produced sequence - each item is pushed to the observer whenever it is added to the sequence, and hence the enumeration is driven by the producer.
You can use MarkerWithLabel with SVG icons.
Update: The Google Maps Javascript API v3 now natively supports multiple characters in the MarkerLabel
proof of concept fiddle (you didn't provide your icon, so I made one up)
Note: there is an issue with labels on overlapping markers that is addressed by this fix, credit to robd who brought it up in the comments.
code snippet:
function initMap() {_x000D_
var latLng = new google.maps.LatLng(49.47805, -123.84716);_x000D_
var homeLatLng = new google.maps.LatLng(49.47805, -123.84716);_x000D_
_x000D_
var map = new google.maps.Map(document.getElementById('map_canvas'), {_x000D_
zoom: 12,_x000D_
center: latLng,_x000D_
mapTypeId: google.maps.MapTypeId.ROADMAP_x000D_
});_x000D_
_x000D_
var marker = new MarkerWithLabel({_x000D_
position: homeLatLng,_x000D_
map: map,_x000D_
draggable: true,_x000D_
raiseOnDrag: true,_x000D_
labelContent: "ABCD",_x000D_
labelAnchor: new google.maps.Point(15, 65),_x000D_
labelClass: "labels", // the CSS class for the label_x000D_
labelInBackground: false,_x000D_
icon: pinSymbol('red')_x000D_
});_x000D_
_x000D_
var iw = new google.maps.InfoWindow({_x000D_
content: "Home For Sale"_x000D_
});_x000D_
google.maps.event.addListener(marker, "click", function(e) {_x000D_
iw.open(map, this);_x000D_
});_x000D_
}_x000D_
_x000D_
function pinSymbol(color) {_x000D_
return {_x000D_
path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',_x000D_
fillColor: color,_x000D_
fillOpacity: 1,_x000D_
strokeColor: '#000',_x000D_
strokeWeight: 2,_x000D_
scale: 2_x000D_
};_x000D_
}_x000D_
google.maps.event.addDomListener(window, 'load', initMap);
_x000D_
html,_x000D_
body,_x000D_
#map_canvas {_x000D_
height: 500px;_x000D_
width: 500px;_x000D_
margin: 0px;_x000D_
padding: 0px_x000D_
}_x000D_
.labels {_x000D_
color: white;_x000D_
background-color: red;_x000D_
font-family: "Lucida Grande", "Arial", sans-serif;_x000D_
font-size: 10px;_x000D_
text-align: center;_x000D_
width: 30px;_x000D_
white-space: nowrap;_x000D_
}
_x000D_
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry,places&ext=.js"></script>_x000D_
<script src="https://cdn.rawgit.com/googlemaps/v3-utility-library/master/markerwithlabel/src/markerwithlabel.js"></script>_x000D_
<div id="map_canvas" style="height: 400px; width: 100%;"></div>
_x000D_
kindly ensure that your dependencies in your package.json files are up to date. Try reinstalling them one at a time after also ensuring that your NPM is the latest version (up-to-date). It worked for me. I advise you to run npm install
for the packages(thats what worked in my own case after it refused to work because I added the dependencies manually).
I use Spring Boot, my solution to the problem was
"src/main/resources/myfile.extension"
Hope it helps someone.
The DataContractJSONSerializer will do everything for you with the same easy as the XMLSerializer. Its trivial to use this in a web app. If you are using WCF, you can specify its use with an attribute. The DataContractSerializer family is also very fast.
I would suspect that there can be as many as 2**32 -1
numbered match variables, on a 32-bit compiled Perl binary.
If you're able to connect to the database using mysql, but you get an error for mysqldump, then the problem may be that you lack privileges to lock the table.
Try the --single-transaction option in that case.
mysqldump -h database.example.com -u mydbuser -p mydatabase --single-transaction > /home/mylinuxuser/mydatabase.sql
I had faced a similar issue and this is what worked for me:
const flavorExists = await Flavors.findOne({
'flavor.name': { $regex: flavorName, $options: 'i' },
});
Your life will be much easier if you can save a List as the value instead of an array in that Map.
public static void Serialize(object value, Stream s)
{
using (StreamWriter writer = new StreamWriter(s))
using (JsonTextWriter jsonWriter = new JsonTextWriter(writer))
{
JsonSerializer ser = new JsonSerializer();
ser.Serialize(jsonWriter, value);
jsonWriter.Flush();
}
}
public static T Deserialize<T>(Stream s)
{
using (StreamReader reader = new StreamReader(s))
using (JsonTextReader jsonReader = new JsonTextReader(reader))
{
JsonSerializer ser = new JsonSerializer();
return ser.Deserialize<T>(jsonReader);
}
}
The dat file has some lines of extra information before the actual data. Skip them with the skip
argument:
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)
An easy way to check this if you are unfamiliar with the dataset is to first use readLines
to check a few lines, as below:
readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
n=10)
# [1] "Ozone data from CZ03 2009" "Local time: GMT + 0"
# [3] "" "Date Hour Value"
# [5] "01.01.2009 00:00 34.3" "01.01.2009 01:00 31.9"
# [7] "01.01.2009 02:00 29.9" "01.01.2009 03:00 28.5"
# [9] "01.01.2009 04:00 32.9" "01.01.2009 05:00 20.5"
Here, we can see that the actual data starts at [4]
, so we know to skip the first three lines.
If you really only wanted the Value
column, you could do that by:
as.vector(
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)$Value)
Again, readLines
is useful for helping us figure out the actual name of the columns we will be importing.
But I don't see much advantage to doing that over reading the whole dataset in and extracting later.
I've encountered this error when my Transaction is nested within another. Is it possible that the stored procedure declares its own transaction or that the calling function declares one?
The method you are looking for is .limit.
Returns a new Dataset by taking the first n rows. The difference between this function and head is that head returns an array while limit returns a new Dataset.
Example usage:
df.limit(1000)
Just need to add *
at the beginning of xpath and closing bracket at last.
element = findElement(By.xpath("//*[@test-id='test-username']"));
Read it in by row and then transpose it in the command line. If you're using Unix, install csvtool and follow the directions in: https://unix.stackexchange.com/a/314482/186237
Creating package.json using npm init solved my issue.
As per https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe, percentage values are no longer allowed. But the following worked for me
<iframe width="100%" height="this.height=window.innerHeight;" style="border:none" src=""></iframe>
Though width:100%
works, height:100%
does not work. So window.innerHeight
has been used. You can also use css pixels for height.
- Where does
user.id
go afterpassport.serializeUser
has been called?
The user id (you provide as the second argument of the done
function) is saved in the session and is later used to retrieve the whole object via the deserializeUser
function.
serializeUser
determines which data of the user object should be stored in the session. The result of the serializeUser method is attached to the session as req.session.passport.user = {}
. Here for instance, it would be (as we provide the user id as the key) req.session.passport.user = {id: 'xyz'}
- We are calling
passport.deserializeUser
right after it where does it fit in the workflow?
The first argument of deserializeUser
corresponds to the key of the user object that was given to the done
function (see 1.). So your whole object is retrieved with help of that key. That key here is the user id (key can be any key of the user object i.e. name,email etc).
In deserializeUser
that key is matched with the in memory array / database or any data resource.
The fetched object is attached to the request object as req.user
Visual Flow
passport.serializeUser(function(user, done) {
done(null, user.id);
}); ¦
¦
¦
+--------------------? saved to session
¦ req.session.passport.user = {id: '..'}
¦
?
passport.deserializeUser(function(id, done) {
+---------------+
¦
?
User.findById(id, function(err, user) {
done(err, user);
}); +--------------? user object attaches to the request as req.user
});
The line's color is defined by EditText
's background property. To change it you should change the android:background
in the layout file.
I should note that this style is achieved by using a 9-patch drawable. If you look in the SDK, you can see that the background of the EditText
is this image:
To change it you could open it in an image manipulation program and color it in desired color. Save it as bg_edit_text.9.png
and then put it in you drawable folder. Now you can apply it as a background for your EditText
like so:
android:background="@drawable/bg_edit_text"