In Kotlin you can create extension property:
inline var TextView.underline: Boolean
set(visible) {
paintFlags = if (visible) paintFlags or Paint.UNDERLINE_TEXT_FLAG
else paintFlags and Paint.UNDERLINE_TEXT_FLAG.inv()
}
get() = paintFlags and Paint.UNDERLINE_TEXT_FLAG == Paint.UNDERLINE_TEXT_FLAG
And use:
textView.underline = true
Try this
-moz-box-shadow:0 5px 5px rgba(182, 182, 182, 0.75);
-webkit-box-shadow: 0 5px 5px rgba(182, 182, 182, 0.75);
box-shadow: 0 5px 5px rgba(182, 182, 182, 0.75);
You can see it in http://jsfiddle.net/wJ7qp/
Here is the easiest solution which works for me without writing additional codes.
// To underline text in UILable
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"Type your text here"];
[text addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(0, text.length)];
lblText.attributedText = text;
In Jupyter Notebooks you can use Markdown in the following way for underlined text. This is similar to HTML5: (<u>
and </u>
).
<u>Underlined Words Here</u>
The simplest option is this:
<a style="text-decoration: none">No underline</a>
Of course, mixing CSS with HTML (i.e. inline CSS) is not a good idea, especially when you are using a
tags all over the place.
That's why it's a good idea to add this to a stylesheet instead:
a {
text-decoration: none;
}
Or even this code in a JS file:
var els = document.getElementsByTagName('a');
for (var el = 0; el < els.length; el++) {
els[el].style["text-decoration"] = "none";
}
You are not applying text-decoration: none;
to an anchor (.boxhead a
) but to a span element (.boxhead
).
Try this:
.boxhead a {
color: #FFFFFF;
text-decoration: none;
}
This is what i use:
html:
<h6><span class="horizontal-line">GET IN</span> TOUCH</h6>
css:
.horizontal-line { border-bottom: 2px solid #FF0000; padding-bottom: 5px; }
There's now a new css3 property for this: text-decoration-color
So you can now have text in one color and a text-decoration underline - in a different color... without needing an extra 'wrap' element
p {_x000D_
text-decoration: underline;_x000D_
-webkit-text-decoration-color: red; /* safari still uses vendor prefix */_x000D_
text-decoration-color: red;_x000D_
}
_x000D_
<p>black text with red underline in one element - no wrapper elements here!</p>
_x000D_
NB:
1) Browser Support is limited at the moment to Firefox and Chrome (fully supported as of V57) and Safari
2) You could also use the text-decoration shorthand property which looks like this:
<text-decoration-line> || <text-decoration-style> || <text-decoration-color>
...so using the text-decoration
shorthand - the example above would simply be:
p {
text-decoration: underline red;
}
p {_x000D_
text-decoration: underline red;_x000D_
}
_x000D_
<p>black text with red underline in one element - no wrapper elements here!</p>
_x000D_
To complete Bhavin answer. For exemple, to add underline or redirection.
((TextView) findViewById(R.id.tv_cgu)).setText(Html.fromHtml(getString(R.string.upload_poi_CGU)));
<string name="upload_poi_CGU"><![CDATA[ J\'accepte les <a href="">conditions générales</a>]]></string>
and you can know compatible tag here : http://commonsware.com/blog/Android/2010/05/26/html-tags-supported-by-textview.html
Add a style with the attribute text-decoration:none;
:
There are a number of different ways of doing this.
Inline style:
<a href="xxx.html" style="text-decoration:none;">goto this link</a>
Inline stylesheet:
<html>
<head>
<style type="text/css">
a {
text-decoration:none;
}
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>
External stylesheet:
<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>
stylesheet.css:
a {
text-decoration:none;
}
Use the following CSS codes...
text-decoration:underline;
text-decoration-style: dotted;
decoration: InputDecoration(
border:OutLineInputBorder(
borderSide:BorderSide.none
bordeRadius: BordeRadius.circular(20.0)
)
)
Something like the following bash script will retrieve the lastest com.company:artifact
snapshot from the snapshot
repo:
# Artifactory location
server=http://artifactory.company.com/artifactory
repo=snapshot
# Maven artifact location
name=artifact
artifact=com/company/$name
path=$server/$repo/$artifact
version=$(curl -s $path/maven-metadata.xml | grep latest | sed "s/.*<latest>\([^<]*\)<\/latest>.*/\1/")
build=$(curl -s $path/$version/maven-metadata.xml | grep '<value>' | head -1 | sed "s/.*<value>\([^<]*\)<\/value>.*/\1/")
jar=$name-$build.jar
url=$path/$version/$jar
# Download
echo $url
wget -q -N $url
It feels a bit dirty, yes, but it gets the job done.
Like others have said, it's not possible with just JavaScript due to the security model of such.
If you are able to, I'd recommend one of the below solutions..both of which use a flash component for the client side validations; however, are wired up using Javascript/jQuery. Both work very well and can be used with any server-side tech.
In Ruby 2.1.3 things have changed:
> endDate = Date.new(2014, 1, 2)
=> #<Date: 2014-01-02 ((2456660j,0s,0n),+0s,2299161j)>
> beginDate = Date.new(2014, 1, 1)
=> #<Date: 2014-01-01 ((2456659j,0s,0n),+0s,2299161j)>
> days = endDate - beginDate
=> (1/1)
> days.class
=> Rational
> days.to_i
=> 1
Try this if you wan't to use SSL certificates:
import subprocess
try:
# Set scp and ssh data.
connUser = 'john'
connHost = 'my.host.com'
connPath = '/home/john/'
connPrivateKey = '/home/user/myKey.pem'
# Use scp to send file from local to host.
scp = subprocess.Popen(['scp', '-i', connPrivateKey, 'myFile.txt', '{}@{}:{}'.format(connUser, connHost, connPath)])
except CalledProcessError:
print('ERROR: Connection to host failed!')
There are indeed global variables in javascript. You can learn more about scopes, which are helpful in this situation.
Your code could look like this:
<script>
var count = 1;
function setColor(btn, color) {
var property = document.getElementById(btn);
if (count == 0) {
property.style.backgroundColor = "#FFFFFF"
count = 1;
}
else {
property.style.backgroundColor = "#7FFF00"
count = 0;
}
}
</script>
Hope this helps.
You'll need to write an insert trigger, and possible an update trigger if you want it to change when the record is changed. This article explains it quite nicely:
http://www.revsys.com/blog/2006/aug/04/automatically-updating-a-timestamp-column-in-postgresql/
CREATE OR REPLACE FUNCTION update_modified_column() RETURNS TRIGGER AS $$ BEGIN NEW.modified = now(); RETURN NEW; END; $$ language 'plpgsql';
Apply the trigger like this:
CREATE TRIGGER update_customer_modtime BEFORE UPDATE ON customer FOR EACH ROW EXECUTE PROCEDURE update_modified_column();
There are many other answers to this question, but still, the following works best for me, as I needed a command line solution:
vim -u NONE -c 'e ++ff=dos' -c 'w ++ff=unix' -c q myfile
Explanation:
myfile
:e ++ff=dos
to force a reload of the entire file as dos line endings.:w ++ff=unix
to write the file using unix line endingsIIRC they suggest using the preg_
functions instead (in this case, preg_replace
).
The first thing you should do with date variables is confirm that R reads it as a Date. To do this, for the variable (i.e. vector/column) called Date, in the data frame called EPL2011_12, input
class(EPL2011_12$Date)
The output should read [1] "Date". If it doesn't, you should format it as a date by inputting
EPL2011_12$Date <- as.Date(EPL2011_12$Date, "%d-%m-%y")
Note that the hyphens in the date format ("%d-%m-%y") above can also be slashes ("%d/%m/%y"). Confirm that R sees it as a Date. If it doesn't, try a different formatting command
EPL2011_12$Date <- format(EPL2011_12$Date, format="%d/%m/%y")
Once you have it in Date format, you can use the subset
command, or you can use brackets
WhateverYouWant <- EPL2011_12[EPL2011_12$Date > as.Date("2014-12-15"),]
Just Call the following single line code:
$expectedString = end(explode('-', $orignalString));
You have two choices:
Use fileno()
to obtain the file descriptor associated with the stdio
stream pointer
Don't use <stdio.h>
at all, that way you don't need to worry about flush either - all writes will go to the device immediately, and for character devices the write()
call won't even return until the lower-level IO has completed (in theory).
For device-level IO I'd say it's pretty unusual to use stdio
. I'd strongly recommend using the lower-level open()
, read()
and write()
functions instead (based on your later reply):
int fd = open("/dev/i2c", O_RDWR);
ioctl(fd, IOCTL_COMMAND, args);
write(fd, buf, length);
Things get messy quickly if you are talking about checked-in code in an enterprise environment. We've found that the best approach is to have the web.Release.config contain the following:
<system.web>
<compilation xdt:Transform="RemoveAttributes(debug)" />
<authentication>
<forms xdt:Transform="Replace" timeout="20" requireSSL="true" />
</authentication>
</system.web>
That way, developers are not affected (running in Debug), and only servers that get Release builds are requiring cookies to be SSL.
If you define your function to take argument of std::vector<int>& arr
and integer value, then you can use push_back
inside that function:
void do_something(int el, std::vector<int>& arr)
{
arr.push_back(el);
//....
}
usage:
std::vector<int> arr;
do_something(1, arr);
set scan off; Above command also works.
On my mac from a terminal:
$ ./adb kill-server
$ ./adb start-server
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
I opened the eclipse and set the ddms port to 5037. it works fine.
$scope.rtGo = function(){
$window.sessionStorage.removeItem('message');
$window.sessionStorage.removeItem('status');
}
I think you are looking for qsort
.
qsort
function is the implementation of quicksort algorithm found in stdlib.h
in C/C++
.
Here is the syntax to call qsort
function:
void qsort(void *base, size_t nmemb, size_t size,int (*compar)(const void *, const void *));
List of arguments:
base: pointer to the first element or base address of the array
nmemb: number of elements in the array
size: size in bytes of each element
compar: a function that compares two elements
Here is a code example which uses qsort
to sort an array:
#include <stdio.h>
#include <stdlib.h>
int arr[] = { 33, 12, 6, 2, 76 };
// compare function, compares two elements
int compare (const void * num1, const void * num2) {
if(*(int*)num1 > *(int*)num2)
return 1;
else
return -1;
}
int main () {
int i;
printf("Before sorting the array: \n");
for( i = 0 ; i < 5; i++ ) {
printf("%d ", arr[i]);
}
// calling qsort
qsort(arr, 5, sizeof(int), compare);
printf("\nAfter sorting the array: \n");
for( i = 0 ; i < 5; i++ ) {
printf("%d ", arr[i]);
}
return 0;
}
You can type man 3 qsort
in Linux/Mac terminal to get a detailed info about qsort
.
Link to qsort man page
You can disable SSL certificate checking by adding one or more of these command line parameters:
-Dmaven.wagon.http.ssl.insecure=true
- enable use of relaxed SSL check for user generated certificates.-Dmaven.wagon.http.ssl.allowall=true
- enable match of the server's X.509 certificate with hostname. If disabled, a browser like check will be used.-Dmaven.wagon.http.ssl.ignore.validity.dates=true
- ignore issues with certificate dates.Official documentation: http://maven.apache.org/wagon/wagon-providers/wagon-http/
Here's the oneliner for an easy copy-and-paste:
-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true -Dmaven.wagon.http.ssl.ignore.validity.dates=true
Ajay Gautam suggested that you could also add the above to the ~/.mavenrc
file as not to have to specify it every time at command line:
$ cat ~/.mavenrc
MAVEN_OPTS="-Dmaven.wagon.http.ssl.insecure=true -Dmaven.wagon.http.ssl.allowall=true -Dmaven.wagon.http.ssl.ignore.validity.dates=true"
this
on a C++ compilerThe C++ compiler will silently lookup for a symbol if it does not find it immediately. Sometimes, most of the time, it is good:
But sometimes, You just don't want the compiler to guess. You want the compiler to pick-up the right symbol and not another.
For me, those times are when, within a method, I want to access to a member method or member variable. I just don't want some random symbol picked up just because I wrote printf
instead of print
. this->printf
would not have compiled.
The point is that, with C legacy libraries (§), legacy code written years ago (§§), or whatever could happen in a language where copy/pasting is an obsolete but still active feature, sometimes, telling the compiler to not play wits is a great idea.
These are the reasons I use this
.
(§) it's still a kind of mystery to me, but I now wonder if the fact you include the <windows.h> header in your source, is the reason all the legacy C libraries symbols will pollute your global namespace
(§§) realizing that "you need to include a header, but that including this header will break your code because it uses some dumb macro with a generic name" is one of those russian roulette moments of a coder's life
List_of_input=list(map(int,input (). split ()))
print(List_of_input)
It's for Python3.
This fixes it:
let str = "This-is-a-news-item-";
str = str.replace(/-/g, ' ');
alert(str);
There were two problems with your code:
g
flag, for 'global', so that all instances will be replaced.//vanilla php
Class Date {
public static function date_added($time){
date_default_timezone_set('Africa/Lagos');//or choose your location
return date('l F Y g:i:s ',$time);
}
}
If you followed instructions like these:
https://getcomposer.org/doc/00-intro.md
Which tell you to do the following:
$ curl -sS https://getcomposer.org/installer | php
$ mv composer.phar /usr/local/bin/composer
Then it's likely that you, like me, ran those commands and didn't read the next part of the page telling you to stop referring to composer.phar by its full name and abbreviate it as an executable (that you just renamed with the mv command). So this:
$ php composer.phar update friendsofsymfony/elastica-bundle
Becomes this:
$ composer update friendsofsymfony/elastica-bundle
It's possible, as addressed in Issue #7396:
When you do want to insert a
<br />
break tag using Markdown, you end a line with two or more spaces, then type return or Enter.
=ADDRESS(ROW(),COLUMN(),4)
will give us the relative address of the current cell.
=INDIRECT(ADDRESS(ROW(),COLUMN()-1,4))
will give us the contents of the cell left of the current cell
=INDIRECT(ADDRESS(ROW()-1,COLUMN(),4))
will give us the contents of the cell above the current cell (great for calculating running totals)
Using CELL() function returns information about the last cell that was changed. So, if we enter a new row or column the CELL() reference will be affected and will not be the current cell's any longer.
Layers refer to logical seperation of code. Logical layers help you organise your code better. For example an application can have the following layers.
1)Presentation Layer or UI Layer 2)Business Layer or Business Logic Layer 3)Data Access Layer or Data Layer
The aboove three layers reside in their own projects, may be 3 projects or even more. When we compile the projects we get the respective layer DLL. So we have 3 DLL's now.
Depending upon how we deploy our application, we may have 1 to 3 tiers. As we now have 3 DLL's, if we deploy all the DLL's on the same machine, then we have only 1 physical tier but 3 logical layers.
If we choose to deploy each DLL on a seperate machine, then we have 3 tiers and 3 layers.
So, Layers are a logical separation and Tiers are a physical separation. We can also say that, tiers are the physical deployment of layers.
There's a description of how to do this at Resize a column in a PostgreSQL table without changing data. You have to hack the database catalog data. The only way to do this officially is with ALTER TABLE, and as you've noted that change will lock and rewrite the entire table while it's running.
Make sure you read the Character Types section of the docs before changing this. All sorts of weird cases to be aware of here. The length check is done when values are stored into the rows. If you hack a lower limit in there, that will not reduce the size of existing values at all. You would be wise to do a scan over the whole table looking for rows where the length of the field is >40 characters after making the change. You'll need to figure out how to truncate those manually--so you're back some locks just on oversize ones--because if someone tries to update anything on that row it's going to reject it as too big now, at the point it goes to store the new version of the row. Hilarity ensues for the user.
VARCHAR is a terrible type that exists in PostgreSQL only to comply with its associated terrible part of the SQL standard. If you don't care about multi-database compatibility, consider storing your data as TEXT and add a constraint to limits its length. Constraints you can change around without this table lock/rewrite problem, and they can do more integrity checking than just the weak length check.
I was using firefox and some reason, it was not taking the click command though from past 2months it was working. My feeling was to make use of sendKeys and this page solved the problem. Now I am using sendKeys(Keys.Enter)
Use your browser's network inspector (F12) to see when the browser is requesting the bgbody.png image and what absolute path it's using and why the server is returning a 404 response.
...assuming that bgbody.png actually exists :)
Is your CSS in a stylesheet file or in a <style>
block in a page? If it's in a stylesheet then the relative path must be relative to the CSS stylesheet (not the document that references it). If it's in a page then it must be relative to the current resource path. If you're using non-filesystem-based resource paths (i.e. using URL rewriting or URL routing) then this will cause problems and it's best to always use absolute paths.
Going by your relative path it looks like you store your images separately from your stylesheets. I don't think this is a good idea - I support storing images and other resources, like fonts, in the same directory as the stylesheet itself, as it simplifies paths and is also a more logical filesystem arrangement.
If you are using Xcode 8.0 to 8.3.3 and swift 2.2 to 3.0
In my case need to change in URL http:// to https:// (if not working then try)
Add an App Transport Security Setting: Dictionary.
Add a NSAppTransportSecurity: Dictionary.
Add a NSExceptionDomains: Dictionary.
Add a yourdomain.com: Dictionary. (Ex: stackoverflow.com)
Add Subkey named " NSIncludesSubdomains" as Boolean: YES
Add Subkey named " NSExceptionAllowsInsecureHTTPLoads" as Boolean: YES
Another advantage of extracting a magic number as a constant gives the possibility to clearly document the business information.
public class Foo {
/**
* Max age in year to get child rate for airline tickets
*
* The value of the constant is {@value}
*/
public static final int MAX_AGE_FOR_CHILD_RATE = 2;
public void computeRate() {
if (person.getAge() < MAX_AGE_FOR_CHILD_RATE) {
applyChildRate();
}
}
}
Other answers assume you want to know it from a popup or background script.
In case you want to know the current URL from a content script, the standard JS way applies:
window.location.toString()
You can use properties of window.location
to access individual parts of the URL, such as host, protocol or path.
Follow up to Eonil's answer related to project level settings. With the target selected and the Build Settings tab selected, there may be no listing under Search Paths for Header Search Paths. In this case, you can change to "All" from "Basic" in the search bar and Header Search Paths will show up in the Search Paths section.
In properly extending dimsuz's answer by providing a real code situation, see the following code snippet:
Drawable buttonDrawable = button.getBackground();
buttonDrawable = DrawableCompat.wrap(buttonDrawable);
//the color is a direct color int and not a color resource
DrawableCompat.setTint(buttonDrawable, Color.RED);
button.setBackground(buttonDrawable);
This solution is for the scenario where a drawable is used as the button's background. It works on pre-Lollipop devices as well.
Yes it does in your case because of the below property in your config. This is ok during testing but in production you need to disable this.
<prop key="hibernate.hbm2ddl.auto">create</prop>
This is how I write my AsyncTask
the key point is add Thread.sleep(1);
@Override protected Integer doInBackground(String... params) {
Log.d(TAG, PRE + "url:" + params[0]);
Log.d(TAG, PRE + "file name:" + params[1]);
downloadPath = params[1];
int returnCode = SUCCESS;
FileOutputStream fos = null;
try {
URL url = new URL(params[0]);
File file = new File(params[1]);
fos = new FileOutputStream(file);
long startTime = System.currentTimeMillis();
URLConnection ucon = url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
byte[] data = new byte[10240];
int nFinishSize = 0;
while( bis.read(data, 0, 10240) != -1){
fos.write(data, 0, 10240);
nFinishSize += 10240;
**Thread.sleep( 1 ); // this make cancel method work**
this.publishProgress(nFinishSize);
}
data = null;
Log.d(TAG, "download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
} catch (IOException e) {
Log.d(TAG, PRE + "Error: " + e);
returnCode = FAIL;
} catch (Exception e){
e.printStackTrace();
} finally{
try {
if(fos != null)
fos.close();
} catch (IOException e) {
Log.d(TAG, PRE + "Error: " + e);
e.printStackTrace();
}
}
return returnCode;
}
Since other questions are being redirected to this one which ask about asanyarray
or other array creation routines, it's probably worth having a brief summary of what each of them does.
The differences are mainly about when to return the input unchanged, as opposed to making a new array as a copy.
array
offers a wide variety of options (most of the other functions are thin wrappers around it), including flags to determine when to copy. A full explanation would take just as long as the docs (see Array Creation, but briefly, here are some examples:
Assume a
is an ndarray
, and m
is a matrix
, and they both have a dtype
of float32
:
np.array(a)
and np.array(m)
will copy both, because that's the default behavior.np.array(a, copy=False)
and np.array(m, copy=False)
will copy m
but not a
, because m
is not an ndarray
.np.array(a, copy=False, subok=True)
and np.array(m, copy=False, subok=True)
will copy neither, because m
is a matrix
, which is a subclass of ndarray
.np.array(a, dtype=int, copy=False, subok=True)
will copy both, because the dtype
is not compatible.Most of the other functions are thin wrappers around array
that control when copying happens:
asarray
: The input will be returned uncopied iff it's a compatible ndarray
(copy=False
).asanyarray
: The input will be returned uncopied iff it's a compatible ndarray
or subclass like matrix
(copy=False
, subok=True
).ascontiguousarray
: The input will be returned uncopied iff it's a compatible ndarray
in contiguous C order (copy=False
, order='C')
.asfortranarray
: The input will be returned uncopied iff it's a compatible ndarray
in contiguous Fortran order (copy=False
, order='F'
).require
: The input will be returned uncopied iff it's compatible with the specified requirements string.copy
: The input is always copied.fromiter
: The input is treated as an iterable (so, e.g., you can construct an array from an iterator's elements, instead of an object
array with the iterator); always copied.There are also convenience functions, like asarray_chkfinite
(same copying rules as asarray
, but raises ValueError
if there are any nan
or inf
values), and constructors for subclasses like matrix
or for special cases like record arrays, and of course the actual ndarray
constructor (which lets you create an array directly out of strides over a buffer).
Here is a workaround using a flag:
//outside your event or method, but inside your class
private bool IsExecuted = false;
private async Task MethodA()
{
//Do Stuff Here
IsExecuted = true;
}
.
.
.
//Inside your event or method
{
await MethodA();
while (!isExecuted) Thread.Sleep(200); // <-------
await MethodB();
}
Modern way:
newParent.append(...oldParent.childNodes);
.append
is the replacement for .appendChild
. The main difference is that it accepts multiple nodes at once and even plain strings, like .append('hello!')
oldParent.childNodes
is iterable so it can be spread with ...
to become multiple parameters of .append()
Compatibility tables of both (in short: Edge 17+, Safari 10+):
It seems that Google has updated its developer page and added various trainings there.
One of them deals with the creation of custom views and can be found here
from torial: If you use winsock, here's a way: http://tangentsoft.net/wskfaq/examples/ipaddr.html
As for the subnet portion of the question; there is not platform agnostic way to retrieve the subnet mask as the POSIX socket API (which all modern operating systems implement) does not specify this. So you will have to use whatever method is available on the platform you are using.
I have faced similar issue and none of the above solution worked as I was in protected network.
To overcome this, I have installed "Fiddler" tool from Telerik, after installation start Fiddler and start installation of Protractor again.
Hope this will resolve your issue.
Thanks.
actually, if you already know the property, this will do it...
for example:
<a href="test.html" style="color:white;zoom:1.2" id="MyLink"></a>
var txt = "";
txt = getStyle(InterTabLink);
setStyle(InterTabLink, txt.replace("zoom\:1\.2\;","");
function setStyle(element, styleText){
if(element.style.setAttribute)
element.style.setAttribute("cssText", styleText );
else
element.setAttribute("style", styleText );
}
/* getStyle function */
function getStyle(element){
var styleText = element.getAttribute('style');
if(styleText == null)
return "";
if (typeof styleText == 'string') // !IE
return styleText;
else // IE
return styleText.cssText;
}
Note that this only works for inline styles... not styles you've specified through a class or something like that...
Other note: you may have to escape some characters in that replace statement, but you get the idea.
Scanner scr = new Scanner(new File(filePathInString));
/*Above line for scanning data from file*/
enter code here
ArrayList<DataType> list = new ArrayList<DateType>();
/*this is a object of arraylist which in data will store after scan*/
while (scr.hasNext()){
list.add(scr.next()); } /*above code is responsible for adding data in arraylist with the help of add function */
There is one more way to use Java
import java.io._
def printToFile(f: java.io.File)(op: java.io.PrintWriter => Unit)
{
val p = new java.io.PrintWriter(f);
try { op(p) }
finally { p.close() }
}
printToFile(new File("C:/TEMP/df.csv")) { p => df.collect().foreach(p.println)}
Jerry's answer is great. However, it doesn't handle large responses. A simple change to handle this:
memset(response, 0, sizeof(response));
total = sizeof(response)-1;
received = 0;
do {
printf("RESPONSE: %s\n", response);
// HANDLE RESPONSE CHUCK HERE BY, FOR EXAMPLE, SAVING TO A FILE.
memset(response, 0, sizeof(response));
bytes = recv(sockfd, response, 1024, 0);
if (bytes < 0)
printf("ERROR reading response from socket");
if (bytes == 0)
break;
received+=bytes;
} while (1);
Even I faced similar issues. This is how I was able to solve the same
$("#lnkDetails").live('click', function (e) {
//Create dynamic element after the element that raised the event. In my case a <a id="lnkDetails" href="/Attendance/Details/2012-07-01" />
$(this).after('<div id=\"dialog-confirm\" />');
//Optional : Load data from an external URL. The attr('href') is the href of the <a> tag.
$('#dialog-confirm').load($(this).attr('href'));
//Copied from jQueryUI site . Do we need this?
$("#dialog:ui-dialog").dialog("destroy");
//Transform the dynamic DOM element into a dialog
$('#dialog-confirm').dialog({
modal: true,
title: 'Details'
});
//Prevent Bubbling up to other elements.
return false;
});
You may want to try out simple function I posted on another thread related to reading date value from excel sheet.
It simply takes text from the cell as input and gives DateTime as output.
I would be happy to see improvement in my sample code provided for benefit of the .Net development community.
Here is the link for the thread C# not reading excel date from spreadsheet
.dex file
Compiled Android application code file.
Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created automatically by Android, by translating the compiled applications written in the Java programming language.
The long boring solution, which is not involved with CLI, you can manually navigate to:
your local repo folder ? .git folder (hidden) ? config file
then choose your text editor to open it and look for url located under the [remote "origin"] section.
Apple hand three categories of certificates: Trusted
, Always Ask
and Blocked
. You'll encounter the issue if your certificate's type on the Blocked
and Always Ask
list. On Safari it show’s like:
And you can find the type of Always Ask
certificates on Settings > General > About > Certificate Trust Setting
There is the List of available trusted root certificates in iOS 11
Use (keyup.enter)
.
Angular can filter the key events for us. Angular has a special syntax for keyboard events. We can listen for just the Enter key by binding to Angular's keyup.enter
pseudo-event.
Another easy way to get epsilon is:
In [1]: 7./3 - 4./3 -1
Out[1]: 2.220446049250313e-16
To convert a string to a stream you need to decide which encoding the bytes in the stream should have to represent that string - for example you can:
MemoryStream mStrm= new MemoryStream( Encoding.UTF8.GetBytes( contents ) );
MSDN references:
Here is a one-off way to do this, which is useful if you don't want to change your default settings:
def fullprint(*args, **kwargs):
from pprint import pprint
import numpy
opt = numpy.get_printoptions()
numpy.set_printoptions(threshold=numpy.inf)
pprint(*args, **kwargs)
numpy.set_printoptions(**opt)
You can use external library:
org.apache.commons.lang.ArrayUtils.remove(java.lang.Object[] array, int index)
It is in project Apache Commons Lang http://commons.apache.org/lang/
It's all a matter of style. It's useful for debugging but otherwise it shouldn't be used in the final version of the program. It really doesn't matter on the memory issue because I'm sure that those guys who invented the system("pause") were anticipating that it'd be used often. In another perspective, computers get throttled on their memory for everything else we use on the computer anyways and it doesn't pose a direct threat like dynamic memory allocation, so I'd recommend it for debugging code, but nothing else.
You can use:
Resources.getSystem().getString(android.R.string.somecommonstuff)
... everywhere in your application, even in static constants declarations. Unfortunately, it supports the system resources only.
For local resources use this solution. It is not trivial, but it works.
If the anonymous type causes trouble for you, you can create a simple data class:
public class PermissionsAndPages
{
public ObjectPermissions Permissions {get;set}
public Pages Pages {get;set}
}
and then in your query:
select new PermissionsAndPages { Permissions = op, Page = pg };
Then you can pass this around:
return queryResult.SingleOrDefault(); // as PermissionsAndPages
Wouldn't you be better off with
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl="CMS_1.aspx"
Target="_blank">
Click here
</asp:HyperLink>
Because, to replicate your desired behavior on an asp:Button
, you have to call window.open
on the OnClientClick
event of the button which looks a lot less cleaner than the above solution. Plus asp:HyperLink
is there to handle scenarios like this.
If you want to replicate this using an asp:Button
, do this.
<asp:Button ID="btn" runat="Server"
Text="SUBMIT"
OnClientClick="javascript:return openRequestedPopup();"/>
JavaScript function.
var windowObjectReference;
function openRequestedPopup() {
windowObjectReference = window.open("CMS_1.aspx",
"DescriptiveWindowName",
"menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes");
}
i = 20
"%x" % i #=> "14"
You can figure out version of Cocoapods by using below command :
pod —-version
o/p : 1.2.1
Now if you want detailed version of Gems and Cocoapods then use below command :
gem which cocoapods
(without sudo)
o/p : /Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.1/lib/cocoapods.rb
sudo gem which cocoapods
(with sudo)
o/p : /Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.1/lib/cocoapods.rb
Now if you want to get specific version of Pod present in Podfile then simply use command pod install
in terminal. This will show list of pod being used in project along with version.
The JTextField
offers a getText()
and a setText()
method - those are for getting and setting the content of the text field.
your understanding is right. For detailed info on {} see bash ref - parameter expansion
'for' and 'while' have different syntax and offer different styles of programmer control for an iteration. Most non-asm languages offer a similar syntax.
With while, you would probably write i=0; while [ $i -lt 10 ]; do echo $i; i=$(( i + 1 )); done
in essence manage everything about the iteration yourself
To get your program to run, please put jsp files under web-content and not under WEB-INF
because in Eclipse the files are not accessed there by the server, so try starting the server and browsing to URL:
http://localhost:8080/YourProject/yourfile.jsp
then your problem will be solved.
The performances are exactly the same, as references are implemented internally as pointers. Thus you do not need to worry about that.
There is no generally accepted convention regarding when to use references and pointers. In a few cases you have to return or accept references (copy constructor, for instance), but other than that you are free to do as you wish. A rather common convention I've encountered is to use references when the parameter must refer an existing object and pointers when a NULL value is ok.
Some coding convention (like Google's) prescribe that one should always use pointers, or const references, because references have a bit of unclear-syntax: they have reference behaviour but value syntax.
Have you included the statement include ("fileName.php");
?
Are you sure that file is in the correct directory?
Another way to add that I used to 'hack' this solution was to do this:
I set up a seperate computed
value that would simply return the nested object value.
data : function(){
return {
my_object : {
my_deep_object : {
my_value : "hello world";
}.
},
};
},
computed : {
helper_name : function(){
return this.my_object.my_deep_object.my_value;
},
},
watch : {
helper_name : function(newVal, oldVal){
// do this...
}
}
I like @Eduardo's answer and I liked the accepted answer. I like to get back a boolean from something like this, so I wrote it up for you guys.
CREATE FUNCTION dbo.DatabaseExists(@dbname nvarchar(128))
RETURNS bit
AS
BEGIN
declare @result bit = 0
SELECT @result = CAST(
CASE WHEN db_id(@dbname) is not null THEN 1
ELSE 0
END
AS BIT)
return @result
END
GO
Now you can use it like this:
select [dbo].[DatabaseExists]('master') --returns 1
select [dbo].[DatabaseExists]('slave') --returns 0
There is an even simpler solution to the accepted answer that involves directly invoking df.__getitem__
.
df = pd.DataFrame('x', index=range(5), columns=list('abc'))
df
a b c
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
For example, to get every 2 rows, you can do
df[::2]
a b c
0 x x x
2 x x x
4 x x x
There's also GroupBy.first
/GroupBy.head
, you group on the index:
df.index // 2
# Int64Index([0, 0, 1, 1, 2], dtype='int64')
df.groupby(df.index // 2).first()
# Alternatively,
# df.groupby(df.index // 2).head(1)
a b c
0 x x x
1 x x x
2 x x x
The index is floor-divved by the stride (2, in this case). If the index is non-numeric, instead do
# df.groupby(np.arange(len(df)) // 2).first()
df.groupby(pd.RangeIndex(len(df)) // 2).first()
a b c
0 x x x
1 x x x
2 x x x
It doesn't work because it doesn't make sense (so little sense that HTML 5 explicitly forbids it).
To fix it, decide if you want a link or a submit button and use whichever one you actually want (Hint: You don't have a form, so a submit button is nonsense).
Since youre using JSON, I would Base64 Encode it before sending it across the wire.
If the files are large, try to look at BSON, or some other format that is better with binary transfers.
You could also zip the files, if they compress well, before base64 encoding them.
30 2 * * * wget https://www.yoursite.com/your_function_name
The first part is for setting cron job and the next part to call your function.
If the user passes it to you, or it will wind up in a URL, you need to escape it.
If it appears in static text on a page? All browsers will get this one right either way, you don't worry much about it, since it will work.
Response.write() don't give formatted output. The latter one allows you to write formatted output.
Response.write - it writes the text stream Response.output.write - it writes the HTTP Output Stream.
Split is slow, but not as slow as Scanner. StringTokenizer is faster than split. However, I found that I could obtain double the speed, by trading some flexibility, to get a speed-boost, which I did at JFastParser https://github.com/hughperkins/jfastparser
Testing on a string containing one million doubles:
Scanner: 10642 ms
Split: 715 ms
StringTokenizer: 544ms
JFastParser: 290ms
use this command php artisan migrate --path=/database/migrations/my_migration.php
it worked for me..
Try this :
$('#resetBtn').on('click', function(e){
e.preventDefault();
$("#myform")[0].reset.click();
}
In my case I'm using C# OracleCommand
with OracleParameter
, and I set all the the parameters Size
property to max length of each column, then the error solved.
OracleParameter parm1 = new OracleParameter();
param1.OracleDbType = OracleDbType.Varchar2;
param1.Value = "test1";
param1.Size = 8;
OracleParameter parm2 = new OracleParameter();
param2.OracleDbType = OracleDbType.Varchar2;
param2.Value = "test1";
param2.Size = 12;
Are you missing a function declaration?
void ac_search(uint num_patterns, uint pattern_length, const char *patterns,
uint num_records, uint record_length, const char *records, int *matches, Node* trie);
Add it just before your implementation of ac_benchmark_search.
You could do something like this if you wanted
package main
import "fmt"
type Pair struct {
a, b interface{}
}
func main() {
p1 := Pair{"finished", 42}
p2 := Pair{6.1, "hello"}
fmt.Println("p1=", p1, "p2=", p2)
fmt.Println("p1.b", p1.b)
// But to use the values you'll need a type assertion
s := p1.a.(string) + " now"
fmt.Println("p1.a", s)
}
However I think what you have already is perfectly idiomatic and the struct describes your data perfectly which is a big advantage over using plain tuples.
1.downlad nvm
2.install chocolaty
3.change C:\Program Files\node to C:\Program Files\nodejsx
emphasized textThe first thing that we need to do is install NVM. website : https://docs.microsoft.com/en-us/windows/nodejs/setup-on-windows
Below code shows the two sub-controllers from where the events are dispatched upwards to parent controller (rootScope)
<body ng-app="App">
<div ng-controller="parentCtrl">
<p>City : {{city}} </p>
<p> Address : {{address}} </p>
<div ng-controller="subCtrlOne">
<input type="text" ng-model="city" />
<button ng-click="getCity(city)">City !!!</button>
</div>
<div ng-controller="subCtrlTwo">
<input type="text" ng-model="address" />
<button ng-click="getAddrress(address)">Address !!!</button>
</div>
</div>
</body>
var App = angular.module('App', []);
// parent controller
App.controller('parentCtrl', parentCtrl);
parentCtrl.$inject = ["$scope"];
function parentCtrl($scope) {
$scope.$on('cityBoom', function(events, data) {
$scope.city = data;
});
$scope.$on('addrBoom', function(events, data) {
$scope.address = data;
});
}
// sub controller one
App.controller('subCtrlOne', subCtrlOne);
subCtrlOne.$inject = ['$scope'];
function subCtrlOne($scope) {
$scope.getCity = function(city) {
$scope.$emit('cityBoom', city);
}
}
// sub controller two
App.controller('subCtrlTwo', subCtrlTwo);
subCtrlTwo.$inject = ["$scope"];
function subCtrlTwo($scope) {
$scope.getAddrress = function(addr) {
$scope.$emit('addrBoom', addr);
}
}
Here is another alternative using Guava
List<Object> lst ...
List<String> ls = Lists.transform(lst, Functions.toStringFunction());
strftime
(C89)
Martin mentioned it, here's an example:
main.c
#include <assert.h>
#include <stdio.h>
#include <time.h>
int main(void) {
time_t t = time(NULL);
struct tm *tm = localtime(&t);
char s[64];
assert(strftime(s, sizeof(s), "%c", tm));
printf("%s\n", s);
return 0;
}
Compile and run:
gcc -std=c89 -Wall -Wextra -pedantic -o main.out main.c
./main.out
Sample output:
Thu Apr 14 22:39:03 2016
The %c
specifier produces the same format as ctime
.
One advantage of this function is that it returns the number of bytes written, allowing for better error control in case the generated string is too long:
RETURN VALUE
Provided that the result string, including the terminating null byte, does not exceed max bytes, strftime() returns the number of bytes (excluding the terminating null byte) placed in the array s. If the length of the result string (including the terminating null byte) would exceed max bytes, then
strftime() returns 0, and the contents of the array are undefined.
Note that the return value 0 does not necessarily indicate an error. For example, in many locales %p yields an empty string. An empty format string will likewise yield an empty string.
asctime
and ctime
(C89, deprecated in POSIX 7)
asctime
is a convenient way to format a struct tm
:
main.c
#include <stdio.h>
#include <time.h>
int main(void) {
time_t t = time(NULL);
struct tm *tm = localtime(&t);
printf("%s", asctime(tm));
return 0;
}
Sample output:
Wed Jun 10 16:10:32 2015
And there is also ctime()
which the standard says is a shortcut for:
asctime(localtime())
As mentioned by Jonathan Leffler, the format has the shortcoming of not having timezone information.
POSIX 7 marked those functions as "obsolescent" so they could be removed in future versions:
The standard developers decided to mark the asctime() and asctime_r() functions obsolescent even though asctime() is in the ISO C standard due to the possibility of buffer overflow. The ISO C standard also provides the strftime() function which can be used to avoid these problems.
C++ version of this question: How to get current time and date in C++?
Tested in Ubuntu 16.04.
Try this
DateTime dDate;
dDate = DateTime.TryParse(inputString);
String.Format("{0:d/MM/yyyy}", dDate);
see this link for more info. http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx
I think the question is a bit confusing.
If you mean "can foreign key 'refer' to a primary key in the same table?", the answer is a firm yes as some replied. For example, in an employee table, a row for an employee may have a column for storing manager's employee number where the manager is also an employee and hence will have a row in the table like a row of any other employee.
If you mean "can column(or set of columns) be a primary key as well as a foreign key in the same table?", the answer, in my view, is a no; it seems meaningless. However, the following definition succeeds in SQL Server!
create table t1(c1 int not null primary key foreign key references t1(c1))
But I think it is meaningless to have such a constraint unless somebody comes up with a practical example.
AmanS, in your example d_id in no circumstance can be a primary key in Employee table. A table can have only one primary key. I hope this clears your doubt. d_id is/can be a primary key only in department table.
Should look like this:
UPDATE DHE.dbo.tblAccounts
SET DHE.dbo.tblAccounts.ControllingSalesRep =
DHE_Import.dbo.tblSalesRepsAccountsLink.SalesRepCode
from DHE.dbo.tblAccounts
INNER JOIN DHE_Import.dbo.tblSalesRepsAccountsLink
ON DHE.dbo.tblAccounts.AccountCode =
DHE_Import.tblSalesRepsAccountsLink.AccountCode
Update table is repeated in FROM clause.
Microkernel:
Moves as much from the kernel into “user” space.
Communication takes place between user modules using message passing.
Benefits:
1-Easier to extend a microkernel
2-Easier to port the operating system to new architectures
3-More reliable (less code is running in kernel mode)
4-More secure
Detriments:
1-Performance overhead of user space to kernel space communication
See docs.python.org:
When you’re done with a file, call f.close() to close it and free up any system resources taken up by the open file. After calling f.close(), attempts to use the file object will automatically fail.
Hence use close()
elegantly with try/finally
:
f = open('file.txt', 'r')
try:
# do stuff with f
finally:
f.close()
This ensures that even if # do stuff with f
raises an exception, f
will still be closed properly.
Note that open
should appear outside of the try
. If open
itself raises an exception, the file wasn't opened and does not need to be closed. Also, if open
raises an exception its result is not assigned to f
and it is an error to call f.close()
.
django_template_filter filter name get_value_from_dict
{{ your_dict|get_value_from_dict:your_key }}
hash.each {|k,v| hash.delete(k) && hash[k[1..-1]]=v if k[0,1] == '_'}
pdf validation with OPEN validator:
DROID (Digital Record Object Identification) http://sourceforge.net/projects/droid/
JHOVE - JSTOR/Harvard Object Validation Environment http://hul.harvard.edu/jhove/
Here is an example that lists all the files on my desktop. you should change the path variable to your path.
Instead of printing the file's name with System.out.println, you should place your own code to operate on the file.
public static void main(String[] args) {
File path = new File("c:/documents and settings/Zachary/desktop");
File [] files = path.listFiles();
for (int i = 0; i < files.length; i++){
if (files[i].isFile()){ //this line weeds out other directories/folders
System.out.println(files[i]);
}
}
}
Not quite sure why it's not mentioned more online (or on this thread), but the Babel package (and Django utilities) from the Edgewall guys is awesome for currency formatting (and lots of other i18n tasks). It's nice because it doesn't suffer from the need to do everything globally like the core Python locale module.
The example the OP gave would simply be:
>>> import babel.numbers
>>> import decimal
>>> babel.numbers.format_currency( decimal.Decimal( "188518982.18" ), "GBP" )
£188,518,982.18
For top right corner try this:
position: absolute;
top: 0;
right: 0;
You should use data.response
in your JS instead of json.response
.
Here is worked example See on Plunker
<body ng-controller="MainCtrl">
<input ng-model="search" type="text">
<br>
Showing {{data.length}} Persons; <br>
Filtered {{counted}}
<ul>
<li ng-repeat="person in data | filter:search">
{{person.name}}
</li>
</ul>
</body>
<script>
var app = angular.module('angularjs-starter', [])
app.controller('MainCtrl', function($scope, $filter) {
$scope.data = [
{
"name": "Jim", "age" : 21
}, {
"name": "Jerry", "age": 26
}, {
"name": "Alex", "age" : 25
}, {
"name": "Max", "age": 22
}
];
$scope.counted = $scope.data.length;
$scope.$watch("search", function(query){
$scope.counted = $filter("filter")($scope.data, query).length;
});
});
Try using the following on the JavaScript side:
window.location.href = '@Url.Action("Index", "Controller")';
If you want to pass parameters to the @Url.Action
, you can do this:
var reportDate = $("#inputDateId").val();//parameter
var url = '@Url.Action("Index", "Controller", new {dateRequested = "findme"})';
window.location.href = url.replace('findme', reportDate);
Merge replication. You can create the subscriber (2008) from the distributor (2008). After the database has fully synchronized, drop the subscription and the publication.
It's easy to create this yourself
In your layout include the following ProgressBar
with a specific drawable (note you should get the width from dimensions instead). The max value is important here:
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:max="500"
android:progress="0"
android:progressDrawable="@drawable/circular" />
Now create the drawable in your resources with the following shape. Play with the radius (you can use innerRadius
instead of innerRadiusRatio
) and thickness values.
circular (Pre Lollipop OR API Level < 21)
<shape
android:innerRadiusRatio="2.3"
android:shape="ring"
android:thickness="3.8sp" >
<solid android:color="@color/yourColor" />
</shape>
circular ( >= Lollipop OR API Level >= 21)
<shape
android:useLevel="true"
android:innerRadiusRatio="2.3"
android:shape="ring"
android:thickness="3.8sp" >
<solid android:color="@color/yourColor" />
</shape>
useLevel is "false" by default in API Level 21 (Lollipop) .
Start Animation
Next in your code use an ObjectAnimator
to animate the progress field of the ProgessBar
of your layout.
ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
ObjectAnimator animation = ObjectAnimator.ofInt(progressBar, "progress", 0, 500); // see this max value coming back here, we animate towards that value
animation.setDuration(5000); // in milliseconds
animation.setInterpolator(new DecelerateInterpolator());
animation.start();
Stop Animation
progressBar.clearAnimation();
P.S. unlike examples above, it give smooth animation.
Here's why: As it is says in the Javadoc:
The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException.
This check is done in the next()
method of the iterator (as you can see by the stacktrace). But we will reach the next()
method only if hasNext()
delivered true, which is what is called by the for each to check if the boundary is met. In your remove method, when hasNext()
checks if it needs to return another element, it will see that it returned two elements, and now after one element was removed the list only contains two elements. So all is peachy and we are done with iterating. The check for concurrent modifications does not occur, as this is done in the next()
method which is never called.
Next we get to the second loop. After we remove the second number the hasNext method will check again if can return more values. It has returned two values already, but the list now only contains one. But the code here is:
public boolean hasNext() {
return cursor != size();
}
1 != 2, so we continue to the next()
method, which now realizes that someone has been messing with the list and fires the exception.
Hope that clears your question up.
List.remove()
will not throw ConcurrentModificationException
when it removes the second last element from the list.
You will have to provide the entire user dn
in SECURITY_PRINCIPAL
like this
env.put(Context.SECURITY_PRINCIPAL, "cn=username,ou=testOu,o=test");
It's an automatically backed property, basically equivalent to:
private string type;
public string Type
{
get{ return type; }
set{ type = value; }
}
Since the border is used just for visual appearance, you could put it into the ListBoxItem's ControlTemplate and modify the properties there. In the ItemTemplate, you could place only the StackPanel and the TextBlock. In this way, the code also remains clean, as in the appearance of the control will be controlled via the ControlTemplate and the data to be shown will be controlled via the DataTemplate.
A couple of things:
You need to set the video bitrate. I have never used minrate and maxrate so I don't know how exactly they work, but by setting the bitrate using the -b
switch, I am able to get high quality video. You need to come up with a bitrate that offers a good tradeoff between compression and video quality. You may have to experiment with this because it all depends on the frame size, frame rate and the amount of motion in the content of your video. Keep in mind that DVD tends to be around 4-5 Mbit/s on average for 720x480, so I usually start from there and decide whether I need more or less and then just experiment. For example, you could add -b 5000k
to the command line to get more or less DVD video bitrate.
You need to specify a video codec. If you don't, ffmpeg will default to MPEG-1 which is quite old and does not provide near the amount of compression as MPEG-4 or H.264. If your ffmpeg version is built with libx264 support, you can specify -vcodec libx264
as part of the command line. Otherwise -vcodec mpeg4
will also do a better job than MPEG-1, but not as well as x264.
There are a lot of other advanced options that will help you squeeze out the best quality at the lowest bitrates. Take a look here for some examples.
puts false or true
--> prints: false
puts false || true
--> prints: true
I just discovered the Hmisc package:
Contains many functions useful for data analysis, high-level graphics, utility operations, functions for computing sample size and power, importing and annotating datasets, imputing missing values, advanced table making, variable clustering, character string manipulation, conversion of R objects to LaTeX and html code, and recoding variables.
library(Hmisc)
plot(...)
minor.tick(nx=10, ny=10) # make minor tick marks (without labels) every 10th
if you want to do very quick plots with secondary Y-Axis then there is much easier way using Pandas wrapper function and just 2 lines of code. Just plot your first column then plot the second but with parameter secondary_y=True
, like this:
df.A.plot(label="Points", legend=True)
df.B.plot(secondary_y=True, label="Comments", legend=True)
This would look something like below:
You can do few more things as well. Take a look at Pandas plotting doc.
The default value can be followed with a :
after the property key, e.g.
<property name="port" value="${my.server.port:8080}" />
Or in java code:
@Value("${my.server.port:8080}")
private String myServerPort;
See:
valueSeparator
(from AbstractPropertyResolver
)
and VALUE_SEPARATOR
(from SystemPropertyUtils
)
BTW, the Elvis Operator is only available within Spring Expression Language (SpEL),
e.g.: https://stackoverflow.com/a/37706167/537554
As others already answered well, they both are interchangeable.
Nonetheless, it's worth mentioning that there could be a case where you may want to use the explicit statement, i.e. pointer != NULL
.
.format('MM/DD/YYYY HH:mm:ss')
The following CSS will right-align both the arrow and the options:
select { text-align-last: right; }_x000D_
option { direction: rtl; }
_x000D_
<!-- example usage -->_x000D_
Choose one: <select>_x000D_
<option>The first option</option>_x000D_
<option>A second, fairly long option</option>_x000D_
<option>Last</option>_x000D_
</select>
_x000D_
Try creating another full backup after you backup the log w/ truncate_only (IIRC you should do this anyway to maintain the log chain). In simple recovery mode, your log shouldn't grow much anyway since it's effectively truncated after every transaction. Then try specifying the size you want the logfile to be, e.g.
-- shrink log file to c. 1 GB
DBCC SHRINKFILE (Wxlog0, 1000);
The TRUNCATEONLY option doesn't rearrange the pages inside the log file, so you might have an active page at the "end" of your file, which could prevent it from being shrunk.
You can also use DBCC SQLPERF(LOGSPACE) to make sure that there really is space in the log file to be freed.
using SimpleDateFormat or DateFormat class through
for e.g.
try{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // here set the pattern as you date in string was containing like date/month/year
Date d = sdf.parse("20/12/2011");
}catch(ParseException ex){
// handle parsing exception if date string was different from the pattern applying into the SimpleDateFormat contructor
}
It really looks as though the object you are referencing is not registered on the system. I know you said it's installed, but that doesn't necessarily mean it's registered. To confirm this, search for the progID that you used in your registry.
Example for this code:
set objFSO = CreateObject("Scripting.FileSystemObject")
I would search for Scripting.FileSystemObject
in the registry. Then I would look at registry key above the found value, for InProcServer32
value. This will give you the path to the ActiveX file that it was registered from (for Scripting.FileSystemObject
the file is "c:\windows\system32\scrrun.dll").
If you can't find your progID in the registry, then it's not registered on your system which is your problem. If it's not registered you need to find out what file registers it, which is usually an .ocx or a .dll in the same folder path of your third party app, and then register these file(s). Here is the command to register a file:
regsvr32 /i "c:\windows\system32\scrrun.dll"
Even if you find the progID value in the registry and it references a file that is present on your system, you may still want to try re-registering the file. I have found that sometimes the registration got broken somehow somewhere and it was easier to re-register the files then it was to fix the issue.
For me ComboBox.DropDownClosed
Event did it.
private void cbValueType_DropDownClosed(object sender, EventArgs e)
{
if (cbValueType.SelectedIndex == someIntValue) //sel ind already updated
{
// change sel Index of other Combo for example
cbDataType.SelectedIndex = someotherIntValue;
}
}
First Look at this example :
The C code for a simple C program is given below
struct Foo {
char a;
int b;
double c;
} foo1,foo2;
void foo_assign(void)
{
foo1 = foo2;
}
int main(/*char *argv[],int argc*/)
{
foo_assign();
return 0;
}
The Equivalent ASM Code for foo_assign() is
00401050 <_foo_assign>:
401050: 55 push %ebp
401051: 89 e5 mov %esp,%ebp
401053: a1 20 20 40 00 mov 0x402020,%eax
401058: a3 30 20 40 00 mov %eax,0x402030
40105d: a1 24 20 40 00 mov 0x402024,%eax
401062: a3 34 20 40 00 mov %eax,0x402034
401067: a1 28 20 40 00 mov 0x402028,%eax
40106c: a3 38 20 40 00 mov %eax,0x402038
401071: a1 2c 20 40 00 mov 0x40202c,%eax
401076: a3 3c 20 40 00 mov %eax,0x40203c
40107b: 5d pop %ebp
40107c: c3 ret
As you can see that a assignment is simply replaced by a "mov" instruction in assembly, the assignment operator simply means moving data from one memory location to another memory location. The assignment will only do it for immediate members of a structures and will fail to copy when you have Complex datatypes in a structure. Here COMPLEX means that you cant have array of pointers ,pointing to lists.
An array of characters within a structure will itself not work on most compilers, this is because assignment will simply try to copy without even looking at the datatype to be of complex type.
echo "text to echo" > file.txt
Fixed positioning doesn't work on iOS like it does on computers.
Imagine you have a sheet of paper (the webpage) under a magnifying glass(the viewport), if you move the magnifying glass and your eye, you see a different part of the page. This is how iOS works.
Now there is a sheet of clear plastic with a word on it, this sheet of plastic stays stationary no matter what (the position:fixed elements). So when you move the magnifying glass the fixed element appears to move.
Alternatively, instead of moving the magnifying glass, you move the paper (the webpage), keeping the sheet of plastic and magnifying glass still. In this case the word on the sheet of plastic will appear to stay fixed, and the rest of the content will appear to move (because it actually is) This is a traditional desktop browser.
So in iOS the viewport moves, in a traditional browser the webpage moves. In both cases the fixed elements stay still in reality; although on iOS the fixed elements appear to move.
The way to get around this, is to follow the last few paragraphs in this article
(basically disable scrolling altogether, have the content in a separate scrollable div (see the blue box at the top of the linked article), and the fixed element positioned absolutely)
"position:fixed" now works as you'd expect in iOS5.
Here is dirty way:
If you don't want a separate CSS file, you can use inline CSS:
<h1>This text should be bold, <span style="font-weight:normal">but this text should not</span></h1>
However, as Madara's comment suggests, you might want to consider putting the unbolded part in a different header, depending on the use case involved.
Anyway the "Block" method is preffered now-a-days. I will explain the simple block below.
Consider the snipped below. bug2 and bug 3 are imageViews. The below animation describes an animation with 1 second duration after a delay of 1 second. The bug3 is moved from its center to bug2's center. Once the animation is completed it will be logged "Center Animation Done!".
-(void)centerAnimation:(id)sender
{
NSLog(@"Center animation triggered!");
CGPoint bug2Center = bug2.center;
[UIView animateWithDuration:1
delay:1.0
options: UIViewAnimationCurveEaseOut
animations:^{
bug3.center = bug2Center;
}
completion:^(BOOL finished){
NSLog(@"Center Animation Done!");
}];
}
Hope that's clean!!!
When there is one commit only in the branch, I usually do
git merge branch_name --ff
For a recursive search:
find . -type f -name '*.log' -printf x | wc -c
wc -c
will count the number of characters in the output of find
, while -printf x
tells find
to print a single x
for each result.
For a non-recursive search, do this:
find . -maxdepth 1 -type f -name '*.log' -printf x | wc -c
I think that is controlled by the expose_php
setting in PHP.ini:
expose_php = off
Decides whether PHP may expose the fact that it is installed on the server (e.g. by adding its signature to the Web server header). It is no security threat in any way, but it makes it possible to determine whether you use PHP on your server or not.
There is no direct security risk, but as David C notes, exposing an outdated (and possibly vulnerable) version of PHP may be an invitation for people to try and attack it.
Most likely your query failed, and the query call returned a boolean FALSE (or an error object of some sort), which you then try to use as if was a resultset object, causing the error. Try something like var_dump($result)
to see what you really got.
Check for errors after EVERY database query call. Even if the query itself is syntactically valid, there's far too many reasons for it to fail anyways - checking for errors every time will save you a lot of grief at some point.
I would use the get_cmap method. Ex.:
import matplotlib.pyplot as plt
plt.imshow(matrix, cmap=plt.get_cmap('gray'))
Please use the below code for your REST API request:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Json;
namespace ConsoleApplication2
{
class Program
{
private const string URL = "https://XXXX/rest/api/2/component";
private const string DATA = @"{
""name"": ""Component 2"",
""description"": ""This is a JIRA component"",
""leadUserName"": ""xx"",
""assigneeType"": ""PROJECT_LEAD"",
""isAssigneeTypeValid"": false,
""project"": ""TP""}";
static void Main(string[] args)
{
AddComponent();
}
private static void AddComponent()
{
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
client.BaseAddress = new System.Uri(URL);
byte[] cred = UTF8Encoding.UTF8.GetBytes("username:password");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred));
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
System.Net.Http.HttpContent content = new StringContent(DATA, UTF8Encoding.UTF8, "application/json");
HttpResponseMessage messge = client.PostAsync(URL, content).Result;
string description = string.Empty;
if (messge.IsSuccessStatusCode)
{
string result = messge.Content.ReadAsStringAsync().Result;
description = result;
}
}
}
}
The answer provided by Joe Stefanelli is already correct.
SELECT name FROM (SELECT name FROM agentinformation) as a
We need to make an alias of the subquery because a query needs a table object which we will get from making an alias for the subquery. Conceptually, the subquery results are substituted into the outer query. As we need a table object in the outer query, we need to make an alias of the inner query.
Statements that include a subquery usually take one of these forms:
Check for more subquery rules and subquery types.
More examples of Nested Subqueries.
IN / NOT IN – This operator takes the output of the inner query after the inner query gets executed which can be zero or more values and sends it to the outer query. The outer query then fetches all the matching [IN operator] or non matching [NOT IN operator] rows.
ANY – [>ANY or ANY operator takes the list of values produced by the inner query and fetches all the values which are greater than the minimum value of the list. The
e.g. >ANY(100,200,300), the ANY operator will fetch all the values greater than 100.
e.g. >ALL(100,200,300), the ALL operator will fetch all the values greater than 300.
You could try powershell. There are get-content and set-content commandlets build in that you could use.
Looking into https://mochajs.org/#usage we see that simply use
mocha test/myfile
will work. You can omit the '.js' at the end.
PAGEIOLATCH_SH
wait type usually comes up as the result of fragmented or unoptimized index.
Often reasons for excessive PAGEIOLATCH_SH
wait type are:
In order to try and resolve having high PAGEIOLATCH_SH
wait type, you can check:
PAGEIOLATCH_SH
wait typesAlways keep in mind that in case of high safety Mirroring or synchronous-commit availability in AlwaysOn AG, increased/excessive PAGEIOLATCH_SH
can be expected.
You can find more details about this topic in the article Handling excessive SQL Server PAGEIOLATCH_SH wait types
$("#yourdropdownid option:selected").text(); // selected option text
$("#yourdropdownid").val(); // selected option value
For large datasets a faster solution is required.
Making use of 'Text to Columns' functionality provides a fast solution.
Example based on column F, starting range at 25 to LastRow
Sub ConvTxt2Nr()
Dim SelectR As Range
Dim sht As Worksheet
Dim LastRow As Long
Set sht = ThisWorkbook.Sheets("DumpDB")
LastRow = sht.Cells(sht.Rows.Count, "F").End(xlUp).Row
Set SelectR = ThisWorkbook.Sheets("DumpDB").Range("F25:F" & LastRow)
SelectR.TextToColumns Destination:=Range("F25"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
:=Array(1, 1), TrailingMinusNumbers:=True
End Sub
Add an annotation to the method using the keyword Obsolete
. Message argument is optional but a good idea to communicate why the item is now obsolete and/or what to use instead.
Example:
[System.Obsolete("use myMethodB instead")]
void myMethodA()
Use a combination of VPTEST(D, W, B) and PSRLDQ instructions to focus in on the byte containing the most significant bit as shown below using an emulation of these instructions in Perl found at:
https://github.com/philiprbrenan/SimdAvx512
if (1) { #TpositionOfMostSignificantBitIn64
my @m = ( # Test strings
#B0 1 2 3 4 5 6 7
#b0123456701234567012345670123456701234567012345670123456701234567
'0000000000000000000000000000000000000000000000000000000000000000',
'0000000000000000000000000000000000000000000000000000000000000001',
'0000000000000000000000000000000000000000000000000000000000000010',
'0000000000000000000000000000000000000000000000000000000000000111',
'0000000000000000000000000000000000000000000000000000001010010000',
'0000000000000000000000000000000000001000000001100100001010010000',
'0000000000000000000001001000010000000000000001100100001010010000',
'0000000000000000100000000000000100000000000001100100001010010000',
'1000000000000000100000000000000100000000000001100100001010010000',
);
my @n = (0, 1, 2, 3, 10, 28, 43, 48, 64); # Expected positions of msb
sub positionOfMostSignificantBitIn64($) # Find the position of the most significant bit in a string of 64 bits starting from 1 for the least significant bit or return 0 if the input field is all zeros
{my ($s64) = @_; # String of 64 bits
my $N = 128; # 128 bit operations
my $f = 0; # Position of first bit set
my $x = '0'x$N; # Double Quad Word set to 0
my $s = substr $x.$s64, -$N; # 128 bit area needed
substr(VPTESTMD($s, $s), -2, 1) eq '1' ? ($s = PSRLDQ $s, 4) : ($f += 32); # Test 2 dwords
substr(VPTESTMW($s, $s), -2, 1) eq '1' ? ($s = PSRLDQ $s, 2) : ($f += 16); # Test 2 words
substr(VPTESTMB($s, $s), -2, 1) eq '1' ? ($s = PSRLDQ $s, 1) : ($f += 8); # Test 2 bytes
$s = substr($s, -8); # Last byte remaining
$s < $_ ? ++$f : last for # Search remaing byte
(qw(10000000 01000000 00100000 00010000
00001000 00000100 00000010 00000001));
64 - $f # Position of first bit set
}
ok $n[$_] eq positionOfMostSignificantBitIn64 $m[$_] for keys @m # Test
}
0.00 is actually 0. If you need to have the 0.00 when you echo, simply use number_format this way:
number_format($number, 2);
Or you can do it like this!
def skip_elements(elements):
# Initialize variables
new_list = []
i = 0
# Iterate through the list
for words in elements:
# Does this element belong in the resulting list?
if i <= len(elements):
# Add this element to the resulting list
new_list.append(elements[i])
# Increment i
i += 2
return new_list
print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach']
print(skip_elements([])) # Should be []
Those steps should be able to be shortened down to:
hg pull
hg update -r MY_BRANCH -C
The -C
flag tells the update command to discard all local changes before updating.
However, this might still leave untracked files in your repository. It sounds like you want to get rid of those as well, so I would use the purge
extension for that:
hg pull
hg update -r MY_BRANCH -C
hg purge
In any case, there is no single one command you can ask Mercurial to perform that will do everything you want here, except if you change the process to that "full clone" method that you say you can't do.
From mere curiosity, I timed the two rivalling answers posted above.
And I had the following results:
dateutil.parser (valid str): 4.6732222699938575
dateutil.parser (invalid str): 1.7270505399937974
datetime.strptime (valid): 0.7822393209935399
datetime.strptime (invalid): 0.4394566189876059
And here's the code I used (Python 3.6)
from dateutil import parser as date_parser
from datetime import datetime
from timeit import timeit
def is_date_parsing(date_str):
try:
return bool(date_parser.parse(date_str))
except ValueError:
return False
def is_date_matching(date_str):
try:
return bool(datetime.strptime(date_str, '%Y-%m-%d'))
except ValueError:
return False
if __name__ == '__main__':
print("dateutil.parser (valid date):", end=' ')
print(timeit("is_date_parsing('2021-01-26')",
setup="from __main__ import is_date_parsing",
number=100000))
print("dateutil.parser (invalid date):", end=' ')
print(timeit("is_date_parsing('meh')",
setup="from __main__ import is_date_parsing",
number=100000))
print("datetime.strptime (valid date):", end=' ')
print(timeit("is_date_matching('2021-01-26')",
setup="from __main__ import is_date_matching",
number=100000))
print("datetime.strptime (invalid date):", end=' ')
print(timeit("is_date_matching('meh')",
setup="from __main__ import is_date_matching",
number=100000))
Neither has anything specific to keyboard or mobile, other than the fact that for years ARM has had a pretty substantial advantage in terms of power consumption, which made it attractive for all sorts of battery operated devices.
As far as the actual differences: ARM has more registers, supported predication for most instructions long before Intel added it, and has long incorporated all sorts of techniques (call them "tricks", if you prefer) to save power almost everywhere it could.
There's also a considerable difference in how the two encode instructions. Intel uses a fairly complex variable-length encoding in which an instruction can occupy anywhere from 1 up to 15 byte. This allows programs to be quite small, but makes instruction decoding relatively difficult (as in: decoding instructions fast in parallel is more like a complete nightmare).
ARM has two different instruction encoding modes: ARM and THUMB. In ARM mode, you get access to all instructions, and the encoding is extremely simple and fast to decode. Unfortunately, ARM mode code tends to be fairly large, so it's fairly common for a program to occupy around twice as much memory as Intel code would. Thumb mode attempts to mitigate that. It still uses quite a regular instruction encoding, but reduces most instructions from 32 bits to 16 bits, such as by reducing the number of registers, eliminating predication from most instructions, and reducing the range of branches. At least in my experience, this still doesn't usually give quite as dense of coding as x86 code can get, but it's fairly close, and decoding is still fairly simple and straightforward. Lower code density means you generally need at least a little more memory and (generally more seriously) a larger cache to get equivalent performance.
At one time Intel put a lot more emphasis on speed than power consumption. They started emphasizing power consumption primarily on the context of laptops. For laptops their typical power goal was on the order of 6 watts for a fairly small laptop. More recently (much more recently) they've started to target mobile devices (phones, tablets, etc.) For this market, they're looking at a couple of watts or so at most. They seem to be doing pretty well at that, though their approach has been substantially different from ARM's, emphasizing fabrication technology where ARM has mostly emphasized micro-architecture (not surprising, considering that ARM sells designs, and leaves fabrication to others).
Depending on the situation, a CPU's energy consumption is often more important than its power consumption though. At least as I'm using the terms, power consumption refers to power usage on a (more or less) instantaneous basis. Energy consumption, however, normalizes for speed, so if (for example) CPU A consumes 1 watt for 2 seconds to do a job, and CPU B consumes 2 watts for 1 second to do the same job, both CPUs consume the same total amount of energy (two watt seconds) to do that job--but with CPU B, you get results twice as fast.
ARM processors tend to do very well in terms of power consumption. So if you need something that needs a processor's "presence" almost constantly, but isn't really doing much work, they can work out pretty well. For example, if you're doing video conferencing, you gather a few milliseconds of data, compress it, send it, receive data from others, decompress it, play it back, and repeat. Even a really fast processor can't spend much time sleeping, so for tasks like this, ARM does really well.
Intel's processors (especially their Atom processors, which are actually intended for low power applications) are extremely competitive in terms of energy consumption. While they're running close to their full speed, they will consume more power than most ARM processors--but they also finish work quickly, so they can go back to sleep sooner. As a result, they can combine good battery life with good performance.
So, when comparing the two, you have to be careful about what you measure, to be sure that it reflects what you honestly care about. ARM does very well at power consumption, but depending on the situation you may easily care more about energy consumption than instantaneous power consumption.
I got this error with GitHub gist. I was trying to push a commit with files in sub-directories. Turned out gist can only have files in root directory.
It's only blank for you because you have not set the sql_mode. If you set it, then that query will show you the details:
mysql> SELECT @@sql_mode;
+------------+
| @@sql_mode |
+------------+
| |
+------------+
1 row in set (0.00 sec)
mysql> set sql_mode=ORACLE;
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT @@sql_mode;
+----------------------------------------------------------------------------------------------------------------------+
| @@sql_mode |
+----------------------------------------------------------------------------------------------------------------------+
| PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ORACLE,NO_KEY_OPTIONS,NO_TABLE_OPTIONS,NO_FIELD_OPTIONS,NO_AUTO_CREATE_USER |
+----------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
when you want to access images which are in public/images folder and if you want to access it without using laravel functions, use as follows:
<img src={{url('/images/photo.type')}} width="" height="" alt=""/>
This works fine.
Here is how you do it:
$http.get("/url/to/resource/", {params:{"param1": val1, "param2": val2}})
.then(function (response) { /* */ })...
Angular takes care of encoding the parameters.
Maxim Shoustin's answer does not work ({method:'GET', url:'/search', jsonData}
is not a valid JavaScript literal) and JeyTheva's answer, although simple, is dangerous as it allows XSS (unsafe values are not escaped when you concatenate them).
Add this to your module-level build.gradle :
android {
defaultConfig {
....
multiDexEnabled true
}
...
}
dependencies {
compile 'com.android.support:multidex:1.0.1'
.........
}
If you override Application
class then extend it from MultiDexApplication
:
YourApplicationClass extends MultiDexApplication
If you cant extend it from MultiDexApplication
class then override attachBaseContext()
method as following :
protected void attachBaseContext(Context base) {
super.attachBaseContext(context);
Multidex.install(this);
}
And dont run anything before MultiDex.install(this)
is executed.
If you dont override the Application
class simply edit your manifest file as following :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
.......>
<application
......
android:name="android.support.multidex.MultiDexApplication" >
...
</application>
......
</manifest>
curses
will allow you to use colors properly for the type of terminal that is being used.
Its just that you need multiple When
for a single case to behave it like if.. Elseif else..
Case when 1=1 //if
Then
When 1=1 //else if
Then....
When ..... //else if
Then
Else //else
.......
End
Finally, the Chrome team will release a fix for this issue with Chrome 37 which will be released to public in July 2014. See example comparison of current stable Chrome 35 and latest Chrome 37 (early development preview) here:
1.) There is NO proper solution when loading fonts via @import
, <link href=
or Google's webfont.js
. The problem is that Chrome simply requests .woff files from Google's API which render horribly. Surprisingly all other font file types render beautifully. However, there are some CSS tricks that will "smoothen" the rendered font a little bit, you'll find the workaround(s) deeper in this answer.
2.) There IS a real solution for this when self-hosting the fonts, first posted by Jaime Fernandez in another answer on this Stackoverflow page, which fixes this issue by loading web fonts in a special order. I would feel bad to simply copy his excellent answer, so please have a look there. There is also an (unproven) solution that recommends using only TTF/OTF fonts as they are now supported by nearly all browsers.
3.) The Google Chrome developer team works on that issue. As there have been several huge changes in the rendering engine there's obviously something in progress.
I've written a large blog post on that issue, feel free to have a look: How to fix the ugly font rendering in Google Chrome
See how the example from the initial question look today, in Chrome 29:
Left: Firefox 23, right: Chrome 29
Top: Firefox 23, bottom: Chrome 29
Fixing the above screenshot with -webkit-text-stroke:
First row is default, second has:
-webkit-text-stroke: 0.3px;
Third row has:
-webkit-text-stroke: 0.6px;
So, the way to fix those fonts is simply giving them
-webkit-text-stroke: 0.Xpx;
or the RGBa syntax (by nezroy, found in the comments! Thanks!)
-webkit-text-stroke: 1px rgba(0,0,0,0.1)
There's also an outdated possibility: Give the text a simple (fake) shadow:
text-shadow: #fff 0px 1px 1px;
RGBa solution (found in Jasper Espejo's blog):
text-shadow: 0 0 1px rgba(51,51,51,0.2);
If you want to be updated on this issue, have a look on the according blog post: How to fix the ugly font rendering in Google Chrome. I'll post news if there're news on this.
This is a big bug in Google Chrome and the Google Chrome Team does know about this, see the official bug report here. Currently, in May 2013, even 11 months after the bug was reported, it's not solved. It's a strange thing that the only browser that messes up Google Webfonts is Google's own browser Chrome (!). But there's a simple workaround that will fix the problem, please see below for the solution.
STATEMENT FROM GOOGLE CHROME DEVELOPMENT TEAM, MAY 2013
Official statement in the bug report comments:
Our Windows font rendering is actively being worked on. ... We hope to have something within a milestone or two that developers can start playing with. How fast it goes to stable is, as always, all about how fast we can root out and burn down any regressions.
Basically you need to look up ArrayList
element based on name getName
. Two approaches to this problem:
1- Don't use ArrayList
, Use HashMap<String,AutionItem>
where String
would be name
2- Use getName
to generate index and use index based addition into array list list.add(int index, E element)
. One way to generate index from name would be to use its hashCode and modulo by ArrayList
current size (something similar what is used inside HashMap
)
For anyone using Flask-SQLAlchemy, this worked for me
from app import db
from app.models import Purchases
from sqlalchemy.orm import aliased
from sqlalchemy import desc
stmt = Purchases.query.distinct(Purchases.address_id).subquery('purchases')
alias = aliased(Purchases, stmt)
distinct = db.session.query(alias)
distinct.order_by(desc(alias.purchased_at))
Found the answer. What I did was was first
sudo apt-get install aptitude
sudo aptitude install libglib2.0-0
sudo aptitude install gcc-4.7 make linux-headers-`uname -r` -y
and tried it but it didn't work so I continued and did
sudo apt-get install build-essential
sudo apt-get install gcc-4.7 linux-headers-`uname -r`
after doing these two steps and trying again, it worked.
Open file CSV by Notepad++ . Choose menu Encoding
\ Encoding in UTF-8
, then fix few cell manuallly.
Then try import again.
We draw a solid line if and only if we have an ID-dependent relationship; otherwise it would be a dashed line.
Consider a weak but not ID-dependent relationship; We draw a dashed line because it is a weak relationship.
Try this,
return RedirectToAction("ActionEventName", "Controller", new { ID = model.ID, SiteID = model.SiteID });
Here i mention you are pass multiple values or model also. That's why here i mention that.
Simple answer
If you want to match single character, put it inside those brackets [ ]
Examples
...and so on. You can check your regular expresion online on this site: https://regex101.com/
(updated based on comment)
To upper case: Ctrl+K, Ctrl+U
and to lower case: Ctrl+K, Ctrl+L.
Mnemonics:
K like the Keyboard
U like the Upper case
L like the Lower case
Actually I think OZ_ may be somewhat correct.
If you have the route '/users/:userId'
and navigate to '/users/'
(note the trailing /), $routeParams
in your controller should be an object containing userId: ""
in 1.1.5. So no the paramater userId
isn't completely ignored, but I think it's the best you're going to get.
In case you want to use the class and pseudo-class:
.simple-control
is your css class
:disabled
is pseudo class
select.simple-control:disabled{
/*For FireFox*/
-webkit-appearance: none;
/*For Chrome*/
-moz-appearance: none;
}
/*For IE10+*/
select:disabled.simple-control::-ms-expand {
display: none;
}
following command will download pyyaml
, which also includes yaml
pip install pyYaml
this is pretty old, but if you are using Python 3.4 or above use PathLib.
# using OS
import os
path=os.path.dirname("C:/folder1/folder2/filename.xml")
print(path)
print(os.path.basename(path))
# using pathlib
import pathlib
path = pathlib.PurePath("C:/folder1/folder2/filename.xml")
print(path.parent)
print(path.parent.name)
this is how I did it
Container(
decoration: new BoxDecoration(
boxShadow: [
BoxShadow(
color: Colors.grey[200],
blurRadius: 2.0, // has the effect of softening the shadow
spreadRadius: 2.0, // has the effect of extending the shadow
offset: Offset(
5.0, // horizontal, move right 10
5.0, // vertical, move down 10
),
)
],
),
child: Container(
color: Colors.white, //in your example it's blue, pink etc..
child: //your content
)
Combine sshpass with a locked-down credentials file and, in practice, it's as secure as anything - if you've got root on the box to read the credentials file, all bets are off anyway.
This command helped me on linux mint when i had exact same problem
gcc filename.c -L/usr/include -lreadline -o filename
You could use alias if you compile it many times Forexample:
alias compilefilename='gcc filename.c -L/usr/include -lreadline -o filename'
You should use onclick method because the function run once when the page is loaded and no button will be clicked then
So you have to add an even which run every time the user press any key to add the changes to the div background
So the function should be something like this
htmlelement.onclick() = function(){
//Do the changes
}
So your code has to look something like this :
var box = document.getElementById("box");
var yes = document.getElementById("yes");
var no = document.getElementById("no");
yes.onclick = function(){
box.style.backgroundColor = "red";
}
no.onclick = function(){
box.style.backgroundColor = "green";
}
This is meaning that when #yes button is clicked the color of the div is red and when the #no button is clicked the background is green
Here is a Jsfiddle
To verify this:-
<div class="Caption">
Model saved
</div>
Write this -
//div[contains(@class, 'Caption') and text()='Model saved']
And to verify this:-
<div id="alertLabel" class="gwt-HTML sfnStandardLeftMargin sfnStandardRightMargin sfnStandardTopMargin">
Save to server successful
</div>
Write this -
//div[@id='alertLabel' and text()='Save to server successful']
If a programmer is interested in only parsing a table from a webpage, they can utilize the pandas method pandas.read_html
.
Let's say we want to extract the GDP data table from the website: https://worldpopulationreview.com/countries/countries-by-gdp/#worldCountries
Then following codes does the job perfectly (No need of beautifulsoup and fancy html):
import pandas as pd
import requests
url = "https://worldpopulationreview.com/countries/countries-by-gdp/#worldCountries"
r = requests.get(url)
df_list = pd.read_html(r.text) # this parses all the tables in webpages to a list
df = df_list[0]
df.head()
For a new project select the home directory of the jdk
eg C:\Java\jdk1.7.0_99
or C:\Program Files\Java\jdk1.7.0_99
For an existing project.
1) You need to have a jdk
installed on the system.
for instance in
C:\Java\jdk1.7.0_99
2) go to project structure
under File
menu ctrl+alt+shift+S
3) SDKs
is located under Platform Settings
. Select it.
4) click the green +
up the top of the window.
5) select JDK
(I have to use keyboard to select it do not know why).
select the home directory for your jdk installation.
should be good to go.
I know it's a bit late to answer here but maybe I may save some once's day.
I have been dealing with the same problem. A model will not populate once you update the value of input from jQuery. I tried using trigger events but no result.
Here is what I did that may save your day.
Declare a variable within your script tag in HTML.
Like:
<script>
var inputValue="";
// update that variable using your jQuery function with appropriate value, you want...
</script>
Once you did that by using below service of angular.
$window
Now below getData function called from the same controller scope will give you the value you want.
var myApp = angular.module('myApp', []);
app.controller('imageManagerCtrl',['$scope','$window',function($scope,$window) {
$scope.getData = function () {
console.log("Window value " + $window.inputValue);
}}]);
Projection: what ever typed in select clause i.e, 'column list' or '*' or 'expressions' that becomes under projection.
*selection:*what type of conditions we are applying on that columns i.e, getting the records that comes under selection.
For example:
SELECT empno,ename,dno,job from Emp
WHERE job='CLERK';
in the above query the columns "empno,ename,dno,job" those comes under projection, "where job='clerk'" comes under selection
You don't have to give version numbers. Just run:
sudo apt-get install php-curl
It worked for me. Don't forgot to restart the server:
sudo service apache2 restart
If trigger("chosen:updated");
not working, use .trigger("liszt:updated");
of @Nhan Tran it is working fine.
C++17 inline
variables
If you Googled "C++ const static", then this is very likely what you really want to use are C++17 inline variables.
This awesome C++17 feature allow us to:
constexpr
: How to declare constexpr extern?main.cpp
#include <cassert>
#include "notmain.hpp"
int main() {
// Both files see the same memory address.
assert(¬main_i == notmain_func());
assert(notmain_i == 42);
}
notmain.hpp
#ifndef NOTMAIN_HPP
#define NOTMAIN_HPP
inline constexpr int notmain_i = 42;
const int* notmain_func();
#endif
notmain.cpp
#include "notmain.hpp"
const int* notmain_func() {
return ¬main_i;
}
Compile and run:
g++ -c -o notmain.o -std=c++17 -Wall -Wextra -pedantic notmain.cpp
g++ -c -o main.o -std=c++17 -Wall -Wextra -pedantic main.cpp
g++ -o main -std=c++17 -Wall -Wextra -pedantic main.o notmain.o
./main
See also: How do inline variables work?
C++ standard on inline variables
The C++ standard guarantees that the addresses will be the same. C++17 N4659 standard draft 10.1.6 "The inline specifier":
6 An inline function or variable with external linkage shall have the same address in all translation units.
cppreference https://en.cppreference.com/w/cpp/language/inline explains that if static
is not given, then it has external linkage.
GCC inline variable implementation
We can observe how it is implemented with:
nm main.o notmain.o
which contains:
main.o:
U _GLOBAL_OFFSET_TABLE_
U _Z12notmain_funcv
0000000000000028 r _ZZ4mainE19__PRETTY_FUNCTION__
U __assert_fail
0000000000000000 T main
0000000000000000 u notmain_i
notmain.o:
0000000000000000 T _Z12notmain_funcv
0000000000000000 u notmain_i
and man nm
says about u
:
"u" The symbol is a unique global symbol. This is a GNU extension to the standard set of ELF symbol bindings. For such a symbol the dynamic linker will make sure that in the entire process there is just one symbol with this name and type in use.
so we see that there is a dedicated ELF extension for this.
Pre-C++ 17: extern const
Before C++ 17, and in C, we can achieve a very similar effect with an extern const
, which will lead to a single memory location being used.
The downsides over inline
are:
constexpr
with this technique, only inline
allows that: How to declare constexpr extern?main.cpp
#include <cassert>
#include "notmain.hpp"
int main() {
// Both files see the same memory address.
assert(¬main_i == notmain_func());
assert(notmain_i == 42);
}
notmain.cpp
#include "notmain.hpp"
const int notmain_i = 42;
const int* notmain_func() {
return ¬main_i;
}
notmain.hpp
#ifndef NOTMAIN_HPP
#define NOTMAIN_HPP
extern const int notmain_i;
const int* notmain_func();
#endif
Pre-C++17 header only alternatives
These are not as good as the extern
solution, but they work and only take up a single memory location:
A constexpr
function, because constexpr
implies inline
and inline
allows (forces) the definition to appear on every translation unit:
constexpr int shared_inline_constexpr() { return 42; }
and I bet that any decent compiler will inline the call.
You can also use a const
or constexpr
static variable as in:
#include <iostream>
struct MyClass {
static constexpr int i = 42;
};
int main() {
std::cout << MyClass::i << std::endl;
// undefined reference to `MyClass::i'
//std::cout << &MyClass::i << std::endl;
}
but you can't do things like taking its address, or else it becomes odr-used, see also: Defining constexpr static data members
C
In C the situation is the same as C++ pre C++ 17, I've uploaded an example at: What does "static" mean in C?
The only difference is that in C++, const
implies static
for globals, but it does not in C: C++ semantics of `static const` vs `const`
Any way to fully inline it?
TODO: is there any way to fully inline the variable, without using any memory at all?
Much like what the preprocessor does.
This would require somehow:
Related:
Tested in Ubuntu 18.10, GCC 8.2.0.
Use this,
var duration = moment.duration(endDate.diff(startDate));
var aa = duration.asHours();
Complementing the answer of @Chris K if you want to call an object's method, you can call it using a single variable with the help of a closure:
function get_method($object, $method){
return function() use($object, $method){
$args = func_get_args();
return call_user_func_array(array($object, $method), $args);
};
}
class test{
function echo_this($text){
echo $text;
}
}
$test = new test();
$echo = get_method($test, 'echo_this');
$echo('Hello'); //Output is "Hello"
I posted another example here
Edited on 1/2/15
C# 6 :
With C# 6 you can initialize auto-properties directly (finally!), there are now other answers in the thread that describe that.
C# 5 and below:
Though the intended use of the attribute is not to actually set the values of the properties, you can use reflection to always set them anyway...
public class DefaultValuesTest
{
public DefaultValuesTest()
{
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(this))
{
DefaultValueAttribute myAttribute = (DefaultValueAttribute)property.Attributes[typeof(DefaultValueAttribute)];
if (myAttribute != null)
{
property.SetValue(this, myAttribute.Value);
}
}
}
public void DoTest()
{
var db = DefaultValueBool;
var ds = DefaultValueString;
var di = DefaultValueInt;
}
[System.ComponentModel.DefaultValue(true)]
public bool DefaultValueBool { get; set; }
[System.ComponentModel.DefaultValue("Good")]
public string DefaultValueString { get; set; }
[System.ComponentModel.DefaultValue(27)]
public int DefaultValueInt { get; set; }
}
To add to @Craig Schwarze answer,
Here are some related MSDN links:
Loading and Running a Local Package Programmatically:
Loading and Running a Remote Package Programmatically
Capturing Events from a Running Package:
using System;
using Microsoft.SqlServer.Dts.Runtime;
namespace RunFromClientAppWithEventsCS
{
class MyEventListener : DefaultEvents
{
public override bool OnError(DtsObject source, int errorCode, string subComponent,
string description, string helpFile, int helpContext, string idofInterfaceWithError)
{
// Add application-specific diagnostics here.
Console.WriteLine("Error in {0}/{1} : {2}", source, subComponent, description);
return false;
}
}
class Program
{
static void Main(string[] args)
{
string pkgLocation;
Package pkg;
Application app;
DTSExecResult pkgResults;
MyEventListener eventListener = new MyEventListener();
pkgLocation =
@"C:\Program Files\Microsoft SQL Server\100\Samples\Integration Services" +
@"\Package Samples\CalculatedColumns Sample\CalculatedColumns\CalculatedColumns.dtsx";
app = new Application();
pkg = app.LoadPackage(pkgLocation, eventListener);
pkgResults = pkg.Execute(null, null, eventListener, null, null);
Console.WriteLine(pkgResults.ToString());
Console.ReadKey();
}
}
}
if you meant comparing nth item with n+1 th item in the list you could also do with
>>> for i in range(len(list[:-1])):
... print list[i]>list[i+1]
note there is no hard coding going on there. This should be ok unless you feel otherwise.
Here is an example of how to use strtok borrowed from MSDN.
And the relevant bits, you need to call it multiple times. The token
char* is the part you would stuff into an array (you can figure that part out).
char string[] = "A string\tof ,,tokens\nand some more tokens";
char seps[] = " ,\t\n";
char *token;
int main( void )
{
printf( "Tokens:\n" );
/* Establish string and get the first token: */
token = strtok( string, seps );
while( token != NULL )
{
/* While there are tokens in "string" */
printf( " %s\n", token );
/* Get next token: */
token = strtok( NULL, seps );
}
}
Let's say you have two activities.
And on click of a Button, this happens.
1) Enable Content Transition
Go to your style.xml
and add this line to enable the content transition.
<item name="android:windowContentTransitions">true</item>
2) Write Default Enter and Exit Transition for your AllCastActivity
public void setAnimation()
{
if(Build.VERSION.SDK_INT>20) {
Slide slide = new Slide();
slide.setSlideEdge(Gravity.LEFT);
slide.setDuration(400);
slide.setInterpolator(new AccelerateDecelerateInterpolator());
getWindow().setExitTransition(slide);
getWindow().setEnterTransition(slide);
}
}
3) Start Activity with Intent
Write this method in Your MovieDetailActivity
to start AllCastActivity
public void startActivity(){
Intent i = new Intent(FirstActivity.this, SecondActivity.class);
i.putStringArrayListExtra(MOVIE_LIST, movie.getImages());
if(Build.VERSION.SDK_INT>20)
{
ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(BlankActivity.this);
startActivity(i,options.toBundle());
}
else {
startActivity(i);
}
}
put your setAnimation()
method before setContentView()
method otherwise the animation will not work.
So your AllCastActivity.java
should look like this
class AllCastActivity extends AppcompatActivity {
@Override
protected void onCreate(Bundle savedInstaceState)
{
super.onCreate(savedInstaceState);
setAnimation();
setContentView(R.layout.all_cast_activity);
.......
}
private void setAnimation(){
if(Build.VERSION.SDK_INT>20) {
Slide slide = new Slide();
slide.setSlideEdge(Gravity.LEFT);
..........
}
}
First of all, dynamically pivot using pivot xml
again needs to be parsed. We have another way of doing this by storing the column names in a variable and passing them in the dynamic sql as below.
Consider we have a table like below.
If we need to show the values in the column YR
as column names and the values in those columns from QTY
, then we can use the below code.
declare
sqlqry clob;
cols clob;
begin
select listagg('''' || YR || ''' as "' || YR || '"', ',') within group (order by YR)
into cols
from (select distinct YR from EMPLOYEE);
sqlqry :=
'
select * from
(
select *
from EMPLOYEE
)
pivot
(
MIN(QTY) for YR in (' || cols || ')
)';
execute immediate sqlqry;
end;
/
RESULT
There is the wget
command or the curl
.
You can now use the file you downloaded with wget. Or you can handle a stream with curl.
Resources :
Use LINQ:
Dictionary<string, int> myDict = new Dictionary<string, int>();
myDict.Add("one", 1);
myDict.Add("four", 4);
myDict.Add("two", 2);
myDict.Add("three", 3);
var sortedDict = from entry in myDict orderby entry.Value ascending select entry;
This would also allow for great flexibility in that you can select the top 10, 20 10%, etc. Or if you are using your word frequency index for type-ahead
, you could also include StartsWith
clause as well.
Compare document.activeElement
with the element you want to check for focus. If they are the same, the element is focused; otherwise, it isn't.
// dummy element
var dummyEl = document.getElementById('myID');
// check for focus
var isFocused = (document.activeElement === dummyEl);
hasFocus
is part of the document
; there's no such method for DOM elements.
Also, document.getElementById
doesn't use a #
at the beginning of myID
. Change this:
var dummyEl = document.getElementById('#myID');
to this:
var dummyEl = document.getElementById('myID');
If you'd like to use a CSS query instead you can use querySelector
(and querySelectorAll
).
As a slight improvement over the other answers, you can do the mkdir
and chmod
as a single operation using mkdir
's -m
switch.
$ mkdir -m 700 ${HOME}/.ssh
From a Linux system
$ mkdir --help
Usage: mkdir [OPTION]... DIRECTORY...
Create the DIRECTORY(ies), if they do not already exist.
Mandatory arguments to long options are mandatory for short options too.
-m, --mode=MODE set file mode (as in chmod), not a=rwx - umask
...
...
Minor note: Please consider that when you import from a default export, the naming is completely independent. This actually has an impact on refactorings.
Let's say you have a class Foo
like this with a corresponding import:
export default class Foo { }
// The name 'Foo' could be anything, since it's just an
// Identifier for the default export
import Foo from './Foo'
Now if you refactor your Foo
class to be Bar
and also rename the file, most IDEs will NOT touch your import. So you will end up with this:
export default class Bar { }
// The name 'Foo' could be anything, since it's just an
// Identifier for the default export.
import Foo from './Bar'
Especially in TypeScript, I really appreciate named exports and the more reliable refactoring. The difference is just the lack of the default
keyword and the curly braces. This btw also prevents you from making a typo in your import since you have type checking now.
export class Foo { }
//'Foo' needs to be the class name. The import will be refactored
//in case of a rename!
import { Foo } from './Foo'
I usually take a look at the data first or just try to import it and do data.head(), if you see that the columns are separated with \t then you should specify sep="\t"
otherwise, sep = " "
.
import pandas as pd
data = pd.read_csv('data.txt', sep=" ", header=None)
You can simply play a setted ringtone with this:
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
If you're using SQL Server, you could add three calculated fields to your table:
Sales (saleID INT, amount INT, created DATETIME)
ALTER TABLE dbo.Sales
ADD SaleYear AS YEAR(Created) PERSISTED
ALTER TABLE dbo.Sales
ADD SaleMonth AS MONTH(Created) PERSISTED
ALTER TABLE dbo.Sales
ADD SaleDay AS DAY(Created) PERSISTED
and now you could easily group by, order by etc. by day, month or year of the sale:
SELECT SaleDay, SUM(Amount)
FROM dbo.Sales
GROUP BY SaleDay
Those calculated fields will always be kept up to date (when your "Created" date changes), they're part of your table, they can be used just like regular fields, and can even be indexed (if they're "PERSISTED") - great feature that's totally underused, IMHO.
Marc
After few years, I moved to leaflet map and I have fixed this issue completely, the following could be applied to google maps too:
var headerHeight = $("#navMap").outerHeight();
var footerHeight = $("footer").outerHeight();
var windowHeight = window.innerHeight;
var mapContainerHeight = headerHeight + footerHeight;
var totalMapHeight = windowHeight - mapContainerHeight;
$("#map").css("margin-top", headerHeight);
$("#map").height(totalMapHeight);
$(window).resize(function(){
var headerHeight = $("#navMap").outerHeight();
var footerHeight = $("footer").outerHeight();
var windowHeight = window.innerHeight;
var mapContainerHeight = headerHeight + footerHeight;
var totalMapHeight = windowHeight - mapContainerHeight;
$("#map").css("margin-top", headerHeight);
$("#map").height(totalMapHeight);
map.fitBounds(group1.getBounds());
});
Those are called XML Comments. They have been a part of Visual Studio since forever.
You can make your documentation process easier by using GhostDoc, a free add-in for Visual Studio which generates XML-doc comments for you. Just place your caret on the method/property you want to document, and press Ctrl-Shift-D.
Here's an example from one of my posts.
Hope that helps :)
Check out the moment.js
library. It works with browsers as well as with Node.JS. Allows you to write
moment().hour();
or
moment().hours();
without prior writing of any functions.
sort -u
will be slightly faster, because it does not need to pipe the output between two commands
also see my question on the topic: calling uniq and sort in different orders in shell
Some sample code:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
this.AllowDrop = true;
this.DragEnter += new DragEventHandler(Form1_DragEnter);
this.DragDrop += new DragEventHandler(Form1_DragDrop);
}
void Form1_DragEnter(object sender, DragEventArgs e) {
if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;
}
void Form1_DragDrop(object sender, DragEventArgs e) {
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files) Console.WriteLine(file);
}
}
As the message error says, you need to Increase the length of your column to fit the length of the data you are trying to insert (0000-00-00)
EDIT 1:
Following your comment, I run a test table:
mysql> create table testDate(id int(2) not null auto_increment, pdd date default null, primary key(id));
Query OK, 0 rows affected (0.20 sec)
Insertion:
mysql> insert into testDate values(1,'0000-00-00');
Query OK, 1 row affected (0.06 sec)
EDIT 2:
So, aparently you want to insert a NULL value to pdd
field as your comment states ?
You can do that in 2 ways like this:
Method 1:
mysql> insert into testDate values(2,'');
Query OK, 1 row affected, 1 warning (0.06 sec)
Method 2:
mysql> insert into testDate values(3,NULL);
Query OK, 1 row affected (0.07 sec)
EDIT 3:
You failed to change the default value of pdd
field. Here is the syntax how to do it (in my case, I set it to NULL in the start, now I will change it to NOT NULL)
mysql> alter table testDate modify pdd date not null;
Query OK, 3 rows affected, 1 warning (0.60 sec)
Records: 3 Duplicates: 0 Warnings: 1
Ben Gripka's solution causes infinite loops. His batch works like this (pseudo code):
IF "no admin privileges?"
"write a VBS that calls this batch with admin privileges"
ELSE
"execute actual commands that require admin privileges"
As you can see, this causes an infinite loop, if the VBS fails requesting admin privileges.
However, the infinite loop can occur, although admin priviliges have been requested successfully.
The check in Ben Gripka's batch file is just error-prone. I played around with the batch and observed that admin privileges are available although the check failed. Interestingly, the check worked as expected, if I started the batch file from windows explorer, but it didn't when I started it from my IDE.
So I suggest to use two separate batch files. The first generates the VBS that calls the second batch file:
@echo off
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
set params = %*:"=""
echo UAC.ShellExecute "cmd.exe", "/c ""%~dp0\my_commands.bat"" %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
The second, named "my_commands.bat" and located in the same directory as the first contains your actual commands:
pushd "%CD%"
CD /D "%~dp0"
REM Your commands which require admin privileges here
This causes no infinite loops and also removes the error-prone admin privilege check.