After spending too much time on this issue and trying out all different answers, here is what found:
The accepted answer by @thewaywewere is no longer applicable. I think this was applicable when opencv-python module still wasn't available.
This is indeed a bug in Anaconda 4.2 because they forgot to ship python3.dll. They have fixed this in next releases but unfortunately 4.2 is the last release with Python 3.5 as default. If you are stuck with Python 3.5 (for example VS2015 is only aware of versions up to 3.5) then you must manually download python3.dll as described in answer by @Ramesh-X.
If you can move on to Python 3.6 (which at present bit difficult if you are using OpenCV and VS2015) then just install latest Anaconda version and you don't have to deal with any of these.
I had the same issue, testing a bunch of different examples, and tried all the possible solutions. What finally got it working for me was when I added a @Path("")
over the class line, I had left that out.
Beyond compare allows you to do that and much more.
It's one of those tools I can't live without.
Take a look here for a reference on the scripting options
Query in Parado's answer is correct, if you want to use MySql too instead GETDATE() you must use (because you've tagged this question with Sql server and Mysql):
select * from tab
where DateCol between adddate(now(),-7) and now()
Use the remove/erase idiom:
std::vector<int>& vec = myNumbers; // use shorter name
vec.erase(std::remove(vec.begin(), vec.end(), number_in), vec.end());
What happens is that remove
compacts the elements that differ from the value to be removed (number_in
) in the beginning of the vector
and returns the iterator to the first element after that range. Then erase
removes these elements (whose value is unspecified).
In HTML
<div style="overflow: hidden;">
in CSS
overflow: hidden;
you can also end scrolling for x or y separately
overflow-y: hidden; /* Hide vertical scrollbar */
overflow-x: hidden; /* Hide horizontal scrollbar */
Here is a one-liner for CodeFights; it is one of the shortest solutions:
MMI = lambda A, n,s=1,t=0,N=0: (n < 2 and t%N or MMI(n, A%n, t, s-A//n*t, N or n),-1)[n<1]
It will return -1
if A
has no multiplicative inverse in n
.
Usage:
MMI(23, 99) # returns 56
MMI(18, 24) # return -1
The solution uses the Extended Euclidean Algorithm.
Before you try searching for the elements within the iframe you will have to switch Selenium focus to the iframe.
Try this before searching for the elements within the iframe:
driver.switchTo().frame(driver.findElement(By.name("iFrameTitle")));
Use this expression:
/\(([^()]+)\)/g
e.g:
function()
{
var mts = "something/([0-9])/([a-z])".match(/\(([^()]+)\)/g );
alert(mts[0]);
alert(mts[1]);
}
I'm not sure if Chrome has added this feature since the last answer, but I was able to view the json response by...
...I was able to view the response as a readable hierarchy that showed what to ask for and what is returned. (Neither Network or Resources tab had anything helpful that I was able to find.)
Happy requesting!
One option:
console.log('Item: ' + JSON.stringify(o));
Another option (as soktinpk pointed out in the comments), and better for console debugging IMO:
console.log('Item: ', o);
If your are using MySQL Latest version following may help to reach your requirement.
select * from products where attribs_json->"$.feature.value[*]" in (1,3)
You could use pandas plot as @Bharath suggest:
import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)
Output:
Updated:
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Updated Pandas 0.21.0+ reindex_axis
is deprecated, use reindex
from matplotlib.colors import ListedColormap
df.set_index('App')\
.reindex(df.set_index('App').sum().sort_values().index, axis=1)\
.T.plot(kind='bar', stacked=True,
colormap=ListedColormap(sns.color_palette("GnBu", 10)),
figsize=(12,6))
Output:
In the accepted answer, for Laravel 4 the headers array is constructed incorrectly. Use:
$headers = array(
'Content-Type' => 'application/pdf',
);
I noticed that Visual Studio's built-in error detector kind of gets goofy if you try to do this:
var intvar = @(ViewBag.someNumericValue);
Because @(ViewBag.someNumericValue) has the potential to evaluate to nothing, which would lead to the following erroneous JavaScript being generated:
var intvar = ;
If you're certain that someNemericValue will be set to a valid numeric data type, you can avoid having Visual Studio warnings by doing the following:
var intvar = Number(@(ViewBag.someNumericValue));
This might generate the following sample:
var intvar = Number(25.4);
And it works for negative numbers. In the event that the item isn't in your viewbag, Number() evaluates to 0.
No more Visual Studio warnings! But make sure the value is set and is numeric, otherwise you're opening doors to possible JavaScript injection attacks or run time errors.
Copy the css file's url and paste it into your browser. If it doesn't load the file than you know the problem is in the url.
Place the image in a source folder, not a regular folder. That is: right-click on project -> New -> Source Folder. Place the image in that source folder. Then:
InputStream input = classLoader.getResourceAsStream("image.jpg");
Note that the path is omitted. That's because the image is directly in the root of the path. You can add folders under your source folder to break it down further if you like. Or you can put the image under your existing source folder (usually called src
).
If you need to have an indexOf method on any old Adapter (and you don't know the underlying implementation) then you can use this:
private int indexOf(final Adapter adapter, Object value)
{
for (int index = 0, count = adapter.getCount(); index < count; ++index)
{
if (adapter.getItem(index).equals(value))
{
return index;
}
}
return -1;
}
Generally you should use String.Format because it's relatively fast and it supports globalization (assuming you're actually trying to write something that is read by the user). It also makes it easier to globalize if you're trying to translate one string versus 3 or more per statement (especially for languages that have drastically different grammatical structures).
Now if you never plan on translating anything, then either rely on Java's built in conversion of + operators into StringBuilder
. Or use Java's StringBuilder
explicitly.
conda env export
lists all conda and pip packages in an environment. conda-env
must be installed in the conda root (conda install -c conda conda-env
).
To write an environment.yml
file describing the current environment:
conda env export > environment.yml
References:
d3dave's answer is cool. However theGreenGarbage mentioned an issue about it which I too find rather annoying. So here's one that doesn't immediately suggest something after '=' sign and when typing blank space:
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.(!+-*/~,[{@#$%^&
What I did was simply remove the space and '=' chars from the array :)
Alternatively if you want suggestions when typing blank space, but not after '=' sign:
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz .(!+-*/~,[{@#$%^&
Assuming your dataframe is mydf:
mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))
If you have
char[] c
then you can do
char* d = &c[0]
and access element c[1] by doing *(d+1)
, etc.
Using LINQ you can do it like this:
var table_enum = table
// Convert to IEnumerable<string>
.OfType<string>()
// Create anonymous type where Index1 and Index2
// reflect the indices of the 2-dim. array
.Select((_string, _index) => new {
Index1 = (_index / 2),
Index2 = (_index % 2), // ? I added this only for completeness
Value = _string
})
// Group by Index1, which generates IEnmurable<string> for all Index1 values
.GroupBy(v => v.Index1)
// Convert all Groups of anonymous type to String-Arrays
.Select(group => group.Select(v => v.Value).ToArray());
// Now you can use the foreach-Loop as you planned
foreach(string[] str_arr in table_enum) {
// …
}
This way it is also possible to use the foreach for looping through the columns instead of the rows by using Index2 in the GroupBy instead of Index 1. If you don't know the dimension of your array then you have to use the GetLength() method to determine the dimension and use that value in the quotient.
After few years, I moved to leaflet map and I have fixed this issue completely, the following could be applied to google maps too:
var headerHeight = $("#navMap").outerHeight();
var footerHeight = $("footer").outerHeight();
var windowHeight = window.innerHeight;
var mapContainerHeight = headerHeight + footerHeight;
var totalMapHeight = windowHeight - mapContainerHeight;
$("#map").css("margin-top", headerHeight);
$("#map").height(totalMapHeight);
$(window).resize(function(){
var headerHeight = $("#navMap").outerHeight();
var footerHeight = $("footer").outerHeight();
var windowHeight = window.innerHeight;
var mapContainerHeight = headerHeight + footerHeight;
var totalMapHeight = windowHeight - mapContainerHeight;
$("#map").css("margin-top", headerHeight);
$("#map").height(totalMapHeight);
map.fitBounds(group1.getBounds());
});
I want to improve Fabio's answer and create a function which adds custom key to the URL string without reloading the page.
function insertUrlParam(key, value) {
if (history.pushState) {
let searchParams = new URLSearchParams(window.location.search);
searchParams.set(key, value);
let newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + searchParams.toString();
window.history.pushState({path: newurl}, '', newurl);
}
}
Use the map
method:
var a = [1, 2, 3]_x000D_
var b = ['a', 'b', 'c']_x000D_
_x000D_
var c = a.map(function(e, i) {_x000D_
return [e, b[i]];_x000D_
});_x000D_
_x000D_
console.log(c)
_x000D_
A heap queue is a generalised solution which allows you to extract the top n keys ordered by value:
from heapq import nlargest
stats = {'a':1000, 'b':3000, 'c': 100}
res1 = nlargest(1, stats, key=stats.__getitem__) # ['b']
res2 = nlargest(2, stats, key=stats.__getitem__) # ['b', 'a']
res1_val = next(iter(res1)) # 'b'
Note dict.__getitem__
is the method called by the syntactic sugar dict[]
. As opposed to dict.get
, it will return KeyError
if a key is not found, which here cannot occur.
In the Options, change the "Restore As" file name to the new database mdf and ldf. It is referencing the source database .mdf and .ldf files.
without having a to write a function, this will split according to list, in this case 'Mr.|Dr.|Mrs.', select everything after split with [1], then split again and grab whatever element. In the case below, 'Morris' is returned.
re.split('Mr.|Dr.|Mrs.', 'Mr. Morgan Morris')[1].split()[1]
You could create a user form:
Use .valid()
from the jQuery Validation plugin:
$("#form_id").valid();
Checks whether the selected form is valid or whether all selected elements are valid. validate() needs to be called on the form before checking it using this method.
Where the form with id='form_id'
is a form that has already had .validate()
called on it.
You can easily create a static object that represents a NULL return.
class Attr;
extern Attr AttrNull;
class Node {
....
Attr& getAttribute(const string& attribute_name) const {
//search collection
//if found at i
return attributes[i];
//if not found
return AttrNull;
}
bool IsNull(const Attr& test) const {
return &test == &AttrNull;
}
private:
vector<Attr> attributes;
};
And somewhere in a source file:
static Attr AttrNull;
form
If the name attribute is specified, the form controller is published onto the current scope under this name.
Alias: ngForm
In Angular, forms can be nested. This means that the outer form is valid when all of the child forms are valid as well. However, browsers do not allow nesting of elements, so Angular provides the ngForm directive which behaves identically to but can be nested. This allows you to have nested forms, which is very useful when using Angular validation directives in forms that are dynamically generated using the ngRepeat directive. Since you cannot dynamically generate the name attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an ngForm directive and nest these in an outer form element.
CSS classes
ng-valid is set if the form is valid.
ng-invalid is set if the form is invalid.
ng-pristine is set if the form is pristine.
ng-dirty is set if the form is dirty.
ng-submitted is set if the form was submitted.
Keep in mind that ngAnimate can detect each of these classes when added and removed.
Submitting a form and preventing the default action
Since the role of forms in client-side Angular applications is different than in classical roundtrip apps, it is desirable for the browser not to translate the form submission into a full page reload that sends the data to the server. Instead some javascript logic should be triggered to handle the form submission in an application-specific way.
For this reason, Angular prevents the default action (form submission to the server) unless the element has an action attribute specified.
You can use one of the following two ways to specify what javascript method should be called when a form is submitted:
ngSubmit directive on the form element
ngClick directive on the first button or input field of type submit (input[type=submit])
To prevent double execution of the handler, use only one of the ngSubmit or ngClick directives.
This is because of the following form submission rules in the HTML specification:
If a form has only one input field then hitting enter in this field triggers form submit (ngSubmit)
if a form has 2+ input fields and no buttons or input[type=submit]
then hitting enter doesn't trigger submit
if a form has one or more input fields and one or more buttons or input[type=submit]
then hitting enter in any of the input fields will trigger the click handler on the first button or input[type=submit]
(ngClick) and a submit handler on the enclosing form (ngSubmit).
Any pending ngModelOptions changes will take place immediately when an enclosing form is submitted. Note that ngClick events will occur before the model is updated.
Use ngSubmit to have access to the updated model.
app.js:
angular.module('formExample', [])
.controller('FormController', ['$scope', function($scope) {
$scope.userType = 'guest';
}]);
Form:
<form name="myForm" ng-controller="FormController" class="my-form">
userType: <input name="input" ng-model="userType" required>
<span class="error" ng-show="myForm.input.$error.required">Required!</span>
userType = {{userType}}
myForm.input.$valid = {{myForm.input.$valid}}
myForm.input.$error = {{myForm.input.$error}}
myForm.$valid = {{myForm.$valid}}
myForm.$error.required = {{!!myForm.$error.required}}
</form>
Source: AngularJS: API: form
use JodaTime
The ISO 8601 calendar system is the default implementation within Joda-Time
Here is the doc for JodaTime Formatter
Edit:
If you don't want to add or if you don't see value of adding above library you could just use in built SimpleDateFormat
class to format the Date to required ISO format
as suggested by @Joachim Sauer
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
String nowAsString = df.format(new Date());
As per you said your both files are in same directory. 1. index.html and 2. style.css
I have copied your code and run it in my local machine its working fine there is no issues.
According to me your browser is not refreshing the file so you can refresh/reload the entire page by pressing CTRL + F5 in windows for mac CMD + R.
Try it if still getting problem then you can test it by using firebug tool for firefox.
For IE8 and Google Chrome you can check it by pressing F12 your developer tool will pop-up and you can see the Html and css.
Still you have any problem please comment so we can help you.
I have written a beautiful, nested select. Maybe it will help you.
https://jsfiddle.net/nomorepls/tg13w5r7/1/
function on_change_select(e) {
alert(e.value, e.title, e.option, e.select);
}
$(document).ready(() => {
// NESTED SELECT
$(document).on('click', '.nested-cell', function() {
$(this).next('div').toggle('medium');
});
$(document).on('change', 'input[name="nested-select-hidden-radio"]', function() {
const parent = $(this).closest(".nested-select");
const value = $(this).attr('value');
const title = $(this).attr('title');
const executer = parent.attr('executer');
if (executer) {
const event = new Object();
event.value = value;
event.title = title;
event.option = $(this);
event.select = parent;
window[executer].apply(null, [event]);
}
parent.attr('value', value);
parent.parent().slideToggle();
const button = parent.parent().prev();
button.toggleClass('active');
button.addClass('selected');
button.children('.nested-select-title').html(title);
});
$(document).on('click', '.nested-select-button', function() {
const button = $(this);
let select = button.parent().children('.nested-select-wrapper');
if (!button.hasClass('active')) {
select = select.detach();
if (button.height() + button.offset().top + $(window).height() * 0.4 > $(window).height()) {
select.insertBefore(button);
select.css('margin-top', '-44vh');
select.css('top', '0');
} else {
select.insertAfter(button);
select.css('margin-top', '');
select.css('top', '40px');
}
}
select.slideToggle();
button.toggleClass('active');
});
});
_x000D_
.container {
width: 200px;
position: relative;
top: 0;
left: 0;
right: 0;
height: auto;
}
.nested-select-box {
font-family: Arial, Helvetica, sans-serif;
display: block;
position: relative;
width: 100%;
height: fit-content;
cursor: pointer;
color: #2196f3;
height: 40px;
font-size: small;
/* z-index: 2000; */
}
.nested-select-box .nested-select-button {
border: 1px solid #2196f3;
position: absolute;
width: calc(100% - 20px);
padding: 0 10px;
min-height: 40px;
word-wrap: break-word;
margin: 0 auto;
overflow: hidden;
}
.nested-select-box.danger .nested-select-button {
border: 1px solid rgba(250, 33, 33, 0.678);
}
.nested-select-box .nested-select-button .nested-select-title {
padding-right: 25px;
padding-left: 25px;
width: calc(100% - 50px);
margin: auto;
height: fit-content;
text-align: center;
vertical-align: middle;
position: absolute;
top: 0;
bottom: 0;
left: 0;
}
.nested-select-box .nested-select-button.selected .nested-select-title {
bottom: unset;
top: 5px;
}
.nested-select-box .nested-select-button .nested-select-title-icon {
position: absolute;
height: 20px;
width: 20px;
top: 10px;
bottom: 10px;
right: 7px;
transition: all 0.5s ease 0s;
}
.nested-select-box .nested-select-button.active .nested-select-title-icon {
-moz-transform: scale(-1, -1);
-o-transform: scale(-1, -1);
-webkit-transform: scale(-1, -1);
transform: scale(-1, -1);
}
.nested-select-box .nested-select-button .nested-select-title-icon::before,
.nested-select-box .nested-select-button .nested-select-title-icon::after {
content: "";
background-color: #2196f3;
position: absolute;
width: 70%;
height: 2px;
transition: all 0.5s ease 0s;
top: 9px;
}
.nested-select-box .nested-select-button .nested-select-title-icon::before {
transform: rotate(45deg);
left: -1.6px;
}
.nested-select-box .nested-select-button .nested-select-title-icon::after {
transform: rotate(-45deg);
left: 7px;
}
.nested-select-box .nested-select-wrapper {
width: 100%;
top: 40px;
position: relative;
border: 1px solid #2196f3;
background: #ffffff;
z-index: 2005;
opacity: 1;
}
.nested-select {
font-family: Arial, Helvetica, sans-serif;
display: inline-block;
overflow-y: scroll;
max-height: 40vh;
width: calc(100% - 10px);
padding: 5px;
-ms-overflow-style: none;
scrollbar-width: none;
}
.nested-select::-webkit-scrollbar {
display: none;
}
.nested-select a,
.nested-select span {
padding: 0 5px;
border-radius: 3px;
cursor: pointer;
text-align: start;
}
.nested-select a:hover {
background-color: #62b2f3;
color: #ffffff;
}
.nested-select span:hover {
background-color: #c4c4c4;
color: #ffffff;
}
.nested-select input[type="radio"] {
display: none;
}
.nested-select input[type="radio"]+span {
display: block;
}
.nested-select input[type="radio"]:checked+span {
background-color: #2196f3;
color: #ffffff;
}
.nested-select div {
margin-left: 15px;
}
.nested-select label>span:before,
.nested-select a:before {
content: "\2022";
margin-right: 5px;
}
.nested-select a {
display: block;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="nested-select-box w-100">
<div class="nested-select-button">
<p class="nested-select-title">
Account
</p>
<span class="nested-select-title-icon"></span>
</div>
<div class="nested-select-wrapper" style="display: none;">
<div class="nested-select" executer="on_change_select">
<label>
<input title="Accounting and legal services" value="1565142000000891539" type="radio" name="nested-select-hidden-radio">
<span>Accounting and legal services</span>
</label>
<label>
<input title="Advertising agencies" value="1565142000000891341" type="radio" name="nested-select-hidden-radio">
<span>Advertising agencies</span>
</label>
<a class="nested-cell">Advertising And Marketing</a>
<div>
<label>
<input title="Advertising agencies" value="1565142000000891341" type="radio" name="nested-select-hidden-radio">
<span>Advertising agencies</span>
</label>
<a class="nested-cell">Adwords - traffic</a>
<div>
<label>
<input title="Adwords - traffic: Charters and general search" value="1565142000003929177" type="radio" name="nested-select-hidden-radio">
<span>Adwords - traffic: Charters and general search</span>
</label>
<label>
<input title="Adwords - traffic: Distance course" value="1565142000007821291" type="radio" name="nested-select-hidden-radio">
<span>Adwords - traffic: Distance course</span>
</label>
<label>
<input title="Adwords - traffic: Events" value="1565142000003929189" type="radio" name="nested-select-hidden-radio">
<span>Adwords - traffic: Events</span>
</label>
<label>
<input title="Adwords - traffic: Practices" value="1565142000003929165" type="radio" name="nested-select-hidden-radio">
<span>Adwords - traffic: Practices</span>
</label>
<label>
<input title="Adwords - traffic: Sailing tours" value="1565142000003929183" type="radio" name="nested-select-hidden-radio">
<span>Adwords - traffic: Sailing tours</span>
</label>
<label>
<input title="Adwords - traffic: Theoretical courses" value="1565142000003929171" type="radio" name="nested-select-hidden-radio">
<span>Adwords - traffic: Theoretical courses</span>
</label>
</div>
<label>
<input title="Branded products" value="1565142000000891533" type="radio" name="nested-select-hidden-radio">
<span>Branded products</span>
</label>
<label>
<input title="Business cards" value="1565142000005438323" type="radio" name="nested-select-hidden-radio">
<span>Business cards</span>
</label>
<a class="nested-cell">Facebook, Instagram - traffic</a>
<div>
<label>
<input title="Facebook, Instagram - traffic: Charters and general search" value="1565142000003929145" type="radio" name="nested-select-hidden-radio">
<span>Facebook, Instagram - traffic: Charters and general search</span>
</label>
<label>
<input title="Facebook, Instagram - traffic: Distance course" value="1565142000007821285" type="radio" name="nested-select-hidden-radio">
<span>Facebook, Instagram - traffic: Distance course</span>
</label>
<label>
<input title="Facebook, Instagram - traffic: Events" value="1565142000003929157" type="radio" name="nested-select-hidden-radio">
<span>Facebook, Instagram - traffic: Events</span>
</label>
<label>
<input title="Facebook, Instagram - traffic: Practices" value="1565142000003929133" type="radio" name="nested-select-hidden-radio">
<span>Facebook, Instagram - traffic: Practices</span>
</label>
<label>
<input title="Facebook, Instagram - traffic: Sailing tours" value="1565142000003929151" type="radio" name="nested-select-hidden-radio">
<span>Facebook, Instagram - traffic: Sailing tours</span>
</label>
<label>
<input title="Facebook, Instagram - traffic: Theoretical courses" value="1565142000003929139" type="radio" name="nested-select-hidden-radio">
<span>Facebook, Instagram - traffic: Theoretical courses</span>
</label>
</div>
<label>
<input title="Offline Advertising (posters, banners, partnerships)" value="1565142000000891377" type="radio" name="nested-select-hidden-radio">
<span>Offline Advertising (posters, banners, partnerships)</span>
</label>
<label>
<input title="Photos, video etc." value="1565142000000891371" type="radio" name="nested-select-hidden-radio">
<span>Photos, video etc.</span>
</label>
<label>
<input title="Prize fund" value="1565142000001404931" type="radio" name="nested-select-hidden-radio">
<span>Prize fund</span>
</label>
<label>
<input title="SEO" value="1565142000000891365" type="radio" name="nested-select-hidden-radio">
<span>SEO</span>
</label>
<label>
<input title="SMM Content creation (texts, copywriting)" value="1565142000000891389" type="radio" name="nested-select-hidden-radio">
<span>SMM Content creation (texts, copywriting)</span>
</label>
<a class="nested-cell">YouTube</a>
<div>
<label>
<input title="YouTube: travel expenses" value="1565142000008100163" type="radio" name="nested-select-hidden-radio">
<span>YouTube: travel expenses</span>
</label>
<label>
<input title="Youtube: video editing" value="1565142000008100157" type="radio" name="nested-select-hidden-radio">
<span>Youtube: video editing</span>
</label>
</div>
</div>
</div>
</div>
</div>
</div>
_x000D_
#define DEBUG
#ifdef DEBUG
#define PRINT print
#else
#define PRINT(...) ((void)0) //strip out PRINT instructions from code
#endif
void print(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
vsprintf(str, fmt, args);
va_end(args);
printf("%s\n", str);
}
int main() {
PRINT("[%s %d, %d] Hello World", "March", 26, 2009);
return 0;
}
If the compiler does not understand variadic macros, you can also strip out PRINT with either of the following:
#define PRINT //
or
#define PRINT if(0)print
The first comments out the PRINT instructions, the second prevents PRINT instruction because of a NULL if condition. If optimization is set, the compiler should strip out never executed instructions like: if(0) print("hello world"); or ((void)0);
Instead of
InputStream fstream = this.getClass().getResourceAsStream("abc.txt");
use
InputStream fstream = this.getClass().getClassLoader().getResourceAsStream("abc.txt");
In this way it will look from the root, not from the path of the current invoking class
The answer is "No, one can't find the median of an arbitrary, unsorted dataset in linear time". The best one can do as a general rule (as far as I know) is Median of Medians (to get a decent start), followed by Quickselect. Ref: [https://en.wikipedia.org/wiki/Median_of_medians][1]
When you have a copy of an object the [checked]
attribute might not work, in that case, you can use (change)
in this way:
<input type="checkbox" [checked]="item.selected" (change)="item.selected = !item.selected">
function closeWin() // Tested Code
{
var someIframe = window.parent.document.getElementById('iframe_callback');
someIframe.parentNode.removeChild(window.parent.document.getElementById('iframe_callback'));
}
<input class="question" name="Close" type="button" value="Close" onClick="closeWin()" tabindex="10" />
This error message is very confusing. I just fixed the other 'warnings' in my project and I really had only one (simple one):
warning C4101: 'i': unreferenced local variable
After I commented this unused i
, and compiled it, the other error went away.
Similar to what Muhammad Iqbal stated.. I was in a VB.NET (may also be C#) project where I did remove a key-value pair from the App.config
which was referenced by a variable global to the Sub Main()
of Module Main
. Therefore, the exception (and break) occurs in Module Main
before the Sub Main()
. If only I had a break-point on the Dim
, but we don't usually break on global variables. Perhaps a good reason not to declare globals referencing App.config? In other words, this...
An unhandled exception of type 'System.TypeInitializationException' occurred in Unknown Module. The type initializer for 'Namespace.Main' threw an exception.
Is caused by...
App.config
<connectionStrings>
<!--<add name="ConnectionString1" connectionString="..." />-->
Main module
Module Main
Dim cnnString As String = ConfigurationManager.ConnectionStrings("ConnectionString1") '<-- BREAK HERE (EXCEPTION)
Sub Main()
// main code
End Main
End Module
C# is strongly typed so you can't create variables dynamically. You could use an array but a better C# way would be to use a Dictionary as follows. More on C# dictionaries here.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QuickTest
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, int> names = new Dictionary<string,int>();
for (int i = 0; i < 10; i++)
{
names.Add(String.Format("name{0}", i.ToString()), i);
}
var xx1 = names["name1"];
var xx2 = names["name2"];
var xx3 = names["name3"];
}
}
}
Try this:
var date = new Date();
var hour = date.getHours();
var min = date.getMinutes();
Just Restart-Service hns
can change the port occupier by Hyper-V. It might release the port you need.
You can use document.write, however it's not a good practice, it may clear the entire page depends on when it's being executed.
You should use Element.innerHtml
like this:
<div>foo</div>
<span id="insertHere"></span>
<div>bar</div>
<script>
document.getElementById('insertHere').innerHTML = '<div>Print this after the script tag</div>';
</script>
@Xaqq has provided a really nice type-safe way to use enum flags here by a flag_set
class.
I published the code in GitHub, usage is as follows:
#include "flag_set.hpp"
enum class AnimalFlags : uint8_t {
HAS_CLAWS,
CAN_FLY,
EATS_FISH,
ENDANGERED,
_
};
int main()
{
flag_set<AnimalFlags> seahawkFlags(AnimalFlags::HAS_CLAWS
| AnimalFlags::EATS_FISH
| AnimalFlags::ENDANGERED);
if (seahawkFlags & AnimalFlags::ENDANGERED)
cout << "Seahawk is endangered";
}
In my case (on windows 10), it would connect fine to adb and I could type any adb
commands. But as soon as it got to the bootloader using adb reboot bootloader
I wasn't able to perform any fastboot
commands.
What I did notice that in the device manager that it refreshed when I connected to device. Next thing to do was to check what changed when connecting. Apparently the fastboot device was inside the Kedacom USB Device
. Not really sure what that was, but I updated the device to use a different driver, in my case the Fastboot interface (Google USB ID)
, and that fixed my waiting for device
issue
Use logcat tool with -d
or -f
switch and exec() method.
Saving to a file on the host computer:
exec( "adb logcat -d > logcat.log" ) // logcat is written to logcat.log file on the host.
If you are just saving to a file on the device itself, you can use:
exec( "adb logcat -f logcat.log" ) // logcat is written to logcat.log file on the device.
This is basically the solution from sola, but just cleaned up a bit. It's different enough that I didn't just want to "improve" his solution (plus, I sort of think that's rude).
Main difference is that it uses the EXECUTE format. Which I think is a bit cleaner, but I believe means that you must be on PostgresSQL 9.1 or newer.
This has been tested on 9.1 and works. Note: It will raise an error if the schema/table_name/or data_type are invalid. That could "fixed", but might be the correct behavior in many cases.
CREATE OR REPLACE FUNCTION add_column(schema_name TEXT, table_name TEXT,
column_name TEXT, data_type TEXT)
RETURNS BOOLEAN
AS
$BODY$
DECLARE
_tmp text;
BEGIN
EXECUTE format('SELECT COLUMN_NAME FROM information_schema.columns WHERE
table_schema=%L
AND table_name=%L
AND column_name=%L', schema_name, table_name, column_name)
INTO _tmp;
IF _tmp IS NOT NULL THEN
RAISE NOTICE 'Column % already exists in %.%', column_name, schema_name, table_name;
RETURN FALSE;
END IF;
EXECUTE format('ALTER TABLE %I.%I ADD COLUMN %I %s;', schema_name, table_name, column_name, data_type);
RAISE NOTICE 'Column % added to %.%', column_name, schema_name, table_name;
RETURN TRUE;
END;
$BODY$
LANGUAGE 'plpgsql';
usage:
select add_column('public', 'foo', 'bar', 'varchar(30)');
Make a swap and run composer command again. I hope it'll work for you.
$ dd if=/dev/zero of=/swapfile bs=1024 count=512k
$ mkswap /swapfile
$ swapon /swapfile
$ echo "/swapfile none swap sw 0 0 " >> /etc/fstab
$ echo 0 > /proc/sys/vm/swappiness
$ chown root:root /swapfile
$ chmod 0600 /swapfile
Work 100%. maybe not relation to creator answer but i share it for users have a problem with export mysql query to excel with phpexcel. Good Luck.
require('../phpexcel/PHPExcel.php');
require('../phpexcel/PHPExcel/Writer/Excel5.php');
$filename = 'userReport'; //your file name
$objPHPExcel = new PHPExcel();
/*********************Add column headings START**********************/
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'username')
->setCellValue('B1', 'city_name');
/*********************Add data entries START**********************/
//get_result_array_from_class**You can replace your sql code with this line.
$result = $get_report_clas->get_user_report();
//set variable for count table fields.
$num_row = 1;
foreach ($result as $value) {
$user_name = $value['username'];
$c_code = $value['city_name'];
$num_row++;
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$num_row, $user_name )
->setCellValue('B'.$num_row, $c_code );
}
/*********************Autoresize column width depending upon contents START**********************/
foreach(range('A','B') as $columnID) {
$objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
}
$objPHPExcel->getActiveSheet()->getStyle('A1:B1')->getFont()->setBold(true);
//Make heading font bold
/*********************Add color to heading START**********************/
$objPHPExcel->getActiveSheet()
->getStyle('A1:B1')
->getFill()
->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
->getStartColor()
->setARGB('99ff99');
$objPHPExcel->getActiveSheet()->setTitle('userReport'); //give title to sheet
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header("Content-Disposition: attachment;Filename=$filename.xls");
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
For Android, if you are using OkHttp in your project. You might get a look at this. It simple and helpful.
final HttpUrl url = HttpUrl.parse(query);
if (url != null) {
final String target = url.queryParameter("target");
final String id = url.queryParameter("id");
}
Try this:
var request = WebRequest.Create("http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG");
using (var response = request.GetResponse())
using (var stream = response.GetResponseStream())
{
pictureBox1.Image = Bitmap.FromStream(stream);
}
Is it essential that you need a NumPy array? Otherwise you could speed things up by loading the data as a nested list.
def load(fname):
''' Load the file using std open'''
f = open(fname,'r')
data = []
for line in f.readlines():
data.append(line.replace('\n','').split(' '))
f.close()
return data
For a text file with 4000x4000 words this is about 10 times faster than loadtxt
.
http://www.viemu.com/a_vi_vim_graphical_cheat_sheet_tutorial.html
This is the greatest thing ever for learning VIM.
Despite setting up dimensions for the columns, they still seem to shrink as the window shrinks.
An initial setting of a flex container is flex-shrink: 1
. That's why your columns are shrinking.
It doesn't matter what width you specify (it could be width: 10000px
), with flex-shrink
the specified width can be ignored and flex items are prevented from overflowing the container.
I'm trying to set up a flexbox with 3 columns where the left and right columns have a fixed width...
You will need to disable shrinking. Here are some options:
.left, .right {
width: 230px;
flex-shrink: 0;
}
OR
.left, .right {
flex-basis: 230px;
flex-shrink: 0;
}
OR, as recommended by the spec:
.left, .right {
flex: 0 0 230px; /* don't grow, don't shrink, stay fixed at 230px */
}
7.2. Components of Flexibility
Authors are encouraged to control flexibility using the
flex
shorthand rather than with its longhand properties directly, as the shorthand correctly resets any unspecified components to accommodate common uses.
More details here: What are the differences between flex-basis and width?
An additional thing I need to do is hide the right column based on user interaction, in which case the left column would still keep its fixed width, but the center column would fill the rest of the space.
Try this:
.center { flex: 1; }
This will allow the center column to consume available space, including the space of its siblings when they are removed.
The patch tells it what file to apply to. The header should be something like (view it in Notepad or your fav text editor):
--- Folder/old_file
+++ Folder/new_file
In the case of a Subversion patch, you'd have revision numbers as well (since the file names are the same).
GNU patch will let you override those names, but I don't know of any GUI tools to do the same. I'd check with the various diff programs - though, it does not appear WinMerge supports applying patches.
I figured it this way:
* { padding: 0; margin: 0 }
body { height: 100%; white-space: nowrap }
html { height: 100% }
.red { background: red }
.blue { background: blue }
.yellow { background: yellow }
.header { width: 100%; height: 10%; position: fixed }
.wrapper { width: 1000%; height: 100%; background: green }
.page { width: 10%; height: 100%; float: left }
<div class="header red"></div>
<div class="wrapper">
<div class="page yellow"></div>
<div class="page blue"></div>
<div class="page yellow"></div>
<div class="page blue"></div>
<div class="page yellow"></div>
<div class="page blue"></div>
<div class="page yellow"></div>
<div class="page blue"></div>
<div class="page yellow"></div>
<div class="page blue"></div>
</div>
I have the wrapper at 1000% and ten pages at 10% each. I set mine up to still have "pages" with each being 100% of the window (color coded). You can do eight pages with an 800% wrapper. I guess you can leave out the colors and have on continues page. I also set up a fixed header, but that's not necessary. Hope this helps.
This maybe is a bit ugly hack, but it works pretty well when you don't need more than the default float precision (about 11 decimals).
The round_to function uses the format method from the built-in str class to round up the float to a string that represents the float with the number of decimals needed, and then applies the eval built-in function to the rounded float string to get back to the float numeric type.
The is_close function just applies a simple conditional to the rounded up float.
def round_to(float_num, prec):
return eval("'{:." + str(int(prec)) + "f}'.format(" + str(float_num) + ")")
def is_close(float_a, float_b, prec):
if round_to(float_a, prec) == round_to(float_b, prec):
return True
return False
>>>a = 10.0
10.0
>>>b = 10.0001
10.0001
>>>print is_close(a, b, prec=3)
True
>>>print is_close(a, b, prec=4)
False
Update:
As suggested by @stepehjfox, a cleaner way to build a rount_to function avoiding "eval" is using nested formatting:
def round_to(float_num, prec):
return '{:.{precision}f}'.format(float_num, precision=prec)
Following the same idea, the code can be even simpler using the great new f-strings (Python 3.6+):
def round_to(float_num, prec):
return f'{float_num:.{prec}f}'
So, we could even wrap it up all in one simple and clean 'is_close' function:
def is_close(a, b, prec):
return f'{a:.{prec}f}' == f'{b:.{prec}f}'
Exporting the DISPLAY
variable is definitely the solution but depending on your setup you may have to do this in a slightly different way.
In my case, I have two different processes: the first one starts Xvfb, the other one launches the tests. So my shell scripting knowledge is a bit rusty but I figured out that exporting the DISPLAY
variable from the first process didn't make it available in the second process.
Fortunately, Selenium WebDriver allows you to 'redefine' your environment. This is my function for creating a driver for Chrome in JS. Pretty sure the equivalent exists for your programming language:
const caps = require('selenium-webdriver/lib/capabilities');
const chrome = require('selenium-webdriver/chrome');
const chromedriver = require('chromedriver');
module.exports = function (cfg) {
let serviceBuilder = new chrome.ServiceBuilder(chromedriver.path);
let options = chrome.Options.fromCapabilities(caps.Capabilities.chrome());
let service;
let myENV = new Map();
// 're-export' the `DISPLAY` variable
myENV.set('DISPLAY', ':1');
serviceBuilder.setEnvironment(myENV);
service = serviceBuilder.build();
options.addArguments('disable-setuid-sandbox');
options.addArguments('no-sandbox');
options.addArguments('allow-insecure-localhost');
options.excludeSwitches('test-type');
return chrome.Driver.createSession(options, service);
};
When you want a flex item to occupy an entire row, set it to width: 100%
or flex-basis: 100%
, and enable wrap
on the container.
The item now consumes all available space. Siblings are forced on to other rows.
.parent {
display: flex;
flex-wrap: wrap;
}
#range, #text {
flex: 1;
}
.error {
flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
border: 1px dashed black;
}
_x000D_
<div class="parent">
<input type="range" id="range">
<input type="text" id="text">
<label class="error">Error message (takes full width)</label>
</div>
_x000D_
More info: The initial value of the flex-wrap
property is nowrap
, which means that all items will line up in a row. MDN
If you don't want to use OutlineButton
and want to stick to normal RaisedButton
, you can wrap your button in ClipRRect
or ClipOval
like:
ClipRRect(
borderRadius: BorderRadius.circular(40),
child: RaisedButton(
child: Text("Button"),
onPressed: () {},
),
),
For information i removed the action attribute and i got this error when i call an ajax post..Even though my action attribute in the form looks like this action="javascript://;"
I thought I had it from the ajax call and serializing the form but I added the dummy action attribute to the form back again and it worked.
Partial Method Declaration only Even the code get compiled with method declaration only and if the implementation of the method isn't present compiler can safely remove that piece of code and no compile time error will occur.
To verify point 4. Just create a winform project and include this line after the Form1 Constructor and try to compile the code
partial void Ontest(string s);
Here are some points to consider while implementing partial classes:-
This just removes the highlight
class from everything that has the edgetoedge
class:
$(".edgetoedge").removeClass("highlight");
I think you want this:
$(".edgetoedge .highlight").removeClass("highlight");
The .edgetoedge .highlight
selector will choose everything that is a child of something with the edgetoedge
class and has the highlight
class.
Use Immersive Full-Screen Mode
call fullScreen()
on ImageView
click.
public void fullScreen() {
// BEGIN_INCLUDE (get_current_ui_flags)
// The UI options currently enabled are represented by a bitfield.
// getSystemUiVisibility() gives us that bitfield.
int uiOptions = getWindow().getDecorView().getSystemUiVisibility();
int newUiOptions = uiOptions;
// END_INCLUDE (get_current_ui_flags)
// BEGIN_INCLUDE (toggle_ui_flags)
boolean isImmersiveModeEnabled =
((uiOptions | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) == uiOptions);
if (isImmersiveModeEnabled) {
Log.i(TAG, "Turning immersive mode mode off. ");
} else {
Log.i(TAG, "Turning immersive mode mode on.");
}
// Navigation bar hiding: Backwards compatible to ICS.
if (Build.VERSION.SDK_INT >= 14) {
newUiOptions ^= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
}
// Status bar hiding: Backwards compatible to Jellybean
if (Build.VERSION.SDK_INT >= 16) {
newUiOptions ^= View.SYSTEM_UI_FLAG_FULLSCREEN;
}
// Immersive mode: Backward compatible to KitKat.
// Note that this flag doesn't do anything by itself, it only augments the behavior
// of HIDE_NAVIGATION and FLAG_FULLSCREEN. For the purposes of this sample
// all three flags are being toggled together.
// Note that there are two immersive mode UI flags, one of which is referred to as "sticky".
// Sticky immersive mode differs in that it makes the navigation and status bars
// semi-transparent, and the UI flag does not get cleared when the user interacts with
// the screen.
if (Build.VERSION.SDK_INT >= 18) {
newUiOptions ^= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
}
getWindow().getDecorView().setSystemUiVisibility(newUiOptions);
//END_INCLUDE (set_ui_flags)
}
Read more
Example Download
There's no simple answer to this question. Apple's mobile version of WebKit, used in iPhones, iPod Touches, and iPads, will scale the page to fit the screen, at which point the user can zoom in and out freely.
That said, you can design your page to minimize the amount of zooming necessary. Your best bet is to make the width and height the same as the lower resolution of the iPad, since you don't know which way it's oriented; in other words, you would make your page 768x768, so that it will fit well on the iPad's screen whether it's oriented to be 1024x768 or 768x1024.
More importantly, you'd want to design your page with big controls with lots of space that are easy to hit with your thumbs - you could easily design a 768x768 page that was very cluttered and therefore required lots of zooming. To accomplish this, you'll likely want to divide your controls among a number of web pages.
On the other hand, it's not the most worthwhile pursuit. If while designing you find opportunities to make your page more "finger-friendly", then go for it...but the reality is that iPad users are very comfortable with moving around and zooming in and out of the page to get to things because it's necessary on most web sites. If anything, you probably want to design it so that it's conducive to this type of navigation.
Make boxes with relevant grouped data that can be easily double-tapped to focus on, and keep related controls close to each other. iPad users will most likely appreciate a page that facilitates the familiar zoom-and-pan navigation they're accustomed to more than they will a page that has fewer controls so that they don't have to.
The following will return true if the element is an input:
$("#elementId").is("input")
or you can use the following to get the name of the tag:
$("#elementId").get(0).tagName
You can load HTML page partial, in your case is everything inside div#mytable.
setTimeout(function(){
$( "#mytable" ).load( "your-current-page.html #mytable" );
}, 2000); //refresh every 2 seconds
more information read this http://api.jquery.com/load/
<button id="refresh-btn">Refresh Table</button>
<script>
$(document).ready(function() {
function RefreshTable() {
$( "#mytable" ).load( "your-current-page.html #mytable" );
}
$("#refresh-btn").on("click", RefreshTable);
// OR CAN THIS WAY
//
// $("#refresh-btn").on("click", function() {
// $( "#mytable" ).load( "your-current-page.html #mytable" );
// });
});
</script>
Note: there is no guarantee this code will work in future versions of the .Net framework. Using private .Net framework internals as done here through reflection is probably not good overall. Use the interop solution mentioned at the bottom, as the Windows API is less likely to change.
If you are looking for a Folder picker that looks more like the Windows 7 dialog, with the ability to copy and paste from a textbox at the bottom and the navigation pane on the left with favorites and common locations, then you can get access to that in a very lightweight way.
The FolderBrowserDialog UI is very minimal:
But you can have this instead:
Here's a class that opens a Vista-style folder picker using the .Net private IFileDialog
interface, without directly using interop in the code (.Net takes care of that for you). It falls back to the pre-Vista dialog if not in a high enough Windows version. Should work in Windows 7, 8, 9, 10 and higher (theoretically).
using System;
using System.Reflection;
using System.Windows.Forms;
namespace MyCoolCompany.Shuriken {
/// <summary>
/// Present the Windows Vista-style open file dialog to select a folder. Fall back for older Windows Versions
/// </summary>
public class FolderSelectDialog {
private string _initialDirectory;
private string _title;
private string _fileName = "";
public string InitialDirectory {
get { return string.IsNullOrEmpty(_initialDirectory) ? Environment.CurrentDirectory : _initialDirectory; }
set { _initialDirectory = value; }
}
public string Title {
get { return _title ?? "Select a folder"; }
set { _title = value; }
}
public string FileName { get { return _fileName; } }
public bool Show() { return Show(IntPtr.Zero); }
/// <param name="hWndOwner">Handle of the control or window to be the parent of the file dialog</param>
/// <returns>true if the user clicks OK</returns>
public bool Show(IntPtr hWndOwner) {
var result = Environment.OSVersion.Version.Major >= 6
? VistaDialog.Show(hWndOwner, InitialDirectory, Title)
: ShowXpDialog(hWndOwner, InitialDirectory, Title);
_fileName = result.FileName;
return result.Result;
}
private struct ShowDialogResult {
public bool Result { get; set; }
public string FileName { get; set; }
}
private static ShowDialogResult ShowXpDialog(IntPtr ownerHandle, string initialDirectory, string title) {
var folderBrowserDialog = new FolderBrowserDialog {
Description = title,
SelectedPath = initialDirectory,
ShowNewFolderButton = false
};
var dialogResult = new ShowDialogResult();
if (folderBrowserDialog.ShowDialog(new WindowWrapper(ownerHandle)) == DialogResult.OK) {
dialogResult.Result = true;
dialogResult.FileName = folderBrowserDialog.SelectedPath;
}
return dialogResult;
}
private static class VistaDialog {
private const string c_foldersFilter = "Folders|\n";
private const BindingFlags c_flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
private readonly static Assembly s_windowsFormsAssembly = typeof(FileDialog).Assembly;
private readonly static Type s_iFileDialogType = s_windowsFormsAssembly.GetType("System.Windows.Forms.FileDialogNative+IFileDialog");
private readonly static MethodInfo s_createVistaDialogMethodInfo = typeof(OpenFileDialog).GetMethod("CreateVistaDialog", c_flags);
private readonly static MethodInfo s_onBeforeVistaDialogMethodInfo = typeof(OpenFileDialog).GetMethod("OnBeforeVistaDialog", c_flags);
private readonly static MethodInfo s_getOptionsMethodInfo = typeof(FileDialog).GetMethod("GetOptions", c_flags);
private readonly static MethodInfo s_setOptionsMethodInfo = s_iFileDialogType.GetMethod("SetOptions", c_flags);
private readonly static uint s_fosPickFoldersBitFlag = (uint) s_windowsFormsAssembly
.GetType("System.Windows.Forms.FileDialogNative+FOS")
.GetField("FOS_PICKFOLDERS")
.GetValue(null);
private readonly static ConstructorInfo s_vistaDialogEventsConstructorInfo = s_windowsFormsAssembly
.GetType("System.Windows.Forms.FileDialog+VistaDialogEvents")
.GetConstructor(c_flags, null, new[] { typeof(FileDialog) }, null);
private readonly static MethodInfo s_adviseMethodInfo = s_iFileDialogType.GetMethod("Advise");
private readonly static MethodInfo s_unAdviseMethodInfo = s_iFileDialogType.GetMethod("Unadvise");
private readonly static MethodInfo s_showMethodInfo = s_iFileDialogType.GetMethod("Show");
public static ShowDialogResult Show(IntPtr ownerHandle, string initialDirectory, string title) {
var openFileDialog = new OpenFileDialog {
AddExtension = false,
CheckFileExists = false,
DereferenceLinks = true,
Filter = c_foldersFilter,
InitialDirectory = initialDirectory,
Multiselect = false,
Title = title
};
var iFileDialog = s_createVistaDialogMethodInfo.Invoke(openFileDialog, new object[] { });
s_onBeforeVistaDialogMethodInfo.Invoke(openFileDialog, new[] { iFileDialog });
s_setOptionsMethodInfo.Invoke(iFileDialog, new object[] { (uint) s_getOptionsMethodInfo.Invoke(openFileDialog, new object[] { }) | s_fosPickFoldersBitFlag });
var adviseParametersWithOutputConnectionToken = new[] { s_vistaDialogEventsConstructorInfo.Invoke(new object[] { openFileDialog }), 0U };
s_adviseMethodInfo.Invoke(iFileDialog, adviseParametersWithOutputConnectionToken);
try {
int retVal = (int) s_showMethodInfo.Invoke(iFileDialog, new object[] { ownerHandle });
return new ShowDialogResult {
Result = retVal == 0,
FileName = openFileDialog.FileName
};
}
finally {
s_unAdviseMethodInfo.Invoke(iFileDialog, new[] { adviseParametersWithOutputConnectionToken[1] });
}
}
}
// Wrap an IWin32Window around an IntPtr
private class WindowWrapper : IWin32Window {
private readonly IntPtr _handle;
public WindowWrapper(IntPtr handle) { _handle = handle; }
public IntPtr Handle { get { return _handle; } }
}
}
}
I developed this as a cleaned up version of .NET Win 7-style folder select dialog by Bill Seddon of lyquidity.com (I have no affiliation). I wrote my own because his solution requires an additional Reflection class that isn't needed for this focused purpose, uses exception-based flow control, doesn't cache the results of its reflection calls. Note that the nested static VistaDialog
class is so that its static reflection variables don't try to get populated if the Show
method is never called.
It is used like so in a Windows Form:
var dialog = new FolderSelectDialog {
InitialDirectory = musicFolderTextBox.Text,
Title = "Select a folder to import music from"
};
if (dialog.Show(Handle)) {
musicFolderTextBox.Text = dialog.FileName;
}
You can of course play around with its options and what properties it exposes. For example, it allows multiselect in the Vista-style dialog.
Also, please note that Simon Mourier gave an answer that shows how to do the exact same job using interop against the Windows API directly, though his version would have to be supplemented to use the older style dialog if in an older version of Windows. Unfortunately, I hadn't found his post yet when I worked up my solution. Name your poison!
perl -pi -e 's/\n$// if(eof)' your_file
You can't do it. But you can use custom Alert and Confirm boxes.
You can read about some User Interface libraries here:
http://speckyboy.com/2010/05/17/15-javascript-web-ui-libraries-frameworks-and-libraries/
Most common libraries are:
LocalDate.now() // Capture the date-only value current in the JVM’s current default time zone.
.getYear() // Extract the year number from that date.
2018
Both the java.util.Date
and java.util.Calendar
classes are legacy, now supplanted by the java.time framework built into Java 8 and later.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
If you want only the date without time-of-day, use LocalDate
. This class lacks time zone info but you can specify a time zone to determine the current date.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate localDate = LocalDate.now( zoneId );
You can get the various pieces of information with getYear
, getMonth
, and getDayOfMonth
. You will actually get the year number with java.time!
int year = localDate.getYear();
2016
If you want a date-time instead of just a date, use ZonedDateTime
class.
ZonedDateTime zdt = ZonedDateTime.now( zoneId ) ;
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & Java 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Anyone can define "token_type" as an OAuth 2.0 extension, but currently "bearer" token type is the most common one.
https://tools.ietf.org/html/rfc6750
Basically that's what Facebook is using. Their implementation is a bit behind from the latest spec though.
If you want to be more secure than Facebook (or as secure as OAuth 1.0 which has "signature"), you can use "mac" token type.
However, it will be hard way since the mac spec is still changing rapidly.
Steps:
After all it works for me and hopefully work for you.
If you are trying to accessing config variable into controller than use
$this->config->item('{variable name which you define into config}');
If you are trying to accessing the config variable into outside the controller(helper/hooks) then use
$mms = get_instance();
$mms->config->item('{variable which you define into config}');
It works for me:
$('#yourselect').on("change", function(e) {
// what you would like to happen
});
Look at Float.intBitsToFloat
and Double.longBitsToDouble
, which sort of explain how bits correspond to floating-point numbers. In particular, the bits of a normal float
look something like
s * 2^exp * 1.ABCDEFGHIJKLMNOPQRSTUVW
where A...W are 23 bits -- 0s and 1s -- representing a fraction in binary -- s is +/- 1, represented by a 0 or a 1 respectively, and exp is a signed 8-bit integer.
Using the given examples:
h = re.compile('hello')
h.match('hello world')
The match method in the example above is not the same as the one used below:
re.match('hello', 'hello world')
re.compile() returns a regular expression object, which means h
is a regex object.
The regex object has its own match method with the optional pos and endpos parameters:
regex.match(string[, pos[, endpos]])
pos
The optional second parameter pos gives an index in the string where the search is to start; it defaults to 0. This is not completely equivalent to slicing the string; the
'^'
pattern character matches at the real beginning of the string and at positions just after a newline, but not necessarily at the index where the search is to start.
endpos
The optional parameter endpos limits how far the string will be searched; it will be as if the string is endpos characters long, so only the characters from pos to
endpos - 1
will be searched for a match. If endpos is less than pos, no match will be found; otherwise, if rx is a compiled regular expression object,rx.search(string, 0, 50)
is equivalent torx.search(string[:50], 0)
.
The regex object's search, findall, and finditer methods also support these parameters.
re.match(pattern, string, flags=0)
does not support them as you can see,
nor does its search, findall, and finditer counterparts.
A match object has attributes that complement these parameters:
match.pos
The value of pos which was passed to the search() or match() method of a regex object. This is the index into the string at which the RE engine started looking for a match.
match.endpos
The value of endpos which was passed to the search() or match() method of a regex object. This is the index into the string beyond which the RE engine will not go.
A regex object has two unique, possibly useful, attributes:
regex.groups
The number of capturing groups in the pattern.
regex.groupindex
A dictionary mapping any symbolic group names defined by (?P) to group numbers. The dictionary is empty if no symbolic groups were used in the pattern.
And finally, a match object has this attribute:
match.re
The regular expression object whose match() or search() method produced this match instance.
Easiest way to fetch any initialize use ng-init directory.
Just put ng-init div scope where you want to fetch init data
index.html
<div class="frame" ng-init="init()">
<div class="bit-1">
<div class="field p-r">
<label ng-show="regi_step2.address" class="show-hide c-t-1 ng-hide" style="">Country</label>
<select class="form-control w-100" ng-model="country" name="country" id="country" ng-options="item.name for item in countries" ng-change="stateChanged()" >
</select>
<textarea class="form-control w-100" ng-model="regi_step2.address" placeholder="Address" name="address" id="address" ng-required="true" style=""></textarea>
</div>
</div>
</div>
index.js
$scope.init=function(){
$http({method:'GET',url:'/countries/countries.json'}).success(function(data){
alert();
$scope.countries = data;
});
};
NOTE: you can use this methodology if you do not have same code more then one place.
Thx guys, I finally found the solution, a really basic one.. In my controller I have
$scope.mySplit = function(string, nb) {
var array = string.split(',');
return array[nb];
}
and in my view
{{mySplit(string,0)}}
This works in all browsers:
window.location.href = '...';
If you wanted to change the page without it reflecting in the browser back history, you can do:
window.location.replace('...');
The error is here:
hasLetter("a",words[]);
You are passing the first item of words
, instead of the array.
Instead, pass the array to the function:
hasLetter("a",words);
Problem solved!
Here's a breakdown of what the problem was:
I'm guessing in your browser (chrome throws a different error), words[] == words[0]
, so when you call hasLetter("a",words[]);
, you are actually calling hasLetter("a",words[0]);
. So, in essence, you are passing the first item of words to your function, not the array as a whole.
Of course, because words
is just an empty array, words[0]
is undefined
. Therefore, your function call is actually:
hasLetter("a", undefined);
which means that, when you try to access d[ascii]
, you are actually trying to access undefined[0]
, hence the error.
JS does not have a sleep function, it has setTimeout() or setInterval() functions.
If you can move the code that you need to run after the pause into the setTimeout()
callback, you can do something like this:
//code before the pause
setTimeout(function(){
//do what you need here
}, 2000);
see example here : http://jsfiddle.net/9LZQp/
This won't halt the execution of your script, but due to the fact that setTimeout()
is an asynchronous function, this code
console.log("HELLO");
setTimeout(function(){
console.log("THIS IS");
}, 2000);
console.log("DOG");
will print this in the console:
HELLO
DOG
THIS IS
(note that DOG is printed before THIS IS)
You can use the following code to simulate a sleep for short periods of time:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
now, if you want to sleep for 1 second, just use:
sleep(1000);
example: http://jsfiddle.net/HrJku/1/
please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.
Wes McKinney (pandas' author) in Python for Data Analysis provides the following recipe:
groups = dict(list(gb))
which returns a dictionary whose keys are your group labels and whose values are DataFrames, i.e.
groups['foo']
will yield what you are looking for:
A B C
0 foo 1.624345 5
2 foo -0.528172 11
4 foo 0.865408 14
Microsoft now recommends using an IHttpClientFactory
with the following benefits:
HttpClient
instances. For example, a client named github could be
registered and configured to access GitHub. A default client can be
registered for general access.HttpClient
. Provides extensions for Polly-based middleware to take
advantage of delegating handlers in HttpClient
.HttpClientMessageHandler
instances. Automatic management avoids
common DNS (Domain Name System) problems that occur when manually
managing HttpClient
lifetimes.ILogger
) for all requests
sent through clients created by the factory.https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1
Setup:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient();
// Remaining code deleted for brevity.
POST example:
public class BasicUsageModel : PageModel
{
private readonly IHttpClientFactory _clientFactory;
public BasicUsageModel(IHttpClientFactory clientFactory)
{
_clientFactory = clientFactory;
}
public async Task CreateItemAsync(TodoItem todoItem)
{
var todoItemJson = new StringContent(
JsonSerializer.Serialize(todoItem, _jsonSerializerOptions),
Encoding.UTF8,
"application/json");
var httpClient = _clientFactory.CreateClient();
using var httpResponse =
await httpClient.PostAsync("/api/TodoItems", todoItemJson);
httpResponse.EnsureSuccessStatusCode();
}
Simply add below maven jar version in properties tag in pom.xml, <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
Then follow below steps,
Step 1: mvn clean
Step 2 : update project
Problem solved for me! You should also try this :)
According to MSDN:
By initializing strings with the
Empty
value instead ofnull
, you can reduce the chances of aNullReferenceException
occurring.
Always using IsNullOrEmpty()
is good practice nevertheless.
Put the date in single quotes and move the parenthesis (after the 'yes'
) to the end:
INSERT INTO custorder
VALUES ('Kevin', 'yes' , STR_TO_DATE('1-01-2012', '%d-%m-%Y') ) ;
^ ^
---parenthesis removed--| and added here ------|
But you can always use dates without STR_TO_DATE()
function, just use the (Y-m-d) '20120101'
or '2012-01-01'
format. Check the MySQL docs: Date and Time Literals
INSERT INTO custorder
VALUES ('Kevin', 'yes', '2012-01-01') ;
Limit The Query To Display Only The Top 3 Highest Paid Employees. : Query « Oracle PL / SQL
create table employee(
emp_no integer primary key
,lastname varchar2(20) not null
,salary number(3)
);
insert into employee(emp_no,lastname,salary)
values(1,'Tomy',2);
insert into employee(emp_no,lastname,salary)
values(2,'Jacky',3);
insert into employee(emp_no,lastname,salary)
values(3,'Joey',4);
insert into employee(emp_no,lastname,salary)
values(4,'Janey',5);
select lastname, salary
from (SELECT lastname, salary FROM employee ORDER BY salary DESC)
where rownum <= 3 ;
OUTPUT
LASTNAME SALARY
-------------------- ----------
Janey 5
Joey 4
Jacky 3
drop table employee;
With the recent update to melt.data.table
, we can now melt multiple columns. With that, we can do:
require(data.table) ## 1.9.5
melt(setDT(df), id=1:2, measure=patterns("^Q3.2", "^Q3.3"),
value.name=c("Q3.2", "Q3.3"), variable.name="loop_number")
# id time loop_number Q3.2 Q3.3
# 1: 1 2009-01-01 1 -0.433978480 0.41227209
# 2: 2 2009-01-02 1 -0.567995351 0.30701144
# 3: 3 2009-01-03 1 -0.092041353 -0.96024077
# 4: 4 2009-01-04 1 1.137433487 0.60603396
# 5: 5 2009-01-05 1 -1.071498263 -0.01655584
# 6: 6 2009-01-06 1 -0.048376809 0.55889996
# 7: 7 2009-01-07 1 -0.007312176 0.69872938
You can get the development version from here.
I am working with Meteor and I just got the same problem. The cause of my bug was this:
{{#if tourmanager}}
{{>contactInformation tourmanager}}
{{else}}
<a href="#addArtistTourmanagerModal" data-toggle="modal"><i class="fa fa-plus"></i> Tourmanager toevoegen</a>
{{>addArtistTourmanagerModal}}
{{/if}}
As you can see I added the modal in the else, so when my modal updated the contactinformation the if had another state. This caused the modal template to be left out of the DOM just before it would close.
The solution: move the modal out of the if-else:
{{#if tourmanager}}
{{>contactInformation tourmanager}}
{{else}}
<a href="#addArtistTourmanagerModal" data-toggle="modal"><i class="fa fa-plus"></i> Tourmanager toevoegen</a>
{{>addArtistTourmanagerModal}}
{{/if}}
You could use a CURSOR in this case:
DECLARE @id INT
DECLARE @name NVARCHAR(100)
DECLARE @getid CURSOR
SET @getid = CURSOR FOR
SELECT table.id,
table.name
FROM table
OPEN @getid
FETCH NEXT
FROM @getid INTO @id, @name
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC stored_proc @varName=@id, @otherVarName='test', @varForName=@name
FETCH NEXT
FROM @getid INTO @id, @name
END
CLOSE @getid
DEALLOCATE @getid
Modified to show multiple parameters from the table.
I would like to thank the person who posted the answer, but he has deleted the post. We can do it like this.
$("#yourElem").uploadify({
'uploader': ...,
'script': ...
'fileExt' : '*.jpg;*.gif;', //add allowed extensions
.....,
'onSelect': function(e, q, f) {
var validExtensions = ['jpg','gif']; //array of valid extensions
var fileName = f.name;
var fileNameExt = fileName.substr(fileName.lastIndexOf('.') + 1);
if ($.inArray(fileNameExt, validExtensions) == -1){
alert("Invalid file type");
$("#yourElem").uploadifyCancel(q);
return false;
}
}
});
Thanks for the answer, it really worked...
The most efficient way to do this (believe it or not) is to make two variables and write a for
loop.
You can install pywin32 wheel packages from PYPI with PIP by pointing to this package: https://pypi.python.org/pypi/pypiwin32 No need to worry about first downloading the package, just use pip:
pip install pypiwin32
Currently I think this is "the easiest" way to get in working :) Hope this helps.
svn rm --keep-local folder_name
Note: In svn 1.5.4 svn rm deletes unversioned files even when --keep-local is specified. See http://svn.haxx.se/users/archive-2009-11/0058.shtml for more information.
If all you want to do is to switch from inline plots to interactive and back (so that you can pan/zoom), it is better to use %matplotlib magic.
#interactive plotting in separate window
%matplotlib qt
and back to html
#normal charts inside notebooks
%matplotlib inline
%pylab magic imports a bunch of other things and may even result in a conflict. It does "from pylab import *".
You also can use new notebook backend (added in matplotlib 1.4):
#interactive charts inside notebooks, matplotlib 1.4+
%matplotlib notebook
If you want to have more interactivity in your charts, you can look at mpld3 and bokeh. mpld3 is great, if you don't have ton's of data points (e.g. <5k+) and you want to use normal matplotlib syntax, but more interactivity, compared to %matplotlib notebook . Bokeh can handle lots of data, but you need to learn it's syntax as it is a separate library.
Also you can check out pivottablejs (pip install pivottablejs)
from pivottablejs import pivot_ui
pivot_ui(df)
However cool interactive data exploration is, it can totally mess with reproducibility. It has happened to me, so I try to use it only at the very early stage and switch to pure inline matplotlib/seaborn, once I got the feel for the data.
# Switch delimiter to //, so phpMyAdmin will not execute it line by line.
DELIMITER //
CREATE PROCEDURE usp_rateChapter12
(IN numRating_Chapter INT(11) UNSIGNED,
IN txtRating_Chapter VARCHAR(250),
IN chapterName VARCHAR(250),
IN addedBy VARCHAR(250)
)
BEGIN
DECLARE numRating_Chapter INT;
DECLARE txtRating_Chapter VARCHAR(250);
DECLARE chapterName1 VARCHAR(250);
DECLARE addedBy1 VARCHAR(250);
DECLARE chapterId INT;
DECLARE studentId INT;
SET chapterName1 = chapterName;
SET addedBy1 = addedBy;
SET chapterId = (SELECT chapterId
FROM chapters
WHERE chaptername = chapterName1);
SET studentId = (SELECT Id
FROM students
WHERE email = addedBy1);
SELECT chapterId;
SELECT studentId;
INSERT INTO ratechapter (rateBy, rateText, rateLevel, chapterRated)
VALUES (studentId, txtRating_Chapter, numRating_Chapter,chapterId);
END //
//DELIMITER;
You should try using quotes.
cmd /C "C:\Program Files (x86)\WinRar\Rar.exe" a "D:\Hello 2\File.rar" "D:\Hello 2\*.*"
import java.io.*;
class AgeCalculator
{
public static void main(String args[])
{
InputStreamReader ins=new InputStreamReader(System.in);
BufferedReader hey=new BufferedReader(ins);
try
{
System.out.println("Please enter your name: ");
String name=hey.readLine();
System.out.println("Please enter your birth date: ");
String date=hey.readLine();
System.out.println("please enter your birth month:");
String month=hey.readLine();
System.out.println("please enter your birth year:");
String year=hey.readLine();
System.out.println("please enter current year:");
String cYear=hey.readLine();
int bDate = Integer.parseInt(date);
int bMonth = Integer.parseInt(month);
int bYear = Integer.parseInt(year);
int ccYear=Integer.parseInt(cYear);
int age;
age = ccYear-bYear;
int totalMonth=12;
int yourMonth=totalMonth-bMonth;
System.out.println(" Hi " + name + " your are " + age + " years " + yourMonth + " months old ");
}
catch(IOException err)
{
System.out.println("");
}
}
}
Glide 4.6
1. To Load gif
GlideApp.with(context)
.load(R.raw.gif) // or url
.into(imageview);
2. To get the file object
GlideApp.with(context)
.asGif()
.load(R.raw.gif) //or url
.into(new SimpleTarget<GifDrawable>() {
@Override
public void onResourceReady(@NonNull GifDrawable resource, @Nullable Transition<? super GifDrawable> transition) {
resource.start();
//resource.setLoopCount(1);
imageView.setImageDrawable(resource);
}
});
For those using Swift 3, the equivalent method for the accepted answer is:
movieArr.sorted { $0.Name < $1.Name }
This may also happen if you have a faulty or accidental equation in your csv file. i.e - One of the cells in your csv file starts with an equals sign (=) (An excel equation) which will, in turn throw an error. If you fix, or remove this equation by getting rid of the equals sign, it should solve the ORA-06502 error.
There are a few details missing from the previous explanations. To better understand how partitioning and bucketing works, you should look at how data is stored in hive. Let's say you have a table
CREATE TABLE mytable (
name string,
city string,
employee_id int )
PARTITIONED BY (year STRING, month STRING, day STRING)
CLUSTERED BY (employee_id) INTO 256 BUCKETS
then hive will store data in a directory hierarchy like
/user/hive/warehouse/mytable/y=2015/m=12/d=02
So, you have to be careful when partitioning, because if you for instance partition by employee_id and you have millions of employees, you'll end up having millions of directories in your file system. The term 'cardinality' refers to the number of possible value a field can have. For instance, if you have a 'country' field, the countries in the world are about 300, so cardinality would be ~300. For a field like 'timestamp_ms', which changes every millisecond, cardinality can be billions. In general, when choosing a field for partitioning, it should not have a high cardinality, because you'll end up with way too many directories in your file system.
Clustering aka bucketing on the other hand, will result with a fixed number of files, since you do specify the number of buckets. What hive will do is to take the field, calculate a hash and assign a record to that bucket. But what happens if you use let's say 256 buckets and the field you're bucketing on has a low cardinality (for instance, it's a US state, so can be only 50 different values) ? You'll have 50 buckets with data, and 206 buckets with no data.
Someone already mentioned how partitions can dramatically cut the amount of data you're querying. So in my example table, if you want to query only from a certain date forward, the partitioning by year/month/day is going to dramatically cut the amount of IO. I think that somebody also mentioned how bucketing can speed up joins with other tables that have exactly the same bucketing, so in my example, if you're joining two tables on the same employee_id, hive can do the join bucket by bucket (even better if they're already sorted by employee_id since it's going to mergesort parts that are already sorted, which works in linear time aka O(n) ).
So, bucketing works well when the field has high cardinality and data is evenly distributed among buckets. Partitioning works best when the cardinality of the partitioning field is not too high.
Also, you can partition on multiple fields, with an order (year/month/day is a good example), while you can bucket on only one field.
CAUSE: "Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app." In this case, "ACCESS_FINE_LOCATION" is a "dangerous permission and for that reason, you get this 'java.lang.SecurityException: "gps" location provider requires ACCESS_FINE_LOCATION permission.' error (https://developer.android.com/training/permissions/requesting.html).
SOLUTION: Implementing the code provided at https://developer.android.com/training/permissions/requesting.html under the "Request the permissions you need" and "Handle the permissions request response" headings.
This is useful to check the status of autocommit;
select @@autocommit;
if it related to hosting site then ask to your hosting or if you want to enable it in local machine then check this youtube step by step tutorial related to enabling rewrite module in wamp apache
https://youtu.be/xIspOX9FuVU?t=1m43s
Wamp server icon -> Apache -> Apache Modules and check the rewrite module option
it should be checked but after that wamp require restart all services
Python 2, using lambda
>>> head, tail = (lambda lst: (lst[0], lst[1:]))([1, 1, 2, 3, 5, 8, 13, 21, 34, 55])
>>> head
1
>>> tail
[1, 2, 3, 5, 8, 13, 21, 34, 55]
What is currentWorksheet
? It works if you use the built-in ActiveSheet
.
dataStartRow=1
dataStartCol=1
dataEndRow=4
dataEndCol=4
Set currentWorksheet=ActiveSheet
dataTable = currentWorksheet.Range(currentWorksheet.Cells(dataStartRow, dataStartCol), currentWorksheet.Cells(dataEndRow, dataEndCol))
I did a little experimenting to see if I could keep the database name as part of the url. I prefer the promise syntax but it should still work for the callback syntax. Notice below that client.db() is called without passing any parameters.
MongoClient.connect(
'mongodb://localhost:27017/mytestingdb',
{ useNewUrlParser: true}
)
.then(client => {
// The database name is part of the url. client.db() seems
// to know that and works even without a parameter that
// relays the db name.
let db = client.db();
console.log('the current database is: ' + db.s.databaseName);
// client.close() if you want to
})
.catch(err => console.log(err));
My package.json lists monbodb ^3.2.5.
The 'useNewUrlParser' option is not required if you're willing to deal with a deprecation warning. But it is wise to use at this point until version 4 comes out where presumably the new driver will be the default and you won't need the option anymore.
For those using frameworks that compress, bundle, and minify files, make sure you define each dependency explicitly as these frameworks tend to rename your variables. That happened to me while using ASP.NET BundleConfig.cs
to bundle my app scripts together.
Before
app.config(function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'list.html',
controller: 'ListController'
}).
when('/items/:itemId', {
templateUrl: 'details.html',
controller: 'DetailsController'
}).
otherwise({
redirectTo: '/'
});
});
After
app.config(["$routeProvider", function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'list.html',
controller: 'ListController'
}).
when('/items/:itemId', {
templateUrl: 'details.html',
controller: 'DetailsController'
}).
otherwise({
redirectTo: '/'
});
}]);
Read more here about Angular Dependency Annotation.
In my opinion a For
loop should be used when a fixed amount of iterations will be done and they won't be stopped before every iteration has been completed. In the other case where you want to quit earlier I prefer to use a While
loop. Even if you read those two little words it seems more logical. Some examples:
for (int i=0;i<10;i++) {
System.out.println(i);
}
When I read this code quickly I will know for sure it will print out 10 lines and then go on.
for (int i=0;i<10;i++) {
if (someCondition) break;
System.out.println(i);
}
This one is already less clear to me. Why would you first state you will take 10 iterations, but then inside the loop add some extra conditions to stop sooner?
I prefer the previous example written in this way (even when it's a little more verbose, but that's only with 1 line more):
int i=0;
while (i<10 && !someCondition) {
System.out.println(i);
i++;
}
Everyone who will read this code will see immediatly that there is an extra condition that might terminate the loop earlier.
Ofcourse in very small loops you can always discuss that every programmer will notice the break statement. But I can tell from my own experience that in larger loops those breaks can be overseen. (And that brings us to another topic to start splitting up code in smaller chunks)
You may use the typescript getter method for this scenario. Like this
public get width() {
return window.innerWidth;
}
And use that in template like this:
<section [ngClass]="{ 'desktop-view': width >= 768, 'mobile-view': width < 768
}"></section>
You won't need any event handler to check for resizing/ of window, this method will check for size every time automatically.
You'll have to have a ContextLoaderListener in your web.xml - It loads your configuration files.
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
You need to understand the difference between Web application context and root application context .
In the web MVC framework, each DispatcherServlet has its own WebApplicationContext, which inherits all the beans already defined in the root WebApplicationContext. These inherited beans defined can be overridden in the servlet-specific scope, and new scope-specific beans can be defined local to a given servlet instance.
The dispatcher servlet's application context is a web application context which is only applicable for the Web classes . You cannot use these for your middle tier layers . These need a global app context using ContextLoaderListener .
Read the spring reference here for spring mvc .
When you use a web service you have a client and a server:
When you use a message queue like RabbitMQ, Beanstalkd, ActiveMQ, IBM MQ Series, Tuxedo you expect different and more fault tolerant results:
Message Queues has a lot more features but this is some rule of thumb to decide if you want to handle error conditions yourself or leave them to the message queue.
Try adding this:
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls";
By looking at your debug logs, you can notice that the failing PhpMailer log shows this:
(..snip..)
SMTP -> ERROR: AUTH not accepted from server: 250 orion.bommtempo.net.br Hello admin-teste.bommtempo.com.br [200.155.129.6]
(..snip..)
503 AUTH command used when not advertised
(..snip..)
While your successful PEAR log shows this:
DEBUG: Send: STARTTLS
DEBUG: Recv: 220 TLS go ahead
My guess is that explicitly asking PHPMailer to use TLS will put it on the right track.
Also, make sure you're using the latest versin of PHPMailer.
I solve it by download the reportviewer.exe and install it. After the installation, all related assemblies will be available in C:\Windows\assembly\GAC_MSIL, then you can refer it in web config
There's a great example in the AngularJS docs.
It's very well commented and should get you pointed in the right direction.
A simple example, maybe more so what you're looking for is below:
HTML
<div ng-app="myDirective" ng-controller="x">
<input type="text" ng-model="test" my-directive>
</div>
JavaScript
angular.module('myDirective', [])
.directive('myDirective', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
scope.$watch(attrs.ngModel, function (v) {
console.log('value changed, new value is: ' + v);
});
}
};
});
function x($scope) {
$scope.test = 'value here';
}
Edit: Same thing, doesn't require ngModel
jsfiddle:
JavaScript
angular.module('myDirective', [])
.directive('myDirective', function () {
return {
restrict: 'A',
scope: {
myDirective: '='
},
link: function (scope, element, attrs) {
// set the initial value of the textbox
element.val(scope.myDirective);
element.data('old-value', scope.myDirective);
// detect outside changes and update our input
scope.$watch('myDirective', function (val) {
element.val(scope.myDirective);
});
// on blur, update the value in scope
element.bind('propertychange keyup paste', function (blurEvent) {
if (element.data('old-value') != element.val()) {
console.log('value changed, new value is: ' + element.val());
scope.$apply(function () {
scope.myDirective = element.val();
element.data('old-value', element.val());
});
}
});
}
};
});
function x($scope) {
$scope.test = 'value here';
}
If a case-insensitive comparison is acceptable, just use =
:
=IF(A1="ENG",1,0)
This is the shortest I've found, though it does return the digits as strings:
let num = 12345;
[...num+''] //["1", "2", "3", "4", "5"]
Or use this to get back integers:
[...num+''].map(n=>+n) //[1, 2, 3, 4, 5]
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
You need to do empty_set = set()
to initialize an empty set. {}
is an empty dict
.
From Github guide: Getting your project to Github:(using Github desktop version)
Set up your project in GitHub Desktop
The easiest way to get your project into GitHub Desktop is to drag the folder which contains your project files onto the main application screen.
If you are dragging in an existing Git repository, you can skip ahead and push your code to GitHub.com.
If the folder isn’t a Git repository yet, GitHub Desktop will prompt you to turn it into a repository. Turning your project into a Git repository won’t delete or ruin the files in your folder—it will simply create some hidden files that allow Git to do its magic.
In Windows it looks like this:(GitHub desktop 3.0.5.2)
this is not the most geeky way but it works.
@keithwyland answer is great. Here's a SCSS mixin:
@mixin font-awesome($content){
font-family: FontAwesome;
font-weight: normal;
font-style: normal;
display: inline-block;
text-decoration: inherit;
content: $content;
}
Usage:
@include font-awesome("\f054");
You can also use something like the code below. I used lombok to avoid writing some of the boilerplate codes for getters and constructor.
@AllArgsConstructor
@Getter
public enum RetroDeviceStatus {
DELIVERED(0,"Delivered"),
ACCEPTED(1, "Accepted"),
REJECTED(2, "Rejected"),
REPAIRED(3, "Repaired");
private final Integer value;
private final String stringValue;
@Override
public String toString() {
return this.stringValue;
}
}
If you tail the error log and reload the page, you should see some more information as to the exact problem.
Grab the environment variables so ${APACHE_LOG_DIR} will actually work...
source /etc/apache2/envvars
Then tail and watch...
tail -f ${APACHE_LOG_DIR}/error.log
If you have complex routing needs and want a built-in GUI to monitor the broker, then RabbitMQ might be best for your application. Otherwise, if you’re looking for a message broker to handle high throughput and provide access to stream history, Kafka is the likely the better choice.
Use outline:none
to anchor tag class
EDIT: After further investigation, my original assumption that this was an anomaly (bug?) of the declare @var datatype = value
syntax is incorrect.
I modified your script for 2005 since that syntax is not supported, then tried the modified version on 2008. In 2005, I get the Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes.
error message. In 2008, the modified script is still successful.
declare @KMsg varchar(max); set @KMsg = REPLICATE('a',1024);
declare @MMsg varchar(max); set @MMsg = REPLICATE(@KMsg,1024);
declare @GMsg varchar(max); set @GMsg = REPLICATE(@MMsg,1024);
declare @GGMMsg varchar(max); set @GGMMsg = @GMsg + @GMsg + @MMsg;
select LEN(@GGMMsg)
If you highlight the method Assert.assertEquals(val1, val2)
and hit Ctrl + Shift + M (Add Import), it will add it as a static import, at least in Eclipse 3.4.
It is not at all clear what the OP meant (even after some back-and-forth in the comments), but here are two answers to possible interpretations of the question:
Use raw_input
in Python 2.x, and input
in Python 3. (These are built in, so you don't need to import anything to use them; you just have to use the right one for your version of python.)
For example:
user_input = raw_input("Some input please: ")
More details can be found here.
So, for example, you might have a script that looks like this
# First, do some work, to show -- as requested -- that
# the user input doesn't need to come first.
from __future__ import print_function
var1 = 'tok'
var2 = 'tik'+var1
print(var1, var2)
# Now ask for input
user_input = raw_input("Some input please: ") # or `input("Some...` in python 3
# Now do something with the above
print(user_input)
If you saved this in foo.py
, you could just call the script from the command line, it would print out tok tiktok
, then ask you for input. You could enter bar baz
(followed by the enter key) and it would print bar baz
. Here's what that would look like:
$ python foo.py
tok tiktok
Some input please: bar baz
bar baz
Here, $
represents the command-line prompt (so you don't actually type that), and I hit Enter
after typing bar baz
when it asked for input.
Suppose you have a script named foo.py
and want to call it with arguments bar
and baz
from the command line like
$ foo.py bar baz
(Again, $
represents the command-line prompt.) Then, you can do that with the following in your script:
import sys
arg1 = sys.argv[1]
arg2 = sys.argv[2]
Here, the variable arg1
will contain the string 'bar'
, and arg2
will contain 'baz'
. The object sys.argv
is just a list containing everything from the command line. Note that sys.argv[0]
is the name of the script. And if, for example, you just want a single list of all the arguments, you would use sys.argv[1:]
.
Note as of Symfony 3.3 EntityManager is depreciated. Use EntityManagerInterface instead.
namespace AppBundle\Service;
use Doctrine\ORM\EntityManagerInterface;
class Someclass {
protected $em;
public function __construct(EntityManagerInterface $entityManager)
{
$this->em = $entityManager;
}
public function somefunction() {
$em = $this->em;
...
}
}
$pos = $name.IndexOf(";")
$leftPart = $name.Substring(0, $pos)
$rightPart = $name.Substring($pos+1)
Internally, PowerShell uses the String class.
OK. After trying out some error handling, I figured out how to solve the issue I was having.
Here's an example of how to make this work (let me know if there's something I'm missing) :
SET XACT_ABORT OFF ; -- > really important to set that to OFF
BEGIN
DECLARE @Any_error int
DECLARE @SSQL varchar(4000)
BEGIN TRANSACTION
INSERT INTO Table1(Value1) VALUES('Value1')
SELECT @Any_error = @@ERROR
IF @Any_error<> 0 AND @Any_error<>2627 GOTO ErrorHandler
INSERT INTO Table1(Value1) VALUES('Value1')
SELECT @Any_error = @@ERROR
IF @Any_error<> 0 AND @Any_error<>2627 GOTO ErrorHandler
INSERT INTO Table1(Value1) VALUES('Value2')
SELECT @Any_error = @@ERROR
IF @Any_error<> 0 AND @Any_error<>2627 GOTO ErrorHandler
ErrorHandler:
IF @Any_error = 0 OR @Any_error=2627
BEGIN
PRINT @ssql
COMMIT TRAN
END
ELSE
BEGIN
PRINT @ssql
ROLLBACK TRAN
END
END
As a result of the above Transaction, Table1 will have the following values Value1, Value2.
2627 is the error code for Duplicate Key by the way.
Thank you all for the prompt reply and helpful suggestions.
As of Rails 4.2, you can use the config.x
property:
# config/application.rb (or config/custom.rb if you prefer)
config.x.colours.options = %w[white blue black red green]
config.x.colours.default = 'white'
Which will be available as:
Rails.configuration.x.colours.options
# => ["white", "blue", "black", "red", "green"]
Rails.configuration.x.colours.default
# => "white"
Another method of loading custom config:
# config/colours.yml
default: &default
options:
- white
- blue
- black
- red
- green
default: white
development:
*default
production:
*default
# config/application.rb
config.colours = config_for(:colours)
Rails.configuration.colours
# => {"options"=>["white", "blue", "black", "red", "green"], "default"=>"white"}
Rails.configuration.colours['default']
# => "white"
In Rails 5 & 6, you can use the configuration
object directly for custom configuration, in addition to config.x
. However, it can only be used for non-nested configuration:
# config/application.rb
config.colours = %w[white blue black red green]
It will be available as:
Rails.configuration.colours
# => ["white", "blue", "black", "red", "green"]
on server console:
$ mysql -u root -p -e "SET GLOBAL sql_mode = 'NO_ENGINE_SUBSTITUTION';"
There is another way to do it, using org.apache.commons.io.IOUtils
to extract the String from the request
String jsonString = IOUtils.toString(request.getInputStream());
Then you can do whatever you want, convert it to JSON
or other object with Gson
, etc.
JSONObject json = new JSONObject(jsonString);
MyObject myObject = new Gson().fromJson(jsonString, MyObject.class);
In order to delete only messages from the queue use :
sudo rabbitmqctl --node <nodename> purge_queue <queue_name>
In order to delete a queue which is empty(--if-empty) or has no consumers(--if-unused) use :
sudo rabbitmqctl --node <nodename> delete_queue <queue_name> --if-empty
or
sudo rabbitmqctl --node <nodename> delete_queue <queue_name> --if-unused
Google HTTP Java Client looks good to me because it can run on Android and App Engine as well.
For me I switched a call for my collection view header where I was registering the nib to registering the class. That fixed it.
In case anyone's searching for this later on, a nice trick to get rid of those jagged edges on CSS transformations in Chrome is to add the CSS property -webkit-backface-visibility
with a value of hidden
. In my own tests, this has completely smoothed them out. Hope that helps.
-webkit-backface-visibility: hidden;
Below snippet is sufficient to understand how I encountered the same issue but in a different scenario and how I solved it using the guidance in the accepted answer. In my case I was trying to log the keys of object present in the 0th index of the 'defaultViewData' array using Object.keys() method.
defaultViewData = [{"name": "DEFAULT_VIEW_PLP","value": {"MSH25": "LIST"}}]
console.log('DEFAULT_VIEW', Object.keys(this.props.defaultViewData[0]));
The console.log was not getting printed and I was getting the same error as posted in this question. To prevent that error I added below condition
if(this.props.defaultViewData[0]) {
console.log('DEFAULT_VIEW', Object.keys(this.props.defaultViewData[0]));
}
Adding this check ensured that I didn't get this error. I hope this helps for someone.
Note: This is React.js code. (although to understand the problem it doesn't matter).
Because it's been a several years since this question was first asked, the other answers are outdated or incomplete.
Here's the code for a modern implementation using jQuery:
$( 'div#1' ).on( 'click', function( event ) {
if ( event.ctrlKey ) {
//is ctrl + click
} else {
//normal click
}
} );
As for detecting right-clicks, this was correctly provided by another user but I'll list it here just to have everything in one place.
$( 'div#1' ).on( 'contextmenu', function( event ) {
// right-click handler
} ) ;
I think the answer located in this article: https://arjunphp.com/laravel-5-5-log-eloquent-queries/
is fast and simple to achieve query logging.
You just have to add to the AppServiceProvider
in the boot
method a callback to listen to DB queries:
namespace App\Providers;
use DB;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
DB::listen(function($query) {
logger()->info($query->sql . print_r($query->bindings, true));
});
}
}
You need to use <script type="text/javascript"> </script>
unless you're using html5. In that case you are encouraged to prefer <script> ... </script>
(because type attribute is specified by default to that value)
The threading.Timer
object (documentation) can count the ten seconds, then get it to set an Event flag indicating that the loop should exit.
The documentation indicates that the timing might not be exact - you'd have to test whether it's accurate enough for your game.
Old thread but I had the same problem now. If anyone encounters this he'll probably find this answer:
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);
This will work only if you add the ImageView as a subView to a LinearLayout. If you add it to a RelativeLayout you will need to call:
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);
All this is about cultures. If you have any other culture than "US English" (and also as good manners of development), you should use something like this:
var d = Convert.ToDecimal("1.2345", new CultureInfo("en-US"));
// (or 1,2345 with your local culture, for instance)
(obviously, you should replace the "en-US" with the culture of your number local culture)
the same way, if you want to do ToString()
d.ToString(new CultureInfo("en-US"));
{ "date" : "1000000" }
in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }
It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback)
and if that works, you have a typing issue.
You should be careful about exceptions during killing processes. So you may use this script:
USE master;
GO
DECLARE @kill varchar(max) = '';
SELECT @kill = @kill + 'BEGIN TRY KILL ' + CONVERT(varchar(5), spid) + ';' + ' END TRY BEGIN CATCH END CATCH ;' FROM master..sysprocesses
EXEC (@kill)
Probably not simpler, but intriguing and ugly:
List<String> newList = new ArrayList<String>() { { addAll(listOne); addAll(listTwo); } };
Don't use it in production code... ;)
This my workaround to solve this problem and check the valid internet connection because as they said that Network info class cannot give you the expected result and it may return true when network connected but no internet.
So this my COMPLETE WORKAROUND based on @Levite Answer:
First you must have AsynckTask for checking Network availability and this is mine:
public class Connectivity {
private static final String TAG = "Connectivity";
private static boolean hasConnected = false, hasChecked = false;
private InternetListener internetListener;
private Activity activity;
public Connectivity(InternetListener internetListener, Activity activity) {
this.internetListener = internetListener;
this.activity = activity;
}
public void startInternetListener() {
CheckURL checkURL = new CheckURL(activity);
checkURL.execute();
long startTime = System.currentTimeMillis();
while (true) {
if (hasChecked && hasConnected) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
internetListener.onConnected();
}
});
checkURL.cancel(true);
return;
}
// check if time
if (System.currentTimeMillis() - startTime >= 1000) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
internetListener.onDisconnected();
}
});
checkURL.cancel(true);
return;
}
}
//return hasConnected;
}
class CheckURL extends AsyncTask<Void, Void, Boolean> {
private Activity activity;
public CheckURL(Activity activity) {
this.activity = activity;
}
@Override
protected Boolean doInBackground(Void... params) {
if (!isNetWorkAvailable(activity)) {
Log.i(TAG, "Internet not available!");
return false;
}
int timeoutMs = 3000;
try {
Socket sock = new Socket();
SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53);
sock.connect(sockaddr, timeoutMs);
sock.close();
Log.i(TAG, "Internet available :)");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
@Override
protected void onPostExecute(Boolean result) {
hasChecked = true;
hasConnected = result;
super.onPostExecute(result);}}
private static final String TAG = "Connectivity";
private static boolean isNetWorkAvailable(Activity activity) {
ConnectivityManager connectivityManager =
(ConnectivityManager)
activity.getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo =
null;
if (connectivityManager != null) {
networkInfo =
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
}
boolean isConnected;
boolean isWifiAvailable = false;
if (networkInfo != null) {
isWifiAvailable = networkInfo.isAvailable();
}
boolean isWifiConnected = false;
if (networkInfo != null) {
isWifiConnected = networkInfo.isConnected();
}
if (connectivityManager != null) {
networkInfo =
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
}
boolean isMobileAvailable = false;
if (networkInfo != null) {
isMobileAvailable = networkInfo.isAvailable();
}
boolean isMobileConnected = false;
if (networkInfo != null) {
isMobileConnected = networkInfo.isConnected();
}
isConnected = (isMobileAvailable && isMobileConnected) ||
(isWifiAvailable && isWifiConnected);
return (isConnected);}
}}
private static boolean isNetWorkAvailable(Context context) {
ConnectivityManager connectivityManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo =
null;
if (connectivityManager != null) {
networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
}
boolean isConnected;
boolean isWifiAvailable = false;
if (networkInfo != null) {
isWifiAvailable = networkInfo.isAvailable();
}
boolean isWifiConnected = false;
if (networkInfo != null) {
isWifiConnected = networkInfo.isConnected();
}
if (connectivityManager != null) {
networkInfo =
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
}
boolean isMobileAvailable = false;
if (networkInfo != null) {
isMobileAvailable = networkInfo.isAvailable();
}
boolean isMobileConnected = false;
if (networkInfo != null) {
isMobileConnected = networkInfo.isConnected();
}
isConnected = (isMobileAvailable && isMobileConnected) ||
(isWifiAvailable && isWifiConnected);
return (isConnected);
}
}
After that you should create another thread to start AscnkTask And listen for result with the InternetListener.
public interface InternetListener {
void onConnected();
void onDisconnected();
}
And the Thread that is waiting for AsynckTask result you can put it in Utility class:
private static Thread thread;
public static void startNetworkListener(Context context, InternetListener
internetListener) {
if (thread == null){
thread = new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
new Connectivity(internetListener,context).startInternetListener();
}
});
}
thread.start();
}
Finally call the startNetworkListener() method and listen for result.
example in activity from My Utils.java class :
Utils.startNetworkListener(this, new InternetListener() {
@Override
public void onConnected() {
// do your work when internet available.
}
@Override
public void onDisconnected() {
// do your work when no internet available.
}
});
Happy Coding :).
You can use split(" ")
method of the String
class and can get each word as code given below:
String s = "I want to walk my dog";
String []strArray=s.split(" ");
for(int i=0; i<strArray.length;i++) {
System.out.println(strArray[i]);
}
Test if the a variable is an array before getting the first element. When dynamically creating the array if it is set to null you get an error.
For Example:
if(is_array($array))
{
reset($array);
$first = key($array);
}
You can wrap the disabled button and put the tooltip on the wrapper:
<div class="tooltip-wrapper" data-title="Dieser Link führt zu Google">
<button class="btn btn-default" disabled>button disabled</button>
</div>
If the wrapper has display:inline
then the tooltip doesn't seem to work. Using display:block
and display:inline-block
seem to work fine. It also appears to work fine with a floated wrapper.
UPDATE Here's an updated JSFiddle that works with the latest Bootstrap (3.3.6). Thanks to @JohnLehmann for suggesting pointer-events: none;
for the disabled button.
If you're creating a framework the whole idea is to make it portable. Tying a framework to the app delegate defeats the purpose of building a framework. What is it you need the app delegate for?
A simple forEach
loop solves this quite well:
let text = 'the red apple and the green ball';
const toStrip = ['red', 'green'];
toStrip.forEach(x => {
text = text.replace(x, '');
});
console.log(text);
// logs -> the apple and the ball
If anybody else is facing this issue in Git for Windows and do not have curl-ca-bundle.crt
anywhere on your system even after reinstalling, this is the process I followed:
curl-**.**.*/lib
in the command line./mk-ca-bundle.prl
ca-bundle.crt
to your git path and update the config as listed in other answersShout out to this gist for helping me get the installation done.
I had the same need as the original poster, except that my client's db schema is a nullable bit (ie, allows for True/False/NULL). Here's some code I wrote to both display Yes/No and handle potential nulls.
Code-Behind:
public string ConvertNullableBoolToYesNo(object pBool)
{
if (pBool != null)
{
return (bool)pBool ? "Yes" : "No";
}
else
{
return "No";
}
}
Front-End:
<%# ConvertNullableBoolToYesNo(Eval("YOUR_FIELD"))%>
Alternatives to Native Support of Java Operator Overloading
Since Java doesn't have operator overloading, here are some alternatives you can look into:
If anyone is aware of others, please comment, and I will add it to this list.
First, you're missing some parentheses in your conditional:
if ($("#about").hasClass("opened")) {
$("#about").animate({right: "-700px"}, 2000);
}
But you can also simplify this to:
$('#about.opened').animate(...);
If #about
doesn't have the opened
class, it won't animate.
If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)
The error message is quite descriptive, try:
ALTER TABLE MyTable ADD Stage INT NOT NULL DEFAULT '-';
Below two commands are most useful
mvn clean package -Dmaven.test.skip=true
mvn clean package -DskipTests
Thanks
All this peace of code put into *.bat file and run all at once:
My code for creating user in oracle. crate_drop_user.sql file
drop user "USER" cascade;
DROP TABLESPACE "USER";
CREATE TABLESPACE USER DATAFILE 'D:\ORA_DATA\ORA10\USER.ORA' SIZE 10M REUSE
AUTOEXTEND
ON NEXT 5M EXTENT MANAGEMENT LOCAL
SEGMENT SPACE MANAGEMENT AUTO
/
CREATE TEMPORARY TABLESPACE "USER_TEMP" TEMPFILE
'D:\ORA_DATA\ORA10\USER_TEMP.ORA' SIZE 10M REUSE AUTOEXTEND
ON NEXT 5M EXTENT MANAGEMENT LOCAL
UNIFORM SIZE 1M
/
CREATE USER "USER" PROFILE "DEFAULT"
IDENTIFIED BY "user_password" DEFAULT TABLESPACE "USER"
TEMPORARY TABLESPACE "USER_TEMP"
/
alter user USER quota unlimited on "USER";
GRANT CREATE PROCEDURE TO "USER";
GRANT CREATE PUBLIC SYNONYM TO "USER";
GRANT CREATE SEQUENCE TO "USER";
GRANT CREATE SNAPSHOT TO "USER";
GRANT CREATE SYNONYM TO "USER";
GRANT CREATE TABLE TO "USER";
GRANT CREATE TRIGGER TO "USER";
GRANT CREATE VIEW TO "USER";
GRANT "CONNECT" TO "USER";
GRANT SELECT ANY DICTIONARY to "USER";
GRANT CREATE TYPE TO "USER";
create file import.bat and put this lines in it:
SQLPLUS SYSTEM/systempassword@ORA_alias @"crate_drop_user.SQL"
IMP SYSTEM/systempassword@ORA_alias FILE=user.DMP FROMUSER=user TOUSER=user GRANTS=Y log =user.log
Be carefull if you will import from one user to another. For example if you have user named user1 and you will import to user2 you may lost all grants , so you have to recreate it.
Good luck, Ivan
By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.
In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.
The client code must set the withCredentials
property on the XMLHttpRequest
to true
in order to give permission.
However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials
header. Responding with this header to true
means that the server allows cookies (or other user credentials) to be included on cross-origin requests.
You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.
Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).
You can run this command from the DB2 command line processor (CLP) or from inside a SQL application by calling the ADMIN_CMD
stored procedure
EXPORT TO result.csv OF DEL MODIFIED BY NOCHARDEL
SELECT col1, col2, coln FROM testtable;
There are lots of options for IMPORT
and EXPORT
that you can use to create a data file that meets your needs. The NOCHARDEL
qualifier will suppress double quote characters that would otherwise appear around each character column.
Keep in mind that any SELECT
statement can be used as the source for your export, including joins or even recursive SQL. The export utility will also honor the sort order if you specify an ORDER BY
in your SELECT
statement.
I think you've just made up shorthand syntax for the border:
property there =)
Try simply:
border-right: 1px solid #000;
border-left: 1px solid #000;
I solved this by doing the following:
Thus the problem will go forever. Do build randomly and debug your C++ projects without any disturbance.
Knowing the version of Windows and SQL Server might be helpful in some cases. From the Native Client 10.0 I infer either SQL Server 2008 or SQL Server 2008 R2.
There are a few possible things to check, but I would check to see if 'priority boost' was configured on the SQL Server. This is a deprecated setting and will eventually be removed. The problem is that it can rob the operating system of needed resources. See the notes at:
http://msdn.microsoft.com/en-in/library/ms180943(v=SQL.105).aspx
If 'priority boost' has been configured to 1, then get it configured back to 0.
exec sp_configure 'priority boost', 0;
RECONFIGURE;
If you have a huge number of objects, this can (at times) be much faster:
try:
orgs[0]
# If you get here, it exists...
except IndexError:
# Doesn't exist!
On a project I'm working on with a huge database, not orgs
is 400+ ms and orgs.count()
is 250ms. In my most common use cases (those where there are results), this technique often gets that down to under 20ms. (One case I found, it was 6.)
Could be much longer, of course, depending on how far the database has to look to find a result. Or even faster, if it finds one quickly; YMMV.
EDIT: This will often be slower than orgs.count()
if the result isn't found, particularly if the condition you're filtering on is a rare one; as a result, it's particularly useful in view functions where you need to make sure the view exists or throw Http404. (Where, one would hope, people are asking for URLs that exist more often than not.)
The non-greedy regex modifiers are like their greedy counter-parts but with a ?
immediately following them:
* - zero or more
*? - zero or more (non-greedy)
+ - one or more
+? - one or more (non-greedy)
? - zero or one
?? - zero or one (non-greedy)
You are looking for:
db.Users.Attach(updatedUser);
var entry = db.Entry(updatedUser);
entry.Property(e => e.Email).IsModified = true;
// other changed properties
db.SaveChanges();
You can override the default css rules with this:
.table tbody tr > td.success {
background-color: #dff0d8 !important;
}
.table tbody tr > td.error {
background-color: #f2dede !important;
}
.table tbody tr > td.warning {
background-color: #fcf8e3 !important;
}
.table tbody tr > td.info {
background-color: #d9edf7 !important;
}
.table-hover tbody tr:hover > td.success {
background-color: #d0e9c6 !important;
}
.table-hover tbody tr:hover > td.error {
background-color: #ebcccc !important;
}
.table-hover tbody tr:hover > td.warning {
background-color: #faf2cc !important;
}
.table-hover tbody tr:hover > td.info {
background-color: #c4e3f3 !important;
}
!important
is needed as bootstrap actually colours the cells individually (afaik it's not possible to just apply background-color to a tr). I couldn't find any colour variables in my version of bootstrap but that's the basic idea anyway.
This wroks for me(in CoffeeScript)
$location.path '/url/path'
$scope.$apply() if (!$scope.$$phase)
tl;dr the "standards" are a hodge-podge mess; it depends who you ask!
Overall, there appears to be no MIME type image/jpg
. Yet, in practice, nearly all software handles image files named "*.jpg
" just fine.
This particular topic is confusing because the varying association of file name extension associated to a MIME type depends which organization created the table of file name extensions to MIME types. In other words, file name extension .jpg
could be many different things.
For example, here are three "complete lists" and one RFC that with varying JPEG Image format file name extensions and the associated MIME types.
.jfif
, .jfif-tbnl
, .jpe
, .jpeg
, .jpg
? image/jpeg
.jfif
, .jpe
, .jpeg
, .jpg
? image/pjpeg
.jpeg
, .jpg
? image/jpeg
.jpeg
, .jpg
? image/x-citrix-jpeg
.pjpeg
? image/pjpeg
jpg
not mentionedjpeg
? see RFC 2045 (no mention), see RFC 2046 ? image/jpeg
13JPEG
? video/JPEG
jpeg2000
? video/jpeg2000
jpm
? image/jpm
(JPEG 2000)jpx
? image/jpx
(JPEG 2000)vnd.sealedmedia.softseal.jpg
? image/vnd.sealedmedia.softseal.jpg
These "complete lists" and RFC do not have MIME type image/jpg
! But for MIME type image/jpeg
some lists do have varying file name extensions (.jpeg
, .jpg
, …). Other lists do not mention image/jpeg
.
Also, there are different types of JPEG Image formats (e.g. Progressive JPEG Image format, JPEG 2000, etcetera) and "JPEG Extensions" that may or may not overlap in file name extension and declared MIME type.
Another confusing thing is RFC 3745 does not appear to match IANA Media Types yet the same RFC is supposed to inform the IANA Media Types document. For example, in RFC 3745 .jpf
is preferred file extension for image/jpx
but in IANA Media Types the name jpf
is not present (and that IANA document references RFC 3745!).
Another confusing thing is IANA Media Types lists "names" but does not list "file name extensions". This is on purpose, but confuses the endeavor of mapping file name extensions to MIME types.
Another confusing thing: is it "mime", or "MIME", or "MIME type", or "mime type", or "mime/type", or "media type"?
The most official seeming document by IANA is surprisingly inadequate. No MIME type is registered for file extension .jpg
yet there exists the odd vnd.sealedmedia.softseal.jpg
. File extension.JPEG
is only known as a video
type while file extension .jpeg
is an image type (when did lowercase and uppercase letters start mattering!?). At the same time, jpeg2000
is type video
yet RFC 3745 considers JPEG 2000 an image
type! The IANA list seems to cater to company-specific jpeg formats (e.g. vnd.sealedmedia.softseal.jpg
).
Because of the prior confusions, it is difficult to find an industry-accepted canonical document that maps file name extensions to MIME types, particularly for the JPEG Image File Format.
Related question "List of ALL MimeTypes on the Planet, mapped to File Extensions?".
Firstly, application.properties in the @PropertySource should read application-test.properties
if that's what the file is named (matching these things up matters):
@PropertySource("classpath:application-test.properties ")
That file should be under your /src/test/resources
classpath (at the root).
I don't understand why you'd specify a dependency hard coded to a file called application-test.properties
. Is that component only to be used in the test environment?
The normal thing to do is to have property files with the same name on different classpaths. You load one or the other depending on whether you are running your tests or not.
In a typically laid out application, you'd have:
src/test/resources/application.properties
and
src/main/resources/application.properties
And then inject it like this:
@PropertySource("classpath:application.properties")
The even better thing to do would be to expose that property file as a bean in your spring context and then inject that bean into any component that needs it. This way your code is not littered with references to application.properties and you can use anything you want as a source of properties. Here's an example: how to read properties file in spring project?
In theory, there's nothing preventing you from sending a request body in a GET
request. The HTTP protocol allows it, but have no defined semantics, so it's up to you to document what exactly is going to happen when a client sends a GET
payload. For instance, you have to define if parameters in a JSON body are equivalent to querystring parameters or something else entirely.
However, since there are no clearly defined semantics, you have no guarantee that implementations between your application and the client will respect it. A server or proxy might reject the whole request, or ignore the body, or anything else. The REST way to deal with broken implementations is to circumvent it in a way that's decoupled from your application, so I'd say you have two options that can be considered best practices.
The simple option is to use POST
instead of GET
as recommended by other answers. Since POST
is not standardized by HTTP, you'll have to document how exactly that's supposed to work.
Another option, which I prefer, is to implement your application assuming the GET
payload is never tampered with. Then, in case something has a broken implementation, you allow clients to override the HTTP method with the X-HTTP-Method-Override
, which is a popular convention for clients to emulate HTTP methods with POST
. So, if a client has a broken implementation, it can write the GET
request as a POST
, sending the X-HTTP-Method-Override: GET
method, and you can have a middleware that's decoupled from your application implementation and rewrites the method accordingly. This is the best option if you're a purist.
$('select').val('')
I simply used this on the select itself and it did the trick.
I'm on jQuery 1.7.1.
SHIFT+CTRL+B
should work
However sometimes an issue can happen in a locked down non-adminstrator evironment:
If you open an existing C# application from the folder you should have a .sln (solution file) etc..
Commonly you can get these message in VS Code
Downloading package 'OmniSharp (.NET 4.6 / x64)' (19343 KB) .................... Done!
Downloading package '.NET Core Debugger (Windows / x64)' (39827 KB) .................... Done!
Installing package 'OmniSharp (.NET 4.6 / x64)'
Installing package '.NET Core Debugger (Windows / x64)'
Finished
Failed to spawn 'dotnet --info' //this is a possible issue
To which then you will be asked to install .NET CLI tools
If impossible to get SDK installed with no admin privilege - then use other solution.
The easiest way would be at the application level. In the file
app/Providers/AppServiceProvider.php
add the following:
use Illuminate\Support\Facades\URL;
and in the boot() method add the following:
$this->app['request']->server->set('HTTPS', true);
URL::forceScheme('https');
This should redirect all request to https at the application level.
( Note: this has been tested with laravel 5.5 LTS )
I've only tested this in Rails 4 but there's an interesting way to use a range with a where
hash to get this behavior.
User.where(id: 201..Float::INFINITY)
will generate the SQL
SELECT `users`.* FROM `users` WHERE (`users`.`id` >= 201)
The same can be done for less than with -Float::INFINITY
.
I just posted a similar question asking about doing this with dates here on SO.
>=
vs >
To avoid people having to dig through and follow the comments conversation here are the highlights.
The method above only generates a >=
query and not a >
. There are many ways to handle this alternative.
For discrete numbers
You can use a number_you_want + 1
strategy like above where I'm interested in Users with id > 200
but actually look for id >= 201
. This is fine for integers and numbers where you can increment by a single unit of interest.
If you have the number extracted into a well named constant this may be the easiest to read and understand at a glance.
Inverted logic
We can use the fact that x > y == !(x <= y)
and use the where not chain.
User.where.not(id: -Float::INFINITY..200)
which generates the SQL
SELECT `users`.* FROM `users` WHERE (NOT (`users`.`id` <= 200))
This takes an extra second to read and reason about but will work for non discrete values or columns where you can't use the + 1
strategy.
Arel table
If you want to get fancy you can make use of the Arel::Table
.
User.where(User.arel_table[:id].gt(200))
will generate the SQL
"SELECT `users`.* FROM `users` WHERE (`users`.`id` > 200)"
The specifics are as follows:
User.arel_table #=> an Arel::Table instance for the User model / users table
User.arel_table[:id] #=> an Arel::Attributes::Attribute for the id column
User.arel_table[:id].gt(200) #=> an Arel::Nodes::GreaterThan which can be passed to `where`
This approach will get you the exact SQL you're interested in however not many people use the Arel table directly and can find it messy and/or confusing. You and your team will know what's best for you.
Starting in Rails 5 you can also do this with dates!
User.where(created_at: 3.days.ago..DateTime::Infinity.new)
will generate the SQL
SELECT `users`.* FROM `users` WHERE (`users`.`created_at` >= '2018-07-07 17:00:51')
Once Ruby 2.6 is released (December 25, 2018) you'll be able to use the new infinite range syntax! Instead of 201..Float::INFINITY
you'll be able to just write 201..
. More info in this blog post.
For Python 3.x, use input()
. For Python 2.x, use raw_input()
. Don't forget you can add a prompt string in your input()
call to create one less print statement. input("GUESS THAT NUMBER!")
.
I know this thread is bit old.
But I'm going to post this anyway hoping it might help someone.
We can store fields of any Object to shared preference by serializing the object to String.
Here I have used GSON
for storing any object to shared preference.
Save Object to Preference :
public static void saveObjectToSharedPreference(Context context, String preferenceFileName, String serializedObjectKey, Object object) {
SharedPreferences sharedPreferences = context.getSharedPreferences(preferenceFileName, 0);
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
final Gson gson = new Gson();
String serializedObject = gson.toJson(object);
sharedPreferencesEditor.putString(serializedObjectKey, serializedObject);
sharedPreferencesEditor.apply();
}
Retrieve Object from Preference:
public static <GenericClass> GenericClass getSavedObjectFromPreference(Context context, String preferenceFileName, String preferenceKey, Class<GenericClass> classType) {
SharedPreferences sharedPreferences = context.getSharedPreferences(preferenceFileName, 0);
if (sharedPreferences.contains(preferenceKey)) {
final Gson gson = new Gson();
return gson.fromJson(sharedPreferences.getString(preferenceKey, ""), classType);
}
return null;
}
Note :
Remember to add compile 'com.google.code.gson:gson:2.6.2'
to dependencies
in your gradle.
Example :
//assume SampleClass exists
SampleClass mObject = new SampleObject();
//to store an object
saveObjectToSharedPreference(context, "mPreference", "mObjectKey", mObject);
//to retrive object stored in preference
mObject = getSavedObjectFromPreference(context, "mPreference", "mObjectKey", SampleClass.class);
As @Sharp_Edge pointed out in comments, the above solution does not work with List
.
A slight modification to the signature of getSavedObjectFromPreference()
- from Class<GenericClass> classType
to Type classType
will make this solution generalized. Modified function signature,
public static <GenericClass> GenericClass getSavedObjectFromPreference(Context context, String preferenceFileName, String preferenceKey, Type classType)
For invoking,
getSavedObjectFromPreference(context, "mPreference", "mObjectKey", (Type) SampleClass.class)
Happy Coding!
Just solved the issue. After digging around for a while longer, I found this SO post which covers the exact same situation. It got me in the right track.
Basically, the XmlSerializer
needs to know the default namespace if derived classes are included as extra types. The exact reason why this has to happen is still unknown but, still, serialization is working now.
One more approach to reading a file that I happen to like is referred to variously as variable notation or variable syntax and involves simply enclosing a filespec within curly braces preceded by a dollar sign, to wit:
$content = ${C:file.txt}
This notation may be used as either an L-value or an R-value; thus, you could just as easily write to a file with something like this:
${D:\path\to\file.txt} = $content
Another handy use is that you can modify a file in place without a temporary file and without sub-expressions, for example:
${C:file.txt} = ${C:file.txt} | select -skip 1
I became fascinated by this notation initially because it was very difficult to find out anything about it! Even the PowerShell 2.0 specification mentions it only once showing just one line using it--but with no explanation or details of use at all. I have subsequently found this blog entry on PowerShell variables that gives some good insights.
One final note on using this: you must use a drive designation, i.e. ${drive:filespec}
as I have done in all the examples above. Without the drive (e.g. ${file.txt}
) it does not work. No restrictions on the filespec on that drive: it may be absolute or relative.
Try this.
Copy an Array :
const myCopiedArray = Object.assign([], myArray);
Copy an object :
const myCopiedObject = Object.assign({}, myObject);
You can call a JavaScript function and use window.location = 'url';
:
You can use the below simple method of sorting:
datatable.DefaultView.Sort = "Col2 ASC,Col3 ASC,Col4 ASC";
By the above method, you will be able to sort N number of columns.
Try to use classpath*:
prefix instead.
Also please try to deploy exploded war, to ensure that all files are there.
Run vim
from the terminal. For the basics, you're advised to run the command vimtutor
.
# On your terminal command line:
$ vim
If you have a specific file to edit, pass it as an argument.
$ vim yourfile.cpp
Likewise, launch the tutorial
$ vimtutor
Sometimes, even when the file is in the right directory, there is still the "file not found" exception. One thing you could do is to drop the text file inside eclipse, where your classes are, on the left side. It is going to ask you if you want to copy, click yes. Sometimes it helps.
The Best way to Print particular Div or any Element
printDiv("myDiv");
function printDiv(id){
var printContents = document.getElementById(id).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
I found catching exception of driver.switchTo().alert();
is so slow in Firefox
(FF V20 & selenium-java-2.32.0).`
So I choose another way:
private static boolean isDialogPresent(WebDriver driver) {
try {
driver.getTitle();
return false;
} catch (UnhandledAlertException e) {
// Modal dialog showed
return true;
}
}
And it's a better way when most of your test cases is NO dialog present (throwing exception is expensive).