You have by default the static
endpoint for static files. Also Flask
application has the following arguments:
static_url_path
: can be used to specify a different path for the static files on the web. Defaults to the name of the static_folder
folder.
static_folder
: the folder with static files that should be served at static_url_path
. Defaults to the 'static' folder in the root path of the application.
It means that the filename
argument will take a relative path to your file in static_folder
and convert it to a relative path combined with static_url_default
:
url_for('static', filename='path/to/file')
will convert the file path from static_folder/path/to/file
to the url path static_url_default/path/to/file
.
So if you want to get files from the static/bootstrap
folder you use this code:
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='bootstrap/bootstrap.min.css') }}">
Which will be converted to (using default settings):
<link rel="stylesheet" type="text/css" href="static/bootstrap/bootstrap.min.css">
Also look at url_for
documentation.
I have experienced a great example of reproducing such a problem. Maybe my experience will help someone one day.
Check that your @Embedded Id of container has no possible collisions.
When Hibernate instantiates collection wrapper, it searches for already instantiated collection by CollectionKey in internal Map.
For Entity with @Embedded id, CollectionKey wraps EmbeddedComponentType and uses @Embedded Id properties for equality checks and hashCode calculation.
So if you have two entities with equal @Embedded Ids, Hibernate will instantiate and put new collection by the first key and will find same collection for the second key. So two entities with same @Embedded Id will be populated with same collection.
Suppose you have Account entity which has lazy set of loans. And Account has @Embedded Id consists of several parts(columns).
@Entity
@Table(schema = "SOME", name = "ACCOUNT")
public class Account {
@OneToMany(fetch = FetchType.LAZY, mappedBy = "account")
private Set<Loan> loans;
@Embedded
private AccountId accountId;
...
}
@Embeddable
public class AccountId {
@Column(name = "X")
private Long x;
@Column(name = "BRANCH")
private String branchId;
@Column(name = "Z")
private String z;
...
}
Then suppose that Account has additional property mapped by @Embedded Id but has relation to other entity Branch.
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "BRANCH")
@MapsId("accountId.branchId")
@NotFound(action = NotFoundAction.IGNORE)//Look at this!
private Branch branch;
It could happen that you have no FK for Account to Brunch relation id DB so Account.BRANCH column can have any value not presented in Branch table.
According to @NotFound(action = NotFoundAction.IGNORE)
if value is not present in related table, Hibernate will load null value for the property.
If X and Y columns of two Accounts are same(which is fine), but BRANCH is different and not presented in Branch table, hibernate will load null for both and Embedded Ids will be equal.
So two CollectionKey objects will be equal and will have same hashCode for different Accounts.
result = {CollectionKey@34809} "CollectionKey[Account.loans#Account@43deab74]"
role = "Account.loans"
key = {Account@26451}
keyType = {EmbeddedComponentType@21355}
factory = {SessionFactoryImpl@21356}
hashCode = 1187125168
entityMode = {EntityMode@17415} "pojo"
result = {CollectionKey@35653} "CollectionKey[Account.loans#Account@33470aa]"
role = "Account.loans"
key = {Account@35225}
keyType = {EmbeddedComponentType@21355}
factory = {SessionFactoryImpl@21356}
hashCode = 1187125168
entityMode = {EntityMode@17415} "pojo"
Because of this, Hibernate will load same PesistentSet for two entities.
For Windows it seems possible to control the amount of memory MongoDB uses, see this tutorial at Captain Codeman:
Line magics are prefixed with the % character and work much like OS command-line calls: they get as an argument the rest of the line, where arguments are passed without parentheses or quotes. Cell magics are prefixed with a double %%, and they are functions that get as an argument not only the rest of the line, but also the lines below it in a separate argument.
I've the same problem and solved with this code. I put this code before the first call to my webservices.
javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
new javax.net.ssl.HostnameVerifier(){
public boolean verify(String hostname,
javax.net.ssl.SSLSession sslSession) {
return hostname.equals("localhost"); // or return true
}
});
It's simple and works fine.
Here is the original source.
Agree with @bluecollarcoder answer, but it's better to use TimeZone.getDefault().getID();
at the end of the connection string:
"jdbc:mysql://localhost/db?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=" + TimeZone.getDefault().getID();
In this case Timezone
parameter automatically updates depending on the local machine timezone.
Use QString::fromUtf16((ushort *)Data.data())
, as shown in the following code example:
#include <QCoreApplication>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// QByteArray to QString
// =====================
const char c_test[10] = {'t', '\0', 'e', '\0', 's', '\0', 't', '\0', '\0', '\0'};
QByteArray qba_test(QByteArray::fromRawData(c_test, 10));
qDebug().nospace().noquote() << "qba_test[" << qba_test << "]"; // Should see: qba_test[t
QString qstr_test = QString::fromUtf16((ushort *)qba_test.data());
qDebug().nospace().noquote() << "qstr_test[" << qstr_test << "]"; // Should see: qstr_test[test]
return a.exec();
}
This is an alternative solution to the one using QTextCodec. The code has been tested using Qt 5.4.
To avoid unnecessary duplication, I added the following to my ~/.bash_profile
case ":$PATH:" in
*:/usr/local/bin:*) ;; # do nothing if $PATH already contains /usr/local/bin
*) PATH=/usr/local/bin:$PATH ;; # in every other case, add it to the front
esac
Credit: https://superuser.com/a/580611
git --work-tree=/tmp/files_without_dot_git clone --depth=1 \
https://git.yourgit.your.com/myawesomerepo.git \
/tmp/deleteme_contents_of_dot_git
Both the directories in /tmp are created on the fly. No need to pre-create these.
You can find some resources related to developing web services client using Apache axis2 here.
http://today.java.net/pub/a/today/2006/12/13/invoking-web-services-using-apache-axis2.html
Below posts gives good explanations about developing web services using Apache axis2.
http://www.ibm.com/developerworks/opensource/library/ws-webaxis1/
Apache Commons Lang's replaceEach method may come in handy dependeding on your specific needs. You can easily use it to replace placeholders by name with this single method call:
StringUtils.replaceEach("There's an incorrect value '%(value)' in column # %(column)",
new String[] { "%(value)", "%(column)" }, new String[] { x, y });
Given some input text, this will replace all occurrences of the placeholders in the first string array with the corresponding values in the second one.
When i will getting this error on my site .it will stop some functionality on my site, after research i find the solution for this problem ,
$colorpicker_inputs.live('focus', function(e) {
jQuery(this).next('.farb-popup').show();
jQuery(this).parents('li').css( {
position : 'relative',
zIndex : '9999'
})
jQuery('#tabber').css( {
overflow : 'visible'
});
});
$colorpicker_inputs.live('blur', function(e) {
jQuery(this).next('.farb-popup').hide();
jQuery(this).parents('li').css( {
zIndex : '0'
})
});
Should be replace 'live' to 'on' check below
$colorpicker_inputs.on('focus', function(e) {
jQuery(this).next('.farb-popup').show();
jQuery(this).parents('li').css( {
position : 'relative',
zIndex : '9999'
})
jQuery('#tabber').css( {
overflow : 'visible'
});
});
$colorpicker_inputs.on('blur', function(e) {
jQuery(this).next('.farb-popup').hide();
jQuery(this).parents('li').css( {
zIndex : '0'
})
});
One more basic exmaple below :
.live(event, selector, function)
Change it to :
.on(event, selector, function)
#pragma
is for compiler directives that are machine-specific or operating-system-specific, i.e. it tells the compiler to do something, set some option, take some action, override some default, etc. that may or may not apply to all machines and operating systems.
See msdn for more info.
that worked but try it this way.
echo "<script>
alert('There are no fields to generate a report');
window.location.href='admin/ahm/panel';
</script>";
alert on top then location next
You can use the @RestController
instead of @Controller
annotation.
At the beginning of your file you set raw_input
to 0. Do not do this, at it modifies the built-in raw_input()
function. Therefore, whenever you call raw_input()
, it is essentially calling 0()
, which raises the error. To remove the error, remove the first line of your code:
M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54
def intro():
print("Welcome! This program will convert measures for you.")
main()
def main():
print("Select operation.")
print("1.Miles to Kilometers")
print("2.Fahrenheit to Celsius")
print("3.Gallons to liters")
print("4.Pounds to kilograms")
print("5.Inches to centimeters")
choice = input("Enter your choice by number: ")
if choice == '1':
convertMK()
elif choice == '2':
converCF()
elif choice == '3':
convertGL()
elif choice == '4':
convertPK()
elif choice == '5':
convertPK()
else:
print("Error")
def convertMK():
input_M = float(raw_input(("Miles: ")))
M_conv = (M) * input_M
print("Kilometers: %f\n" % M_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def converCF():
input_F = float(raw_input(("Fahrenheit: ")))
F_conv = (input_F - 32) * 5/9
print("Celcius: %f\n") % F_conv
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def convertGL():
input_G = float(raw_input(("Gallons: ")))
G_conv = input_G * 3.6
print("Centimeters: %f\n" % G_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertPK():
input_P = float(raw_input(("Pounds: ")))
P_conv = input_P * 0.45
print("Centimeters: %f\n" % P_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertIC():
input_cm = float(raw_input(("Inches: ")))
inches_conv = input_cm * 2.54
print("Centimeters: %f\n" % inches_conv)
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def end():
print("This program will close.")
exit()
intro()
You can delete the browser cache by setting these headers:
<?php
header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
?>
var formData = new FormData($("#YOUR_FORM_ID")[0]);
$.ajax({
url: "upload.php",
type: "POST",
data : formData,
processData: false,
contentType: false,
beforeSend: function() {
},
success: function(data){
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
You can save the struct into a map by matching the struct Key
and Value
components to their fictive key and value parts on the map:
mapConfig := map[string]string{}
for _, v := range myconfig {
mapConfig[v.Key] = v.Value
}
Then using the golang comma ok idiom you can test for the key presence:
if v, ok := mapConfig["key1"]; ok {
fmt.Printf("%s exists", v)
}
Adding following in the page header works for me:
<?php
if($i_wanna_reload_the_full_page_on_top == "yes")
{
$reloadneeded = "1";
}
else
{
$reloadneeded = "0";
}
if($reloadneeded > 0)
{
?>
<script type="text/javascript">
top.window.location='indexframes.php';
</script>
<?php
}else{}
?>
ES6 will provide Map.prototype.forEach(callback) which can be used like this
myMap.forEach(function(value, key, myMap) {
// Do something
});
after some test: If you send an email to an outlook client, and the subject is >77 chars, and it needs to use "=?ISO"
inside the subject (in my case because of accents) then OutLook will "cut" the subject in the middle of it and mesh it all that comes after, including body text, attaches, etc... all a mesh!
I have several examples like this one:
Subject: =?ISO-8859-1?Q?Actas de la obra N=BA.20100154 (Expediente N=BA.20100182) "NUEVA RED FERROVIARIA.=
TRAMO=20BEASAIN=20OESTE(Pedido=20PC10/00123-125),=20BEASAIN".?=
To:
As you see, in the subject line it cutted on char 78 with a "=" followed by 2 or 3 line feeds, then continued with the rest of the subject baddly.
It was reported to me from several customers who all where using OutLook, other email clients deal with those subjects ok.
If you have no ISO on it, it doesn't hurt, but if you add it to your subject to be nice to RFC, then you get this surprise from OutLook. Bit if you don't add the ISOs, then iPhone email will not understand it(and attach files with names using such characters will not work on iPhones).
Are you using JavaScript or jQuery besides the html? If you are, you can do something like:
HTML:
<select id='some_selector'></select>?
jQuery:
var select = '';
for (i=1;i<=100;i++){
select += '<option val=' + i + '>' + i + '</option>';
}
$('#some_selector').html(select);
As you can see here.
Another option for compatible browsers instead of select, you can use is HTML5's input type=number
:
<input type="number" min="1" max="100" value="1">
//You are not expected to understand this
classic.
Just set the JDK path from the below steps:
Go to 'Run' ->External Tools -> External Tools Configuration
-> Select 'JRE' Then from the DropDown list select the available JDK . ex. jdk1.8.0_25
For those searching this error, another thing that can trigger AtributeError: can't set attribute
is if you try to set a decorated @property
that has no setter method. Not the problem in the OP's question, but I'm putting it here to help any searching for the error message directly. (if you don't like it, go edit the question's title :)
class Test:
def __init__(self):
self._attr = "original value"
# This will trigger an error...
self.attr = "new value"
@property
def attr(self):
return self._attr
Test()
A nice way is to use Spring's ResponseStatusException
Rather than returning a ResponseEntity
or similar you simply throw the ResponseStatusException
from the controller with an HttpStatus
and cause, for example:
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Cause description here");
or:
throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Cause description here");
This results in a response to the client containing the HTTP status (e.g. 400 Bad request) with a body like:
{
"timestamp": "2020-07-09T04:43:04.695+0000",
"status": 400,
"error": "Bad Request",
"message": "Cause description here",
"path": "/test-api/v1/search"
}
Sets remove duplicate items. In order to do that, the item can't change while in the set. Lists can change after being created, and are termed 'mutable'. You cannot put mutable things in a set.
Lists have an unmutable equivalent, called a 'tuple'. This is how you would write a piece of code that took a list of lists, removed duplicate lists, then sorted it in reverse.
result = sorted(set(map(tuple, my_list)), reverse=True)
Additional note: If a tuple contains a list, the tuple is still considered mutable.
Some examples:
>>> hash( tuple() )
3527539
>>> hash( dict() )
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
hash( dict() )
TypeError: unhashable type: 'dict'
>>> hash( list() )
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
hash( list() )
TypeError: unhashable type: 'list'
use cin.ignore(1000,'\n')
to clear all of chars of the previous cin.get()
in the buffer and it will choose to stop when it meet '\n' or 1000 chars
first.
n = eval(input('Num books: '))
books = {}
for i in range(n):
titlez = input("Enter Title: ")
copy = eval(input("Num of copies: "))
books[titlez] = copy
prob = input('Sell a book; enter YES or NO: ')
if prob == 'YES' or 'yes':
choice = input('Enter book title: ')
if choice in books:
init_num = books[choice]
init_num -= 1
books[choice] = init_num
print(books)
The solution found here helped us to update master to a previous commit that had already been pushed:
git checkout master
git reset --hard e3f1e37
git push --force origin e3f1e37:master
The key difference from the accepted answer is the commit hash "e3f1e37:" before master in the push command.
Not sure if your question was answered.
This will write the time & date every 20 seconds in the file ping_ip.txt. The second to last line just says run the same batch file again, and agan, and again,..........etc.
Does not seem to create multiple instances, so that's a good thing.
@echo %time% %date% >>ping_ip.txt
ping -n 20 -w 3 127.0.0.1 >>ping_ip.txt
This_Batch_FileName.bat
cls
Two conditional functions are needed: one for Google Chrome, and a second for the remaining browsers.
$scope.printDiv = function (divName) {
var printContents = document.getElementById(divName).innerHTML;
if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
var popupWin = window.open('', '_blank', 'width=600,height=600,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no');
popupWin.window.focus();
popupWin.document.write('<!DOCTYPE html><html><head>' +
'<link rel="stylesheet" type="text/css" href="style.css" />' +
'</head><body onload="window.print()"><div class="reward-body">' + printContents + '</div></body></html>');
popupWin.onbeforeunload = function (event) {
popupWin.close();
return '.\n';
};
popupWin.onabort = function (event) {
popupWin.document.close();
popupWin.close();
}
} else {
var popupWin = window.open('', '_blank', 'width=800,height=600');
popupWin.document.open();
popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
popupWin.document.close();
}
popupWin.document.close();
return true;
}
Use index to show the first value as default
<option *ngFor="let workout of workouts; #i = index" [selected]="i == 0">{{workout.name}}</option>
Immediately after you start a new activity, using startActivity
, make sure you call finish()
so that the current activity is not stacked behind the new one.
As far as i know this Pipeline Plugin is the "Engine" of the new Jenkinsfile mechanics, so im quite positive you could use this to locally test your scripts.
Im not sure if there is any additional steps needed when you copy it into a Jenkinsfile, however the syntax etc should be exactly the same.
Edit: Found the reference on the "engine", check this feature description, last paragraph, first entry.
Here is a way to remove the element from the array in the state using ES6 spread syntax.
onRemovePerson: (index) => {
const data = this.state.data;
this.setState({
data: [...data.slice(0,index), ...data.slice(index+1)]
});
}
Suppose you have a DataFrame
and you want to do some modification on the fields data by converting it to RDD[Row]
.
val aRdd = aDF.map(x=>Row(x.getAs[Long]("id"),x.getAs[List[String]]("role").head))
To convert back to DataFrame
from RDD
we need to define the structure type of the RDD
.
If the datatype was Long
then it will become as LongType
in structure.
If String
then StringType
in structure.
val aStruct = new StructType(Array(StructField("id",LongType,nullable = true),StructField("role",StringType,nullable = true)))
Now you can convert the RDD to DataFrame using the createDataFrame method.
val aNamedDF = sqlContext.createDataFrame(aRdd,aStruct)
You are looking for JavaScript's String
method substring
e.g.
'Hiya how are you'.substring(0,8);
Which returns the string starting at the first character and finishing before the 9th character - i.e. 'Hiya how'.
If you are trying to run the macro from your personal workbook it might not work as opening an Excel file with a VBScript doesnt automatically open your PERSONAL.XLSB. you will need to do something like this:
Dim oFSO
Dim oShell, oExcel, oFile, oSheet
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oShell = CreateObject("WScript.Shell")
Set oExcel = CreateObject("Excel.Application")
Set wb2 = oExcel.Workbooks.Open("C:\..\PERSONAL.XLSB") 'Specify foldername here
oExcel.DisplayAlerts = False
For Each oFile In oFSO.GetFolder("C:\Location\").Files
If LCase(oFSO.GetExtensionName(oFile)) = "xlsx" Then
With oExcel.Workbooks.Open(oFile, 0, True, , , , True, , , , False, , False)
oExcel.Run wb2.Name & "!modForm"
For Each oSheet In .Worksheets
oSheet.SaveAs "C:\test\" & oFile.Name & "." & oSheet.Name & ".txt", 6
Next
.Close False, , False
End With
End If
Next
oExcel.Quit
oShell.Popup "Conversion complete", 10
So at the beginning of the loop it is opening personals.xlsb and running the macro from there for all the other workbooks. Just thought I should post in here just in case someone runs across this like I did but cant figure out why the macro is still not running.
time.second helps a lot put that at the top of your python.
Running this command was my mistake.
npm config set prefix /usr/local
Path /usr/local
is not for windows. This command changed the prefix variable at 'C:\Program Files (x86)\Git\local'
To access and make a change to this directory I need to run my cmd as administrator.
So I did:
npm config edit
(You will get notepad editor)prefix
variable to C:\Users\<User Name>\AppData\Roaming\npm
Then npm start
works in a normal console.
For me, the only thing which worked is
git diff HEAD
including the staged files, git diff --cached
only shows staged files.
If you're willing to use C, you can use the strtok function. You should pay attention to multi-threading issues when using it.
tr:hover td.someclass {
background: #EDB01C;
color:#FFF;
}
only someclass cell highlight
AJAX file uploads are now possible by passing a FormData
object to the data
property of the $.ajax
request.
As the OP specifically asked for a jQuery implementation, here you go:
<form id="upload" enctype="multipart/form-data" action="@Url.Action("JsonSave", "Survey")" method="POST">
<input type="file" name="fileUpload" id="fileUpload" size="23" /><br />
<button>Upload!</button>
</form>
$('#upload').submit(function(e) {
e.preventDefault(); // stop the standard form submission
$.ajax({
url: this.action,
type: this.method,
data: new FormData(this),
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data.UploadedFileCount + ' file(s) uploaded successfully');
},
error: function(xhr, error, status) {
console.log(error, status);
}
});
});
public JsonResult Survey()
{
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
// save file as required here...
}
return Json(new { UploadedFileCount = Request.Files.Count });
}
More information on FormData at MDN
I'm just beginner to help you for getting edittext value to textview. Try out this code -
EditText edit = (EditText)findViewById(R.id.editext1);
TextView tview = (TextView)findViewById(R.id.textview1);
String result = edit.getText().toString();
tview.setText(result);
This will get the text which is in EditText
Hope this helps you.
You must sort your data according your needs (es. in reverse order) and use select top query
You can use childNodes
instead of children
, childNodes
is also more reliable considering browser compatibility issues, more info here:
parent.childNodes.forEach(function (child) {
console.log(child)
});
or using spread operator:
[...parent.children].forEach(function (child) {
console.log(child)
});
To add my 2 cents, the exception can occur even if you call your code through System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke()
.
The point is that you have to call Invoke()
of the Dispatcher
of the control that you're trying to access, which in some cases may not be the same as System.Windows.Threading.Dispatcher.CurrentDispatcher
. So instead you should use YourControl.Dispatcher.Invoke()
to be safe. I was banging my head for a couple of hours before I realized this.
For future readers, it looks like this has changed in the newer versions of .NET (4.0 and above). Now you no longer have to worry about the correct dispatcher when updating UI-backing properties in your VM. WPF engine will marshal cross-thread calls on the correct UI thread. See more details here. Thanks to @aaronburro for the info and link. You may also want to read our conversation below in comments.
Other answers have already explained why virtual
function calls don't work as expected when called from a constructor. I'd like to instead propose another possible work around for getting polymorphic-like behavior from a base type's constructor.
By adding a template constructor to the base type such that the template argument is always deduced to be the derived type it's possible to be aware of the derived type's concrete type. From there, you can call static
member functions for that derived type.
This solution does not allow non-static
member functions to be called. While execution is in the base type's constructor, the derived type's constructor hasn't even had time to go through it's member initialization list. The derived type portion of the instance being created hasn't begun being initialized it. And since non-static
member functions almost certainly interact with data members it would be unusual to want to call the derived type's non-static
member functions from the base type's constructor.
Here is a sample implementation :
#include <iostream>
#include <string>
struct Base {
protected:
template<class T>
explicit Base(const T*) : class_name(T::Name())
{
std::cout << class_name << " created\n";
}
public:
Base() : class_name(Name())
{
std::cout << class_name << " created\n";
}
virtual ~Base() {
std::cout << class_name << " destroyed\n";
}
static std::string Name() {
return "Base";
}
private:
std::string class_name;
};
struct Derived : public Base
{
Derived() : Base(this) {} // `this` is used to allow Base::Base<T> to deduce T
static std::string Name() {
return "Derived";
}
};
int main(int argc, const char *argv[]) {
Derived{}; // Create and destroy a Derived
Base{}; // Create and destroy a Base
return 0;
}
This example should print
Derived created
Derived destroyed
Base created
Base destroyed
When a Derived
is constructed, the Base
constructor's behavior depends on the actual dynamic type of the object being constructed.
You might be able to do a "cherry-pick" to pull the exact commit(s) that you need in to your feature branch.
Do a git checkout hotfix1
to get on the hotfix1 branch. Then do a git log
to get the SHA-1 hash (big sequence of random letters and numbers that uniquely identifies a commit) of the commit in question. Copy that (or the first 10 or so characters).
Then, git checkout feature1
to get back onto your feature branch.
Then, git cherry-pick <the SHA-1 hash that you just copied>
That will pull that commit, and only that commit, into your feature branch. That change will be in the branch - you just "cherry-picked" it in. Then, resume work, edit, commit, push, etc. to your heart's content.
When, eventually, you perform another merge from one branch into your feature branch (or vice-versa), Git will recognize that you've already merged in that particular commit, know that it doesn't have to make it again, and just "skip over" it.
The easiest way to have a permanent and sustainable solution for the Docker Compose installation and the way to upgrade it, is to just use the package manager pip with:
pip install docker-compose
I was searching for a good solution for the ugly "how to upgrade to the latest version number"-problem, which appeared after you´ve read the official docs - and just found it occasionally - just have a look at the docker-compose pip package - it should reflect (mostly) the current number of the latest released Docker Compose version.
A package manager is always the best solution if it comes to managing software installations! So you just abstract from handling the versions on your own.
First check out config files for syntax errors with apachectl configtest
and then look into apache error logs.
Like the following. It will make the user database owner.
EXEC sp_addrolemember N'db_owner', N'USerNAme'
Apple have changed the name of the certificate that is issued. You can now use the same certificate for both development and production. While you can still request a development only certificate you can no longer request a production only certificate.
In the meantime (since version 3.2, in the year 2013, thanks to SEC-2298) the authentication can be injected into MVC methods using the annotation @AuthenticationPrincipal:
@Controller
class Controller {
@RequestMapping("/somewhere")
public void doStuff(@AuthenticationPrincipal UserDetails myUser) {
}
}
In your unit test you can obviously call this Method directly. In integration tests using org.springframework.test.web.servlet.MockMvc
you can use org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user()
to inject the user like this:
mockMvc.perform(get("/somewhere").with(user(myUserDetails)));
This will however just directly fill the SecurityContext. If you want to make sure that the user is loaded from a session in your test, you can use this:
mockMvc.perform(get("/somewhere").with(sessionUser(myUserDetails)));
/* ... */
private static RequestPostProcessor sessionUser(final UserDetails userDetails) {
return new RequestPostProcessor() {
@Override
public MockHttpServletRequest postProcessRequest(final MockHttpServletRequest request) {
final SecurityContext securityContext = new SecurityContextImpl();
securityContext.setAuthentication(
new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities())
);
request.getSession().setAttribute(
HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext
);
return request;
}
};
}
For Windows:
$ ssh-keygen -t rsa -b 4096 -C [email protected]
When the text is a number with leading zeros, then do: (Cuando el texto es un número que empieza por ceros, hacer)
$objPHPExcel->getActiveSheet()->setCellValueExplicit('A1', $val,PHPExcel_Cell_DataType::TYPE_STRING);
As it was said you have a unique index.
However, when I added most of the list yesterday I didn't get this error once even though a lot of the entries I added yesterday have a blank cell in column 2 as well. Whats going on?
That means that all these entries contain value NULL
, not empty string ''
. Mysql lets you have multiple NULL
values in unique fields.
This is a guaranteed way to get it done in Vanilla (or simply Pure) JavaScript:
var picurl = 'pictures/apple.png';
document.getElementById("image_id").src=picurl;
Sharing my experience, how to import simple Netbeans java project into Eclipse workspace. Please follow the following steps:
Create .project file, inside the project folder at root level. Below code is the sample reference. Change your project name appropriately.
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>PROJECT_NAME</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
Now open Eclipse and follow the steps,
File > import > Existing Projects into Workspace > Select root directory > Finish
Now we need to correct the build path for proper compilation of src, by following these steps:
Right Click on project folder > Properties > Java Build Path > Click Source tab > Add Folder
(Add the correct src path from project and remove the incorrect ones). Find the image ref link how it looks.
if you use class component then only 3 steps- first you need to declare state for your input filed for example this.state = {name:''}. Secondly, you need to write a function for setting the state when it changes in bellow example it is setName() and finally you have to write the input jsx for example < input value={this.name} onChange = {this.setName}/>
import React, { Component } from 'react'
export class InputComponents extends Component {
constructor(props) {
super(props)
this.state = {
name:'',
agree:false
}
this.setName = this.setName.bind(this);
this.setAgree=this.setAgree.bind(this);
}
setName(e){
e.preventDefault();
console.log(e.target.value);
this.setState({
name:e.target.value
})
}
setAgree(){
this.setState({
agree: !this.state.agree
}, function (){
console.log(this.state.agree);
})
}
render() {
return (
<div>
<input type="checkbox" checked={this.state.agree} onChange={this.setAgree}></input>
< input value={this.state.name} onChange = {this.setName}/>
</div>
)
}
}
export default InputComponents
You may find useful this implementation: http://www.codeproject.com/Articles/126751/Priority-queue-in-Csharp-with-help-of-heap-data-st.aspx
it is generic and based on heap data structure
I faced the same issue where I started a node app in port 3000 and it didn't close correctly and the process kept running even after restart.
None of the taskkill or powershell commands running in Administrator mode worked for me.
I used MS Process Expoler > Properties > Image > Current directory (which was supposed to be the my project directory).
Finally, I had to reboot in SafeMode and rename the project folder and restart. The Node processes which were consuming port 3000 killed itself.
For vector graphics, ImageMagick has both a render resolution and an output size that are independent of each other.
Try something like
convert -density 300 image.eps -resize 1024x1024 image.jpg
Which will render your eps at 300dpi. If 300 * width > 1024, then it will be sharp. If you render it too high though, you waste a lot of memory drawing a really high-res graphic only to down sample it again. I don't currently know of a good way to render it at the "right" resolution in one IM command.
The order of the arguments matters! The -density X
argument needs to go before image.eps
because you want to affect the resolution that the input file is rendered at.
This is not super obvious in the manpage for convert
, but is hinted at:
SYNOPSIS
convert [input-option] input-file [output-option] output-file
Microsoft API Code Pack. ShellObjectWatcher class.
After Python 3.5 you can also use:
import subprocess
f = open('test.txt', 'w')
process = subprocess.run(['ls', '-la'], stdout=subprocess.PIPE, universal_newlines=True)
f.write(process.stdout)
f.close()
The execution of the command is blocking and the output will be in process.stdout.
To get the specific tag code try to create a new branch add get the tag code in it.
I have done it by command : $git checkout -b newBranchName tagName
The best method would be using a javascript -only function:
var myArr = Array.prototype.slice.call(myObj, 0);
# Make sure only root can run our script
if [ "$(id -u)" != "0" ]; then
echo "This script must be run as root" 1>&2
exit 1
fi
A shortcut you can add to your .bashrc etc, based on other answers here:
function perf {
curl -o /dev/null -s -w "%{time_connect} + %{time_starttransfer} = %{time_total}\n" "$1"
}
Usage:
> perf stackoverflow.com
0.521 + 0.686 = 1.290
This is the answer to make this work for Java 11 and above since the entire JAXB APIs were removed.
Download Jakarta XML Binding, specifically this zip file. You need only the 3 files within mod folder i.e. jakarta.activation.jar, jakarta.xml.bind-api.jar and jakarta.xml.bind-api.jar and you can toss the rest off.
Move these files to APP_HOME/lib folder. I created a sub folder jaxb inside for this. So, on my macOS system this was: $HOME/Library/Android/sdk/tools/lib/jaxb
Now open sdkmanager using your favorite text editor and under CLASSPATH= add the following at th beginning:
$APP_HOME/lib/jaxb/jakarta.activation.jar:$APP_HOME/lib/jaxb/jakarta.xml.bind-api.jar:$APP_HOME/lib/jaxb/jaxb-impl.jar
So it ended up looking like:
CLASSPATH=$APP_HOME/lib/jaxb/jakarta.activation.jar:$APP_HOME/lib/jaxb/jakarta.xml.bind-api.jar:$APP_HOME/lib/jaxb/jaxb-impl.jar:$APP_HOME/lib/dvlib-26.0.0-dev.jar:$APP_HOME/lib/jimfs-1.1.jar:$APP_HOME/lib/jsr305-1.3.9.jar:$APP_HOME/lib/repository-26.0.0-dev.jar:$APP_HOME/lib/j2objc-annotations-1.1.jar:$APP_HOME/lib/layoutlib-api-26.0.0-dev.jar:$APP_HOME/lib/gson-2.3.jar:$APP_HOME/lib/httpcore-4.2.5.jar:$APP_HOME/lib/commons-logging-1.1.1.jar:$APP_HOME/lib/commons-compress-1.12.jar:$APP_HOME/lib/annotations-26.0.0-dev.jar:$APP_HOME/lib/error_prone_annotations-2.0.18.jar:$APP_HOME/lib/animal-sniffer-annotations-1.14.jar:$APP_HOME/lib/httpclient-4.2.6.jar:$APP_HOME/lib/commons-codec-1.6.jar:$APP_HOME/lib/common-26.0.0-dev.jar:$APP_HOME/lib/kxml2-2.3.0.jar:$APP_HOME/lib/httpmime-4.1.jar:$APP_HOME/lib/annotations-12.0.jar:$APP_HOME/lib/sdklib-26.0.0-dev.jar:$APP_HOME/lib/guava-22.0.jar
And that's pretty much it, should solve the issue.
I did these steps because flutter doctor --android-licenses
was giving me issues. And this fixed it.
The standard way to pass a list of values as URL parameters is to repeat them:
http://our.api.com/Product?id=101404&id=7267261
Most server code will interpret this as a list of values, although many have single value simplifications so you may have to go looking.
Delimited values are also okay.
If you are needing to send JSON to the server, I don't like seeing it in in the URL (which is a different format). In particular, URLs have a size limitation (in practice if not in theory).
The way I have seen some do a complicated query RESTfully is in two steps:
POST
your query requirements, receiving back an ID (essentially creating a search criteria resource)GET
the search, referencing the above IDYou can use the ??
operator to set the default value but first you must set the Nullable
property to true
in your dbml file in the required field (xx.Online
)
var hht = from x in db.HandheldAssets
join a in db.HandheldDevInfos on x.AssetID equals a.DevName into DevInfo
from aa in DevInfo.DefaultIfEmpty()
select new
{
AssetID = x.AssetID,
Status = xx.Online ?? false
};
Create a new Android Application Project
and uncheck Create activity
in step two (Configure project).
The range
function wil give you a list of numbers, while the for
loop will iterate through the list and execute the given code for each of its items.
for i in range(5):
print i
This simply executes print i
five times, for i ranging from 0 to 4.
for i in range(5):
a=i+1
This will execute a=i+1
five times. Since you are overwriting the value of a
on each iteration, at the end you will only get the value for the last iteration, that is 4+1.
Useful links:
http://www.network-theory.co.uk/docs/pytut/rangeFunction.html
http://www.ibiblio.org/swaroopch/byteofpython/read/for-loop.html
the easiest way i have found is to just use the nodejs.org site:
I closed Visual studio IDE and reopened it by right clicking on the Visual Studio icon and saying "Run as Administrator", Then when I ran the host , It worked!!!
For Each row As DataRow In dtDataTable.Rows
strDetail = row.Item("Detail")
Next row
There's also a shorthand:
For Each row As DataRow In dtDataTable.Rows
strDetail = row("Detail")
Next row
Note that Microsoft's style guidelines for .Net now specifically recommend against using hungarian type prefixes for variables. Instead of "strDetail", for example, you should just use "Detail".
EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245
To see exactly what is happening, use nc -l
or an ECHO server and an user agent like a browser or cURL.
Save the form to an .html
file:
<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
<p><input type="text" name="text" value="text default">
<p><input type="file" name="file1">
<p><input type="file" name="file2">
<p><button type="submit">Submit</button>
</form>
Create files to upload:
echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html
Run:
nc -l localhost 8000
Open the HTML on your browser, select the files and click on submit and check the terminal.
nc
prints the request received. Firefox sent:
POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"
text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain
Content of a.txt.
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html
<!DOCTYPE html><title>Content of a.html.</title>
-----------------------------9051914041544843365972754266--
Aternativelly, cURL should send the same POST request as your a browser form:
nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000
You can do multiple tests with:
while true; do printf '' | nc -l localhost 8000; done
if you want to use gitk:
gitk master..branch-X
it has a nice old school GUi
I had this problem and it went away when I moved from ADO.Net to Dapper for my queries.
Just use the following method, pass it lat and long and get distance in meter:
private static double distance_in_meter(final double lat1, final double lon1, final double lat2, final double lon2) {
double R = 6371000f; // Radius of the earth in m
double dLat = (lat1 - lat2) * Math.PI / 180f;
double dLon = (lon1 - lon2) * Math.PI / 180f;
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(latlong1.latitude * Math.PI / 180f) * Math.cos(latlong2.latitude * Math.PI / 180f) *
Math.sin(dLon/2) * Math.sin(dLon/2);
double c = 2f * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double d = R * c;
return d;
}
Beware that in Mysql, the utf8
character set is only a subset of the real UTF8 character set. In order to save one byte of storage, the Mysql team decided to store only three bytes of a UTF8 characters instead of the full four-bytes. That means that some east asian language and emoji aren't fully supported. To make sure you can store all UTF8 characters, use the utf8mb4
data type, and utf8mb4_bin
or utf8mb4_general_ci
in Mysql.
HTML4/XHTML1 requires
<script type="...">...</script>
HTML5 faces the fact that there is only one scripting language on the web, and allows
<script>...</script>
The latter works in any browser that supports scripting (NN2+).
There are several long standing discussions about how to do this in a consistent, well understood and portable way. No complete resolution but I'll link you to the discussions below.
In any event you many want to try using the --add-host option to docker run to add the ip address of the host into the container's /etc/host file. From there it's trivial to connect to the host on any required port:
Adding entries to a container hosts file
You can add other hosts into a container's /etc/hosts file by using one or more --add-host flags. This example adds a static address for a host named docker:
$ docker run --add-host=docker:10.180.0.1 --rm -it debian $$ ping docker PING docker (10.180.0.1): 48 data bytes 56 bytes from 10.180.0.1: icmp_seq=0 ttl=254 time=7.600 ms 56 bytes from 10.180.0.1: icmp_seq=1 ttl=254 time=30.705 ms ^C--- docker ping statistics --- 2 packets transmitted, 2 packets received, 0% packet loss round-trip min/avg/max/stddev = 7.600/19.152/30.705/11.553 ms
Note: Sometimes you need to connect to the Docker host, which means getting the IP address of the host. You can use the following shell commands to simplify this process:
$ alias hostip="ip route show 0.0.0.0/0 | grep -Eo 'via \S+' | awk '{ print $2 }'" $ docker run --add-host=docker:$(hostip) --rm -it debian
Documentation:
https://docs.docker.com/engine/reference/commandline/run/
Discussions on accessing host from container:
If the image is part of the layout it might be "View.VISIBLE" but that doesn't mean it's within the confines of the visible screen. If that's what you're after; this will work:
Rect scrollBounds = new Rect();
scrollView.getHitRect(scrollBounds);
if (imageView.getLocalVisibleRect(scrollBounds)) {
// imageView is within the visible window
} else {
// imageView is not within the visible window
}
Chrome has disabled it. https://bugs.chromium.org/p/chromium/issues/detail?id=159336 Even the jQuery play() is blocked. They want user to initiate it so bandwidth can be saved.
Borders on tables are always a bit flaky. One possibility would be to add a border-right declaration to each table cell except for the ones in right-most column. If you're using any kind of table-spacing this won't work very well.
Another option would be to use a 1px high background image with the borders inside it, but that'll only work if you can guarantee the width of each cell at all times.
Another possibility is to experiment with colgroup / col. This had fairly horrible support cross-browser the last time i looked at it but could have improved since then: http://www.webmasterworld.com/forum83/6826.htm
A very good, and working, javascript solution is provided here : https://github.com/niutech/showModalDialog
I personnally used it, works like before for other browser and it creates a new dialog for chrome browser.
Here is an example on how to use it :
function handleReturnValue(returnValue) {
if (returnValue !== undefined) {
// do what you want
}
}
var myCallback = function (returnValue) { // callback for chrome usage
handleReturnValue(returnValue);
};
var returnValue = window.showModalDialog('someUrl', 'someDialogTitle', 'someDialogParams', myCallback);
handleReturnValue(returnValue); // for other browsers except Chrome
There are a set of available properties to all Maven projects.
From Introduction to the POM:
project.basedir
: The directory that the current project resides in.
This means this points to where your Maven projects resides on your system. It corresponds to the location of the pom.xml
file. If your POM is located inside /path/to/project/pom.xml
then this property will evaluate to /path/to/project
.
Some properties are also inherited from the Super POM, which is the case for project.build.directory
. It is the value inside the <project><build><directory>
element of the POM. You can get a description of all those values by looking at the Maven model. For project.build.directory
, it is:
The directory where all files generated by the build are placed. The default value is
target
.
This is the directory that will hold every generated file by the build.
You can use GCD to dispatch the scroll into the next iteration of main run loop in viewDidLoad to achieve this behavior. The scroll will be performed before the collection view is showed on screen, so there will be no flashing.
- (void)viewDidLoad {
dispatch_async (dispatch_get_main_queue (), ^{
NSIndexPath *indexPath = YOUR_DESIRED_INDEXPATH;
[self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
});
}
Try using .strip() at the end of your line
line.strip()
worked well for me
If you what to add bootstrap attributes in anchor tag dynamically than this will helps you lot
$(".dropdown a").attr({
class: "dropdown-toggle",
'data-toggle': "dropdown",
role: "button",
'aria-haspopup': "true",
'aria-expanded': "true"
});
First, you want to use
model <- lm(Total ~ Coupon, data=df)
not model <-lm(df$Total ~ df$Coupon, data=df)
.
Second, by saying lm(Total ~ Coupon)
, you are fitting a model that uses Total
as the response variable, with Coupon
as the predictor. That is, your model is of the form Total = a + b*Coupon
, with a
and b
the coefficients to be estimated. Note that the response goes on the left side of the ~
, and the predictor(s) on the right.
Because of this, when you ask R to give you predicted values for the model, you have to provide a set of new predictor values, ie new values of Coupon
, not Total
.
Third, judging by your specification of newdata
, it looks like you're actually after a model to fit Coupon
as a function of Total
, not the other way around. To do this:
model <- lm(Coupon ~ Total, data=df)
new.df <- data.frame(Total=c(79037022, 83100656, 104299800))
predict(model, new.df)
if (string.IsNullOrEmpty(myString))
{
. . .
. . .
}
To undo git checkout
do git checkout -
, similarly to cd
and cd -
in shell.
You may also need the following directive to be set before the first "sub_filter" for backend-servers with data compression:
proxy_set_header Accept-Encoding "";
Otherwise it may not work. For your example it will look like:
location /admin/ {
proxy_pass http://localhost:8080/;
proxy_set_header Accept-Encoding "";
sub_filter "http://your_server/" "http://your_server/admin/";
sub_filter_once off;
}
I have just written this code into gradle.properties and it is ok now
org.gradle.jvmargs=-XX:MaxHeapSize\=2048m -Xmx2048m
$sth = mysqli_query($conn, "SELECT ...");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
The function json_encode
needs PHP >= 5.2 and the php-json package - as mentioned here
NOTE: mysql
is deprecated as of PHP 5.5.0, use mysqli
extension instead http://php.net/manual/en/migration55.deprecated.php.
You can change
Range("B3:B65536").Copy Destination:=Sheets("DB").Range("B" & lastrow)
to
Range("B3:B65536").Copy
Sheets("DB").Range("B" & lastrow).PasteSpecial xlPasteValues
BTW, if you have xls file (excel 2003), you would get an error if your lastrow
would be greater 3.
Try to use this code instead:
Sub Get_Data()
Dim lastrowDB As Long, lastrow As Long
Dim arr1, arr2, i As Integer
With Sheets("DB")
lastrowDB = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
End With
arr1 = Array("B", "C", "D", "E", "F", "AH", "AI", "AJ", "J", "P", "AF")
arr2 = Array("B", "A", "C", "P", "D", "E", "G", "F", "H", "I", "J")
For i = LBound(arr1) To UBound(arr1)
With Sheets("Sheet1")
lastrow = Application.Max(3, .Cells(.Rows.Count, arr1(i)).End(xlUp).Row)
.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
End With
Next
Application.CutCopyMode = False
End Sub
Note, above code determines last non empty row on DB
sheet in column A
(variable lastrowDB
). If you need to find lastrow for each destination column in DB
sheet, use next modification:
For i = LBound(arr1) To UBound(arr1)
With Sheets("DB")
lastrowDB = .Cells(.Rows.Count, arr2(i)).End(xlUp).Row + 1
End With
' NEXT CODE
Next
You could also use next approach instead Copy/PasteSpecial
. Replace
.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
with
Sheets("DB").Range(arr2(i) & lastrowDB).Resize(lastrow - 2).Value = _
.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Value
For those who want to access a file from an already loaded PowerShell session, either use Unblock-File to mark the file as safe (though you already need to have set a relaxed execution policy like Unrestricted
for this to work), or change the execution policy just for the current PowerShell session:
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process
Why use SurfaceView and not the classic View class...
One main reason is that SurfaceView can rapidly render the screen.
In simple words a SV is more capable of managing the timing and render animations.
To have a better understanding what is a SurfaceView we must compare it with the View class.
What is the difference... check this simple explanation in the video
https://m.youtube.com/watch?feature=youtu.be&v=eltlqsHSG30
Well with the View we have one major problem....the timing of rendering animations.
Normally the onDraw() is called from the Android run-time system.
So, when Android run-time system calls onDraw() then the application cant control
the timing of display, and this is important for animation. We have a gap of timing
between the application (our game) and the Android run-time system.
The SV it can call the onDraw() by a dedicated Thread.
Thus: the application controls the timing. So we can display the next bitmap image of the animation.
Another approach would be to extended jquery like this:
$.fn.toggleCheckbox = function() {
this.attr('checked', !this.attr('checked'));
}
Then call:
$('.offer').find(':checkbox').toggleCheckbox();
It really depends on the type of HTML file you're creating.
For such tasks, I use to create an object, serialize it to XML, then transform it with XSL. The pros of this approach are:
The cons are:
<textarea/>
tags (which make the page unusable), XML declaration (which can cause problems with IE), whitespace (with <pre></pre>
tags etc.), HTML entities (
), etc.Now, if your HTML is very short or very repetitive or if the HTML has a volatile structure which changes dynamically, this approach must not be taken in account. On the other hand, if you serve HTML files which have all a similar structure and you want to reduce the amount of Java code and use templates, this approach may work.
create your own style overriding android:Theme
<style name="noAnimationStyle" parent="android:Theme">
<item name="android:windowAnimationStyle">@null</item>
</style>
Then use it in manifest like this:
<activity android:name=".MainActivity"
android:theme="@style/noAnimationStyle">
</activity>
am assuming that you want to know how to format numbers in SSRS
Just right click
the TextBox
on which you want to apply formatting, go to its expression
.
suppose its expression is something like below
=Fields!myField.Value
then do this
=Format(Fields!myField.Value,"##.##")
or
=Format(Fields!myFields.Value,"00.00")
difference between the two is that former one would make 4 as 4 and later one would make 4 as 04.00
this should give you an idea.
also: you might have to convert your field into a numerical one. i.e.
=Format(CDbl(Fields!myFields.Value),"00.00")
so: 0 in format expression means, when no number is present, place a 0 there and # means when no number is present, leave it. Both of them works same when numbers are present ie. 45.6567 would be 45.65 for both of them:
UPDATE :
if you want to apply variable formatting on the same column based on row values i.e.
you want myField
to have no formatting when it has no decimal value but formatting with double precision when it has decimal then you can do it through logic. (though you should not be doing so)
Go to the appropriate textbox and go to its expression and do this:
=IIF((Fields!myField.Value - CInt(Fields!myField.Value)) > 0,
Format(Fields!myField.Value, "##.##"),Fields!myField.Value)
so basically you are using IIF(condition, true,false)
operator of SSRS,
ur condition is to check whether the number has decimal value, if it has, you apply the formatting and if no, you let it as it is.
this should give you an idea, how to handle variable formatting.
You can access the local webserver which is running in your host machine in two ways.
Approach 1 with public IP
Use host machine public IP address to access webserver in Jenkins docker container.
Approach 2 with the host network
Use "--net host" to add the Jenkins docker container on the host's network stack. Containers which are deployed on host's stack have entire access to the host interface. You can access local webserver in docker container with a private IP address of the host machine.
NETWORK ID NAME DRIVER SCOPE
b3554ea51ca3 bridge bridge local
2f0d6d6fdd88 host host local
b9c2a4bc23b2 none null local
Start a container with the host network
Eg: docker run --net host -it ubuntu
and run ifconfig
to list all available network IP addresses which are reachable from docker container.
Eg: I started a nginx server in my local host machine and I am able to access the nginx website URLs from Ubuntu docker container.
docker run --net host -it ubuntu
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a604f7af5e36 ubuntu "/bin/bash" 22 seconds ago Up 20 seconds ubuntu_server
Accessing the Nginx web server (running in local host machine) from Ubuntu docker container with private network IP address.
root@linuxkit-025000000001:/# curl 192.168.x.x -I
HTTP/1.1 200 OK
Server: nginx/1.15.10
Date: Tue, 09 Apr 2019 05:12:12 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 26 Mar 2019 14:04:38 GMT
Connection: keep-alive
ETag: "5c9a3176-264"
Accept-Ranges: bytes
Nope.
But lo! If you use std::vector<Car>
, like you should be (never ever use new[]
), then you can specify exactly how elements should be constructed*.
*Well sort of. You can specify the value of which to make copies of.
Like this:
#include <iostream>
#include <vector>
class Car
{
private:
Car(); // if you don't use it, you can just declare it to make it private
int _no;
public:
Car(int no) :
_no(no)
{
// use an initialization list to initialize members,
// not the constructor body to assign them
}
void printNo()
{
// use whitespace, itmakesthingseasiertoread
std::cout << _no << std::endl;
}
};
int main()
{
int userInput = 10;
// first method: userInput copies of Car(5)
std::vector<Car> mycars(userInput, Car(5));
// second method:
std::vector<Car> mycars; // empty
mycars.reserve(userInput); // optional: reserve the memory upfront
for (int i = 0; i < userInput; ++i)
mycars.push_back(Car(i)); // ith element is a copy of this
// return 0 is implicit on main's with no return statement,
// useful for snippets and short code samples
}
With the additional function:
void printCarNumbers(Car *cars, int length)
{
for(int i = 0; i < length; i++) // whitespace! :)
std::cout << cars[i].printNo();
}
int main()
{
// ...
printCarNumbers(&mycars[0], mycars.size());
}
Note printCarNumbers
really should be designed differently, to accept two iterators denoting a range.
My problem was that I wrote down files to ignore with quotes " " separation not with slash /.
This did not work and was ignored by git :
"db.sqlite3"
"tdd_venv/"
This worked just fine :
/db.sqlite3
/tdd_venv/
I also checked my file encoding in windows with Notepad++. Encoding was set to UTF-8.
use SimpleDateFormat
to first parse()
String
to Date
and then format()
Date
to String
Try Html.fromHtml()
, and mark up your text with bold and italic HTML tags e.g:
Spanned text = Html.fromHtml("This mixes <b>bold</b> and <i>italic</i> stuff");
textView.setText(text);
Another option if you don't have Python 2.6:
import commands
n = commands.getoutput("grep -c processor /proc/cpuinfo")
In a nutshell :
-> Git Merge: It will simply merge your local changes and remote changes, and that will create another commit history record
-> Git Rebase: It will put your changes above all new remote changes, and rewrite commit history, so your commit history will be much cleaner than git merge. Rebase is a destructive operation. That means, if you do not apply it correctly, you could lose committed work and/or break the consistency of other developer's repositories.
git rebase -i HEAD^^
where the number of ^'s is X
(in this case, squash the two last commits)
For Ruby programmers here is how you can assert. Have to include Minitest to get the asserts
assert(@driver.find_element(:tag_name => "body").text.include?("Name"))
here's how:
import pygame
screen=pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])
red=255
blue=0
green=0
left=50
top=50
width=90
height=90
filled=0
pygame.draw.rect(screen, [red, blue, green], [left, top, width, height], filled)
pygame.display.flip()
running=True
while running:
for event in pygame.event.get():
if event.type==pygame.QUIT:
running=False
pygame.quit()
I was writing my code in PHP, and I had a bit of trouble using concat and union functions, and also did not use SQL variables, any ways I got it to work, here is my code:
//first I connected to the information_scheme DB
$headercon=mysqli_connect("localhost", "USERNAME", "PASSWORD", "information_schema");
//took the healders out in a string (I could not get the concat function to work, so I wrote a loop for it)
$headers = '';
$sql = "SELECT column_name AS columns FROM `COLUMNS` WHERE table_schema = 'YOUR_DB_NAME' AND table_name = 'YOUR_TABLE_NAME'";
$result = $headercon->query($sql);
while($row = $result->fetch_row())
{
$headers = $headers . "'" . $row[0] . "', ";
}
$headers = substr("$headers", 0, -2);
// connect to the DB of interest
$con=mysqli_connect("localhost", "USERNAME", "PASSWORD", "YOUR_DB_NAME");
// export the results to csv
$sql4 = "SELECT $headers UNION SELECT * FROM YOUR_TABLE_NAME WHERE ... INTO OUTFILE '/output.csv' FIELDS TERMINATED BY ','";
$result4 = $con->query($sql4);
Find last time of update on a table
SELECT
tbl.name
,ius.last_user_update
,ius.user_updates
,ius.last_user_seek
,ius.last_user_scan
,ius.last_user_lookup
,ius.user_seeks
,ius.user_scans
,ius.user_lookups
FROM
sys.dm_db_index_usage_stats ius INNER JOIN
sys.tables tbl ON (tbl.OBJECT_ID = ius.OBJECT_ID)
WHERE ius.database_id = DB_ID()
http://www.sqlserver-dba.com/2012/10/sql-server-find-last-time-of-update-on-a-table.html
I do not recommend keeping bad data in the database and then only correcting it on the output. We have a database where phone numbers are entered in variously as :
Different people in an organization may write various retrieval functions and updates to the database, and therefore it would be harder to set in place formatting and retrieval rules. I am therefore correcting the data in the database first and foremost and then setting in place rules and form validations that protect the integrity of this database going forward.
I see no justification for keeping bad data unless as suggested a duplicate column be added with corrected formatting and the original data kept around for redundancy and reference, and YES I consider badly formatted data as BAD data.
The proper way to do this is like this:
LIBS += -L/path/to -lpsapi
This way it will work on all platforms supported by Qt. The idea is that you have to separate the directory from the library name (without the extension and without any 'lib' prefix). Of course, if you are including a Windows specific lib, this really doesn't matter.
In case you want to store your lib files in the project directory, you can reference them with the $$_PRO_FILE_PWD_
variable, e.g.:
LIBS += -L"$$_PRO_FILE_PWD_/3rdparty/libs/" -lpsapi
To do TDD many times I've used 'friend' keyword in C++.
Can a friend know everything about me?
No, its only a one way friendship :`(
There are a bunch of good solutions here but I'd suggest going the other route with this. If searching is the most important thing and the 'secret' property is not used on the view at all; my approach for this would be to use the built-in angular filter with all its benefits and simply map the model to a new array of objects.
Example from the question:
$scope.people = members.map(function(member) {
return {
name: member.name,
phone: member.phone
}});
Now, in html simply use the regular filter to search both these properties.
<div ng-repeat="member in people | filter: searchString">
"Helvetica Neue Condensed Bold" get working with firefox:
.class {
font-family: "Helvetica Neue";
font-weight: bold;
font-stretch: condensed;
}
But it's fail with Opera.
Using a single sed
echo "/var/cpanel/users/joebloggs:DNS9=domain.com" | sed 's/.*\/\(.*\):.*/\1/'
There are codes for other space characters, and the codes as such work well, but the characters themselves are legacy character. They have been included into character sets only due to their presence in existing character data, rather than for use in new documents. For some combinations of font and browser version, they may cause a generic glyph of unrepresentable character to be shown. For details, check my page about Unicode spaces.
So using CSS is safer and lets you specify any desired amount of spacing, not just the specific widths of fixed-width spaces. If you just want to have added spacing around your h2 elements, as it seems to me, then setting padding on those elements (changing the value of the padding: 0 settings that you already have) should work fine.
In case you are using Buildout, you can easily automate the installation processes that Pykler describes using the gp.recipe.node recipe.
[nodejs]
recipe = gp.recipe.node
version = 0.10.32
npms = phantomjs
scripts = phantomjs
That part installs node.js as binary (at least on my system) and then uses npm to install PhantomJS. Finally it creates an entry point bin/phantomjs
, which you can call the PhantomJS webdriver with. (To install Selenium, you need to specify it in your egg requirements or in the Buildout configuration.)
driver = webdriver.PhantomJS('bin/phantomjs')
You can adjust the plot margins with plot.margin
in theme()
and then move your axis labels and title with the vjust
argument of element_text()
. For example :
library(ggplot2)
library(grid)
qplot(rnorm(100)) +
ggtitle("Title") +
theme(axis.title.x=element_text(vjust=-2)) +
theme(axis.title.y=element_text(angle=90, vjust=-0.5)) +
theme(plot.title=element_text(size=15, vjust=3)) +
theme(plot.margin = unit(c(1,1,1,1), "cm"))
will give you something like this :
If you want more informations about the different theme()
parameters and their arguments, you can just enter ?theme
at the R prompt.
To zoom on Eclipse you can use : CTRL SHIFT + OR -
As an alternative to Directory.Exists(), you can use the File.GetAttributes() method to get the attributes of a file or a directory, so you could create a helper method like this:
private static bool IsDirectory(string path)
{
System.IO.FileAttributes fa = System.IO.File.GetAttributes(path);
return (fa & FileAttributes.Directory) != 0;
}
You could also consider adding an object to the tag property of the TreeView control when populating the control that contains additional metadata for the item. For instance, you could add a FileInfo object for files and a DirectoryInfo object for directories and then test for the item type in the tag property to save making additional system calls to get that data when clicking on the item.
Killing the process specified in the Dockerfile's CMD
/ ENTRYPOINT
works for me. (The container restarts automatically)
Rebooting was not allowed in my container, so I had to use this workaround.
It's simple if you already have Homebrew: Assuming you have homebrew installed, type the following:
brew install git
This should automatically install git and set it in your path, replacing the Apple one. Quit and restart terminal. Check git version to confirm.
git --version
If the output of the above command shows the latest version and does not mention Apple with the version details, then you are all set.
If however you still see apple version, then type the following two lines, which will manually set our path to the local git distro instead of the Apple one.
export PATH=/usr/local/bin:$PATH
git --version
IF YOU DON'T HAVE HOMEBREW, FOLLOW THESE STEPS
Check version
$ git --version
Backup (or remove) Apple git (Optional)
$ sudo mv /usr/bin/git /usr/bin/git-apple
Install Homebrew if you didn’t have
$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Or update if you already have
$ brew update && brew upgrade
Install Git with Homebrew
$ brew install git
Symbolic link
$ brew link --force git
Quit terminal and open a new terminal, then check version.
$ git --version
You should see…
git version <latest version>
Nice! We’re safe now! And next time you can just…
$ brew update && brew upgrade
If you have apache running, put your file in server folder for html files and then call it from web-browser (Like http://localhost/myfile.php ).
There are two contradicting recommendations by microsoft and many people use DbContexts in a completely divergent manner.
Those contradict to each other because if your Request is doing a lot of unrelated to the Db stuff , then your DbContext is kept for no reason. Thus it is waste to keep your DbContext alive while your request is just waiting for random stuff to get done...
So many people who follow rule 1 have their DbContexts inside their "Repository pattern" and create a new Instance per Database Query so X*DbContext per Request
They just get their data and dispose the context ASAP. This is considered by MANY people an acceptable practice. While this has the benefits of occupying your db resources for the minimum time it clearly sacrifices all the UnitOfWork and Caching candy EF has to offer.
Keeping alive a single multipurpose instance of DbContext maximizes the benefits of Caching but since DbContext is not thread safe and each Web request runs on it's own thread, a DbContext per Request is the longest you can keep it.
So EF's team recommendation about using 1 Db Context per request it's clearly based on the fact that in a Web Application a UnitOfWork most likely is going to be within one request and that request has one thread. So one DbContext per request is like the ideal benefit of UnitOfWork and Caching.
But in many cases this is not true. I consider Logging a separate UnitOfWork thus having a new DbContext for Post-Request Logging in async threads is completely acceptable
So Finally it turns down that a DbContext's lifetime is restricted to these two parameters. UnitOfWork and Thread
Class Assertions in org.junit.jupiter.api
Use:
public static void assertArrayEquals(int[] expected,
int[] actual)
You can see that JSONObject extends a HashMap
, so you can simply use it as a HashMap:
JSONObject jsonChildObject = (JSONObject)jsonObject.get("LanguageLevels");
for (Map.Entry in jsonChildOBject.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
There are some cases where you can use the e.message or e.messages.. But it does not work in all cases. Anyway the more safe is to use the str(e)
try:
...
except Exception as e:
print(e.message)
No it doesn't. I would expect this in a future api release, but for now we are stuck with EditText. Another option is this library:
https://github.com/marvinlabs/android-floatinglabel-widgets
Below I sum up Prateek Joshi's awesome explanation.
The theory:
That is:
And for an example:
Also, if you haven't already, I suggest reading Roger Pate's answer.
I prefer this way
Using ajaxStop
+ setInterval
,, this will refresh the page after any XHR[ajax] request in the same page
$(document).ajaxStop(function() {
setInterval(function() {
location.reload();
}, 3000);
});
The identity (===)
operator behaves identically to the equality (==)
operator except no type conversion is done, and the types must be the same to be considered equal.
I have this page bookmarked and refer back to it frequently, but no one mentions the size for newer 11 inch iPad pro. It's 1668x2388.
Here's a bash script that will resize generic screenshots to the appropriate dimensions. I could not get an iPhone 4 simulator running in the latest xcode as of 2020, so this was necessary for me.
#!/usr/bin/env bash
HERE="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
declare -A sizes
sizes["6-5-inch-iphone-xs-max"]="1242x2688"
sizes["5-8-inch-iphone-x"]="1125x2436"
sizes["5-5-inch-iphone-6"]="1242x2208"
sizes["4-7-inch-iphone-6"]="750x1334"
sizes["4-inch-iphone-6"]="640x1096"
sizes["3-5-inch-iphone-4s"]="640x920"
sizes["12-9-inch-ipad-pro-@3"]="2048x2732"
sizes["12-9-inch-ipad-pro-@2"]="2048x2732"
sizes["11-inch-ipad-pro"]="1668x2388"
sizes["10-5-inch-ipad-pro"]="1668x2224"
sizes["9-7-inch-ipad"]="1536x2008"
for i in "${!sizes[@]}"; do
if [[ "$i" == *"ipad"* ]]; then
[ -d "$HERE/ipad" ] || continue
mkdir -p "$HERE/$i"
cd "$HERE/ipad"
for file in *.jpg; do
[ -e "$file" ] || continue
convert "$file" -resize "${sizes[$i]}"\! "$HERE/$i/$file"
echo "scaled $file"
done
else
[ -d "$HERE/iphone" ] || continue
mkdir -p "$HERE/$i"
cd "$HERE/iphone"
for file in *.jpg; do
[ -e "$file" ] || continue
convert "$file" -resize "${sizes[$i]}"\! "$HERE/$i/$file"
echo "scaled $file"
done
fi
done
To use it, put it in a new directory, and create a /iphone
and an /ipad
directory next to it. Put your generic ipad and iphone screenshots in those folders. Run the script, it will generate named folders for all sizes.
ios_screenshots/
+-- run.sh
+-- iphone/
¦ +-- screenshot_1.jpg
¦ +-- screenshot_2.jpg
¦ +-- screenshot_3.jpg
+-- ipad/
¦ +-- screenshot_1.jpg
¦ +-- screenshot_2.jpg
¦ +-- screenshot_3.jpg
Is this possible in angular 2?
Yes, it is possible.
If both of the conditions are true, will they enable the button?
No, if they are true, then the button will be disabled. disabled="true"
.
I try the above code but it's not working well
What did you expect? the button will be disabled when valid
is false and the angular formGroup
, SAForm
is not valid.
A recommendation here as well, Please make the button of type button not a submit because this may cause the whole form to submit and you would need to use invalidate
and listen to (ngSubmit)
.
None of the existing answers helped me as I had the same app installed in my other profile. Solution -
Simple answer with bash:
if [[ $(ls /some/dir/) ]]; then echo "huzzah"; fi;
Or if you need inline then you can do this:
<a href="#" ng-click="show = !show; $event.preventDefault()">Click to show</a>
I just did the same. If you look in the "Android SDK Manager" in the "Android 4.0 (API 14)" section you'll see a few packages. One of these is named "ARM EABI v7a System Image".
This is what you need to download in order to create an Android 4.0 virtual device:
sudo nano /etc/nginx/nginx.conf
Add these variables to nginx.conf file:
http {
# .....
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;
send_timeout 600;
}
And then restart:
service nginx reload
With try-with-resources writer will be automatically closed:
import org.apache.commons.lang3.StringUtils;
final File file = new File("SomeFile");
try (PrintWriter writer = new PrintWriter(file)) {
writer.print(StringUtils.EMPTY);
}
// here we can be sure that writer will be closed automatically
FileReader API with jQuery, simple example.
( function ( $ ) {_x000D_
// Add click event handler to button_x000D_
$( '#load-file' ).click( function () {_x000D_
if ( ! window.FileReader ) {_x000D_
return alert( 'FileReader API is not supported by your browser.' );_x000D_
}_x000D_
var $i = $( '#file' ), // Put file input ID here_x000D_
input = $i[0]; // Getting the element from jQuery_x000D_
if ( input.files && input.files[0] ) {_x000D_
file = input.files[0]; // The file_x000D_
fr = new FileReader(); // FileReader instance_x000D_
fr.onload = function () {_x000D_
// Do stuff on onload, use fr.result for contents of file_x000D_
$( '#file-content' ).append( $( '<div/>' ).html( fr.result ) )_x000D_
};_x000D_
//fr.readAsText( file );_x000D_
fr.readAsDataURL( file );_x000D_
} else {_x000D_
// Handle errors here_x000D_
alert( "File not selected or browser incompatible." )_x000D_
}_x000D_
} );_x000D_
} )( jQuery );
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="file" id="file" />_x000D_
<input type='button' id='load-file' value='Load'>_x000D_
<div id="file-content"></div>
_x000D_
To read as text... uncomment //fr.readAsText(file);
line and comment fr.readAsDataURL(file);
max_allowed_packet
is set in mysql config, not on php side
[mysqld]
max_allowed_packet=16M
You can see it's curent value in mysql like this:
SHOW VARIABLES LIKE 'max_allowed_packet';
You can try to change it like this, but it's unlikely this will work on shared hosting:
SET GLOBAL max_allowed_packet=16777216;
You can read about it here http://dev.mysql.com/doc/refman/5.1/en/packet-too-large.html
EDIT
The [mysqld] is necessary to make the max_allowed_packet
working since at least mysql version 5.5.
Recently setup an instance on AWS EC2 with Drupal and Solr Search Engine, which required 32M max_allowed_packet
. It you set the value under [mysqld_safe]
(which is default settings came with the mysql installation) mode in /etc/my.cnf, it did no work. I did not dig into the problem. But after I change it to [mysqld]
and restarted the mysqld, it worked.
JSON itself has no date format, it does not care how anyone stores dates. However, since this question is tagged with javascript, I assume you want to know how to store javascript dates in JSON. You can just pass in a date to the JSON.stringify
method, and it will use Date.prototype.toJSON
by default, which in turns uses Date.prototype.toISOString
(MDN on Date.toJSON):
const json = JSON.stringify(new Date());
const parsed = JSON.parse(json); //2015-10-26T07:46:36.611Z
const date = new Date(parsed); // Back to date object
I also found it useful to use the reviver
parameter of JSON.parse
(MDN on JSON.parse) to automatically convert ISO strings back to javascript dates whenever I read JSON strings.
const isoDatePattern = new RegExp(/\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/);
const obj = {
a: 'foo',
b: new Date(1500000000000) // Fri Jul 14 2017, etc...
}
const json = JSON.stringify(obj);
// Convert back, use reviver function:
const parsed = JSON.parse(json, (key, value) => {
if (typeof value === 'string' && value.match(isoDatePattern)){
return new Date(value); // isostring, so cast to js date
}
return value; // leave any other value as-is
});
console.log(parsed.b); // // Fri Jul 14 2017, etc...
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>_x000D_
<script>_x000D_
angular.module('app', []).controller('appc', ['$scope',_x000D_
function($scope) {_x000D_
$scope.selected = 'male';_x000D_
}_x000D_
]);_x000D_
</script>_x000D_
</head>_x000D_
_x000D_
<body ng-app="app" ng-controller="appc">_x000D_
<label>SELECTED: {{selected}}</label>_x000D_
<div>_x000D_
<input type="checkbox" ng-checked="selected=='male'" ng-true-value="'male'" ng-model="selected">Male_x000D_
<br>_x000D_
<input type="checkbox" ng-checked="selected=='female'" ng-true-value="'female'" ng-model="selected">Female_x000D_
<br>_x000D_
<input type="checkbox" ng-checked="selected=='other'" ng-true-value="'other'" ng-model="selected">Other_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
I came across the same issue while trying to create a cardview programmatically, what is strange is that looking at the doc https://developer.android.com/reference/android/support/v7/widget/CardView.html#setCardBackgroundColor%28int%29, Google guys made public the api to change the background color of a card view but weirdly i didn't succeed to have access to it in the support library, so here is what worked for me:
CardViewBuilder.java
mBaseLayout = new FrameLayout(context);
// FrameLayout Params
FrameLayout.LayoutParams baseLayoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
mBaseLayout.setLayoutParams(baseLayoutParams);
// Create the card view.
mCardview = new CardView(context);
mCardview.setCardElevation(4f);
mCardview.setRadius(8f);
mCardview.setPreventCornerOverlap(true); // The default value for that attribute is by default TRUE, but i reset it to true to make it clear for you guys
CardView.LayoutParams cardLayoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
cardLayoutParams.setMargins(12, 0, 12, 0);
mCardview.setLayoutParams(cardLayoutParams);
// Add the card view to the BaseLayout
mBaseLayout.addView(mCardview);
// Create a child view for the cardView that match it's parent size both vertically and horizontally
// Here i create a horizontal linearlayout, you can instantiate the view of your choice
mFilterContainer = new LinearLayout(context);
mFilterContainer.setOrientation(LinearLayout.HORIZONTAL);
mFilterContainer.setPadding(8, 8, 8, 8);
mFilterContainer.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT, Gravity.CENTER));
// And here is the magic to get everything working
// I create a background drawable for this view that have the required background color
// and match the rounded radius of the cardview to have it fit in.
mFilterContainer.setBackgroundResource(R.drawable.filter_container_background);
// Add the horizontal linearlayout to the cardview.
mCardview.addView(mFilterContainer);
filter_container_background.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:radius="8dp"/>
<solid android:color="@android:color/white"/>
Doing that i succeed in keeping the cardview shadow and rounded corners.
if your using php for the backend maybe you can use this code.
// Validate image file size
if (($_FILES["file-input"]["size"] > 2000000)) {
$msg = "Image File Size is Greater than 2MB.";
header("Location: ../product.php?error=$msg");
exit();
}
HTML Code:
<div id="welcomeDiv" style="display:none;" class="answer_list" > WELCOME</div>
<input type="button" name="answer" value="Show Div" onclick="showDiv()" />
Javascript:
function showDiv() {
document.getElementById('welcomeDiv').style.display = "block";
}
See the Demo: http://jsfiddle.net/rathoreahsan/vzmnJ/
=CountIf(ArrayFormula(range<>""),TRUE)
The answer by eniacAvenger will yield the correct solution without worrying about edge cases as =A1<>""
seems to arrive at the correct truthy/falsy value based on how we intuitively think of blank cells, either virgin blanks or created blanks.
So imagine we have this data and we want the Count of non-blanks in B2:B6
:
| | A | B | C |
|---|-------------|-------|---------|
| 1 | Description | Value | B1<>"" |
| 2 | Text | H | TRUE |
| 3 | Number | 1 | TRUE |
| 4 | IF -> "" | | FALSE |
| 5 | IF -> Text | h | TRUE |
| 6 | Blank | | FALSE |
If we relied on Column C, we could get the count of values in B like this:
=COUNTIF(C2:C6,True)
FormulaArray
to dynamically create Extra ColumnHowever, consideRatio's comment is a valid one - if you need an extra column, you can often accomplish the same goal with an ArrayFormula
which can create a column in memory without eating up sheet space.
So if we want to create C dynamically, we can use an array formula like this:
=ArrayFormula(B2:B6<>"")
If we simply put it in C2, it would create the vertical array with a single stroke of the pen:
| | A | B | C |
|---|-------------|-------|--------------------------|
| 1 | Description | Value | =ArrayFormula(B2:B6<>"") |
| 2 | Text | H | TRUE |
| 3 | Number | 1 | TRUE |
| 4 | IF -> "" | | FALSE |
| 5 | IF -> Text | h | TRUE |
| 6 | Blank | | FALSE |
But with that solved, we no longer need the column to merely display the values.
ArrayFormula
will resolve to the following range: {True,True,False,True,False}
.
CountIf
just takes in any range and in this case can count the number of True values.
So we can wrap CountIf
around the values produced by ArrayFormula
like this:
=CountIf(ArrayFormula(B2:B6<>""),TRUE)
The other solutions in this thread are either overly complex, or fail in particular edge cases that I've enumerated in this test sheet:
For why CountA
works the wonky way it does, see my answer here
$scope has a different 'this' then the controller 'this'.Thus if you put a console.log(this) inside controller it gives you a object(controller) and this.addPane() adds addPane Method to the controller Object. But the $scope has different scope and all method in its scope need to be accesed by $scope.methodName().
this.methodName()
inside controller means to add methos inside controller object.$scope.functionName()
is in HTML and inside
$scope.functionName(){
this.name="Name";
//or
$scope.myname="myname"//are same}
Paste this code in your editor and open console to see...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>this $sope vs controller</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
<script>
var app=angular.module("myApp",[]);
app.controller("ctrlExample",function($scope){
console.log("ctrl 'this'",this);
//this(object) of controller different then $scope
$scope.firstName="Andy";
$scope.lastName="Bot";
this.nickName="ABot";
this.controllerMethod=function(){
console.log("controllerMethod ",this);
}
$scope.show=function(){
console.log("$scope 'this",this);
//this of $scope
$scope.message="Welcome User";
}
});
</script>
</head>
<body ng-app="myApp" >
<div ng-controller="ctrlExample">
Comming From $SCOPE :{{firstName}}
<br><br>
Comming from $SCOPE:{{lastName}}
<br><br>
Should Come From Controller:{{nickName}}
<p>
Blank nickName is because nickName is attached to
'this' of controller.
</p>
<br><br>
<button ng-click="controllerMethod()">Controller Method</button>
<br><br>
<button ng-click="show()">Show</button>
<p>{{message}}</p>
</div>
</body>
</html>
If you only care about pushing one block of text to file, this will overwrite it each time.
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
FileOutputStream stream = null;
PrintStream out = null;
try {
File file = chooser.getSelectedFile();
stream = new FileOutputStream(file);
String text = "Your String goes here";
out = new PrintStream(stream);
out.print(text); //This will overwrite existing contents
} catch (Exception ex) {
//do something
} finally {
try {
if(stream!=null) stream.close();
if(out!=null) out.close();
} catch (Exception ex) {
//do something
}
}
}
This example allows the user to select a file using a file chooser.
Hibernate is a JPA implementation, while Spring Data JPA is a JPA data access abstraction. Spring Data JPA cannot work without a JPA provider.
Spring Data offers a solution to the DDD Repository
pattern or the legacy GenericDao
custom implementations. It can also generate JPA queries on your behalf through method name conventions.
With Spring Data, you may use Hibernate, EclipseLink, or any other JPA provider. A very interesting benefit of using Spring or Java EE is that you can control transaction boundaries declaratively using the @Transactional
annotation.
Spring JDBC is much more lightweight, and it's intended for native querying, and if you only intend to use JDBC alone, then you are better off using Spring JDBC to deal with the JDBC verbosity.
Therefore, Hibernate and Spring Data are complementary rather than competitors.
set OPENSSL_CONF=c:/{path to openSSL}/bin/openssl.cfg
take care of the right extension (openssl.cfg not cnf)!
I have installed OpenSSL from here: http://slproweb.com/products/Win32OpenSSL.html
I'm a little surprised that this question has been asked so many times before, but the most reuseable and friendly solution hasn't been documented.
I often have webpages using AngularJS, and when I click on a Save button, I'll "POST" this data back to my .aspx page or .ashx handler to save this back to the database. The data will be in the form of a JSON record.
On the server, to turn the raw posted data back into a C# class, here's what I would do.
First, define a C# class which will contain the posted data.
Supposing my webpage is posting JSON data like this:
{
"UserID" : 1,
"FirstName" : "Mike",
"LastName" : "Mike",
"Address1" : "10 Really Street",
"Address2" : "London"
}
Then I'd define a C# class like this...
public class JSONRequest
{
public int UserID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
}
(These classes can be nested, but the structure must match the format of the JSON data. So, if you're posting a JSON User record, with a list of Order records within it, your C# class should also contain a List<>
of Order records.)
Now, in my .aspx.cs or .ashx file, I just need to do this, and leave JSON.Net to do the hard work...
protected void Page_Load(object sender, EventArgs e)
{
string jsonString = "";
HttpContext.Current.Request.InputStream.Position = 0;
using (StreamReader inputStream = new StreamReader(this.Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
}
JSONRequest oneQuestion = JsonConvert.DeserializeObject<JSONRequest>(jsonString);
And that's it. You now have a JSONRequest
class containing the various fields which were POSTed to your server.
You have two approaches. Selenium has been specifically written to NOT allow interaction with hidden elements. The rational is that if a person cannot perform that action, then neither should Selenium. Therefore, to perform the click via Selenium, you must perform the action a user would do to make that button visible (e.g mouse over event, click another element, etc) then perform the click once visible.
However, Selenium does allow you to execute Javascript within the context of an element, so you could write Javascript to perform the click event even if it is hidden.
My preference is to always try and perform the actions to make the button visible
There is a python package exactly for this purpose. see cstruct2py
cstruct2py
is a pure python library for generate python classes from C code and use them to pack and unpack data. The library can parse C headres (structs, unions, enums, and arrays declarations) and emulate them in python. The generated pythonic classes can parse and pack the data.
For example:
typedef struct {
int x;
int y;
} Point;
after generating pythonic class...
p = Point(x=0x1234, y=0x5678)
p.packed == "\x34\x12\x00\x00\x78\x56\x00\x00"
How to use
First we need to generate the pythonic structs:
import cstruct2py
parser = cstruct2py.c2py.Parser()
parser.parse_file('examples/example.h')
Now we can import all names from the C code:
parser.update_globals(globals())
We can also do that directly:
A = parser.parse_string('struct A { int x; int y;};')
Using types and defines from the C code
a = A()
a.x = 45
print a
buf = a.packed
b = A(buf)
print b
c = A('aaaa11112222', 2)
print c
print repr(c)
The output will be:
{'x':0x2d, 'y':0x0}
{'x':0x2d, 'y':0x0}
{'x':0x31316161, 'y':0x32323131}
A('aa111122', x=0x31316161, y=0x32323131)
Clone
For clone cstruct2py
run:
git clone https://github.com/st0ky/cstruct2py.git --recursive
As you have said if you want to add 24 hours to the timestamp for right now then simply you can do:
<?php echo strtotime('+1 day'); ?>
Above code will add 1 day or 24 hours to your current timestamp.
in place of +1 day
you can take whatever you want, As php manual says strtotime can Parse about any English textual datetime description into a Unix timestamp.
examples from the manual are as below:
<?php
echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n";
echo strtotime("+1 week"), "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n";
echo strtotime("last Monday"), "\n";
?>
There is a quick method to set the syntax:
Ctrl
+Shift
+P
,then type in the input box
ss + (which type you want set)
eg: ss html +Enter
and ss means "set syntax"
it is really quicker than check in the menu's checkbox.
Recently I came across a very elegant solution that take in random JSON that you have no idea the structure:
[HttpPost]
public JsonResult Test([FromBody] JsonElement json)
{
return Json(json);
}
Just that easy.
IntelliJ IDEA 14 & 15 & 2017:
View > Tool Windows > Terminal
or
Alt + F12
you can do like this.....the below example shows text box(user control) value changed
// Declare a delegate
public delegate void ValueChangedEventHandler(object sender, ValueChangedEventArgs e);
public partial class SampleUserControl : TextBox
{
public SampleUserControl()
{
InitializeComponent();
}
// Declare an event
public event ValueChangedEventHandler ValueChanged;
protected virtual void OnValueChanged(ValueChangedEventArgs e)
{
if (ValueChanged != null)
ValueChanged(this,e);
}
private void SampleUserControl_TextChanged(object sender, EventArgs e)
{
TextBox tb = (TextBox)sender;
int value;
if (!int.TryParse(tb.Text, out value))
value = 0;
// Raise the event
OnValueChanged( new ValueChangedEventArgs(value));
}
}
At least some versions of SQL (Oracle, Informix, DB2, ISO Standard) support:
WHERE MOD(value, 2) = 1
MySQL supports '%' as the modulus operator:
WHERE value % 2 = 1
I guess you cant, this maybe a limitation or not included in the IE browser. I have tried your jsfiddle with IE6-8 and all of it doesn't show the scrollbar and not sure with IE9. While in FF and chrome the scrollbar is shown. I also want to see how to do it in IE if possible.
If you really want to show the scrollbar, you can add a fake scrollbar. If you are familiar with some of the js library which use in RIA. Like in jquery/dojo some of the select is editable, because it is a combination of textbox + select or it can also be a textbox + div.
As an example, see it here a JavaScript that make select like editable.
I just want to make a specific point about the for in loop in Ruby. It might seem like a construct similar to other languages, but in fact it is an expression like every other looping construct in Ruby. In fact, the for in works with Enumerable objects just as the each iterator.
The collection passed to for in can be any object that has an each iterator method. Arrays and hashes define the each method, and many other Ruby objects do, too. The for/in loop calls the each method of the specified object. As that iterator yields values, the for loop assigns each value (or each set of values) to the specified variable (or variables) and then executes the code in body.
This is a silly example, but illustrates the point that the for in loop works with ANY object that has an each method, just like how the each iterator does:
class Apple
TYPES = %w(red green yellow)
def each
yield TYPES.pop until TYPES.empty?
end
end
a = Apple.new
for i in a do
puts i
end
yellow
green
red
=> nil
And now the each iterator:
a = Apple.new
a.each do |i|
puts i
end
yellow
green
red
=> nil
As you can see, both are responding to the each method which yields values back to the block. As everyone here stated, it is definitely preferable to use the each iterator over the for in loop. I just wanted to drive home the point that there is nothing magical about the for in loop. It is an expression that invokes the each method of a collection and then passes it to its block of code. Hence, it is a very rare case you would need to use for in. Use the each iterator almost always (with the added benefit of block scope).
cPickle
comes with the standard library… in python 2.x. You are on python 3.x, so if you want cPickle
, you can do this:
>>> import _pickle as cPickle
However, in 3.x, it's easier just to use pickle
.
No need to install anything. If something requires cPickle
in python 3.x, then that's probably a bug.
Answer to your first question is As every object in java has only one lock(monitor)
andwait(),notify(),notifyAll()
are used for monitor sharing thats why they are part of Object
class rather than Thread
class.
Suppose df is a pandas DataFrame then to get number of non-null values and data types of all column at once use:
df.info()
curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'
FROM
First of all ^
is a Bitwise XOR operator not power operator.
You can use other things to find power of any number. You can use for loop to find power of any number
Here is a program to find x^y i.e. xy
double i, x, y, pow;
x = 2;
y = 5;
pow = 1;
for(i=1; i<=y; i++)
{
pow = pow * x;
}
printf("2^5 = %lf", pow);
You can also simply use pow() function to find power of any number
double power, x, y;
x = 2;
y = 5;
power = pow(x, y); /* include math.h header file */
printf("2^5 = %lf", power);
I have done it using AutotextView
:
AutotextView textView = (AutotextView) findViewById(R.id.autotextview);
textView.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
seq = cs;
}
@Override
public void beforeTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
}
@Override
public void afterTextChanged(Editable arg0) {
new SearchTask().execute(seq.toString().trim());
}
});
If you want to handle show/hide of IMM (virtual) keyboard window from your Activity, you'll need to subclass your layout and override onMesure method(so that you can determine the measured width and the measured height of your layout). After that set subclassed layout as main view for your Activity by setContentView(). Now you'll be able to handle IMM show/hide window events. If this sounds complicated, it's not that really. Here's the code:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<EditText
android:id="@+id/SearchText"
android:text=""
android:inputType="text"
android:layout_width="fill_parent"
android:layout_height="34dip"
android:singleLine="True"
/>
<Button
android:id="@+id/Search"
android:layout_width="60dip"
android:layout_height="34dip"
android:gravity = "center"
/>
</LinearLayout>
Now inside your Activity declare subclass for your layout (main.xml)
public class MainSearchLayout extends LinearLayout {
public MainSearchLayout(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.main, this);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Log.d("Search Layout", "Handling Keyboard Window shown");
final int proposedheight = MeasureSpec.getSize(heightMeasureSpec);
final int actualHeight = getHeight();
if (actualHeight > proposedheight){
// Keyboard is shown
} else {
// Keyboard is hidden
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
You can see from the code that we inflate layout for our Activity in subclass constructor
inflater.inflate(R.layout.main, this);
And now just set content view of subclassed layout for our Activity.
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MainSearchLayout searchLayout = new MainSearchLayout(this, null);
setContentView(searchLayout);
}
// rest of the Activity code and subclassed layout...
}
I use this:
git log --name-status <branch>..<branch> | grep -E '^[A-Z]\b' | sort | uniq
which outputs a list of files only and their state (added, modified, deleted):
A sites/api/branding/__init__.py
M sites/api/branding/wtv/mod.py
...
Resurrecting the dead here, but just in case someone stumbles against this like myself. I know where to get the maximum value of a double, the (more) interesting part was to how did they get to that number.
double has 64 bits. The first one is reserved for the sign.
Next 11 represent the exponent (that is 1023 biased). It's just another way to represent the positive/negative values. If there are 11 bits then the max value is 1023.
Then there are 52 bits that hold the mantissa.
This is easily computed like this for example:
public static void main(String[] args) {
String test = Strings.repeat("1", 52);
double first = 0.5;
double result = 0.0;
for (char c : test.toCharArray()) {
result += first;
first = first / 2;
}
System.out.println(result); // close approximation of 1
System.out.println(Math.pow(2, 1023) * (1 + result));
System.out.println(Double.MAX_VALUE);
}
You can also prove this in reverse order :
String max = "0" + Long.toBinaryString(Double.doubleToLongBits(Double.MAX_VALUE));
String sign = max.substring(0, 1);
String exponent = max.substring(1, 12); // 11111111110
String mantissa = max.substring(12, 64);
System.out.println(sign); // 0 - positive
System.out.println(exponent); // 2046 - 1023 = 1023
System.out.println(mantissa); // 0.99999...8
I've already posted
GetItemValue
extension method in this post Get the value for a listbox item by index. This extension method will work for allListControl
classes includingCheckedListBox
,ListBox
andComboBox
.
None of the existing answers are general enough, but there is a general solution for the problem.
In all cases, the underlying Value
of an item should be calculated regarding to ValueMember
, regardless of the type of data source.
The data source of the CheckedListBox
may be a DataTable
or it may be a list which contains objects, like a List<T>
, so the items of a CheckedListBox
control may be DataRowView
, Complex Objects, Anonymous types, primary types and other types.
GetItemValue Extension Method
We need a GetItemValue
which works similar to GetItemText
, but return an object, the underlying value of an item, regardless of the type of object you added as item.
We can create GetItemValue
extension method to get item value which works like GetItemText
:
using System;
using System.Windows.Forms;
using System.ComponentModel;
public static class ListControlExtensions
{
public static object GetItemValue(this ListControl list, object item)
{
if (item == null)
throw new ArgumentNullException("item");
if (string.IsNullOrEmpty(list.ValueMember))
return item;
var property = TypeDescriptor.GetProperties(item)[list.ValueMember];
if (property == null)
throw new ArgumentException(
string.Format("item doesn't contain '{0}' property or column.",
list.ValueMember));
return property.GetValue(item);
}
}
Using above method you don't need to worry about settings of ListBox
and it will return expected Value
for an item. It works with List<T>
, Array
, ArrayList
, DataTable
, List of Anonymous Types, list of primary types and all other lists which you can use as data source. Here is an example of usage:
//Gets underlying value at index 2 based on settings
this.checkedListBox.GetItemValue(this.checkedListBox.Items[2]);
Since we created the GetItemValue
method as an extension method, when you want to use the method, don't forget to include the namespace in which you put the class.
This method is applicable on ComboBox
and CheckedListBox
too.
**@page {
margin-top:21% !important;
@top-left{
content: element(header);
}
@bottom-left {
content: element(footer
}
div.header {
position: running(header);
}
div.footer {
position: running(footer);
border-bottom: 2px solid black;
}
.pagenumber:before {
content: counter(page);
}
.pagecount:before {
content: counter(pages);
}
<div class="footer" style="font-size:12pt; font-family: Arial; font-family: Arial;">
<span>Page <span class="pagenumber"/> of <span class="pagecount"/></span>
</div >**
Request.Headers["Referer"]
Request.UrlReferer
property will throw a System.UriFormatException
if the referer HTTP header is malformed (which can happen since it is not usually under your control).Therefore, the Request.UrlReferer
property is not 100% reliable - it may contain data that cannot be parsed into a Uri
class. To ensure the value is always readable, use Request.Headers["Referrer"]
instead.
As for using Request.ServerVariables
as others here have suggested, per MSDN:
Request.ServerVariables Collection
The ServerVariables collection retrieves the values of predetermined environment variables and request header information.
Request.Headers Property
Gets a collection of HTTP headers.
Request.Headers
is a better choice than Request.ServerVariables
, since Request.ServerVariables
contains all of the environment variables as well as the headers, where Request.Headers
is a much shorter list that only contains the headers.
So the most reliable solution is to use the Request.Headers
collection to read the value directly. Do heed Microsoft's warnings about HTML encoding the value if you are going to display it on a form, though.
It's very simple. just add this to the body -
body{
margin:0;
padding:0;
overflow:hidden;
}
Try applying this style to your div class="input-group"
:
text-align:center;
View it: Fiddle.
$ git clone
will give you the whole repository.
After the clone, you can list the tags with $ git tag -l
and then checkout a specific tag:
$ git checkout tags/<tag_name>
Even better, checkout and create a branch (otherwise you will be on a branch named after the revision number of tag):
$ git checkout tags/<tag_name> -b <branch_name>
Similar to Yipio, I added notab="notab"
as an attribute to any element I wanted to disable the tab too. My jQuery is then one line.
$('input[notab=notab]').on('keydown', function(e){ if (e.keyCode == 9) e.preventDefault() });
Btw, keypress
doesn't work for many control keys.
i'd particularly want to add unserialize() to this list. It has had a long history of various vulnerabilities including arbitrary code execution, denial of service and memory information leakage. It should never be called on user-supplied data. Many of these vuls have been fixed in releases over the last dew years, but it still retains a couple of nasty vuls at the current time of writing.
For other information about dodgy php functions/usage look around the Hardened PHP Project and its advisories. Also the recent Month of PHP Security and 2007's Month of PHP Bugs projects
Also note that, by design, unserializing an object will cause the constructor and destructor functions to execute; another reason not to call it on user-supplied data.
Take a look into jQuery's .load() function:
<script>
$(function(){
$('#siteloader').load('http://www.somesitehere.com');
});
</script>
However, this only works on the same domain of the JS file.
the size attribute matters, if the size=5 then first 5 items will be shown and for others you need to scroll down..
<select name="numbers" size="5">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
</select>
With literal syntax you can check as follows
static const NSString* kKeyToCheck = @"yourKey"
if (xyz[kKeyToCheck])
NSLog(@"Key: %@, has Value: %@", kKeyToCheck, xyz[kKeyToCheck]);
else
NSLog(@"Key pair do not exits for key: %@", kKeyToCheck);
Maybe just restart postgres
=> sudo service postgresql restart