function getCityState($zip, $blnUSA = true) {
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $zip . "&sensor=true";
$address_info = file_get_contents($url);
$json = json_decode($address_info);
$city = "";
$state = "";
$country = "";
if (count($json->results) > 0) {
//break up the components
$arrComponents = $json->results[0]->address_components;
foreach($arrComponents as $index=>$component) {
$type = $component->types[0];
if ($city == "" && ($type == "sublocality_level_1" || $type == "locality") ) {
$city = trim($component->short_name);
}
if ($state == "" && $type=="administrative_area_level_1") {
$state = trim($component->short_name);
}
if ($country == "" && $type=="country") {
$country = trim($component->short_name);
if ($blnUSA && $country!="US") {
$city = "";
$state = "";
break;
}
}
if ($city != "" && $state != "" && $country != "") {
//we're done
break;
}
}
}
$arrReturn = array("city"=>$city, "state"=>$state, "country"=>$country);
die(json_encode($arrReturn));
}
This is how you can find the latitude and longitude of where we have click on map.
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
//---when user lifts his finger---
if (event.getAction() == 1)
{
GeoPoint p = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
Toast.makeText(getBaseContext(),
p.getLatitudeE6() / 1E6 + "," +
p.getLongitudeE6() /1E6 ,
Toast.LENGTH_SHORT).show();
}
return false;
}
it works well.
To get the location's address we can use geocoder class.
I have wasted 3 days
ultimately solved a graph question
used for
finding shortest distance
using BFS
Want to share the experience.
When the (undirected for me) graph has
fixed distance (1, 6, etc.) for edges
#1
We can use BFS to find shortest path simply by traversing it
then, if required, multiply with fixed distance (1, 6, etc.)
#2
As noted above
with BFS
the very 1st time an adjacent node is reached, it is shortest path
#3
It does not matter what queue you use
deque/queue(c++) or
your own queue implementation (in c language)
A circular queue is unnecessary
#4
Number of elements required for queue is N+1 at most, which I used
(dint check if N works)
here, N is V, number of vertices.
#5
Wikipedia BFS will work, and is sufficient.
https://en.wikipedia.org/wiki/Breadth-first_search#Pseudocode
I have lost 3 days trying all above alternatives, verifying & re-verifying again and again above
they are not the issue.
(Try to spend time looking for other issues, if you dint find any issues with above 5).
More explanation from the comment below:
A
/ \
B C
/\ /\
D E F G
Assume above is your graph
graph goes downwards
For A, the adjacents are B & C
For B, the adjacents are D & E
For C, the adjacents are F & G
say, start node is A
when you reach A, to, B & C the shortest distance to B & C from A is 1
when you reach D or E, thru B, the shortest distance to A & D is 2 (A->B->D)
similarly, A->E is 2 (A->B->E)
also, A->F & A->G is 2
So, now instead of 1 distance between nodes, if it is 6, then just multiply the answer by 6
example,
if distance between each is 1, then A->E is 2 (A->B->E = 1+1)
if distance between each is 6, then A->E is 12 (A->B->E = 6+6)
yes, bfs may take any path
but we are calculating for all paths
if you have to go from A to Z, then we travel all paths from A to an intermediate I, and since there will be many paths we discard all but shortest path till I, then continue with shortest path ahead to next node J
again if there are multiple paths from I to J, we only take shortest one
example,
assume,
A -> I we have distance 5
(STEP) assume, I -> J we have multiple paths, of distances 7 & 8, since 7 is shortest
we take A -> J as 5 (A->I shortest) + 8 (shortest now) = 13
so A->J is now 13
we repeat now above (STEP) for J -> K and so on, till we get to Z
Read this part, 2 or 3 times, and draw on paper, you will surely get what i am saying, best of luck
I had same problem. I did cell.setCellType(Cell.CELL_TYPE_STRING);
before reading the string value, which solved the problem regardless of how the user formatted the cell.
I had multiple remotes. All but one pushed correctly, so I knew I didn't have a detached HEAD or commit issues.
Instead, I had accidentally given two remotes the same URL. The remote with the duplicated URL failed because I was pushing to a URL that had already been pushed to!
Using git remote -v
showed my list of remotes and their URLs, where I realized the issue.
Resetting the failing remote to its correct URL fixed the issue:
git remote set-url <remote-name> <correct-url>
Because the second element is null after you clear the list.
Use:
String s = myList.get(0);
And remember, index 0 is the first element.
I think the new preferred way might be to use IDataErrorInfo
Read more here
If your ultimate aim is just to resign the first responder, this should work: [self.view endEditing:YES]
I know this is an old question, but thought that I should anyway present the simple solution using the paste() function as suggested to by the questioner:
data_1<-data.frame(a=data$a,"x"=paste(data$b,data$c,data$d,sep="-"))
data_1
a x
1 1 a-d-g
2 2 b-e-h
3 3 c-f-i
My goal was to avoid any hacky methods that assume something (e.g. setTimeout) and I ended up implementing the accepted solution with a bit of RxJS flavour on top:
private ngUnsubscribe = new Subject();
private tabSetInitialized = new Subject();
public tabSet: TabsetComponent;
@ViewChild('tabSet') set setTabSet(tabset: TabsetComponent) {
if (!!tabSet) {
this.tabSet = tabSet;
this.tabSetInitialized.next();
}
}
ngOnInit() {
combineLatest(
this.route.queryParams,
this.tabSetInitialized
).pipe(
takeUntil(this.ngUnsubscribe)
).subscribe(([queryParams, isTabSetInitialized]) => {
let tab = [undefined, 'translate', 'versions'].indexOf(queryParams['view']);
this.tabSet.tabs[tab > -1 ? tab : 0].active = true;
});
}
My scenario: I wanted to fire an action on a @ViewChild
element depending on the router queryParams
. Due to a wrapping *ngIf
being false until the HTTP request returns the data, the initialization of the @ViewChild
element happens with a delay.
How does it work: combineLatest
emits a value for the first time only when each of the provided Observables emit the first value since the moment combineLatest
was subscribed to. My Subject tabSetInitialized
emits a value when the @ViewChild
element is being set. Therewith, I delay the execution of the code under subscribe
until the *ngIf
turns positive and the @ViewChild
gets initialized.
Of course don't forget to unsubscribe on ngOnDestroy, I do it using the ngUnsubscribe
Subject:
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
Since you gave me nothing to start on, here is a simple example.
Example implementation:
function incrementValue()
{
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value;
value++;
document.getElementById('number').value = value;
}
Example Html
<form>
<input type="text" id="number" value="0"/>
<input type="button" onclick="incrementValue()" value="Increment Value" />
</form>
Its not my own creation, its a modification of previous posts. credits goes to karim79.
function limit_text($text, $limit) {
$strings = $text;
if (strlen($text) > $limit) {
$words = str_word_count($text, 2);
$pos = array_keys($words);
if(sizeof($pos) >$limit)
{
$text = substr($text, 0, $pos[$limit]) . '...';
}
return $text;
}
return $text;
}
I recommend the answer found here: How do I concatenate two arrays in C#?
e.g.
var z = new int[x.Length + y.Length];
x.CopyTo(z, 0);
y.CopyTo(z, x.Length);
Roughly the same kinds of things you've done in C#. Calling getch()
is probably the simplest.
Use array.prototype.map and array.prototype.some:
var values = [
{ name: 'someName1' },
{ name: 'someName2' },
{ name: 'someName4' },
{ name: 'someName2' }
];
var valueArr = values.map(function(item){ return item.name });
var isDuplicate = valueArr.some(function(item, idx){
return valueArr.indexOf(item) != idx
});
console.log(isDuplicate);
This procedure works even if ADB is not available.
You can use the following. They all wrap the window
object into a jQuery object.
$(window).load(function () {
topInViewport($("#mydivname"))
});
$(window).resize(function () {
topInViewport($("#mydivname"))
});
$(window).scroll(function () {
topInViewport($("#mydivname"))
});
Or bind to them all using on
:
$(window).on("load resize scroll",function(e){
topInViewport($("#mydivname"))
});
Check your enviroment:
echo $http_proxy
echo $https_proxy
echo $HTTPS_PROXY
echo $HTTP_PROXY
and delete with export http_proxy=
Or check https and http proxy
git config --global --unset https.proxy
git config --global --unset http.proxy
Or do you have the proxy in the local config?
git config --unset http.proxy
git config --unset https.proxy
This like a trick,
UILabel *customLabel = [[UILabel alloc] init];
UIColor *color = [UIColor blueColor];
customLabel.layer.shadowColor = [color CGColor];
customLabel.layer.shadowRadius = 5.0f;
customLabel.layer.shadowOpacity = 1;
customLabel.layer.shadowOffset = CGSizeZero;
customLabel.layer.masksToBounds = NO;
It can also be solved using the following query along with other answers.
WITH purchase_data AS (
SELECT address_id, purchased_at, product_id,
row_number() OVER (PARTITION BY address_id ORDER BY purchased_at DESC) AS row_number
FROM purchases
WHERE product_id = 1)
SELECT address_id, purchased_at, product_id
FROM purchase_data where row_number = 1
Is the opaque overlay for aesthetic purposes?
If so, you can use:
#overlay {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 50;
background: #000;
pointer-events: none;
opacity: 0.8;
color: #fff;
}
'pointer-events: none' will change the overlay behavior so that it can be physically opaque. Of course, this will only work in good browsers.
ObjectOutputStream.writeObject(clubs)
ObjectInputStream.readObject();
Also, you 'add' logic is logically equivalent to using a Set instead of a List. Lists can have duplicates and Sets cannot. You should consider using a set. After all, can you really have 2 chess clubs in the same school?
One word: Don't.
OK obviously that isn't a real answer. But still SOAP should be avoided at all costs. ;-) Is it possible to add a proxy server between the iPhone and the web service? Perhaps something that converts REST into SOAP for you?
You could try CSOAP, a SOAP library that depends on libxml2 (which is included in the iPhone SDK).
I've written my own SOAP framework for OSX. However it is not actively maintained and will require some time to port to the iPhone (you'll need to replace NSXML with TouchXML for a start)
So I had a similar situation with the same error. I forgot I changed the compatibility mode on my dev machine and I had a console.log command in my javascript as well. I changed compatibility mode back in IE, and removed the console.log command. No more issue.
Here's a python way. Note: this isn't really that "pythonic" but it demonstrates the algorithm.
def IsPalindromeString(n):
myLen = len(n)
i = 0
while i <= myLen/2:
if n[i] != n[myLen-1-i]:
return False
i += 1
return True
You could listen to the 'keydown'
event and then check for an enter key.
Your handler would be like:
function (e) {
if (13 == e.keyCode) {
... do whatever ...
}
}
I know is a bit later to reply, sorry. But that works for me.
export K8S_public_load_balancer_url="$(kubectl get services -n ${TENANT}-production -o wide | grep "ingress-nginx-internal$" | awk '{print $4}')"
And now I am able to fetch and pass the content of the variable to jq
export TF_VAR_public_load_balancer_url="$(aws elbv2 describe-load-balancers --region eu-west-1 | jq -r '.LoadBalancers[] | select (.DNSName == "'$K8S_public_load_balancer_url'") | .LoadBalancerArn')"
In my case I needed to use double quote and quote to access the variable value.
Cheers.
You need to handle the AppDomain.AssemblyResolve or AppDomain.ReflectionOnlyAssemblyResolve events (depending on which load you're doing) in case the referenced assembly is not in the GAC or on the CLR's probing path.
You can easily find the size of each of your repository in your Accounts settings
I created an extension method (gosh I wish Java had these) called IsEmpty
as follows:
public static bool IsEmpty(this DataRow row)
{
return row == null || row.ItemArray.All(i => i is DBNull);
}
The other answers here are correct. I just felt mine lent brevity in its succinct use of Linq to Objects. BTW, this is really useful in conjunction with Excel parsing since users may tack on a row down the page (thousands of lines) with no regard to how that affects parsing the data.
In the same class, I put any other helpers I found useful, like parsers so that if the field contains text that you know should be a number, you can parse it fluently. Minor pro tip for anyone new to the idea. (Anyone at SO, really? Nah!)
With that in mind, here is an enhanced version:
public static bool IsEmpty(this DataRow row)
{
return row == null || row.ItemArray.All(i => i.IsNullEquivalent());
}
public static bool IsNullEquivalent(this object value)
{
return value == null
|| value is DBNull
|| string.IsNullOrWhiteSpace(value.ToString());
}
Now you have another useful helper, IsNullEquivalent
which can be used in this context and any other, too. You could extend this to include things like "n/a"
or "TBD"
if you know that your data has placeholders like that.
I assume we are talking about doing this in Bash?
I like to use sed to load the date values into an array so I can break down each field and do whatever I want with it. The following example assumes and input format of mm/dd/yyyy...
DATE=$2
DATE_ARRAY=(`echo $DATE | sed -e 's/\// /g'`)
MONTH=(`echo ${DATE_ARRAY[0]}`)
DAY=(`echo ${DATE_ARRAY[1]}`)
YEAR=(`echo ${DATE_ARRAY[2]}`)
LOAD_DATE=$YEAR$MONTH$DAY
you also may want to read up on the date command in linux. It can be very useful: http://unixhelp.ed.ac.uk/CGI/man-cgi?date
Hope that helps... :)
-Ryan
First we'll consider loops where the number of iterations of the inner loop is independent of the value of the outer loop's index. For example:
for (i = 0; i < N; i++) {
for (j = 0; j < M; j++) {
sequence of statements
}
}
The outer loop executes N times. Every time the outer loop executes, the inner loop executes M times. As a result, the statements in the inner loop execute a total of N * M times. Thus, the total complexity for the two loops is O(N2).
I would recommend you look at getting the anaconda package, it will install and configure Sklearn and its dependencies.
You should generally try to avoid <b>
and <i>
. They were introduced for layouting the page (changing the way how it looks) in early HMTL versions prior to the creation of CSS, like the meanwhile removed font
tag, and were mainly kept for backward compatibility and because some forums allow inline HTML and that's an easy way to change the look of text (like BBCode using [i]
, you can use <i>
and so on).
Since the creation of CSS, layouting is actually nothing that should be done in HTML anymore, that's why CSS has been created in the first place (HTML == Structure, CSS == Layout). These tags may as well vanish in the future, after all you can just use CSS and span
tags to make text bold/italic if you need a "meaningless" font variation. HTML 5 still allows them but declares that marking text that way has no meaning.
<em>
and <strong>
on the other hand only says that something is "emphasized" or "strongly emphasized", it leaves it completely open to the browser how to render it. Most browsers will render em
as italic and strong
as bold as the standard suggests by default, but they are not forced to do that (they may use different colors, font sizes, fonts, whatever). You can use CSS to change the behavior the way you desire. You can make em
bold if you like and strong
bold and red, for example.
I spent some time on this very problem - I was trying to verify a file existed before opening it.
Eventually, I came up with a solution using XML and SOAP - use the EnumerateFolder method and pull in an XML response with the folder's contents.
I blogged about it here.
String stringrep = myintvar.ToString("X");
int num = int.Parse("FF", System.Globalization.NumberStyles.HexNumber);
Edit file: C:\Users\kpate\hw6\python-zulip-api\zulip_bots\setup.py in line 108
to
rcode = pip.main(['install', '-r', req_path, '--quiet'])
do
rcode = getattr(pip, '_main', pip.main)(['install', '-r', req_path, '--quiet'])´
And for yet another option, I'd go with awk!
echo "foo bar <foo> bla 1 2 3.4" | awk '{ print $(NF-1), $NF; }'
This will split the input (I'm using STDIN here, but your input could easily be a file) on spaces, and then print out the last-but-one field, and then the last field. The $NF
variables hold the number of fields found after exploding on spaces.
The benefit of this is that it doesn't matter if what precedes the last two fields changes, as long as you only ever want the last two it'll continue to work.
loop { begin Bar.new rescue SystemExit p $! #: #<SystemExit: exit> end }
This will print #<SystemExit: exit>
in an infinite loop, without ever exiting.
Check this code. It gives you the clear solution of JSON parse error. It commonly happen by the newlines and the space between json key start and json key end
data_val = data_val.replace(/[\n\s]{1,}\"/g, "\"")
.replace(/\"[\n\s]{1,}/g, "\"")
.replace(/[\n]/g, "\\n")
Create the opposite dictionary:
PIX1 = {}
for key in PIX0.keys():
PIX1[PIX0.get(key)] = key
Then run the same code on this dictionary instead (using PIX1
instead of PIX0
).
BTW, I'm not sure about Python 3, but in Python 2 you need to use raw_input
instead of input
.
tl;dr the "standards" are a hodge-podge mess; it depends who you ask!
Overall, there appears to be no MIME type image/jpg
. Yet, in practice, nearly all software handles image files named "*.jpg
" just fine.
This particular topic is confusing because the varying association of file name extension associated to a MIME type depends which organization created the table of file name extensions to MIME types. In other words, file name extension .jpg
could be many different things.
For example, here are three "complete lists" and one RFC that with varying JPEG Image format file name extensions and the associated MIME types.
.jfif
, .jfif-tbnl
, .jpe
, .jpeg
, .jpg
? image/jpeg
.jfif
, .jpe
, .jpeg
, .jpg
? image/pjpeg
.jpeg
, .jpg
? image/jpeg
.jpeg
, .jpg
? image/x-citrix-jpeg
.pjpeg
? image/pjpeg
jpg
not mentionedjpeg
? see RFC 2045 (no mention), see RFC 2046 ? image/jpeg
13JPEG
? video/JPEG
jpeg2000
? video/jpeg2000
jpm
? image/jpm
(JPEG 2000)jpx
? image/jpx
(JPEG 2000)vnd.sealedmedia.softseal.jpg
? image/vnd.sealedmedia.softseal.jpg
These "complete lists" and RFC do not have MIME type image/jpg
! But for MIME type image/jpeg
some lists do have varying file name extensions (.jpeg
, .jpg
, …). Other lists do not mention image/jpeg
.
Also, there are different types of JPEG Image formats (e.g. Progressive JPEG Image format, JPEG 2000, etcetera) and "JPEG Extensions" that may or may not overlap in file name extension and declared MIME type.
Another confusing thing is RFC 3745 does not appear to match IANA Media Types yet the same RFC is supposed to inform the IANA Media Types document. For example, in RFC 3745 .jpf
is preferred file extension for image/jpx
but in IANA Media Types the name jpf
is not present (and that IANA document references RFC 3745!).
Another confusing thing is IANA Media Types lists "names" but does not list "file name extensions". This is on purpose, but confuses the endeavor of mapping file name extensions to MIME types.
Another confusing thing: is it "mime", or "MIME", or "MIME type", or "mime type", or "mime/type", or "media type"?
The most official seeming document by IANA is surprisingly inadequate. No MIME type is registered for file extension .jpg
yet there exists the odd vnd.sealedmedia.softseal.jpg
. File extension.JPEG
is only known as a video
type while file extension .jpeg
is an image type (when did lowercase and uppercase letters start mattering!?). At the same time, jpeg2000
is type video
yet RFC 3745 considers JPEG 2000 an image
type! The IANA list seems to cater to company-specific jpeg formats (e.g. vnd.sealedmedia.softseal.jpg
).
Because of the prior confusions, it is difficult to find an industry-accepted canonical document that maps file name extensions to MIME types, particularly for the JPEG Image File Format.
Related question "List of ALL MimeTypes on the Planet, mapped to File Extensions?".
The Unix utility diff
is meant for exactly this purpose.
$ diff -u file1 file2 > file3
See the manual and the Internet for options, different output formats, etc.
Alternate solution can be:
baseKey hKeyLocalMachine = baseKey.HKEY_LOCAL_MACHINE;
uint value = (uint)hKeyLocalMachine;
Or just:
uint value = (uint)baseKey.HKEY_LOCAL_MACHINE;
%Started Program or Command% | taskkill /F /IM cmd.exe
Example:
notepad.exe | taskkill /F /IM cmd.exe
Let me share an example which I developed with BS4, thymeleaf and Spring boot.
I am using two SELECTs, where the second ("subtopic") gets filled by an AJAX call based on the selection of the first("topic").
First, the thymeleaf snippet:
<div class="form-group">
<label th:for="topicId" th:text="#{label.topic}">Topic</label>
<select class="custom-select"
th:id="topicId" th:name="topicId"
th:field="*{topicId}"
th:errorclass="is-invalid" required>
<option value="" selected
th:text="#{option.select}">Select
</option>
<optgroup th:each="topicGroup : ${topicGroups}"
th:label="${topicGroup}">
<option th:each="topicItem : ${topics}"
th:if="${topicGroup == topicItem.grp} "
th:value="${{topicItem.baseIdentity.id}}"
th:text="${topicItem.name}"
th:selected="${{topicItem.baseIdentity.id==topicId}}">
</option>
</optgroup>
<option th:each="topicIter : ${topics}"
th:if="${topicIter.grp == ''} "
th:value="${{topicIter.baseIdentity.id}}"
th:text="${topicIter.name}"
th:selected="${{topicIter.baseIdentity?.id==topicId}}">
</option>
</select>
<small id="topicHelp" class="form-text text-muted"
th:text="#{label.topic.tt}">select</small>
</div><!-- .form-group -->
<div class="form-group">
<label for="subtopicsId" th:text="#{label.subtopicsId}">subtopics</label>
<select class="custom-select"
id="subtopicsId" name="subtopicsId"
th:field="*{subtopicsId}"
th:errorclass="is-invalid" multiple="multiple">
<option value="" disabled
th:text="#{option.multiple.optional}">Select
</option>
<option th:each="subtopicsIter : ${subtopicsList}"
th:value="${{subtopicsIter.baseIdentity.id}}"
th:text="${subtopicsIter.name}">
</option>
</select>
<small id="subtopicsHelp" class="form-text text-muted"
th:unless="${#fields.hasErrors('subtopicsId')}"
th:text="#{label.subtopics.tt}">select</small>
<small id="subtopicsIdError" class="invalid-feedback"
th:if="${#fields.hasErrors('subtopicsId')}"
th:errors="*{subtopicsId}">Errors</small>
</div><!-- .form-group -->
I am iterating over a list of topics that is stored in the model context, showing all groups with their topics, and after that all topics that do not have a group. BaseIdentity is an @Embedded composite key BTW.
Now, here's the jQuery that handles changes:
$('#topicId').change(function () {
selectedOption = $(this).val();
if (selectedOption === "") {
$('#subtopicsId').prop('disabled', 'disabled').val('');
$("#subtopicsId option").slice(1).remove(); // keep first
} else {
$('#subtopicsId').prop('disabled', false)
var orig = $(location).attr('origin');
var url = orig + "/getsubtopics/" + selectedOption;
$.ajax({
url: url,
success: function (response) {
var len = response.length;
$("#subtopicsId option[value!='']").remove(); // keep first
for (var i = 0; i < len; i++) {
var id = response[i]['baseIdentity']['id'];
var name = response[i]['name'];
$("#subtopicsId").append("<option value='" + id + "'>" + name + "</option>");
}
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
}).change(); // and call it once defined
The initial call of change() makes sure it will be executed on page re-load or if a value has been preselected by some initialization in the backend.
BTW: I am using "manual" form validation (see "is-valid"/"is-invalid"), because I (and users) didn't like that BS4 marks non-required empty fields as green. But that's byond scope of this Q and if you are interested then I can post it also.
This is exactly what you need. See it in action here 8FydL/445
Example's Code below:
$(".dropdown img.flag").addClass("flagvisibility");_x000D_
$(".dropdown dt a").click(function() {_x000D_
$(".dropdown dd ul").toggle();_x000D_
});_x000D_
_x000D_
$(".dropdown dd ul li a").click(function() {_x000D_
var text = $(this).html();_x000D_
$(".dropdown dt a span").html(text);_x000D_
$(".dropdown dd ul").hide();_x000D_
$("#result").html("Selected value is: " + getSelectedValue("sample"));_x000D_
});_x000D_
_x000D_
function getSelectedValue(id) {_x000D_
return $("#" + id).find("dt a span.value").html();_x000D_
}_x000D_
_x000D_
$(document).bind('click', function(e) {_x000D_
var $clicked = $(e.target);_x000D_
if (! $clicked.parents().hasClass("dropdown"))_x000D_
$(".dropdown dd ul").hide();_x000D_
});_x000D_
_x000D_
$(".dropdown img.flag").toggleClass("flagvisibility");
_x000D_
.desc { color:#6b6b6b;}_x000D_
.desc a {color:#0092dd;}_x000D_
_x000D_
.dropdown dd, .dropdown dt, .dropdown ul { margin:0px; padding:0px; }_x000D_
.dropdown dd { position:relative; }_x000D_
.dropdown a, .dropdown a:visited { color:#816c5b; text-decoration:none; outline:none;}_x000D_
.dropdown a:hover { color:#5d4617;}_x000D_
.dropdown dt a:hover { color:#5d4617; border: 1px solid #d0c9af;}_x000D_
.dropdown dt a {background:#e4dfcb url('http://www.jankoatwarpspeed.com/wp-content/uploads/examples/reinventing-drop-down/arrow.png') no-repeat scroll right center; display:block; padding-right:20px;_x000D_
border:1px solid #d4ca9a; width:150px;}_x000D_
.dropdown dt a span {cursor:pointer; display:block; padding:5px;}_x000D_
.dropdown dd ul { background:#e4dfcb none repeat scroll 0 0; border:1px solid #d4ca9a; color:#C5C0B0; display:none;_x000D_
left:0px; padding:5px 0px; position:absolute; top:2px; width:auto; min-width:170px; list-style:none;}_x000D_
.dropdown span.value { display:none;}_x000D_
.dropdown dd ul li a { padding:5px; display:block;}_x000D_
.dropdown dd ul li a:hover { background-color:#d0c9af;}_x000D_
_x000D_
.dropdown img.flag { border:none; vertical-align:middle; margin-left:10px; }_x000D_
.flagvisibility { display:none;}
_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>_x000D_
<dl id="sample" class="dropdown">_x000D_
<dt><a href="#"><span>Please select the country</span></a></dt>_x000D_
<dd>_x000D_
<ul>_x000D_
<li><a href="#">Brazil<img class="flag" src="http://www.jankoatwarpspeed.com/wp-content/uploads/examples/reinventing-drop-down/br.png" alt="" /><span class="value">BR</span></a></li>_x000D_
<li><a href="#">France<img class="flag" src="http://www.jankoatwarpspeed.com/wp-content/uploads/examples/reinventing-drop-down/fr.png" alt="" /><span class="value">FR</span></a></li>_x000D_
_x000D_
</ul>_x000D_
</dd>_x000D_
</dl>_x000D_
<span id="result"></span>
_x000D_
Check if the following folders exists, if not create these folders.
Only such dialog is FileDialog. Its part of WinForms, but its actually only wrapper around WinAPI standard OS file dialog. And I don't think it is ugly, its actually part of OS, so it looks like OS it is run on.
Other way, there is nothing to help you with. You either need to look for 3rd party implementation, either free (and I don't think there are any good) or paid.
It stops and starts the services that IIS consists of.
You can think of it as closing the relevant program and starting it up again.
use inline-block
instead of inline
. Read more information here about the difference between inline and inline-block.
.inline {
display: inline-block;
border: 1px solid red;
margin:10px;
}
In my XFCE (version 4.12), it's in Settings -> Window Manager Tweaks -> Accessibility
.
There's a dropdown field Key used to grab and move windows:
, set this to None
.
Alt + Click works now in VS Code to add more cursor.
ASMX Web services can only be invoked by HTTP (traditional webservice with .asmx). While WCF Service or a WCF component can be invoked by any protocol (like http, tcp etc.) and any transport type.
Second, ASMX web services are not flexible. However, WCF Services are flexible. If you make a new version of the service then you need to just expose a new end. Therefore, services are agile and which is a very practical approach looking at the current business trends.
We develop WCF as contracts, interface, operations, and data contracts. As the developer we are more focused on the business logic services and need not worry about channel stack. WCF is a unified programming API for any kind of services so we create the service and use configuration information to set up the communication mechanism like HTTP/TCP/MSMQ etc
A "raw" type in Java is a class which is non-generic and deals with "raw" Objects, rather than type-safe generic type parameters.
For example, before Java generics was available, you would use a collection class like this:
LinkedList list = new LinkedList();
list.add(new MyObject());
MyObject myObject = (MyObject)list.get(0);
When you add your object to the list, it doesn't care what type of object it is, and when you get it from the list, you have to explicitly cast it to the type you are expecting.
Using generics, you remove the "unknown" factor, because you must explicitly specify which type of objects can go in the list:
LinkedList<MyObject> list = new LinkedList<MyObject>();
list.add(new MyObject());
MyObject myObject = list.get(0);
Notice that with generics you don't have to cast the object coming from the get call, the collection is pre-defined to only work with MyObject. This very fact is the main driving factor for generics. It changes a source of runtime errors into something that can be checked at compile time.
If you prefer good ol' cron, CRONw is the way to go.
Supported systems
* Windows 2000 (any version) works
* Windows XP (SP 2) works
* Windows Server 2003 works
* Windows NT 4 (SP 6) should work but not tested
* Windows 3.11, Windows 95,
Windows 98, Windows ME,
Windows XP beneath SP2 not supported by design
You can add nulls to the ArrayList
, and you will have to check for nulls in the loop:
for(Item i : itemList) {
if (i != null) {
}
}
itemsList.size();
would take the null
into account.
List<Integer> list = new ArrayList<Integer>();
list.add(null);
list.add (5);
System.out.println (list.size());
for (Integer value : list) {
if (value == null)
System.out.println ("null value");
else
System.out.println (value);
}
Output :
2
null value
5
Option 1
http://jquery.malsup.com/corner/
Option 2
http://code.google.com/p/curved-corner/downloads/detail?name=border-radius-demo.zip
Option 3
Option 4
http://www.netzgesta.de/corner/
Option 5
EDIT: Option 6
In GNU Awk 4.1.0 (released 2013) and later, it has the option of "inplace" file editing:
[...] The "inplace" extension, built using the new facility, can be used to simulate the GNU "
sed -i
" feature. [...]
Example usage:
$ gawk -i inplace '{ gsub(/foo/, "bar") }; { print }' file1 file2 file3
To keep the backup:
$ gawk -i inplace -v INPLACE_SUFFIX=.bak '{ gsub(/foo/, "bar") }
> { print }' file1 file2 file3
answer = True
myvar = 'the answer is ' + str(answer) #since answer variable is in boolean format, therefore, we have to convert boolean into string format which can be easily done using this
print(myvar)
Add the all tiles jars like(tiles-jsp,tiles-servlet,tiles-template,tiles-extras.tiles-core ) to your server lib folder and your application build path then it work if you using apache tailes with spring mvc application
Try two things:
java/jdk1.6.0_31/jre/lib/security/Java.security
change securerandom.source=file:/dev/urandom
to securerandom.source=file:///dev/urandom
First create an object of class2 in class1 and then use that object to call any function of class2 for example write this in class1
class2 obj= new class2();
obj.thefunctioname(args);
I think this will handle it better:
my_dict = {0: "c", 1: "d", 2: "e", 3: "f"}
def validate(x, y, z):
for ele in [x, y, z]:
if ele in my_dict.keys():
return my_dict[ele]
Output:
print validate(0, 8, 9)
c
print validate(9, 8, 9)
None
print validate(9, 8, 2)
e
package com.sanjayacchana.challangingprograms;
public class RemoveAllWhiteSpacesInString {
public static void main(String[] args) {
String str = "name=john age=13 year=2001";
str = str.replaceAll("\\s", "");
System.out.println(str);
}
}
For jQuery 1.6+ :
.attr() is deprecated for properties; use the new .prop() function instead as:
$('#myCheckbox').prop('checked', true); // Checks it
$('#myCheckbox').prop('checked', false); // Unchecks it
For jQuery < 1.6:
To check/uncheck a checkbox, use the attribute checked
and alter that. With jQuery you can do:
$('#myCheckbox').attr('checked', true); // Checks it
$('#myCheckbox').attr('checked', false); // Unchecks it
Cause you know, in HTML, it would look something like:
<input type="checkbox" id="myCheckbox" checked="checked" /> <!-- Checked -->
<input type="checkbox" id="myCheckbox" /> <!-- Unchecked -->
However, you cannot trust the .attr() method to get the value of the checkbox (if you need to). You will have to rely in the .prop() method.
In case you want to do it programmatically,
checkBoxOrRadioButton.setButtonDrawable(null);
checkBoxOrRadioButton.setBackgroundResource(R.drawable.resource_name);
For Windows Environments:
If you don't want to go to the command prompt (or work in an environment where command prompt is restricted), I think the following solution is better than inserting code into python that asks you to press any key - because if the program crashes before it reaches that point, the window closes and you lose the crash info. The solution I use is to create a bat file.
Use notepad to create a text file. In the file the contents will look something like:
my_python_program.py
pause
Then save the file as "my_python_program.bat"
When you run the bat file it will run the python program and pause at the end to allow you to read the output. Then if you press any key it will close the window.
Specifically, if you are dealing with a UserForm, then you might try the Repaint method. You might encounter an issue with DoEvents if you are using event triggers in your form. For instance, any keys pressed while a function is running will be sent by DoEvents The keyboard input will be processed before the screen is updated, so if you are changing cells on a spreadsheet by holding down one of the arrow keys on the keyboard, then the cell change event will keep firing before the main function finishes.
A UserForm will not be refreshed in some cases, because DoEvents will fire the events; however, Repaint will update the UserForm and the user will see the changes on the screen even when another event immediately follows the previous event.
In the UserForm code it is as simple as:
Me.Repaint
MAC users may face this issue when xcode tools are not installed properly. Below is the command to get rid of the issue.
xcode-select --install
If one only cares about whitespace at the beginning and end of the string (but not in the middle), then another option is to use String.trim():
" your string contents ".trim();
// => "your string contents"
Adapted from here, building on scunliffe's answer:
function getStyle(className) {
var cssText = "";
var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
for (var x = 0; x < classes.length; x++) {
if (classes[x].selectorText == className) {
cssText += classes[x].cssText || classes[x].style.cssText;
}
}
return cssText;
}
alert(getStyle('.test'));
Since the count is the intended final value, in your query pass
$this->db->distinct();
$this->db->select('accessid');
$this->db->where('record', $record);
$query = $this->db->get()->result_array();
return count($query);
The count the retuned value
Its much easier than all this: Simply transition the same property on your element
.earth { width: 0.92%; transition: width 1s; }
.earth:hover { width: 50%; transition: width 1s; }
Regarding Tom Beech's answer; I came up with the following instead:
public bool ValidateJSON(string s)
{
try
{
JToken.Parse(s);
return true;
}
catch (JsonReaderException ex)
{
Trace.WriteLine(ex);
return false;
}
}
With a usage of the following:
if (ValidateJSON(strMsg))
{
var newGroup = DeserializeGroup(strMsg);
}
The following tables are store WooCommerce products database :
wp_posts -
The core of the WordPress data is the posts. It is stored a post_type
like product or variable_product
.
wp_postmeta-
Each post features information called the meta data and it is stored in the wp_postmeta. Some plugins may add their own information to this table like WooCommerce plugin store product_id
of product in wp_postmeta table.
Product categories, subcategories stored in this table :
following Query Return a list of product categories
SELECT wp_terms.*
FROM wp_terms
LEFT JOIN wp_term_taxonomy ON wp_terms.term_id = wp_term_taxonomy.term_id
WHERE wp_term_taxonomy.taxonomy = 'product_cat';
for more reference -
Bootstrap 4
Use the data-parent=""
attribute on the collapse element (instead of the trigger element)
<div id="accordion">
<div class="card">
<div class="card-header">
<h5>
<button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne">
Collapsible #1 trigger
</button>
</h5>
</div>
<div id="collapseOne" class="collapse show" data-parent="#accordion">
<div class="card-body">
Collapsible #1 element
</div>
</div>
</div>
... (more cards/collapsibles inside #accordion parent)
</div>
Bootstrap 3
See this issue on GitHub: https://github.com/twbs/bootstrap/issues/10966
There is a "bug" that makes the accordion dependent on the .panel
class when using the data-parent
attribute. To workaround it, you can wrap each accordion group in a 'panel' div..
<div class="accordion" id="myAccordion">
<div class="panel">
<button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-1" data-parent="#myAccordion">Question 1?</button>
<div id="collapsible-1" class="collapse">
..
</div>
</div>
<div class="panel">
<button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-2" data-parent="#myAccordion">Question 2?</button>
<div id="collapsible-2" class="collapse">
..
</div>
</div>
<div class="panel">
<button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-3" data-parent="#myAccordion">Question 3?</button>
<div id="collapsible-3" class="collapse">
...
</div>
</div>
</div>
Edit
As mentioned in the comments, each section doesn't have to be a .panel
. However...
.panel
must be a direct child of the element used as data-parent=
data-toggle=
) must be a direct child of the .panel
(http://www.bootply.com/AbiRW7BdD6#)You need to set useaccessibleheader
attribute of the gridview to true
and also then also specify a TableSection
to be a header after calling the DataBind()
method on you GridView object. So if your grid view is mygv
mygv.UseAccessibleHeader = True
mygv.HeaderRow.TableSection = TableRowSection.TableHeader
This should result in a proper formatted grid with thead
and tbody
tags
FolderBrowserDialog fbd = new FolderBrowserDialog();
DialogResult result = fbd.ShowDialog();
string[] files = Directory.GetFiles(fbd.SelectedPath);
string[] dirs = Directory.GetDirectories(fbd.SelectedPath);
foreach (string item2 in dirs)
{
FileInfo f = new FileInfo(item2);
listBox1.Items.Add(f.Name);
}
foreach (string item in files)
{
FileInfo f = new FileInfo(item);
listBox1.Items.Add(f.Name);
}
It appears that with newer versions of bundler (>= 1.14) it's:
bundle update --conservative gem-name
This is the shortest solution.
timeSpan.ToString(@"hh\:mm");
Use curly braces around the variable name:
`tail -1 ${filepath}_newstap.sh`
The cssrewrite filter is not compatible with the @bundle notation for now. So you have two choices:
Reference the CSS files in the web folder (after: console assets:install --symlink web
)
{% stylesheets '/bundles/myCompany/css/*." filter="cssrewrite" %}
Use the cssembed filter to embed images in the CSS like this.
{% stylesheets '@MyCompanyMyBundle/Resources/assets/css/*.css' filter="cssembed" %}
This worked for me
jQuery(document).ready(function(){
jQuery('input').keyup(function() {
this.value = this.value.toLocaleUpperCase();
});
jQuery('textarea').keyup(function() {
this.value = this.value.toLocaleUpperCase();
});
});
The add_subplot() method has several call signatures:
add_subplot(nrows, ncols, index, **kwargs)
add_subplot(pos, **kwargs)
add_subplot(ax)
add_subplot()
<-- since 3.1.0Calls 1 and 2 achieve the same thing as one another (up to a limit, explained below). Think of them as first specifying the grid layout with their first 2 numbers (2x2, 1x8, 3x4, etc), e.g:
f.add_subplot(3,4,1)
# is equivalent to:
f.add_subplot(341)
Both produce a subplot arrangement of (3 x 4 = 12) subplots in 3 rows and 4 columns. The third number in each call indicates which axis object to return, starting from 1 at the top left, increasing to the right.
This code illustrates the limitations of using call 2:
#!/usr/bin/env python3
import matplotlib.pyplot as plt
def plot_and_text(axis, text):
'''Simple function to add a straight line
and text to an axis object'''
axis.plot([0,1],[0,1])
axis.text(0.02, 0.9, text)
f = plt.figure()
f2 = plt.figure()
_max = 12
for i in range(_max):
axis = f.add_subplot(3,4,i+1, fc=(0,0,0,i/(_max*2)), xticks=[], yticks=[])
plot_and_text(axis,chr(i+97) + ') ' + '3,4,' +str(i+1))
# If this check isn't in place, a
# ValueError: num must be 1 <= num <= 15, not 0 is raised
if i < 9:
axis = f2.add_subplot(341+i, fc=(0,0,0,i/(_max*2)), xticks=[], yticks=[])
plot_and_text(axis,chr(i+97) + ') ' + str(341+i))
f.tight_layout()
f2.tight_layout()
plt.show()
You can see with call 1 on the LHS you can return any axis object, however with call 2 on the RHS you can only return up to index = 9 rendering subplots j), k), and l) inaccessible using this call.
I.e it illustrates this point from the documentation:
pos is a three digit integer, where the first digit is the number of rows, the second the number of columns, and the third the index of the subplot. i.e. fig.add_subplot(235) is the same as fig.add_subplot(2, 3, 5). Note that all integers must be less than 10 for this form to work.
In rare circumstances, add_subplot may be called with a single argument, a subplot axes instance already created in the present figure but not in the figure's list of axes.
If no positional arguments are passed, defaults to (1, 1, 1).
i.e., reproducing the call fig.add_subplot(111)
in the question.
I believe Enterprise Architect can do that.
You should use datetime.datetime.strptime
:
import datetime
dt = datetime.datetime.strptime(string_date, fmt)
fmt
will need to be the appropriate format for your string. You'll find the reference on how to build your format here.
Detection is automatic. You must specify what css can be used for each screen resolution:
/* for all screens, use 14px font size */
body {
font-size: 14px;
}
/* responsive, form small screens, use 13px font size */
@media (max-width: 479px) {
body {
font-size: 13px;
}
}
select
*
from
pg_catalog.pg_tables
where
schemaname != 'information_schema'
and schemaname != 'pg_catalog';
Use curl
instead of file_get_contents
:
$address = "India+Panchkula";
$url = "http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false®ion=India";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response_a = json_decode($response);
echo $lat = $response_a->results[0]->geometry->location->lat;
echo "<br />";
echo $long = $response_a->results[0]->geometry->location->lng;
Another approach!
string str = "12345";
bool containsOnlyDigits = true;
try { if(Convert.ToInt32(str) < 0){ containsOnlyDigits = false; } }
catch { containsOnlyDigits = false; }
Here, if the statement Convert.ToInt32(str)
fails, then string does not contain digits only. Another possibility is that if the string has "-12345"
which gets converted to -12345
successfully, then there is a check for verifying that the number converted is not less than zero.
I'd say the code you need is:
test = input("enter the test")
print(test)
Otherwise it shouldn't run at all, due to a syntax error. The print
function requires brackets in python 3. I cannot reproduce your error, though. Are you sure it's those lines causing that error?
On macOS Big Sur (11.0) beta for TextMate: none of the environment variable options worked. (Set all three: GIT_EDITOR, VISUAL, and EDITOR.)
Finally set the global core.editor in git, and that worked:
git config --global core.editor "~/bin/mate -w"
Open (and close!) your PHP tags right after, and before, your textarea
tags:
<textarea style="width:350px; height:80px;" cols="42" rows="5" name="sitelink"><?php
if($siteLink_val) echo $siteLink_val;
?></textarea>
Well how to find dates between two given date in SQL server is explain on http://ektaraval.blogspot.com/2010/09/writing-recursive-query-to-find-out-all.html
I am using IIS and mysql (directly downloaded, without wamp or xampp) My php was installed in c:\php I was getting the error of "call to undefined function mysql_connect()" For me the change of extension_dir worked. This is what I did. In the php.ini, Originally, I had this line
; On windows: extension_dir = "ext"
I changed it to:
; On windows: extension_dir = "C:\php\ext"
And it worked. Of course, I did the other things also like uncommenting the dll extensions etc, as explained in others remarks.
const toIntArray = (n) => ([...n + ""].map(v => +v))
_x000D_
Give your button an id something like this:
<input id="mybutton" type="button" value="Dont show this again! " />
Then use jquery (to make this unobtrusive) and attach click action like so:
$(document).ready(function (){
$('#mybutton').click(function (){
fbLikeDump();
WriteCookie();
});
});
(this part should be in your .js file too)
I should have mentioned that you will need the jquery libraries on your page, so right before your closing body tag add these:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://PATHTOYOURJSFILE"></script>
The reason to add just before body closing tag is for performance of perceived page loading times
It's old question but just in case someone bump on this tread...
var input = document.getElementById("your_input");
var file = input.value.split("\\");
var fileName = file[file.length-1];
No need for regex, jQuery....
You could use cast
(as int) after replacing NaN
with 0
,
data_df = df.withColumn("Plays", df.call_time.cast('float'))
I think this is cool
SELECT value,
PARSENAME(REPLACE(String,',','.'),2) 'Name' ,
PARSENAME(REPLACE(String,',','.'),1) 'Sur Name'
FROM table WITH (NOLOCK)
Not ideal, but you could change the id and name of the textbox each time you render it - you'd have to track it server side too so you could get the data out.
Not sure if this will work or not, was just a thought.
A bit verbose, but it's the standard way of parsing and formatting dates in Java:
DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
try {
Date dt = formatter.parse("08:19:12");
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int hour = cal.get(Calendar.HOUR);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
} catch (ParseException e) {
// This can happen if you are trying to parse an invalid date, e.g., 25:19:12.
// Here, you should log the error and decide what to do next
e.printStackTrace();
}
Had the same problem. If server is configured correctly and .htacces is not the answer, might want to look the svg source you are embedding. Mine were created with text editor, rendered well on Chrome&Safari inside html5 code, once embedded, nothing was visible. Added correct version, dimensions etc to the svg code and works like a charm. Also, all styles inline.
Ie
<svg version="1.1" baseProfile="full" width="24" height="24" xmlns="http://www.w3.org/2000/svg">
<rect x="0" y="0" rx="2" ry="2" width="24" height="24" style="fill:#fbc800;width:24px;height:24px;" />
</svg>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
alert( "document loaded" );
});
$( window ).load(function() {
alert( "window loaded" );
});
</script>
</head>
<body>
<iframe src="http://stackoverflow.com"></iframe>
</body>
</html>
window.load will be triggered after all the iframe content is loaded
This function:
CREATE FUNCTION ToProperCase(@string VARCHAR(255)) RETURNS VARCHAR(255)
AS
BEGIN
DECLARE @i INT -- index
DECLARE @l INT -- input length
DECLARE @c NCHAR(1) -- current char
DECLARE @f INT -- first letter flag (1/0)
DECLARE @o VARCHAR(255) -- output string
DECLARE @w VARCHAR(10) -- characters considered as white space
SET @w = '[' + CHAR(13) + CHAR(10) + CHAR(9) + CHAR(160) + ' ' + ']'
SET @i = 1
SET @l = LEN(@string)
SET @f = 1
SET @o = ''
WHILE @i <= @l
BEGIN
SET @c = SUBSTRING(@string, @i, 1)
IF @f = 1
BEGIN
SET @o = @o + @c
SET @f = 0
END
ELSE
BEGIN
SET @o = @o + LOWER(@c)
END
IF @c LIKE @w SET @f = 1
SET @i = @i + 1
END
RETURN @o
END
Result:
dbo.ToProperCase('ALL UPPER CASE and SOME lower ÄÄ ÖÖ ÜÜ ÉÉ ØØ CC ÆÆ')
-----------------------------------------------------------------
All Upper Case and Some lower Ää Öö Üü Éé Øø Cc Ææ
Make your variable nullable. Like:
Color? color = null;
or
Nullable<Color> color = null;
For python3 use either with xxxx = name
of yourfile
.
exec(open('./xxxx.py').read())
There are lots of different ways to do this. One way is to use the RewriteRule techniques mentioned earlier to mask query string values.
One of the ways I really like is if you use the front controller pattern, you can also use urls like http://yoursite.com/index.php/path/to/your/page/here and parse the value of $_SERVER['REQUEST_URI'].
You can easily extract the /path/to/your/page/here bit with the following bit of code:
$route = substr($_SERVER['REQUEST_URI'], strlen($_SERVER['SCRIPT_NAME']));
From there, you can parse it however you please, but for pete's sake make sure you sanitise it ;)
Using a $where
query will be slow, in part because it can't use indexes. For this sort of problem, I think it would be better to store a high value for the "expires" field that will naturally always be greater than Now(). You can either store a very high date millions of years in the future, or use a separate type to indicate never. The cross-type sort order is defined at here.
An empty Regex or MaxKey (if you language supports it) are both good choices.
private void textBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
button.PerformClick();
}
//form/descendant::input[@type='submit']
It is only possible as from C# 4.0
However, when you use a version of C#, prior to 4.0, you can work around this by using overloaded methods:
public void Func( int i, int j )
{
Console.WriteLine (String.Format ("i = {0}, j = {1}", i, j));
}
public void Func( int i )
{
Func (i, 4);
}
public void Func ()
{
Func (5);
}
(Or, you can upgrade to C# 4.0 offcourse).
If you're not using HTML5 this is a pretty basic JavaScript form validation.
Side note - I'd change the value to 0 on the blur event instead of keyup (as a user I think changing the text as I'm typing would be annoying to no end).
Have a look at the UUID class bundled with Java 5 and later.
For example:
Though classmethod
and staticmethod
are quite similar, there's a slight difference in usage for both entities: classmethod
must have a reference to a class object as the first parameter, whereas staticmethod
can have no parameters at all.
class Date(object):
def __init__(self, day=0, month=0, year=0):
self.day = day
self.month = month
self.year = year
@classmethod
def from_string(cls, date_as_string):
day, month, year = map(int, date_as_string.split('-'))
date1 = cls(day, month, year)
return date1
@staticmethod
def is_date_valid(date_as_string):
day, month, year = map(int, date_as_string.split('-'))
return day <= 31 and month <= 12 and year <= 3999
date2 = Date.from_string('11-09-2012')
is_date = Date.is_date_valid('11-09-2012')
Let's assume an example of a class, dealing with date information (this will be our boilerplate):
class Date(object):
def __init__(self, day=0, month=0, year=0):
self.day = day
self.month = month
self.year = year
This class obviously could be used to store information about certain dates (without timezone information; let's assume all dates are presented in UTC).
Here we have __init__
, a typical initializer of Python class instances, which receives arguments as a typical instancemethod
, having the first non-optional argument (self
) that holds a reference to a newly created instance.
Class Method
We have some tasks that can be nicely done using classmethod
s.
Let's assume that we want to create a lot of Date
class instances having date information coming from an outer source encoded as a string with format 'dd-mm-yyyy'. Suppose we have to do this in different places in the source code of our project.
So what we must do here is:
Date
by passing those values to the initialization call.This will look like:
day, month, year = map(int, string_date.split('-'))
date1 = Date(day, month, year)
For this purpose, C++ can implement such a feature with overloading, but Python lacks this overloading. Instead, we can use classmethod
. Let's create another "constructor".
@classmethod
def from_string(cls, date_as_string):
day, month, year = map(int, date_as_string.split('-'))
date1 = cls(day, month, year)
return date1
date2 = Date.from_string('11-09-2012')
Let's look more carefully at the above implementation, and review what advantages we have here:
cls
is an object that holds the class itself, not an instance of the class. It's pretty cool because if we inherit our Date
class, all children will have from_string
defined also.Static method
What about staticmethod
? It's pretty similar to classmethod
but doesn't take any obligatory parameters (like a class method or instance method does).
Let's look at the next use case.
We have a date string that we want to validate somehow. This task is also logically bound to the Date
class we've used so far, but doesn't require instantiation of it.
Here is where staticmethod
can be useful. Let's look at the next piece of code:
@staticmethod
def is_date_valid(date_as_string):
day, month, year = map(int, date_as_string.split('-'))
return day <= 31 and month <= 12 and year <= 3999
# usage:
is_date = Date.is_date_valid('11-09-2012')
So, as we can see from usage of staticmethod
, we don't have any access to what the class is---it's basically just a function, called syntactically like a method, but without access to the object and its internals (fields and another methods), while classmethod does.
either send the user to another page which does it
<a href="exec.php">Execute PHP</a>
or do it with ajax
<script type="text/javascript">
// <![CDATA[
document.getElementById('link').onclick = function() {
// call script via ajax...
return false;
}
// ]]>
</script>
...
<a href="#" id="link">Execute PHP</a>
Two possibilities here. Java Version incompatible or import
The @ symbol allows you to use reserved word. For example:
int @class = 15;
The above works, when the below wouldn't:
int class = 15;
Here is the example macro to convert the Excel worksheet to XML file.
#'vba code to convert excel to xml
Sub vba_code_to_convert_excel_to_xml()
Set wb = Workbooks.Open("C:\temp\testwb.xlsx")
wb.SaveAs fileName:="C:\temp\testX.xml", FileFormat:= _
xlXMLSpreadsheet, ReadOnlyRecommended:=False, CreateBackup:=False
End Sub
This macro will open an existing Excel workbook from the C drive and Convert the file into XML and Save the file with .xml extension in the specified Folder. We are using Workbook Open method to open a file. SaveAs method to Save the file into destination folder. This example will be help full, if you wan to convert all excel files in a directory into XML (xlXMLSpreadsheet format) file.
erm it does work? I've just tested it?
/****** Object: Table [dbo].[DateTest] Script Date: 09/26/2008 10:44:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[DateTest](
[Date1] [datetime] NULL,
[Date2] [datetime] NOT NULL
) ON [PRIMARY]
GO
Insert into DateTest (Date1,Date2) VALUES (NULL,'1-Jan-2008')
Insert into DateTest (Date1,Date2) VALUES ('1-Jan-2008','1-Jan-2008')
Go
SELECT * FROM DateTest WHERE Date1 is not NULL
GO
SELECT * FROM DateTest WHERE Date2 is not NULL
I just encountered a case where changing from
</div>
<script src="addressofjavascriptfile.js"></script>
</body>
</html>
to
<script src="addressofjavascriptfile.js"></script>
</div>
</body>
</html>
fixed this problem.
If you need to use the latest versions of SciPy rather than the packaged version, without going through the hassle of building BLAS and LAPACK, you can follow the below procedure.
Install linear algebra libraries from repository (for Ubuntu),
sudo apt-get install gfortran libopenblas-dev liblapack-dev
Then install SciPy, (after downloading the SciPy source): python setup.py install
or
pip install scipy
As the case may be.
Perhaps I missed an example of where someone is handling nulls, but 3 TOP answers did not work for me when I had nulls ( Sure I realize that error handling is and million other things is NOT the responsibility of the person answering the question, but since I had used an existing function along with one of the excellent truncation ellipsis answers I thought I would provide it for others.
e.g.
javascript:
news.comments
using truncation function
news.comments.trunc(20, true);
However, on news.comments being null this would "break"
Final
checkNull(news.comments).trunc(20, true)
trunc function courtesy of KooiInc
String.prototype.trunc =
function (n, useWordBoundary) {
console.log(this);
var isTooLong = this.length > n,
s_ = isTooLong ? this.substr(0, n - 1) : this;
s_ = (useWordBoundary && isTooLong) ? s_.substr(0, s_.lastIndexOf(' ')) : s_;
return isTooLong ? s_ + '…' : s_;
};
My simple null checker (checks for literal "null" thing too (this catches undefined, "", null, "null", etc..)
function checkNull(val) {
if (val) {
if (val === "null") {
return "";
} else {
return val;
}
} else {
return "";
}
}
This is more to help people who end up here rather than answer the OP's question:
Try closing and re-opening visual studio, did the trick for me.
Hope this helps someone.
I did a test on MS SQL 2005 using the following tables: A 400K rows, B 26K rows and C 450 rows.
The estimated query plan indicated that the basic inner join would be 3 times slower than the nested sub-queries, however when actually running the query, the basic inner join was twice as fast as the nested queries, The basic inner join took 297ms on very minimal server hardware.
What database are you using, and what times are you seeing? I'm thinking if you are seeing poor performance then it is probably an index problem.
To the best of my knowledge, you need to put your entire Java app in UTC timezone (so that Hibernate will store dates in UTC), and you'll need to convert to whatever timezone desired when you display stuff (at least we do it this way).
At startup, we do:
TimeZone.setDefault(TimeZone.getTimeZone("Etc/UTC"));
And set the desired timezone to the DateFormat:
fmt.setTimeZone(TimeZone.getTimeZone("Europe/Budapest"))
This will work for an environment variable that is machine setting. For Users, just change to User instead.
String EnvironmentPath = System.Environment
.GetEnvironmentVariable("Variable_Name", EnvironmentVariableTarget.Machine);
end-of-file on communication channel:
One of the course of this error is due to database fail to write the log when its in the stage of opening;
Solution check the database if its running in ARCHIVELOG or NOARCHIVELOG
to check use
select log_mode from v$database;
if its on ARCHIVELOG
try to change into NOARCHIVELOG
by using sqlplus
if it works for this
Then you can adjust your flashrecovery area its possibly that your flashrecovery area is full
-> then after confirm that your flashrecovery area has the space you can alter your database into the ARCHIVELOG
As others have noted, strings are copied with strcpy()
or its variants. In certain cases, you could use snprintf()
as well.
You can only assign arrays the way you want as part of a structure assignment:
typedef struct { char a[18]; } array;
array array1 = { "abcdefg" };
array array2;
array2 = array1;
If your arrays are passed to a function, it will appear that you are allowed to assign them, but this is just an accident of the semantics. In C, an array will decay to a pointer type with the value of the address of the first member of the array, and this pointer is what gets passed. So, your array parameter in your function is really just a pointer. The assignment is just a pointer assignment:
void foo (char x[10], char y[10]) {
x = y; /* pointer assignment! */
puts(x);
}
The array itself remains unchanged after returning from the function.
This "decay to pointer value" semantic for arrays is the reason that the assignment doesn't work. The l-value has the array type, but the r-value is the decayed pointer type, so the assignment is between incompatible types.
char array1[18] = "abcdefg";
char array2[18];
array2 = array1; /* fails because array1 becomes a pointer type,
but array2 is still an array type */
As to why the "decay to pointer value" semantic was introduced, this was to achieve a source code compatibility with the predecessor of C. You can read The Development of the C Language for details.
The easiest way to do this is:
String hexadecimalString = String.format("%x", integerValue);
First, convert the timestamp using the built-in eloquent functionality, as described in this answer.
Then you can just use Carbon's min()
or max()
function for comparison. For example:
$dt1 = Carbon::create(2012, 1, 1, 0, 0, 0);
$dt2 = Carbon::create(2014, 1, 30, 0, 0, 0);
echo $dt1->min($dt2);
This will echo
the lesser of the two dates, which in this case is $dt1
.
UPDATE 2019-06-24
Based on the @Jodiug comment if you have a 1.15
version you can use the command:
kubectl rollout restart deployment/demo
Read more on the issue:
https://github.com/kubernetes/kubernetes/issues/13488
Well there is an interesting discussion about this subject on the kubernetes GitHub project. See the issue: https://github.com/kubernetes/kubernetes/issues/33664
From the solutions described there, I would suggest one of two.
1.Prepare deployment
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: demo
spec:
replicas: 1
template:
metadata:
labels:
app: demo
spec:
containers:
- name: demo
image: registry.example.com/apps/demo:master
imagePullPolicy: Always
env:
- name: FOR_GODS_SAKE_PLEASE_REDEPLOY
value: 'THIS_STRING_IS_REPLACED_DURING_BUILD'
2.Deploy
sed -ie "s/THIS_STRING_IS_REPLACED_DURING_BUILD/$(date)/g" deployment.yml
kubectl apply -f deployment.yml
kubectl patch deployment web -p \
"{\"spec\":{\"template\":{\"metadata\":{\"labels\":{\"date\":\"`date +'%s'`\"}}}}}"
Of course the imagePullPolicy: Always
is required on both cases.
Not being a Python person, but the easiest without any libraries is just:
total = 3800
seconds = total % 60
total = total - seconds
hours = total / 3600
total = total - (hours * 3600)
mins = total / 60
Apart from the <h:panelGroup>
component (which comes as a bit of a surprise to me), you could use a <f:verbatim>
tag with the escape parameter set to false
to generate any mark-up you want. For example:
<f:verbatim escape="true">
<div id="blah"></div>
</f:verbatim>
Bear in mind it's a little less elegant than the panelGroup
solution, as you have to generate this for both the start and end tags if you want to wrap any of your JSF code with the div
tag.
Alternatively, all the major UI Frameworks have a div
component tag, or you could write your own.
You can increase body size in nginx configuration file as
sudo nano /etc/nginx/nginx.conf
client_max_body_size 100M;
Restart nginx to apply the changes.
sudo service nginx restart
c = [i for i in b if i not in a]
Use the Apache XMLSerializer
here's an example: http://www.informit.com/articles/article.asp?p=31349&seqNum=3&rl=1
you can check this as well
In your codethis
refers to the select element not to the selected option
to refer the selected option you can do this -
$(this).find('option:selected').attr("name");
Concurrent signal assignment:
library ieee;
use ieee.std_logic_1164.all;
entity foo is
end;
architecture behave of foo is
signal clk: std_logic := '0';
begin
CLOCK:
clk <= '1' after 0.5 ns when clk = '0' else
'0' after 0.5 ns when clk = '1';
end;
ghdl -a foo.vhdl
ghdl -r foo --stop-time=10ns --wave=foo.ghw
ghdl:info: simulation stopped by --stop-time
gtkwave foo.ghw
Simulators simulate processes and it would be transformed into the equivalent process to your process statement. Simulation time implies the use of wait for or after when driving events for sensitivity clauses or sensitivity lists.
you could use something like:
[^0-9]+([0-9]+)[^0-9]+([0-9]+).+
Then get the first and second capture groups.
A little slower, but readable I think:
>>> s, l, m
([5, 4, 3, 2, 1, 0], [0, 1, 3, 5], [0, 0, 0, 0])
>>> d = dict(zip(l, m))
>>> d #dict is better then using two list i think
{0: 0, 1: 0, 3: 0, 5: 0}
>>> [d.get(i, j) for i, j in enumerate(s)]
[0, 0, 3, 0, 1, 0]
If you know the extension, you can use basename
$ basename /home/jsmith/base.wiki .wiki
base
Check out Math.Round. You can then cast the result to an int
.
Here is how i fixed it.
it will reinstall your pip within the environment and uninstall the previous version automatically.
now boom!! install whatever you like
In production site this seems suitable:
<?xml version="1.0"?>
<cross-domain-policy>
<allow-access-from domain="www.mysite.com" />
<allow-access-from domain="mysite.com" />
</cross-domain-policy>
you can use Intent for this:
Intent browserIntent = new Intent("android.intent.action.VIEW", Uri.parse("your Url"));
startActivity(browserIntent);
(this answer is not useful, but leaving it here since some of the comments may be)
docker images
will show the 'virtual size', i.e. how much in total including all the lower layers. So some double-counting if you have containers that share the same base image.
You cannot call a function that requires arguments in a template. Write a template tag or filter instead.
Use this jQuery extension by James Padoley
json
works with Unicode text in Python 3 (JSON format itself is defined only in terms of Unicode text) and therefore you need to decode bytes received in HTTP response. r.headers.get_content_charset('utf-8')
gets your the character encoding:
#!/usr/bin/env python3
import io
import json
from urllib.request import urlopen
with urlopen('https://httpbin.org/get') as r, \
io.TextIOWrapper(r, encoding=r.headers.get_content_charset('utf-8')) as file:
result = json.load(file)
print(result['headers']['User-Agent'])
It is not necessary to use io.TextIOWrapper
here:
#!/usr/bin/env python3
import json
from urllib.request import urlopen
with urlopen('https://httpbin.org/get') as r:
result = json.loads(r.read().decode(r.headers.get_content_charset('utf-8')))
print(result['headers']['User-Agent'])
Really, I went to this thread because of my Ubuntu locks screen after this shortcut Ctrl + Alt + L. So if you are have the same problem just go to the Settings - Keyboard - Shortcuts - System and change the default shortcut for the "Lock screen".
URL-encoded payload must be provided on the body
parameter of the http.NewRequest(method, urlStr string, body io.Reader)
method, as a type that implements io.Reader
interface.
Based on the sample code:
package main
import (
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
)
func main() {
apiUrl := "https://api.com"
resource := "/user/"
data := url.Values{}
data.Set("name", "foo")
data.Set("surname", "bar")
u, _ := url.ParseRequestURI(apiUrl)
u.Path = resource
urlStr := u.String() // "https://api.com/user/"
client := &http.Client{}
r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
resp, _ := client.Do(r)
fmt.Println(resp.Status)
}
resp.Status
is 200 OK
this way.
You can check if the string contains a decimal point using
string s="";
if (s.Contains(','))
{
//treat as double how you wish
}
and then treat that as a decimal, otherwise just pass the non-double value along.
A very simple answer to this very-complicated question. It involves no knowledge of code-signing and everything connected with it.
Take an old app that is not needed any more. Make sure it works, then replace its code with that of the new app having the code-signing error. The old app should now work fine, accomplishing what you wanted with the new app.
Only down side: the working app has the title of the old one.
If a bash script
If [[ $input -gt number || $input -lt number ]]
then
echo .........
else
echo .........
fi
exit
What about that?
private static List<String> extractString(List<Optional<String>> list) {
List<String> result = new ArrayList<>();
list.forEach(element -> element.ifPresent(result::add));
return result;
}
Here's one way:
// Utility function to extract arg name-value pairs
function getArgs(args) {
var argsObj = {};
var argList = /\(([^)]*)/.exec(args.callee)[1];
var argCnt = 0;
var tokens;
var argRe = /\s*([^,]+)/g;
while (tokens = argRe.exec(argList)) {
argsObj[tokens[1]] = args[argCnt++];
}
return argsObj;
}
// Test subject
function add(number1, number2) {
var args = getArgs(arguments);
console.log(args); // ({ number1: 3, number2: 4 })
}
// Invoke test subject
add(3, 4);
Note: This only works on browsers that support arguments.callee
.
If you want to achieve this selectively (ie: only to that particular link), you can use a non-breaking space instead of a normal space:
<li>submit resume</li>
https://en.wikipedia.org/wiki/Non-breaking_space#Encodings
edit: I understand that this is HTML, not CSS as requested by the OP, but some may find it helpful…
Simple.
Assuming that in your Activity-1
, you did this:
String stringExtra = "Some string you want to pass";
Intent intent = new Intent(this, AndroidTabRestaurantDescSearchListView.class);
//include the string in your intent
intent.putExtra("string", stringExtra);
startActivity(intent);
And in your AndroidTabRestaurantDescSearchListView class, do this:
//fetch the string from the intent
String extraFromAct1 = getIntent().getStringExtra("string");
Intent intent = new Intent(this, RatingDescriptionSearchActivity.class);
//attach same string and send it with the intent
intent.putExtra("string", extraFromAct1);
startActivity(intent);
Then in your RatingDescriptionSearchActivity class, do this:
String extraFromAct1 = getIntent().getStringExtra("string");
Another way to think of it is to calculate the unit vector for a given direction and then apply a 90 degree counterclockwise rotation to get the normal vector.
The matrix representation of the general 2D transformation looks like this:
x' = x cos(t) - y sin(t)
y' = x sin(t) + y cos(t)
where (x,y) are the components of the original vector and (x', y') are the transformed components.
If t = 90 degrees, then cos(90) = 0 and sin(90) = 1. Substituting and multiplying it out gives:
x' = -y
y' = +x
Same result as given earlier, but with a little more explanation as to where it comes from.
The correct way to change directories is actually with process.chdir(directory)
. Here's an example from the documentation:
console.log('Starting directory: ' + process.cwd());
try {
process.chdir('/tmp');
console.log('New directory: ' + process.cwd());
}
catch (err) {
console.log('chdir: ' + err);
}
This is also testable in the Node.js REPL:
[monitor@s2 ~]$ node
> process.cwd()
'/home/monitor'
> process.chdir('../');
undefined
> process.cwd();
'/home'
You can redirect standard input and use a StreamWriter to write to it:
Process p = new Process();
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "cmd.exe";
info.RedirectStandardInput = true;
info.UseShellExecute = false;
p.StartInfo = info;
p.Start();
using (StreamWriter sw = p.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
sw.WriteLine("mysql -u root -p");
sw.WriteLine("mypassword");
sw.WriteLine("use mydb;");
}
}
Found this works for me:
In the link:
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#message<?php echo $row['id'];?>">Message</button>
In the modal:
<div id="message<?php echo $row['id'];?>" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
<?php echo $row['id'];?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Here is a UITableView extension with Swift 5:
import UIKit
extension UITableView
{
func updateRow(row: Int, section: Int = 0)
{
let indexPath = IndexPath(row: row, section: section)
self.beginUpdates()
self.reloadRows(at: [indexPath as IndexPath], with: UITableView.RowAnimation.automatic)
self.endUpdates()
}
}
Call with
self.tableView.updateRow(row: 1)
Problem is due to problem in my applicationContext.xml vs spring-servlet.xml - it was scoping issue between the beans.
pedjaradenkovic kindly pointed me to an existing resource: Spring @Value annotation in @Controller class not evaluating to value inside properties file and Spring 3.0.5 doesn't evaluate @Value annotation from properties
Actually they are the same. LEFT OUTER JOIN
is same as LEFT JOIN
and RIGHT OUTER JOIN
is same as RIGHT JOIN
. It is more informative way to compare from INNER Join
.
See this Wikipedia article for details.
I had a problem with implementing the code until I found some website (I can't find it again right now) that explained that you need to include the package name in the name of the intent.putExtra.
It would pull up the application, but it wouldn't recognize any barcodes, and when I changed it from.
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
to
intent.putExtra("com.google.zxing.client.android.SCAN.SCAN_MODE", "QR_CODE_MODE");
It worked great. Just a tip for any other novice Android programmers.
write old function on your fields value for example
<input type="text" name="username" value="{{ old('username') }}">
In SQL
you can not have a variable array.
However, the best alternative solution is to use a temporary table.
There is a sorting algorithm in the standard library, in the header <algorithm>
. It sorts inplace, so if you do the following, your original word will become sorted.
std::sort(word.begin(), word.end());
If you don't want to lose the original, make a copy first.
std::string sortedWord = word;
std::sort(sortedWord.begin(), sortedWord.end());
*data interprets arguments as tuples, instead you have to pass **data which interprets the arguments as dictionary.
data = {'school':'DAV', 'class': '7', 'name': 'abc', 'city': 'pune'}
def my_function(**data):
schoolname = data['school']
cityname = data['city']
standard = data['class']
studentname = data['name']
You can call the function like this:
my_function(**data)
I don't know this is correct format or not. but it can solved my problem with removing type="text/css" when insert css code in html/tpl file with php.
<style type="text/css"></style>
_x000D_
become
<style></style>
_x000D_
If you are inside of Spring bean (in this case @Controller
bean) you shouldn't use Spring context instance at all. Just autowire className
bean directly.
BTW, avoid using field injection as it's considered as bad practice.
@Alexander Mills answer - just to make it easier to find:
RUN npm set unsafe-perm true
Thank you all for responding. After a further investigation I got to the right answer. As mentioned by Skip Head, the TimeStamped I was getting from my application was being adjusted to the user's TimeZone. So if the User entered 6:12 PM (EST) I would get 2:12 PM (GMT). What I needed was a way to undo the conversion so that the time entered by the user is the time I sent to the WebServer request. Here's how I accomplished this:
// Get TimeZone of user
TimeZone currentTimeZone = sc_.getTimeZone();
Calendar currentDt = new GregorianCalendar(currentTimeZone, EN_US_LOCALE);
// Get the Offset from GMT taking DST into account
int gmtOffset = currentTimeZone.getOffset(
currentDt.get(Calendar.ERA),
currentDt.get(Calendar.YEAR),
currentDt.get(Calendar.MONTH),
currentDt.get(Calendar.DAY_OF_MONTH),
currentDt.get(Calendar.DAY_OF_WEEK),
currentDt.get(Calendar.MILLISECOND));
// convert to hours
gmtOffset = gmtOffset / (60*60*1000);
System.out.println("Current User's TimeZone: " + currentTimeZone.getID());
System.out.println("Current Offset from GMT (in hrs):" + gmtOffset);
// Get TS from User Input
Timestamp issuedDate = (Timestamp) getACPValue(inputs_, "issuedDate");
System.out.println("TS from ACP: " + issuedDate);
// Set TS into Calendar
Calendar issueDate = convertTimestampToJavaCalendar(issuedDate);
// Adjust for GMT (note the offset negation)
issueDate.add(Calendar.HOUR_OF_DAY, -gmtOffset);
System.out.println("Calendar Date converted from TS using GMT and US_EN Locale: "
+ DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT)
.format(issueDate.getTime()));
The code's output is: (User entered 5/1/2008 6:12PM (EST)
Current User's TimeZone: EST
Current Offset from GMT (in hrs):-4 (Normally -5, except is DST adjusted)
TS from ACP: 2008-05-01 14:12:00.0
Calendar Date converted from TS using GMT and US_EN Locale: 5/1/08 6:12 PM (GMT)
Using spring-data-jpa save()
, I was having same problem as @DtechNet. I mean every save()
was creating new object instead of update. To solve this I had to add version
field to entity and related table.
EDIT: The canonical way using newer JavaScript features is -
const identity = x =>
x
const omap = (f = identity, o = {}) =>
Object.fromEntries(
Object.entries(o).map(([ k, v ]) =>
[ k, f(v) ]
)
)
Where o
is some object and f
is your mapping function. Or we could say, given a function from a -> b
, and an object with values of type a
, produce an object with values of type b
. As a pseudo type signature -
// omap : (a -> b, { a }) -> { b }
The original answer was written to demonstrate a powerful combinator, mapReduce
which allows us to think of our transformation in a different way
m
, the mapping function – gives you a chance to transform the incoming element before…r
, the reducing function – this function combines the accumulator with the result of the mapped elementIntuitively, mapReduce
creates a new reducer we can plug directly into Array.prototype.reduce
. But more importantly, we can implement our object functor implementation omap
plainly by utilizing the object monoid, Object.assign
and {}
.
const identity = x =>_x000D_
x_x000D_
_x000D_
const mapReduce = (m, r) =>_x000D_
(a, x) => r (a, m (x))_x000D_
_x000D_
const omap = (f = identity, o = {}) =>_x000D_
Object_x000D_
.keys (o)_x000D_
.reduce_x000D_
( mapReduce_x000D_
( k => ({ [k]: f (o[k]) })_x000D_
, Object.assign_x000D_
)_x000D_
, {}_x000D_
)_x000D_
_x000D_
const square = x =>_x000D_
x * x_x000D_
_x000D_
const data =_x000D_
{ a : 1, b : 2, c : 3 }_x000D_
_x000D_
console .log (omap (square, data))_x000D_
// { a : 1, b : 4, c : 9 }
_x000D_
Notice the only part of the program we actually had to write is the mapping implementation itself –
k => ({ [k]: f (o[k]) })
Which says, given a known object o
and some key k
, construct an object and whose computed property k
is the result of calling f
on the key's value, o[k]
.
We get a glimpse of mapReduce
's sequencing potential if we first abstract oreduce
// oreduce : (string * a -> string * b, b, { a }) -> { b }
const oreduce = (f = identity, r = null, o = {}) =>
Object
.keys (o)
.reduce
( mapReduce
( k => [ k, o[k] ]
, f
)
, r
)
// omap : (a -> b, {a}) -> {b}
const omap = (f = identity, o = {}) =>
oreduce
( mapReduce
( ([ k, v ]) =>
({ [k]: f (v) })
, Object.assign
)
, {}
, o
)
Everything works the same, but omap
can be defined at a higher-level now. Of course the new Object.entries
makes this look silly, but the exercise is still important to the learner.
You won't see the full potential of mapReduce
here, but I share this answer because it's interesting to see just how many places it can be applied. If you're interested in how it is derived and other ways it could be useful, please see this answer.
In general Value Objects should be Immutable. Like Integer or String objects in Java. We can use them for transferring data between software layers. If the software layers or services running in different remote nodes like in a microservices environment or in a legacy Java Enterprise App. We must make almost exact copies of two classes. This is the where we met DTOs.
|-----------| |--------------|
| SERVICE 1 |--> Credentials DTO >--------> Credentials DTO >-- | AUTH SERVICE |
|-----------| |--------------|
In legacy Java Enterprise Systems DTOs can have various EJB stuff in it.
I do not know this is a best practice or not but I personally use Value Objects in my Spring MVC/Boot Projects like this:
|------------| |------------------| |------------|
-> Form | | -> Form | | -> Entity | |
| Controller | | Service / Facade | | Repository |
<- View | | <- View | | <- Entity / Projection View | |
|------------| |------------------| |------------|
Controller layer doesn't know what are the entities are. It communicates with Form and View Value Objects. Form Objects has JSR 303 Validation annotations (for instance @NotNull) and View Value Objects have Jackson Annotations for custom serialization. (for instance @JsonIgnore)
Service layer communicates with repository layer via using Entity Objects. Entity objects have JPA/Hibernate/Spring Data annotations on it. Every layer communicates with only the lower layer. The inter-layer communication is prohibited because of circular/cyclic dependency.
User Service ----> XX CANNOT CALL XX ----> Order Service
Some ORM Frameworks have the ability of projection via using additional interfaces or classes. So repositories can return View objects directly. There for you do not need an additional transformation.
For instance this is our User entity:
@Entity
public final class User {
private String id;
private String firstname;
private String lastname;
private String phone;
private String fax;
private String address;
// Accessors ...
}
But you should return a Paginated list of users that just include id, firstname, lastname. Then you can create a View Value Object for ORM projection.
public final class UserListItemView {
private String id;
private String firstname;
private String lastname;
// Accessors ...
}
You can easily get the paginated result from repository layer. Thanks to spring you can also use just interfaces for projections.
List<UserListItemView> find(Pageable pageable);
Don't worry for other conversion operations BeanUtils.copy
method works just fine.
Some important facts were not given in other answers:
"async await" is more complex at CIL level and thus costs memory and CPU time.
Any task can be canceled if the waiting time is unacceptable.
In the case "async await" we do not have a handler for such a task to cancel it or monitoring it.
Using Task is more flexible then "async await".
Any sync functionality can by wrapped by async.
public async Task<ActionResult> DoAsync(long id)
{
return await Task.Run(() => { return DoSync(id); } );
}
"async await" generate many problems. We do not now is await statement will be reached without runtime and context debugging. If first await not reached everything is blocked. Some times even await seems to be reached still everything is blocked:
https://github.com/dotnet/runtime/issues/36063
I do not see why I'm must live with the code duplication for sync and async method or using hacks.
Conclusion: Create Task manually and control them is much better. Handler to Task give more control. We can monitor Tasks and manage them:
https://github.com/lsmolinski/MonitoredQueueBackgroundWorkItem
Sorry for my english.
This code lists modules imported by your module:
import sys
before = [str(m) for m in sys.modules]
import my_module
after = [str(m) for m in sys.modules]
print [m for m in after if not m in before]
It should be useful if you want to know what external modules to install on a new system to run your code, without the need to try again and again.
It won't list the sys
module or modules imported from it.
Window->Show View->Navigator, should pop up the navigator panel on the left hand side, showing the projects list.
It's probably already open in the workspace, but you may have closed the navigator panel, so it looks like you don't have the project open.
Eclipse using ADT Build v22.0.0-675183 on Linux.
You could use Spring AOP aproach. For example if you have some service, that needs to know current principal. You could introduce custom annotation i.e. @Principal , which indicate that this Service should be principal dependent.
public class SomeService {
private String principal;
@Principal
public setPrincipal(String principal){
this.principal=principal;
}
}
Then in your advice, which I think needs to extend MethodBeforeAdvice, check that particular service has @Principal annotation and inject Principal name, or set it to 'ANONYMOUS' instead.
It looks like you're passing in Null for every argument except for PropertyValueID and DropDownOptionID, right? I don't think any of your IF statements will fire if only these two values are not-null. In short, I think you have a logic error.
Other than that, I would suggest two things...
First, instead of testing for NULL, use this kind syntax on your if statements (it's safer)...
ELSE IF ISNULL(@UnitValue, 0) != 0 AND ISNULL(@UnitOfMeasureID, 0) = 0
Second, add a meaningful PRINT statement before each UPDATE. That way, when you run the sproc in MSSQL, you can look at the messages and see how far it's actually getting.
try something like this
#vote_links a
will catch all ids inside vote links div id ...
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(\'#vote_links a\').click(function() {// alert(\'vote clicked\');
var det = jQuery(this).get(0).id.split("-");// alert(jQuery(this).get(0).id);
var votes_id = det[0];
$("#about-button").css({
opacity: 0.3
});
$("#contact-button").css({
opacity: 0.3
});
$("#page-wrap div.button").click(function(){
Removing a activity from a History is done By setting the flag before the activity You Don't want
A->B->C->D
Suppose A,B,C and D are 4 Activities if you want to clear B and C then set flag
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
In the activity A and B
Here is the code bit
Intent intent = new Intent(this,Activity_B.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
Below conf works for me:
JAVA_HOME=/JDK1.7.51-64/jdk1.7.0_51/
PATH=/JDK1.7.51-64/jdk1.7.0_51/bin:$PATH
export PATH
export JAVA_HOME
JVM_ARGS="-d64 -Xms1024m -Xmx15360m -server"
/JDK1.7.51-64/jdk1.7.0_51/bin/java $JVM_ARGS -jar `dirname $0`/ApacheJMeter.jar "$@"
As hoijui mentions. The selected answer from Stephen Katulka contains a comment about Collections.copy that is incorrect. The author probably accepted it because the first line of code was doing the copy that he wanted. The additional call to Collections.copy just copies again. (Resulting in the copy happening twice).
Here is code to prove it.
public static void main(String[] args) {
List<String> a = new ArrayList<String>();
a.add("a");
a.add("b");
a.add("c");
List<String> b = new ArrayList<String>(a);
System.out.println("There should be no output after this line.");
// Note, b is already a shallow copy of a;
for (int i = 0; i < a.size(); i++) {
if (a.get(i) != b.get(i)) {
System.out.println("Oops, this was a deep copy."); // Note this is never called.
}
}
// Now use Collections.copy and note that b is still just a shallow copy of a
Collections.copy(b, a);
for (int i = 0; i < a.size(); i++) {
if (a.get(i) != b.get(i)) {
System.out.println("Oops, i was wrong this was a deep copy"); // Note this is never called.
}
}
// Now do a deep copy - requires you to explicitly copy each element
for (int i = 0; i < a.size(); i++) {
b.set(i, new String(a.get(i)));
}
// Now see that the elements are different in each
for (int i = 0; i < a.size(); i++) {
if (a.get(i) == b.get(i)) {
System.out.println("oops, i was wrong, a shallow copy was done."); // note this is never called.
}
}
}
Cant we simply say it like.. We cannot inherit constructors. So there is no point declaring them virtual because the virtual provides polymorphism .
When it comes to using a very long number that may exceed 32 bits to represent, you may use long to make sure that you'll not have strange behavior.
From Java 5 you can use in-boxing and out-boxing features to make the use of int and Integer completely the same. It means that you can do :
int myInt = new Integer(11);
Integer myInt2 = myInt;
The in and out boxing allow you to switch between int and Integer without any additional conversion (same for Long
,Double
,Short
too)
You may use int
all the time, but Integer
contains some helper methods that can help you to do some complex operations with integers (such as Integer.parseInt(String)
)
In Jan2018 the only solution worked for me:
<?php
if (ob_get_level() == 0) ob_start();
for ($i = 0; $i<10; $i++){
echo "<br> Line to show.";
echo str_pad('',4096)."\n";
ob_flush();
flush();
sleep(2);
}
echo "Done.";
ob_end_flush();
?>
From stack trace:
HikariPool: Timeout failure pool HikariPool-0 stats (total=20, active=20, idle=0, waiting=0) Means pool reached maximum connections limit set in configuration.
The next line: HikariPool-0 - Connection is not available, request timed out after 30000ms. Means pool waited 30000ms for free connection but your application not returned any connection meanwhile.
Mostly it is connection leak (connection is not closed after borrowing from pool), set leakDetectionThreshold to the maximum value that you expect SQL query would take to execute.
otherwise, your maximum connections 'at a time' requirement is higher than 20 !
git diff -p
used in muhqu's answer may not show all discrepancies.
core.filemode
is false
(which is the default for MSysGit)This code reads the metadata directly instead:
(set -o errexit pipefail nounset;
git ls-tree HEAD -z | while read -r -d $'\0' mask type blob path
do
if [ "$type" != "blob" ]; then continue; fi;
case "$mask" in
#do not touch other bits
100644) chmod a-x "$path";;
100755) chmod a+x "$path";;
*) echo "invalid: $mask $type $blob\t$path" >&2; false;;
esac
done)
A non-production-grade one-liner (replaces masks entirely):
git ls-tree HEAD | perl -ne '/^10(0\d{3}) blob \S+\t(.+)$/ && { system "chmod",$1,$2 || die }'
(Credit for "$'\0'" goes to http://transnum.blogspot.ru/2008/11/bashs-read-built-in-supports-0-as.html)
You should take a look the reference documentation. It's well explained.
In your case, I think you cannot use between because you need to pass two parameters
Between - findByStartDateBetween … where x.startDate between ?1 and ?2
In your case take a look to use a combination of LessThan
or LessThanEqual
with GreaterThan
or GreaterThanEqual
LessThan - findByEndLessThan … where x.start< ?1
LessThanEqual findByEndLessThanEqual … where x.start <= ?1
GreaterThan - findByStartGreaterThan … where x.end> ?1
GreaterThanEqual - findByStartGreaterThanEqual … where x.end>= ?1
You can use the operator And
and Or
to combine both.
First, let's make some test data:
create table client (client_id integer not null primary key auto_increment,
name varchar(64));
create table portfolio (portfolio_id integer not null primary key auto_increment,
client_id integer references client.id,
cash decimal(10,2),
stocks decimal(10,2));
insert into client (name) values ('John Doe'), ('Jane Doe');
insert into portfolio (client_id, cash, stocks) values (1, 11.11, 22.22),
(1, 10.11, 23.22),
(2, 30.30, 40.40),
(2, 40.40, 50.50);
If you didn't need the portfolio ID, it would be easy:
select client_id, name, max(cash + stocks)
from client join portfolio using (client_id)
group by client_id
+-----------+----------+--------------------+
| client_id | name | max(cash + stocks) |
+-----------+----------+--------------------+
| 1 | John Doe | 33.33 |
| 2 | Jane Doe | 90.90 |
+-----------+----------+--------------------+
Since you need the portfolio ID, things get more complicated. Let's do it in steps. First, we'll write a subquery that returns the maximal portfolio value for each client:
select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id
+-----------+----------+
| client_id | maxtotal |
+-----------+----------+
| 1 | 33.33 |
| 2 | 90.90 |
+-----------+----------+
Then we'll query the portfolio table, but use a join to the previous subquery in order to keep only those portfolios the total value of which is the maximal for the client:
select portfolio_id, cash + stocks from portfolio
join (select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal
+--------------+---------------+
| portfolio_id | cash + stocks |
+--------------+---------------+
| 5 | 33.33 |
| 6 | 33.33 |
| 8 | 90.90 |
+--------------+---------------+
Finally, we can join to the client table (as you did) in order to include the name of each client:
select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal
+-----------+----------+--------------+---------------+
| client_id | name | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
| 1 | John Doe | 5 | 33.33 |
| 1 | John Doe | 6 | 33.33 |
| 2 | Jane Doe | 8 | 90.90 |
+-----------+----------+--------------+---------------+
Note that this returns two rows for John Doe because he has two portfolios with the exact same total value. To avoid this and pick an arbitrary top portfolio, tag on a GROUP BY clause:
select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal
group by client_id, cash + stocks
+-----------+----------+--------------+---------------+
| client_id | name | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
| 1 | John Doe | 5 | 33.33 |
| 2 | Jane Doe | 8 | 90.90 |
+-----------+----------+--------------+---------------+
You can also use the boar
package to run your notebook within a python code.
from boar.running import run_notebook
outputs = run_notebook("nb.ipynb")
If you update your notebook, you won't have to convert it again to a python file.
More information at:
https://github.com/alexandreCameron/boar/blob/master/USAGE.md
chmod a+x
modifies the argument's mode while chmod 755
sets it. Try both variants on something that has full or no permissions and you will notice the difference.
Just to add to the answers above,
I was having a 2 regular buttons as shown below. (No type="submit"anywhere)
<button ng-click="clearAll();" class="btn btn-default">Clear Form</button>
<button ng-disabled="form.$invalid" ng-click="submit();"class="btn btn-primary pull-right">Submit</button>
No matter how much i tried, pressing enter once the form was valid, the "Clear Form" button was called, clearing the entire form.
As a workaround,
I had to add a dummy submit button which was disabled and hidden. And This dummy button had to be on top of all the other buttons as shown below.
<button type="submit" ng-hide="true" ng-disabled="true">Dummy</button>
<button ng-click="clearAll();" class="btn btn-default">Clear Form</button>
<button ng-disabled="form.$invalid" ng-click="submit();"class="btn btn-primary pull-right">Submit</button>
Well, my intention was never to submit on Enter, so the above given hack just works fine.
Take a look at WordUtils in the Apache Commons lang library:
Specifically, the capitalizeFully(String str, char[] delimiters) method should do the job:
String blah = "LORD_OF_THE_RINGS";
assertEquals("LordOfTheRings", WordUtils.capitalizeFully(blah, new char[]{'_'}).replaceAll("_", ""));
Green bar!