On many devices (such as the iPhone), it prevents the user from using the browser's zoom. If you have a map and the browser does the zooming, then the user will see a big ol' pixelated image with huge pixelated labels. The idea is that the user should use the zooming provided by Google Maps. Not sure about any interaction with your plugin, but that's what it's there for.
More recently, as @ehfeng notes in his answer, Chrome for Android (and perhaps others) have taken advantage of the fact that there's no native browser zooming on pages with a viewport tag set like that. This allows them to get rid of the dreaded 300ms delay on touch events that the browser takes to wait and see if your single touch will end up being a double touch. (Think "single click" and "double click".) However, when this question was originally asked (in 2011), this wasn't true in any mobile browser. It's just added awesomeness that fortuitously arose more recently.
viewport
meta tag on mobile browser,
The initial-scale property controls the zoom level when the page is first loaded. The maximum-scale, minimum-scale, and user-scalable properties control how users are allowed to zoom the page in or out.
this worked for me:
document.documentElement.addEventListener('touchmove', function (event) {
event.preventDefault();
}, false);
you could try
$('*').not('#div').bind('touchmove', false);
add this if necessary
$('#div').bind('touchmove');
note that everything is fixed except #div
Here is a function that calculates the current position of an element within the viewport:
/**
* Calculates the position of a given element within the viewport
*
* @param {string} obj jQuery object of the dom element to be monitored
* @return {array} An array containing both X and Y positions as a number
* ranging from 0 (under/right of viewport) to 1 (above/left of viewport)
*/
function visibility(obj) {
var winw = jQuery(window).width(), winh = jQuery(window).height(),
elw = obj.width(), elh = obj.height(),
o = obj[0].getBoundingClientRect(),
x1 = o.left - winw, x2 = o.left + elw,
y1 = o.top - winh, y2 = o.top + elh;
return [
Math.max(0, Math.min((0 - x1) / (x2 - x1), 1)),
Math.max(0, Math.min((0 - y1) / (y2 - y1), 1))
];
}
The return values are calculated like this:
Usage:
visibility($('#example')); // returns [0.3742887830933581, 0.6103752759381899]
Demo:
function visibility(obj) {var winw = jQuery(window).width(),winh = jQuery(window).height(),elw = obj.width(),_x000D_
elh = obj.height(), o = obj[0].getBoundingClientRect(),x1 = o.left - winw, x2 = o.left + elw, y1 = o.top - winh, y2 = o.top + elh; return [Math.max(0, Math.min((0 - x1) / (x2 - x1), 1)),Math.max(0, Math.min((0 - y1) / (y2 - y1), 1))];_x000D_
}_x000D_
setInterval(function() {_x000D_
res = visibility($('#block'));_x000D_
$('#x').text(Math.round(res[0] * 100) + '%');_x000D_
$('#y').text(Math.round(res[1] * 100) + '%');_x000D_
}, 100);
_x000D_
#block { width: 100px; height: 100px; border: 1px solid red; background: yellow; top: 50%; left: 50%; position: relative;_x000D_
} #container { background: #EFF0F1; height: 950px; width: 1800px; margin-top: -40%; margin-left: -40%; overflow: scroll; position: relative;_x000D_
} #res { position: fixed; top: 0; z-index: 2; font-family: Verdana; background: #c0c0c0; line-height: .1em; padding: 0 .5em; font-size: 12px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="res">_x000D_
<p>X: <span id="x"></span></p>_x000D_
<p>Y: <span id="y"></span></p>_x000D_
</div>_x000D_
<div id="container"><div id="block"></div></div>
_x000D_
Note that if the problem is being caused by appearing scrollbars, putting
body {
overflow: hidden;
}
in your CSS might be an easy fix (if you don't need the page to scroll).
No hack or js needed. Just apply the following rule to your root element:
min-height: 100%;
height: auto;
It will automatically choose the bigger one from the two as its height, which means if the content is longer than the browser, it will be the height of the content, otherwise, the height of the browser. This is standard css.
I looked and found a cross browser way:
function myFunction(){_x000D_
if(window.innerWidth !== undefined && window.innerHeight !== undefined) { _x000D_
var w = window.innerWidth;_x000D_
var h = window.innerHeight;_x000D_
} else { _x000D_
var w = document.documentElement.clientWidth;_x000D_
var h = document.documentElement.clientHeight;_x000D_
}_x000D_
var txt = "Page size: width=" + w + ", height=" + h;_x000D_
document.getElementById("demo").innerHTML = txt;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body onresize="myFunction()" onload="myFunction()">_x000D_
<p>_x000D_
Try to resize the page._x000D_
</p>_x000D_
<p id="demo">_x000D_
_x000D_
</p>_x000D_
</body>_x000D_
</html>
_x000D_
You can use $(window).resize() to detect if the viewport is resized.
jQuery does not have any function to consistently detect the correctly width and height of the viewport[1] when there is a scroll bar present.
I found a solution that uses the Modernizr library and specifically the mq function which opens media queries for javascript.
Here is my solution:
// A function for detecting the viewport minimum width.
// You could use a similar function for minimum height if you wish.
var min_width;
if (Modernizr.mq('(min-width: 0px)')) {
// Browsers that support media queries
min_width = function (width) {
return Modernizr.mq('(min-width: ' + width + ')');
};
}
else {
// Fallback for browsers that does not support media queries
min_width = function (width) {
return $(window).width() >= width;
};
}
var resize = function() {
if (min_width('768px')) {
// Do some magic
}
};
$(window).resize(resize);
resize();
My answer will probably not help resizing a iframe to 100% viewport width with a margin on each side, but I hope it will provide solace for webdevelopers frustrated with browser incoherence of javascript viewport width and height calculation.
Maybe this could help with regards to the iframe:
$('iframe').css('width', '100%').wrap('<div style="margin:2em"></div>');
[1] You can use $(window).width() and $(window).height() to get a number which will be correct in some browsers, but incorrect in others. In those browsers you can try to use window.innerWidth and window.innerHeight to get the correct width and height, but i would advice against this method because it would rely on user agent sniffing.
Usually the different browsers are inconsistent about whether or not they include the scrollbar as part of the window width and height.
Note: Both $(window).width() and window.innerWidth vary between operating systems using the same browser. See: https://github.com/eddiemachado/bones/issues/468#issuecomment-23626238
In Safari 9.0 and up you can use shrink-to-fit in viewport meta tag as shown below
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
Another tip from my side:
In order to set the window's width to let's say exactly 80 columns, use
80 CTRL+W |
In order to set it to maximum width, just omit the preceding number:
CTRL+W |
As stats on iOS usage, indicating that iOS 9.0-9.2.x usage is currently at 0.17%. If these numbers are truly indicative of global use of these versions, then it’s even more likely to be safe to remove shrink-to-fit from your viewport meta tag.
After 9.2.x. IOS remove this tag check on its' browser.
You can check this page https://www.scottohara.me/blog/2018/12/11/shrink-to-fit.html
As @Indigenuity states, this appears to be caused by browsers parsing the <meta name="viewport">
tag.
To solve this problem at the source, try the following:
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
.
In my tests this prevents the user from zooming out to view the overflowed content, and as a result prevents panning/scrolling to it as well.
Was just trying to work this out myself, and the solution I came up with was:
<meta name="viewport" content="initial-scale = 1.0,maximum-scale = 1.0" />
This seems to lock the device into 1.0 scale regardless of it's orientation. As a side effect, it does however completely disable user scaling (pinch zooming, etc).
This is all I needed:
<meta name="viewport" content="user-scalable=no"/>
For Android there is the addition of target-density tag.
target-densitydpi=device-dpi
So, the code would look like
<meta name="viewport" content="width=device-width, target-densitydpi=device-dpi, initial-scale=0, maximum-scale=1, user-scalable=yes" />
Please note, that I believe this addition is only for Android (but since you have answers, I felt this was a good extra) but this should work for most mobile devices.
iOS doens't update screen.width
& screen.height
when orientation changes. Android doens't update window.orientation
when it changes.
My solution to this problem:
var isAndroid = /(android)/i.test(navigator.userAgent);
if(isAndroid)
{
if(screen.width < screen.height){
//portrait mode on Android
}
} else {
if(window.orientation == 0){
//portrait mode iOS and other devices
}
}
You can detect this change in orientation on Android as well as iOS with the following code:
var supportsOrientationChange = "onorientationchange" in window,
orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";
window.addEventListener(orientationEvent, function() {
alert("the orientation has changed");
}, false);
If the onorientationchange
event is not supported, the event bound will be the resize
event.
I was looking to find the answer to this question too, but the accepted answer was breaking for me. Apparently using window.innerWidth isn't portable. It does work in some browsers, but I noticed Firefox didn't like it.
Gregg Tavares posted a great resource here that addresses this issue directly: http://webglfundamentals.org/webgl/lessons/webgl-anti-patterns.html (See anti-pattern #'s 3 and 4).
Using canvas.clientWidth instead of window.innerWidth seems to work nicely.
Here's Gregg's suggested render loop:
function resize() {
var width = gl.canvas.clientWidth;
var height = gl.canvas.clientHeight;
if (gl.canvas.width != width ||
gl.canvas.height != height) {
gl.canvas.width = width;
gl.canvas.height = height;
return true;
}
return false;
}
var needToRender = true; // draw at least once
function checkRender() {
if (resize() || needToRender) {
needToRender = false;
drawStuff();
}
requestAnimationFrame(checkRender);
}
checkRender();
You can also try this:
constructor(props) {
super(props);
this.state = {height: props.height, width:props.width};
}
componentWillMount(){
console.log("WINDOW : ",window);
this.setState({height: window.innerHeight + 'px',width:window.innerWidth+'px'});
}
render() {
console.log("VIEW : ",this.state);
}
in your <head>
<meta id="viewport"
name="viewport"
content="width=1024, height=768, initial-scale=0, minimum-scale=0.25" />
somewhere in your javascript
document.getElementById("viewport").setAttribute("content",
"initial-scale=0.5; maximum-scale=1.0; user-scalable=0;");
... but good luck with tweaking it for your device, fiddling for hours... and i'm still not there!
Why don't you use a combination of HTML/CSS instead? Image maps are obsolete.
This btw is Search Engine Optimised as well :)
Source code follows:
.image-map {
background: url('https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png');
width: 272px;
height: 92px;
display: block;
position: relative;
margin-top:10px;
float: left;
}
.image-map > a.map {
position: absolute;
display: block;
border: 1px solid green;
}
_x000D_
<div class="image-map">
<a class="map" rel="G" style="top: 0px; left: 0px; width: 70px; height: 95px;" href="#"></a>
<a class="map" rel="o" style="top: 0px; left: 70px; width: 50px; height: 95px" href="#"></a>
<a class="map" rel="o" style="top: 0px; left: 120px; width: 50px; height: 95px" href="#"></a>
<a class="map" rel="g" style="top: 0px; left: 170px; width: 40px; height: 95px" href="#"></a>
<a class="map" rel="l" style="top: 0px; left: 210px; width: 20px; height: 95px" href="#"></a>
<a class="map" rel="e" style="top: 0px; left: 230px; width: 40px; height: 95px" href="#"></a>
</div>
_x000D_
EDIT:
After the numerous negative points this answer has received I have to come back and say that I can clearly see that you don't agree with my answer, but I personally still believe that is a better option than image maps.
Sure it cannot do polygons, it might have issues on manual page zoom, but personally I feel image maps are obsolete although still on the html5 specification. (It makes make more sense nowadays to try and replicate them using html5 canvas instead)
However I guess the target audience for this question does not agree with me.
You could also check this Are HTML Image Maps still used? and see the most highly voted answer just for reference.
If you want data validation too
<!-- form -->
<form name="loginForm">
...
<input type="email" ng-keyup="$loginForm.$valid && $event.keyCode == 13 && signIn()" ng-model="email"... />
<input type="password" ng-keyup="$loginForm.$valid && $event.keyCode == 13 && signIn()" ng-model="password"... />
</form>
The important addition here is $loginForm.$valid
which will validate the form before executing function. You will have to add other attributes for validation which is beyond the scope of this question.
Good Luck.
You could just write to the file as you would write any normal file.
with open('csvfile.csv','wb') as file:
for l in text:
file.write(l)
file.write('\n')
If just in case, it is a list of lists, you could directly use built-in csv
module
import csv
with open("csvfile.csv", "wb") as file:
writer = csv.writer(file)
writer.writerows(text)
There's already a lot of good answers here so why not one more, use a library like lodash or underscore :)
obj = {
1 : { name : 'bob' , dinner : 'pizza' },
2 : { name : 'john' , dinner : 'sushi' },
3 : { name : 'larry', dinner : 'hummus' }
}
_.where(obj, {dinner: 'pizza'})
>> [{"name":"bob","dinner":"pizza"}]
You could use a Filter and do the following test:
HttpSession session = request.getSession(false);// don't create if it doesn't exist
if(session != null && !session.isNew()) {
chain.doFilter(request, response);
} else {
response.sendRedirect("/login.jsp");
}
The above code is untested.
This isn't the most extensive solution however. You should also test that some domain-specific object or flag is available in the session before assuming that because a session isn't new the user must've logged in. Be paranoid!
The specificity is calculated based on the amount of id, class and tag selectors in your rule. Id has the highest specificity, then class, then tag. Your first rule is now more specific than the second one, since they both have a class selector, but the first one also has two tag selectors.
To make the second one override the first one, you can make more specific by adding information of it's parents:
table.rule1 tr td.rule2 {
background-color: #ffff00;
}
Here is a nice article for more information on selector precedence.
You cannot simply add number to datetime
because it's unclear what unit is used: seconds, hours, weeks...
There is timedelta
class for manipulations with date and time. datetime
minus datetime
gives timedelta
, datetime
plus timedelta
gives datetime
, two datetime
objects cannot be added although two timedelta
can.
Create timedelta
object with how many seconds you want to add and add it to datetime
object:
>>> from datetime import datetime, timedelta
>>> t = datetime.now() + timedelta(seconds=3000)
>>> print(t)
datetime.datetime(2018, 1, 17, 21, 47, 13, 90244)
There is same concept in C++: std::chrono::duration
.
I found that on Windows 8.1 with an instance of SQL 2014 already installed, if I ran the SQLEXPR.EXE and then dismissed the Windows 'warning this may be incompatible' dialogs, that the installer completed successfully.
I suspect having 2014 bits already in place probably helped.
0 */6 * * *
crontab every 6 hours is a commonly used cron schedule.
According to wikipedia, it means a "double colon" scope resolution operator.
It seems you need to do combobox->itemData(combobox->currentIndex())
if you want to get the current data of the QComboBox.
If you are using your own class derived from QComboBox, you can add a currentData()
function.
I had a similar problem when I had to create a dictionary that contained the elements of an array and their count. The answer is relevant because, I flatten a list of lists, get the elements I need and then do a group and count. I used Python's map function to produce a tuple of element and it's count and groupby over the array. Note that the groupby takes the array element itself as the keyfunc. As a relatively new Python coder, I find it to me more easier to comprehend, while being Pythonic as well.
Before I discuss the code, here is a sample of data I had to flatten first:
{ "_id" : ObjectId("4fe3a90783157d765d000011"), "status" : [ "opencalais" ],
"content_length" : 688, "open_calais_extract" : { "entities" : [
{"type" :"Person","name" : "Iman Samdura","rel_score" : 0.223 },
{"type" : "Company", "name" : "Associated Press", "rel_score" : 0.321 },
{"type" : "Country", "name" : "Indonesia", "rel_score" : 0.321 }, ... ]},
"title" : "Indonesia Police Arrest Bali Bomb Planner", "time" : "06:42 ET",
"filename" : "021121bn.01", "month" : "November", "utctime" : 1037836800,
"date" : "November 21, 2002", "news_type" : "bn", "day" : "21" }
It is a query result from Mongo. The code below flattens a collection of such lists.
def flatten_list(items):
return sorted([entity['name'] for entity in [entities for sublist in
[item['open_calais_extract']['entities'] for item in items]
for entities in sublist])
First, I would extract all the "entities" collection, and then for each entities collection, iterate over the dictionary and extract the name attribute.
For everybody who codes Java for Android devices and ends up here: use SparseArray
for better performance;
private final SparseArray<myObject> myMap = new SparseArray<myObject>();
with this you can use int instead of Integer like;
int newPos = 3;
myMap.put(newPos, newObject);
myMap.get(newPos);
To switch between different images when the ImageButton is clicked I used a boolean like this:
ImageButton imageButton;
boolean buttonOn;
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!buttonOn) {
buttonOn = true;
imageButton.setBackground(getResources().getDrawable(R.drawable.button_is_on));
} else {
buttonOn = false;
imageButton.setBackground(getResources().getDrawable(R.drawable.button_is_off));
}
}
});
The message means that both the packages have functions with the same names. In this particular case, the testthat
and assertive
packages contain five functions with the same name.
R will look through the search
path to find functions, and will use the first one that it finds.
search()
## [1] ".GlobalEnv" "package:assertive" "package:testthat"
## [4] "tools:rstudio" "package:stats" "package:graphics"
## [7] "package:grDevices" "package:utils" "package:datasets"
## [10] "package:methods" "Autoloads" "package:base"
In this case, since assertive
was loaded after testthat
, it appears earlier in the search path, so the functions in that package will be used.
is_true
## function (x, .xname = get_name_in_parent(x))
## {
## x <- coerce_to(x, "logical", .xname)
## call_and_name(function(x) {
## ok <- x & !is.na(x)
## set_cause(ok, ifelse(is.na(x), "missing", "false"))
## }, x)
## }
<bytecode: 0x0000000004fc9f10>
<environment: namespace:assertive.base>
The functions in testthat
are not accessible in the usual way; that is, they have been masked.
You can explicitly provide a package name when you call a function, using the double colon operator, ::
. For example:
testthat::is_true
## function ()
## {
## function(x) expect_true(x)
## }
## <environment: namespace:testthat>
If you know about the function name clash, and don't want to see it again, you can suppress the message by passing warn.conflicts = FALSE
to library
.
library(testthat)
library(assertive, warn.conflicts = FALSE)
# No output this time
Alternatively, suppress the message with suppressPackageStartupMessages
:
library(testthat)
suppressPackageStartupMessages(library(assertive))
# Also no output
If you have altered some of R's startup configuration options (see ?Startup
) you may experience different function masking behavior than you might expect. The precise order that things happen as laid out in ?Startup
should solve most mysteries.
For example, the documentation there says:
Note that when the site and user profile files are sourced only the base package is loaded, so objects in other packages need to be referred to by e.g. utils::dump.frames or after explicitly loading the package concerned.
Which implies that when 3rd party packages are loaded via files like .Rprofile
you may see functions from those packages masked by those in default packages like stats, rather than the reverse, if you loaded the 3rd party package after R's startup procedure is complete.
First, get a character vector of all the environments on the search path. For convenience, we'll name each element of this vector with its own value.
library(dplyr)
envs <- search() %>% setNames(., .)
For each environment, get the exported functions (and other variables).
fns <- lapply(envs, ls)
Turn this into a data frame, for easy use with dplyr.
fns_by_env <- data_frame(
env = rep.int(names(fns), lengths(fns)),
fn = unlist(fns)
)
Find cases where the object appears more than once.
fns_by_env %>%
group_by(fn) %>%
tally() %>%
filter(n > 1) %>%
inner_join(fns_by_env)
To test this, try loading some packages with known conflicts (e.g., Hmisc
, AnnotationDbi
).
The conflicted
package throws an error with a helpful error message, whenever you try to use a variable with an ambiguous name.
library(conflicted)
library(Hmisc)
units
## Error: units found in 2 packages. You must indicate which one you want with ::
## * Hmisc::units
## * base::units
The easiest is setting a program variable (see GDB: assignment):
(gdb) l
6 {
7 int i;
8 struct file *f, *ftmp;
9
(gdb) set variable i = 10
(gdb) p i
$1 = 10
Or you can just update arbitrary (writable) location by address:
(gdb) set {int}0x83040 = 4
There's more. Read the manual.
I took Stano's excellent answer and wrapped it in a promise. This might be useful if you don't have an option like node or webpack to fall back on to load a json file from the file system:
// wrapped XMLHttpRequest in a promise
const readFileP = (file, options = {method:'get'}) =>
new Promise((resolve, reject) => {
let request = new XMLHttpRequest();
request.onload = resolve;
request.onerror = reject;
request.overrideMimeType("application/json");
request.open(options.method, file, true);
request.onreadystatechange = () => {
if (request.readyState === 4 && request.status === "200") {
resolve(request.responseText);
}
};
request.send(null);
});
You can call it like this:
readFileP('<path to file>')
.then(d => {
'<do something with the response data in d.srcElement.response>'
});
You can create one using like the following:
var dictionary = { Name:"Some Programmer", Age:24, Job:"Writing Programs" };
// Iterate over using keys
for (var key in dictionary) {
console.log("Key: " + key + " , " + "Value: "+ dictionary[key]);
}
// Access a key using object notation:
console.log("Her name is: " + dictionary.Name)
_x000D_
Better is to Make a global Constants
class to save key or variables to fetch or save data.
To save data call this method to save data from every where.
public static void saveData(Context con, String variable, String data)
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(con);
prefs.edit().putString(variable, data).commit();
}
Use it to get data.
public static String getData(Context con, String variable, String defaultValue)
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(con);
String data = prefs.getString(variable, defaultValue);
return data;
}
and a method something like this will do the trick
public static User getUserInfo(Context con)
{
String id = getData(con, Constants.USER_ID, null);
String name = getData(con, Constants.USER_NAME, null);
if(id != null && name != null)
{
User user = new User(); //Hope you will have a user Object.
user.setId(id);
user.setName(name);
//Here set other credentials.
return user;
}
else
return null;
}
It's important to understand that your code will sleep for 50 seconds between ending one loop, and starting the next...
A timer will call your loop every 50 seconds, which isn't exactly the same.
They're both valid, but a timer is probably what you're looking for here.
To expand on the above and make a quick reference:
ALTER USER username WITH SUPERUSER;
ALTER USER username WITH NOSUPERUSER;
ALTER USER username CREATEDB;
You can also use CREATEROLE
and CREATEUSER
to allow a user privileges without making them a superuser.
From the numpy fft page http://docs.scipy.org/doc/numpy/reference/routines.fft.html:
When the input a is a time-domain signal and A = fft(a), np.abs(A) is its amplitude spectrum and np.abs(A)**2 is its power spectrum. The phase spectrum is obtained by np.angle(A).
DateTimeFormatter
in Java 8 is immutable and thread-safe alternative to SimpleDateFormat
.
First of All Theory
Big O = Upper Limit O(n)
Theta = Order Function - theta(n)
Omega = Q-Notation(Lower Limit) Q(n)
In many Blogs & Books How this Statement is emphasised is Like
"This is Big O(n^3)" etc.
and people often Confuse like weather
O(n) == theta(n) == Q(n)
But What Worth keeping in mind is They Are Just Mathematical Function With Names O, Theta & Omega
so they have same General Formula of Polynomial,
Let,
f(n) = 2n4 + 100n2 + 10n + 50 then,
g(n) = n4, So g(n) is Function which Take function as Input and returns Variable with Biggerst Power,
Same f(n) & g(n) for Below all explainations
Big O(n4) = 3n4, Because 3n4 > 2n4
3n4 is value of Big O(n4) Just like f(x) = 3x
n4 is playing a role of x here so,
Replacing n4 with x'so, Big O(x') = 2x', Now we both are happy General Concept is
So 0 = f(n) = O(x')
O(x') = cg(n) = 3n4
Putting Value,
0 = 2n4 + 100n2 + 10n + 50 = 3n4
3n4 is our Upper Bound
Theta(n4) = cg(n) = 2n4 Because 2n4 = Our Example f(n)
2n4 is Value of Theta(n4)
so, 0 = cg(n) = f(n)
0 = 2n4 = 2n4 + 100n2 + 10n + 50
2n4 is our Lower Bound
This is Calculated to find out that weather lower Bound is similar to Upper bound,
Case 1). Upper Bound is Similar to Lower Bound
if Upper Bound is Similar to Lower Bound, The Average Case is Similar
Example, 2n4 = f(x) = 2n4,
Then Omega(n) = 2n4
Case 2). if Upper Bound is not Similar to Lower Bound
in this case, Omega(n) is Not fixed but Omega(n) is the set of functions with the same order of growth as g(n).
Example 2n4 = f(x) = 3n4, This is Our Default Case,
Then, Omega(n) = c'n4, is a set of functions with 2 = c' = 3
Hope This Explained!!
Another nice package which I used for migrating form a beta version of Angular2 to Angular2 2.0.0 final
is npm-check-updates
It shows the latest available version of all packages specified within your package.json. In contrast to npm outdated
it is also capable to edit your package.json, enabling you to do a npm upgrade
later.
Install
sudo npm install -g npm-check-updates
Usage
ncu
for display
ncu -u
for re-writing your package.json
SelectionChange is the event built into the Excel Object model for this. It should do exactly as you want, firing any time the user clicks anywhere...
I'm not sure that I understand your objections to global variables here, you would only need 1 if you use the Application.SelectionChange event. However, you wouldn't need any if you utilize the Workbook class code behind (to trap the Workbook.SelectionChange event) or the Worksheet class code behind (to trap the Worksheet.SelectionChange) event. (Unless your issue is the "global variable reset" problem in VBA, for which there is only one solution: error handling everywhere. Do not allow any unhandled errors, instead log them and/or "soft-report" an error as a message box to the user.)
You might also need to trap the Worksheet.Activate() and Worksheet.Deactivate() events (or the equivalent in the Workbook class) and/or the Workbook.Activate and Workbook.Deactivate() events so that you know when the user has switched worksheets and/or workbooks. The Window activate and deactivate events should make this approach complete. They could all call the same exact procedure, however, they all denote the same thing: the user changed the "focus", if you will.
If you don't like VBA, btw, you can do the same using VB.NET or C#.
[Edit: Dbb makes a very good point about the SelectionChange event not picking up a click when the user clicks within the currently selected cell. If you need to pick that up, then you would need to use subclassing.]
To expand on joemailer's answer, if you want to have the pattern-matching ability to match any subset of remote machines (just as the ansible
command does), but still want to make it very difficult to accidentally run the playbook on all machines, this is what I've come up with:
Same playbook as the in other answer:
# file: user.yml (playbook)
---
- hosts: '{{ target }}'
user: ...
Let's have the following hosts:
imac-10.local
imac-11.local
imac-22.local
Now, to run the command on all devices, you have to explicty set the target variable to "all"
ansible-playbook user.yml --extra-vars "target=all"
And to limit it down to a specific pattern, you can set target=pattern_here
or, alternatively, you can leave target=all
and append the --limit
argument, eg:
--limit imac-1*
ie.
ansible-playbook user.yml --extra-vars "target=all" --limit imac-1* --list-hosts
which results in:
playbook: user.yml
play #1 (office): host count=2
imac-10.local
imac-11.local
You can change the max length of the GROUP_CONCAT
value by setting the group_concat_max_len
parameter.
See details in the MySQL documantation.
Install jquery with npm
npm install jquery --save
Add typings
npm install --save-dev @types/jquery
Add scripts to angular-cli.json
"apps": [{
...
"scripts": [
"../node_modules/jquery/dist/jquery.min.js",
],
...
}]
Build project and serve
ng build
Hope this helps! Enjoy coding
Andrea solution is absolutely right, I will just write another implementation based on the same idea. If you took a look at the THREE.ImageUtils.loadTexture() source you will find it uses the javascript Image object. The $(window).load event is fired after all Images are loaded ! so at that event we can render our scene with the textures already loaded...
CoffeeScript
$(document).ready ->
material = new THREE.MeshLambertMaterial(map: THREE.ImageUtils.loadTexture("crate.gif"))
sphere = new THREE.Mesh(new THREE.SphereGeometry(radius, segments, rings), material)
$(window).load ->
renderer.render scene, camera
JavaScript
$(document).ready(function() {
material = new THREE.MeshLambertMaterial({ map: THREE.ImageUtils.loadTexture("crate.gif") });
sphere = new THREE.Mesh(new THREE.SphereGeometry(radius, segments, rings), material);
$(window).load(function() {
renderer.render(scene, camera);
});
});
Thanks...
You need to generate an SSH key (if you don't have one) and associate the public key with your Github account. See Github's own documentation.
Starting in pandas 0.24 you can simplify this with the mode
keyword argument of ExcelWriter
:
import pandas as pd
with pd.ExcelWriter('the_file.xlsx', engine='openpyxl', mode='a') as writer:
data_filtered.to_excel(writer)
In case it helps others, the option I prefer, which is not listed here, uses Guava's Maps functionality:
public enum Vebosity {
BRIEF("BRIEF"),
NORMAL("NORMAL"),
FULL("FULL");
private String value;
private Verbosity(final String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
private static ImmutableMap<String, Verbosity> reverseLookup =
Maps.uniqueIndex(Arrays.asList(Verbosity.values()), Verbosity::getValue);
public static Verbosity fromString(final String id) {
return reverseLookup.getOrDefault(id, NORMAL);
}
}
With the default you can use null
, you can throw IllegalArgumentException
or your fromString
could return an Optional
, whatever behavior you prefer.
This is fixed in npm 7. See npm/cli#PR169
This won't solve your problem, but if you only needed lat/long data for these addresses, the Google Maps API will parse non-formatted addresses pretty well.
Good suggestion, alternatively you can execute a CURL request for each address to Google Maps and it will return the properly formatted address. From that, you can regex to your heart's content.
I am just providing another case where you can get this error message. The solution will be the same as Adam has mentioned above. This is from a real code and I renamed the class name.
class FooReader {
public:
/** Constructor */
FooReader() : d(new FooReaderPrivate(this)) { } // will not compile here
.......
private:
FooReaderPrivate* d;
};
====== In a separate file =====
class FooReaderPrivate {
public:
FooReaderPrivate(FooReader*) : parent(p) { }
private:
FooReader* parent;
};
The above will no pass the compiler and get error: invalid use of incomplete type FooReaderPrivate. You basically have to put the inline portion into the *.cpp implementation file. This is OK. What I am trying to say here is that you may have a design issue. Cross reference of two classes may be necessary some cases, but I would say it is better to avoid them at the start of the design. I would be wrong, but please comment then I will update my posting.
Inject a script into the page you want to get the source from and message it back to the popup....
manifest.json
{
"name": "Get pages source",
"version": "1.0",
"manifest_version": 2,
"description": "Get pages source from a popup",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": ["tabs", "<all_urls>"]
}
popup.html
<!DOCTYPE html>
<html style=''>
<head>
<script src='popup.js'></script>
</head>
<body style="width:400px;">
<div id='message'>Injecting Script....</div>
</body>
</html>
popup.js
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
message.innerText = request.source;
}
});
function onWindowLoad() {
var message = document.querySelector('#message');
chrome.tabs.executeScript(null, {
file: "getPagesSource.js"
}, function() {
// If you try and inject into an extensions page or the webstore/NTP you'll get an error
if (chrome.runtime.lastError) {
message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
}
});
}
window.onload = onWindowLoad;
getPagesSource.js
// @author Rob W <http://stackoverflow.com/users/938089/rob-w>
// Demo: var serialized_html = DOMtoString(document);
function DOMtoString(document_root) {
var html = '',
node = document_root.firstChild;
while (node) {
switch (node.nodeType) {
case Node.ELEMENT_NODE:
html += node.outerHTML;
break;
case Node.TEXT_NODE:
html += node.nodeValue;
break;
case Node.CDATA_SECTION_NODE:
html += '<![CDATA[' + node.nodeValue + ']]>';
break;
case Node.COMMENT_NODE:
html += '<!--' + node.nodeValue + '-->';
break;
case Node.DOCUMENT_TYPE_NODE:
// (X)HTML documents are identified by public identifiers
html += "<!DOCTYPE " + node.name + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + '>\n';
break;
}
node = node.nextSibling;
}
return html;
}
chrome.runtime.sendMessage({
action: "getSource",
source: DOMtoString(document)
});
You can replace it with its clone like so
var clone = $('#control').clone();
$('#control').replacewith(clone);
But this clones with its value too so you had better like so
var emtyValue = $('#control').val('');
var clone = emptyValue.clone();
$('#control').replacewith(clone);
I found this article very helpful to understand the difference between them:
RUN - RUN instruction allows you to install your application and packages required for it. It executes any commands on top of the current image and creates a new layer by committing the results. Often you will find multiple RUN instructions in a Dockerfile.
CMD -
CMD instruction allows you to set a default command, which will be
executed only when you run container without specifying a command.
If Docker container runs with a command, the default command will be
ignored. If Dockerfile has more than one CMD instruction, all but last
CMD instructions are ignored.
Although approved answer is correct, I want to show a bit different approach (based on this answer).
Vscode can automatically choose correct anaconda environment if you start vscode from it. Just add to user/workspace settings:
{
"python.pythonPath": "C:/<proper anaconda path>/Anaconda3/envs/${env:CONDA_DEFAULT_ENV}/python"
}
It works on Windows, macOS and probably Unix. Further read on variable substitution in vscode: here.
This might work for you:
sed 's|$ROOT|'"${HOME}"'|g' abc.sh > abc.sh.1
Just think about the jquery-ui menu as being the verticle dropdown when you hover over a topic on your main horizonal menu. That way, you have a separate jquery ui menu for each topic on your main menu. The horizonal main menu is just a collection of float:left divs wrapped in a mainmenu div. You then use the hover in and hover out to pop up each menu.
$('.mainmenuitem').hover(
function(){
$(this).addClass('ui-state-focus');
$(this).addClass('ui-corner-all');
$(this).addClass('ui-state-hover');
$(this).addClass('ui-state-active');
$(this).addClass('mainmenuhighlighted');
// trigger submenu
var position=$(this).offset();
posleft=position.left;
postop=position.top;
submenu=$(this).attr('submenu');
showSubmenu(posleft,postop,submenu);
},
function(){
$(this).removeClass('ui-state-focus');
$(this).removeClass('ui-corner-all');
$(this).removeClass('ui-state-hover');
$(this).removeClass('ui-state-active');
$(this).removeClass('mainmenuhighlighted');
// remove submenu
$('.submenu').hide();
}
);
The showSubmenu function is simple - it just positions the submenu and shows it.
function showSubmenu(left,top,submenu){
var tPosX=left;
var tPosY=top+28;
$('#'+submenu).css({left:tPosX, top:tPosY,position:'absolute'});
$('#'+submenu).show();
}
You then need to make sure the submenu is visible while your cursor is on it and disappears when you leave (this should be in your document.ready function.
$('.submenu').hover(
function(){
$(this).show();
},
function(){
$(this).hide();
}
);
Also don't forget to hide your submenus to start with - in the document.ready function
$(".submenu" ).hide();
See the full code here
Follow following steps:
- Copy hello.ko to /lib/modules/'uname-r'/misc/
- Add misc/hello.ko entry in /lib/modules/'uname-r'/modules.dep
- sudo depmod
- sudo modprobe hello
modprobe will check modules.dep file for any dependency.
I had the same problem. I solve it with a for loop.
Example:
If I want to write in 2 identical tables, using a loop
for x = 0 to 1
if x = 0 then TableToWrite = "Table1"
if x = 1 then TableToWrite = "Table2"
Sql = "INSERT INTO " & TableToWrite & " VALUES ('1','2','3')"
NEXT
either
ArrTable = ("Table1", "Table2")
for xArrTable = 0 to Ubound(ArrTable)
Sql = "INSERT INTO " & ArrTable(xArrTable) & " VALUES ('1','2','3')"
NEXT
If you have a small query I don't know if this is the best solution, but if you your query is very big and it is inside a dynamical script with if/else/case conditions this is a good solution.
Here is a piece of code that worked for me
this.WindowState = FormWindowState.Minimized;
this.Show();
this.WindowState = FormWindowState.Normal;
It always brings the desired window to the front of all the others.
Stuart's answer provides a great explanation, but I'd like to provide another example.
I ran into this issue when attempting to perform a reduce
on a Stream containing null values (actually it was LongStream.average()
, which is a type of reduction). Since average() returns OptionalDouble
, I assumed the Stream could contain nulls but instead a NullPointerException was thrown. This is due to Stuart's explanation of null v. empty.
So, as the OP suggests, I added a filter like so:
list.stream()
.filter(o -> o != null)
.reduce(..);
Or as tangens pointed out below, use the predicate provided by the Java API:
list.stream()
.filter(Objects::nonNull)
.reduce(..);
From the mailing list discussion Stuart linked: Brian Goetz on nulls in Streams
Java's Scanner class does not have a built in method to read from a Scanner character-by-character.
http://java.sun.com/javase/6/docs/api/java/util/Scanner.html
However, it should still be possible to fetch individual characters from the Scanner as follows:
Scanner sc:
char c = sc.findInLine(".").charAt(0);
And you could use it to fetch each character in your scanner like this:
while(sc.hasNext()){
char c = sc.findInLine(".").charAt(0);
System.out.println(c); //to print out every char in the scanner
}
The findInLine() method searches through your scanner and returns the first String that matches the regular expression you give it.
You can use arguments with default values.
def someMethod(def mandatory,def optional=null){}
if argument "optional" not exist, it turns to "null".
Quickfix
I had similar issue and I resolved it doing the following
Alternative 1: Disable sandbox
As this article explains in depth, groovy scripts are run in sandbox mode by default. This means that a subset of groovy methods are allowed to run without administrator approval. It's also possible to run scripts not in sandbox mode, which implies that the whole script needs to be approved by an administrator at once. This preventing users from approving each line at the time.
Running scripts without sandbox can be done by unchecking this checkbox in your project config just below your script:
Alternative 2: Disable script security
As this article explains it also possible to disable script security completely. First install the permissive script security plugin and after that change your jenkins.xml file add this argument:
-Dpermissive-script-security.enabled=true
So you jenkins.xml will look something like this:
<executable>..bin\java</executable>
<arguments>-Dpermissive-script-security.enabled=true -Xrs -Xmx4096m -Dhudson.lifecycle=hudson.lifecycle.WindowsServiceLifecycle -jar "%BASE%\jenkins.war" --httpPort=80 --webroot="%BASE%\war"</arguments>
Make sure you know what you are doing if you implement this!
try this:
select convert(varchar, dob2, 101)
select convert(varchar, dob2, 102)
select convert(varchar, dob2, 103)
select convert(varchar, dob2, 104)
select convert(varchar, dob2, 105)
select convert(varchar, dob2, 106)
select convert(varchar, dob2, 107)
select convert(varchar, dob2, 108)
select convert(varchar, dob2, 109)
select convert(varchar, dob2, 110)
select convert(varchar, dob2, 111)
select convert(varchar, dob2, 112)
select convert(varchar, dob2, 113)
refernces: http://msdn.microsoft.com/en-us/library/ms187928.aspx
path.py is another alternative: https://github.com/jaraco/path.py
from path import path
p = path('/path/to/the/directory')
for f in p.files(pattern='*.txt'):
print f
Try this (LINQ method syntax):
string[] columnNames = dt.Columns.Cast<DataColumn>()
.Select(x => x.ColumnName)
.ToArray();
or in LINQ Query syntax:
string[] columnNames = (from dc in dt.Columns.Cast<DataColumn>()
select dc.ColumnName).ToArray();
Cast
is required, because Columns is of type DataColumnCollection which is a IEnumerable
, not IEnumerable<DataColumn>
. The other parts should be obvious.
You can solve the issue by
Got it. Quite stupid, actually. It worked after I removed & added the SessionStateModule like so:
<configuration>
...
<system.webServer>
...
<modules>
<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
...
</modules>
</system.webServer>
</configuration>
Simply adding it won't work since "Session" should have already been defined in the machine.config
.
Now, I wonder if that is the usual thing to do. It surely doesn't seem so since it seems so crude...
The safest way to avoid events on an href would be to define it as
<a href="javascript:void(0)" ....>
This doesn't touch on the immediate question at hand, but this Q/A comes up for searches related to trying to assign the selected value to a ChoiceField
.
If you have already called super().__init__
in your Form class, you should update the form.initial
dictionary, not the field.initial
property. If you study form.initial
(e.g. print self.initial
after the call to super().__init__
), it will contain values for all the fields. Having a value of None
in that dict will override the field.initial
value.
e.g.
class MyForm(forms.Form):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
# assign a (computed, I assume) default value to the choice field
self.initial['choices_field_name'] = 'default value'
# you should NOT do this:
self.fields['choices_field_name'].initial = 'default value'
You can also use AWK which can give you more flexibility to handle the file
awk '{ print "chmod 755 "$0"" | "/bin/sh"}' file.txt
if your file has a field separator like:
field1,field2,field3
To get only the first field you do
awk -F, '{ print "chmod 755 "$1"" | "/bin/sh"}' file.txt
You can check more details on GNU Documentation https://www.gnu.org/software/gawk/manual/html_node/Very-Simple.html#Very-Simple
As far as I know, the order of the repositories in your pom.xml will also decide the order of the repository access.
As for configuring repositories in settings.xml, I've read that the order of repositories is interestingly enough the inverse order of how the repositories will be accessed.
Here a post where someone explains this curiosity:
http://community.jboss.org/message/576851
int[] arr = new int[5] {1,2,3,4,5};
You can use Linq for it
String arrTostr = arr.Select(a => a.ToString()).Aggregate((i, j) => i + "," + j);
An Error Was Encountered Unable to load the requested file:
Sometimes we face this error because the requested file doesn't exist in that directory.
Suppose we have a folder home
in views
directory and trying to load home_view.php
file as:
$this->load->view('home/home_view', $data);// $data is array
If home_view.php
file doesn't exist in views/home
directory then it will raise an error.
An Error Was Encountered Unable to load the requested file: home\home_view.php
So how to fix this error go to views/home
and check the home_view.php
file exist if not then create it.
With a Spring Boot one can do the following:
values[0]=abc
values[1]=def
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
@Component
@ConfigurationProperties
public class Configuration {
List<String> values = new ArrayList<>();
public List<String> getValues() {
return values;
}
}
This is needed, without this class or without the values
in class it is not working.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.util.List;
@SpringBootApplication
public class SpringBootConsoleApplication implements CommandLineRunner {
private static Logger LOG = LoggerFactory.getLogger(SpringBootConsoleApplication.class);
// notice #{} is used instead of ${}
@Value("#{configuration.values}")
List<String> values;
public static void main(String[] args) {
SpringApplication.run(SpringBootConsoleApplication.class, args);
}
@Override
public void run(String... args) {
LOG.info("values: {}", values);
}
}
You need to add this as the last line...
HttpContext.Current.Response.Cookies.Add(userid);
When you need to read the value of the cookie, you'd use a method similar to this:
string cookieUserID= String.Empty;
try
{
if (HttpContext.Current.Request.Cookies["userid"] != null)
{
cookieUserID = HttpContext.Current.Request.Cookies["userid"];
}
}
catch (Exception ex)
{
//handle error
}
return cookieUserID;
SQL Server does not track the order of inserted rows, so there is no reliable way to get that information given your current table structure. Even if employee_id
is an IDENTITY
column, it is not 100% foolproof to rely on that for order of insertion (since you can fill gaps and even create duplicate ID values using SET IDENTITY_INSERT ON
). If employee_id
is an IDENTITY
column and you are sure that rows aren't manually inserted out of order, you should be able to use this variation of your query to select the data in sequence, newest first:
SELECT
ROW_NUMBER() OVER (ORDER BY EMPLOYEE_ID DESC) AS ID,
EMPLOYEE_ID,
EMPLOYEE_NAME
FROM dbo.CSBCA1_5_FPCIC_2012_EES207201222743
ORDER BY ID;
You can make a change to your table to track this information for new rows, but you won't be able to derive it for your existing data (they will all me marked as inserted at the time you make this change).
ALTER TABLE dbo.CSBCA1_5_FPCIC_2012_EES207201222743
-- wow, who named this?
ADD CreatedDate DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;
Note that this may break existing code that just does INSERT INTO dbo.whatever SELECT/VALUES()
- e.g. you may have to revisit your code and define a proper, explicit column list.
public static class TimeSpanFormattingExtensions
{
public static string ToReadableString(this TimeSpan span)
{
return string.Join(", ", span.GetReadableStringElements()
.Where(str => !string.IsNullOrWhiteSpace(str)));
}
private static IEnumerable<string> GetReadableStringElements(this TimeSpan span)
{
yield return GetDaysString((int)Math.Floor(span.TotalDays));
yield return GetHoursString(span.Hours);
yield return GetMinutesString(span.Minutes);
yield return GetSecondsString(span.Seconds);
}
private static string GetDaysString(int days)
{
if (days == 0)
return string.Empty;
if (days == 1)
return "1 day";
return string.Format("{0:0} days", days);
}
private static string GetHoursString(int hours)
{
if (hours == 0)
return string.Empty;
if (hours == 1)
return "1 hour";
return string.Format("{0:0} hours", hours);
}
private static string GetMinutesString(int minutes)
{
if (minutes == 0)
return string.Empty;
if (minutes == 1)
return "1 minute";
return string.Format("{0:0} minutes", minutes);
}
private static string GetSecondsString(int seconds)
{
if (seconds == 0)
return string.Empty;
if (seconds == 1)
return "1 second";
return string.Format("{0:0} seconds", seconds);
}
}
You could use the tr
instead:
$p =~ tr/fo//d;
will delete every f and every o from $p
. In your case it should be:
$p =~ tr/\$#@~!&*()[];.,:?^ `\\\///d
tr/SEARCHLIST/REPLACEMENTLIST/cdsr
Transliterates all occurrences of the characters found (or not found if the
/c
modifier is specified) in the search list with the positionally corresponding character in the replacement list, possibly deleting some, depending on the modifiers specified.[…]
If the
/d
modifier is specified, any characters specified by SEARCHLIST not found in REPLACEMENTLIST are deleted.
public String removeDoubleQuotes(String request) {
return request.replace("\"", "");
}
In typer ...
is used to create required parameters: The Argument
class expects a default value, and if you pass the ...
it will complain if the user does not pass the particular argument.
You could use None
for the same if Ellipsis
was not there, but this would remove the opportunity to express that None
is the default value, in case that made any sense in your program.
You need to make sure you specify the classpath in the MANIFEST.MF file. If you are using Maven to do the packaging, you can configure the following plugins:
1. maven-depedency-plugin:
2. maven-jar-plugin:
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<version>${version.plugin.maven-dependency-plugin}</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
<overWriteReleases>false</overWriteReleases>
<overWriteSnapshots>true</overWriteSnapshots>
<includeScope>runtime</includeScope>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>${version.plugin.maven-jar-plugin}</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
</manifest>
</archive>
</configuration>
</plugin>
The resulting manifest file will be packaged in the executable jar under META-INF and will look like this:
Manifest-Version: 1.0
Implementation-Title: myexecjar
Implementation-Version: 1.0.0-SNAPSHOT
Built-By: razvanone
Class-Path: lib/first.jar lib/second.jar
Build-Jdk: your-buildjdk-version
Created-By: Maven Integration for Eclipse
Main-Class: ro.razvanone.MyMainClass
The Windows script would look like this:
@echo on
echo "Starting up the myexecjar application..."
java -jar myexecjar-1.0.0-SNAPSHOT.jar
This should be complete config for building an executable jar using Maven :)
You should not use those headers, the headers determine what kind of type you are sending, and you are clearly sending an object, which means, JSON.
Instead you should set the option responseType
to text
:
addToCart(productId: number, quantity: number): Observable<any> {
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
return this.http.post(
'http://localhost:8080/order/addtocart',
{ dealerId: 13, createdBy: "-1", productId, quantity },
{ headers, responseType: 'text'}
).pipe(catchError(this.errorHandlerService.handleError));
}
I found that this works when run in the Package Manager Console:
dotnet ef migrations list | select -Last 2 | select -First 1 | ForEach-Object { Update-Database -Migration $_ }
You could create a script that makes it easier.
Well it depends on what you have in your table.
its one of the following If you have only one table
var count = $('#gvPerformanceResult tr').length;
If you are concerned about sub tables but this wont work with tbody and thead (if you use them)
var count = $('#gvPerformanceResult>tr').length;
Where by this will work (but is quite frankly overkill.)
var count = $('#gvPerformanceResult>tbody>tr').length;
like Answers above, if you do bootstrap 4 just add few line of css to .carousel , carousel-inner ,carousel-item and img as follows
.carousel .carousel-inner{
height:500px
}
.carousel-inner .carousel-item img{
min-height:200px;
//prevent it from stretch in screen size < than 768px
object-fit:cover
}
@media(max-width:768px){
.carousel .carousel-inner{
//prevent it from adding a white space between carousel and container elements
height:auto
}
}
None of the above answers worked for me but this does -- Use <P style='line-height: 8px;'>
to replace <p>
wherever needed (or put it in the style tag like <style>P {line-height: 8px;}</style>
to affect all <p>
tags). I realise Mauro says this, but if someone comes here for help, I expect they would want to see an example.
Since bash
5.0 (released on 7 Jan 2019) you can use the built-in variable EPOCHSECONDS
.
$ echo $EPOCHSECONDS
1547624774
There is also EPOCHREALTIME
which includes fractions of seconds.
$ echo $EPOCHREALTIME
1547624774.371215
EPOCHREALTIME
can be converted to micro-seconds (µs) by removing the decimal point. This might be of interest when using bash
's built-in arithmetic (( expression ))
which can only handle integers.
$ echo ${EPOCHREALTIME/./}
1547624774371215
In all examples from above the printed time values are equal for better readability. In reality the time values would differ since each command takes a small amount of time to be executed.
Your JSON string is malformed: the type of center
is an array of invalid objects. Replace [
and ]
with {
and }
in the JSON string around longitude
and latitude
so they will be objects:
[
{
"name" : "New York",
"number" : "732921",
"center" : {
"latitude" : 38.895111,
"longitude" : -77.036667
}
},
{
"name" : "San Francisco",
"number" : "298732",
"center" : {
"latitude" : 37.783333,
"longitude" : -122.416667
}
}
]
Sometime when you render the current page as shown in below code will generate the same error
StringWriter str_wrt = new StringWriter();
HtmlTextWriter html_wrt = new HtmlTextWriter(str_wrt);
Page.RenderControl(html_wrt);
String HTML = str_wrt.ToString();
so how can we sort it?
or if you have still problems you can use this
$mail->Body = html_entity_decode($Body);
A "JSON object" doesn't make sense : JSON is an exchange format based on the structure of Javascript object declaration.
If you want to convert your javascript object to a json string, use JSON.stringify(yourObject)
;
If you want to create a javascript object, simply do it like this :
var yourObject = {
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
};
Try using the below syntax:
Common Syntax:
begin
dbms_mview.refresh('mview_name');
end;
Example:
begin
dbms_mview.refresh('inv_trans');
end;
Hope the above helps.
Use:
string.replace(r"C:\Users\Josh\Desktop\20130216", "\\", "\\")
Escape the \
character.
The problem could be in the path of the file you want to open. Try and print the path and see if it is fine I had a similar problem
def scrap(soup,filenm):
htm=(soup.prettify().replace("https://","")).replace("http://","")
if ".php" in filenm or ".aspx" in filenm or ".jsp" in filenm:
filenm=filenm.split("?")[0]
filenm=("{}.html").format(filenm)
print("Converted a file into html that was not compatible")
if ".aspx" in htm:
htm=htm.replace(".aspx",".aspx.html")
print("[process]...conversion fron aspx")
if ".jsp" in htm:
htm=htm.replace(".jsp",".jsp.html")
print("[process]..conversion from jsp")
if ".php" in htm:
htm=htm.replace(".php",".php.html")
print("[process]..conversion from php")
output=open("data/"+filenm,"w",encoding="utf-8")
output.write(htm)
output.close()
print("{} bits of data written".format(len(htm)))
but after adding this code:
nofilenametxt=filenm.split('/')
nofilenametxt=nofilenametxt[len(nofilenametxt)-1]
if (len(nofilenametxt)==0):
filenm=("{}index.html").format(filenm)
For urllib
you can use:
from urllib import FancyURLopener
class MyOpener(FancyURLopener, object):
version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11'
myopener = MyOpener()
myopener.retrieve('https://www.google.com/search?q=test', 'useragent.html')
Take a look at the keypress
function.
I believe the enter
key is 13
so you would want something like:
$('#searchButton').keypress(function(e){
if(e.which == 13){ //Enter is key 13
//Do something
}
});
AddressRegex = "^(ftp|http|https):\/\/([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}:[0-9]{1,5})$";
HostnameRegex = /^(ftp|http|https):\/\/([a-z0-9]+\.)?[a-z0-9][a-z0-9-]*((\.[a-z]{2,6})|(\.[a-z]{2,6})(\.[a-z]{2,6}))$/i
this re are used only for for this type validation
work only if http://www.kk.com http://www.kk.co.in
not works for
Just subscribe to the control's ToolTipTextNeeded event, and return e.TooltipText, much simpler.
2020 Swift 5 :
override var supportedInterfaceOrientations:UIInterfaceOrientationMask {
return .portrait
}
Should be :
HTML :
<form method="post" action="">
<input id="name" name="name" type="text" size="40"/>
<input type="radio" name="radio" value="test"/>Test
<input type="submit" name="submit" value="submit"/>
</form>
PHP Code :
if(isset($_POST['submit']))
{
echo $radio_value = $_POST["radio"];
}
End of the user session means when the browser is shut down.
Read this: http://en.wikipedia.org/wiki/HTTP_cookie#Expires_and_Max-Age
You can try the simple one
select to_date('2020-07-08T15:30:42Z','yyyy-mm-dd"T"hh24:mi:ss"Z"') from dual;
Not sure what you are asking, but... Class.forname, maybe?
After a lot for surfing on web I found this.
PPTRAAS > A free tool to capture screenshot by passing your URL as a parameter
They provide multiple options by simply hitting their URL.
Get full page screenshot
https://pptraas.com/screenshot?url={YOU URL HERE}
Get page screenshot of specific size
https://pptraas.com/screenshot?url={YOU URL HERE}&size=400,400
One can even convert the page to pdf
https://pptraas.com/pdf?url={YOU URL HERE}
I guess that the most correct answer is: Use :nth-child
(or, in this specific case, its counterpart :nth-last-child
). Most only know this selector by its first argument to grab a range of items based on a calculation with n, but it can also take a second argument "of [any CSS selector]".
Your scenario could be solved with this selector: .commentList .comment:nth-last-child(1 of .comment)
But being technically correct doesn't mean you can use it, though, because this selector is as of now only implemented in Safari.
For further reading:
With the verify
parameter you can provide a custom certificate authority bundle
requests.get(url, verify=path_to_bundle_file)
From the docs:
You can pass
verify
the path to a CA_BUNDLE file with certificates of trusted CAs. This list of trusted CAs can also be specified through the REQUESTS_CA_BUNDLE environment variable.
The solution 7 does not give the correct result in the case there's just one word. You should not just count the elements in gregexpr's result (which is -1 if there where not matches) but count the elements > 0.
Ergo:
sapply(gregexpr("\\W+", str1), function(x) sum(x>0) ) + 1
Actually, you can do what you want. If you want to provide multiple interfaces or a class plus interfaces, you have to have your wildcard look something like this:
<T extends ClassA & InterfaceB>
See the Generics Tutorial at sun.com, specifically the Bounded Type Parameters section, at the bottom of the page. You can actually list more than one interface if you wish, using & InterfaceName
for each one that you need.
This can get arbitrarily complicated. To demonstrate, see the JavaDoc declaration of Collections#max
, which (wrapped onto two lines) is:
public static <T extends Object & Comparable<? super T>> T
max(Collection<? extends T> coll)
why so complicated? As said in the Java Generics FAQ: To preserve binary compatibility.
It looks like this doesn't work for variable declaration, but it does work when putting a generic boundary on a class. Thus, to do what you want, you may have to jump through a few hoops. But you can do it. You can do something like this, putting a generic boundary on your class and then:
class classB { }
interface interfaceC { }
public class MyClass<T extends classB & interfaceC> {
Class<T> variable;
}
to get variable
that has the restriction that you want. For more information and examples, check out page 3 of Generics in Java 5.0. Note, in <T extends B & C>
, the class name must come first, and interfaces follow. And of course you can only list a single class.
You can set up a background with your GIF file and set the body this way:
body{
background-image:url('http://www.example.com/yourfile.gif');
background-position: center;
background-size: cover;
}
Change background image URL with your GIF. With background-position: center
you can put the image to the center and with background-size: cover
you set the picture to fit all the screen. You can also set background-size: contain
if you want to fit the picture at 100% of the screen but without leaving any part of the picture without showing.
Here's more info about the property:
http://www.w3schools.com/cssref/css3_pr_background-size.asp
Hope it helps :)
In vim You can type :%!xxd to turn it into a hexeditor. :%!xxd -r to go back to normal mode. xxd is shipped in a vim installation.
See here for some remarks about editing binary files with vim (boils down to :set binary to avoid trouble, use only the "R" or "r" command to change text, don't delete characters).
If You are an Emacs fan, see here for a guide on how to edit a binary file with Emacs.
This error will also appear if you try to connect to an exposed port from within a Docker container, when nothing is actively serving the port.
On a host where nothing is listening/bound to that port you'd get a No connection could be made because the target machine actively refused it
error instead when making a request to a local URL that is not served, eg: localhost:5000
. However, if you start a container that binds to the port, but there is no server running inside of it actually serving the port, any requests to that port on localhost will result in:
[Errno 99] Cannot assign requested address
(if called from within the container), or[Errno 0] Error
(if called from outside of the container).You can reproduce this error and the behaviour described above as follows:
Start a dummy container (note: this will pull the python image if not found locally):
docker run --name serv1 -p 5000:5000 -dit python
Then for [Errno 0] Error
enter a Python console on host, while for [Errno 99] Cannot assign requested address
access a Python console on the container by calling:
docker exec -it -u 0 serv1 python
And then in either case call:
import urllib.request
urllib.request.urlopen('https://localhost:5000')
I concluded with treating either of these errors as equivalent to No connection could be made because the target machine actively refused it
rather than trying to fix their cause - although please advise if that's a bad idea.
I've spent over a day figuring this one out, given that all resources and answers I could find on the [Errno 99] Cannot assign requested address
point in the direction of binding to an occupied port, connecting to an invalid IP, sysctl
conflicts, docker network issues, TIME_WAIT
being incorrect, and many more things. Therefore I wanted to leave this answer here, despite not being a direct answer to the question at hand, given that it can be a common cause for the error described in this question.
I already have used Reportlab in one project.
Just to improve Wael's answer and put it on a single line:
dt.Columns.Add("Better", typeof(Boolean)).SetOrdinal(0);
UPDATE: Note that this works when you don't need to do anything else with the DataColumn. Add() returns the column in question, SetOrdinal() returns nothing.
MonoDevelop from: http://monodevelop.com/
There is no equivalent to Visual Studio. However, for writing C# on Mac or Linux, you can't get better than MonoDevelop.
The Mac build is pre beta. From the MonoDevelop site on Mac:
The Mac OS X port of MonoDevelop is under active development and has not seen a stable release yet. Recent work described by Michael Hutchinson has focussed on improving the usability and stability of Monodevelop on the Mac. This work will be released in MonoDevelop 2.2. Right now it's not finished, and is very much an alpha.
Who are you writing the message for? And is that reader typically reading the message pre- or post- ownership the commit themselves?
I think good answers here have been given from both perspectives, I’d perhaps just fall short of suggesting there is a best answer for every project. The split vote might suggest as much.
i.e. to summarise:
Is the message predominantly for other people, typically reading at some point before they have assumed the change: A proposal of what taking the change will do to their existing code.
Is the message predominantly as a journal/record to yourself (or to your team), but typically reading from the perspective of having assumed the change and searching back to discover what happened.
Perhaps this will lead the motivation for your team/project, either way.
If you want to round off then use the round function. Use ceiling function when you want to get the smallest integer just greater than your argument.
For ex: select round(843.4923423423,0) from dual gives you 843 and
select round(843.6923423423,0) from dual gives you 844
Pull from the repository to a new directory, then rename the old one to old_crufty
, and the new one to my_real_webserver_directory
, and you're good to go.
If your intention is that every single file is in SVN, then this is a good way to test your theory. If your intention is that some files are not in SVN, then use Brian's copy/paste technique.
You can change vagrant default machine name by changing value of config.vm.define
.
Here is the simple Vagrantfile which uses getopts and allows you to change the name dynamically:
# -*- mode: ruby -*-
require 'getoptlong'
opts = GetoptLong.new(
[ '--vm-name', GetoptLong::OPTIONAL_ARGUMENT ],
)
vm_name = ENV['VM_NAME'] || 'default'
begin
opts.each do |opt, arg|
case opt
when '--vm-name'
vm_name = arg
end
end
rescue
end
Vagrant.configure(2) do |config|
config.vm.define vm_name
config.vm.provider "virtualbox" do |vbox, override|
override.vm.box = "ubuntu/wily64"
# ...
end
# ...
end
So to use different name, you can run for example:
vagrant --vm-name=my_name up --no-provision
Note: The --vm-name
parameter needs to be specified before up
command.
or:
VM_NAME=my_name vagrant up --no-provision
int days = 1;
var newDate = new Date(Date.now() + days*24*60*60*1000);
var days = 2;_x000D_
var newDate = new Date(Date.now()+days*24*60*60*1000);_x000D_
_x000D_
document.write('Today: <em>');_x000D_
document.write(new Date());_x000D_
document.write('</em><br/> New: <strong>');_x000D_
document.write(newDate);
_x000D_
Try this,
.success { background-color: #ccffcc; float:left;}
Take a look at the section about filling in forms using webdriver in the selenium documentation and the javadoc for the Select class.
To select an option based on the label:
Select select = new Select(driver.findElement(By.xpath("//path_to_drop_down")));
select.deselectAll();
select.selectByVisibleText("Value1");
To get the first selected value:
WebElement option = select.getFirstSelectedOption()
Restart Android Studio Worked in my case
Self Answer (pretty much summary of other's comments and answers):
In RStudio
, Esc
works, on windows, Mac, and ubuntu (and I would guess on other linux distributions as well).
If the process is ran in say ubuntu shell (and this is not R
specific), for example using:
Rscript my_file.R
Ctrl + c
kills the process
Ctrl + z
suspends the process
Within R shell, Ctrl + C
kills helps you escape it
What is a file with extension .sh?
It is a Bourne shell script. They are used in many variations of UNIX-like operating systems. They have no "language" and are interpreted by your shell (interpreter of terminal commands) or if the first line is in the form
#!/path/to/interpreter
they will use that particular interpreter. Your file has the first line:
#!/bin/bash
and that means that it uses Bourne Again Shell, so called bash. It is for all practical purposes a replacement for good old sh.
Depending upon the interpreter you will have different language in which the file is written.
Keep in mind, that in UNIX world, it is not the extension of the file that determines what the file is (see How to execute a shell script).
If you come from the world of DOS/Windows, you will be familiar with files that have .bat or .cmd extensions (batch files). They are not similar in content, but are akin in design.
How to execute a shell script
Unlike some silly operating systems, *nix does not rely exclusively on extensions to determine what to do with a file. Permissions are also used. This means that if you attempt to run the shell script after downloading it, it will be the same as trying to "run" any text file. The ".sh" extension is there only for your convenience to recognize that file.
You will need to make the file executable. Let's assume that you have downloaded your file as file.sh
, you can then run in your terminal:
chmod +x file.sh
chmod
is a command for changing file's permissions, +x
sets execute permissions (in this case for everybody) and finally you have your file name.
You can also do it in GUI. Most of the time you can right click on the file and select properties, in XUbuntu the permissions options look like this:
If you do not wish to change the permissions. You can also force the shell to run the command. In the terminal you can run:
bash file.sh
The shell should be the same as in the first line of your script.
How safe is it?
You may find it weird that you must perform another task manually in order to execute a file. But this is partially because of strong need for security.
Basically when you download and run a bash script, it is the same thing as somebody telling you "run all these commands in sequence on your computer, I promise that the results will be good and safe". Ask yourself if you trust the party that has supplied this file, ask yourself if you are sure that have downloaded the file from the same place as you thought, maybe even have a glance inside to see if something looks out of place (although that requires that you know something about *nix commands and bash programming).
Unfortunately apart from the warning above I cannot give a step-by-step description of what you should do to prevent evil things from happening with your computer; so just keep in mind that any time you get and run an executable file from someone you're actually saying, "Sure, you can use my computer to do something".
Not having a compiler by me right now, I'll answer by asking a question:
Have you tried this? Does it work?
long key = -1L;
PreparedStatement statement = connection.prepareStatement();
statement.executeUpdate(YOUR_SQL_HERE, PreparedStatement.RETURN_GENERATED_KEYS);
ResultSet rs = statement.getGeneratedKeys();
if (rs != null && rs.next()) {
key = rs.getLong(1);
}
Disclaimer: Obviously, I haven't compiled this, but you get the idea.
PreparedStatement is a subinterface of Statement, so I don't see a reason why this wouldn't work, unless some JDBC drivers are buggy.
Based on @erakitin answer, but also compatible for Android versions < API level 17. Sadly Activity.isDestroyed() is only supported since API level 17, so if you're targeting an older API level just like me, you'll have to check it yourself. Haven't got the View not attached to window manager
exception after that.
Example code
public class MainActivity extends Activity {
private TestAsyncTask mAsyncTask;
private ProgressDialog mProgressDialog;
private boolean mIsDestroyed;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (condition) {
mAsyncTask = new TestAsyncTask();
mAsyncTask.execute();
}
}
@Override
protected void onResume() {
super.onResume();
if (mAsyncTask != null && mAsyncTask.getStatus() != AsyncTask.Status.FINISHED) {
Toast.makeText(this, "Still loading", Toast.LENGTH_LONG).show();
return;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
mIsDestroyed = true;
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
public class TestAsyncTask extends AsyncTask<Void, Void, AsyncResult> {
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = ProgressDialog.show(MainActivity.this, "Please wait", "doing stuff..");
}
@Override
protected AsyncResult doInBackground(Void... arg0) {
// Do long running background stuff
return null;
}
@Override
protected void onPostExecute(AsyncResult result) {
// Use MainActivity.this.isDestroyed() when targeting API level 17 or higher
if (mIsDestroyed)// Activity not there anymore
return;
mProgressDialog.dismiss();
// Handle rest onPostExecute
}
}
}
In my case, there were an error in the php.ini open_basedir variable.
If you're using PHP you just do your query and then you can unset an specific element:
$sql = "SELECT * FROM ........ your query";
$result = $conection->query($sql); // execute your query
$row_cnt = $result->num_rows;
if ($row_cnt > 0) {
while ($row = $result->fetch_object()) {
unset($row->your_column_name); // Exclude column from your fetch
$data[] = $row;
}
echo json_encode($data); // or whatever
In java you can do some thing like:
if(driver.getTitle().contains("some expected text"))
//Pass
System.out.println("Page title contains \"some expected text\" ");
else
//Fail
System.out.println("Page title doesn't contains \"some expected text\" ");
You can do it the same way you do it with Mockito on real instances. For example you can chain stubs, the following line will make the first call do nothing, then second and future call to getResources
will throw the exception :
// the stub of the static method
doNothing().doThrow(Exception.class).when(StaticResource.class);
StaticResource.getResource("string");
// the use of the mocked static code
StaticResource.getResource("string"); // do nothing
StaticResource.getResource("string"); // throw Exception
Thanks to a remark of Matt Lachman, note that if the default answer is not changed at mock creation time, the mock will do nothing by default. Hence writing the following code is equivalent to not writing it.
doNothing().doThrow(Exception.class).when(StaticResource.class);
StaticResource.getResource("string");
Though that being said, it can be interesting for colleagues that will read the test that you expect nothing for this particular code. Of course this can be adapted depending on how is perceived understandability of the test.
By the way, in my humble opinion you should avoid mocking static code if your crafting new code. At Mockito we think it's usually a hint to bad design, it might lead to poorly maintainable code. Though existing legacy code is yet another story.
Generally speaking if you need to mock private or static method, then this method does too much and should be externalized in an object that will be injected in the tested object.
Hope that helps.
Regards
The same origin policy is applicable only for browser side programming languages. So if you try to post to a different server than the origin server using JavaScript, then the same origin policy comes into play but if you post directly from the form i.e. the action points to a different server like:
<form action="http://someotherserver.com">
and there is no javascript involved in posting the form, then the same origin policy is not applicable.
See wikipedia for more information
Remove those char * ret
declarations inside if
blocks which hide outer ret
. Therefor you have memory leak and on the other hand un-allocated memory for ret
.
To compare a c-style string you should use strcmp(array,"")
not array!=""
. Your final code should looks like below:
char* appendCharToCharArray(char* array, char a)
{
size_t len = strlen(array);
char* ret = new char[len+2];
strcpy(ret, array);
ret[len] = a;
ret[len+1] = '\0';
return ret;
}
Note that, you must handle the allocated memory of returned ret
somewhere by delete[]
it.
Why you don't use std::string
? it has .append
method to append a character at the end of a string:
std::string str;
str.append('x');
// or
str += x;
Object* o; o = new Object();
Object* o = new Object();
Both these statement creates the object in the heap memory since you are creating the object using "new".
To be able to make the object creation happen in the stack, you need to follow this:
Object o;
Object *p = &o;
The Quassnoi query with a change for large table. Parents with more childs then 10: Formating as str(5) the row_number()
WITH q AS ( SELECT m.*, CAST(str(ROW_NUMBER() OVER (ORDER BY m.ordernum),5) AS VARCHAR(MAX)) COLLATE Latin1_General_BIN AS bc FROM #t m WHERE ParentID =0 UNION ALL SELECT m.*, q.bc + '.' + str(ROW_NUMBER() OVER (PARTITION BY m.ParentID ORDER BY m.ordernum),5) COLLATE Latin1_General_BIN FROM #t m JOIN q ON m.parentID = q.DBID ) SELECT * FROM q ORDER BY bc
There's the possibility of a mis-understanding here. The WinForms framework in .Net automatically designates the first window created (e.g., Application.Run(new SomeForm())
) as the MainWindow
. The win32 API, however, doesn't recognize the idea of a "main window" per process. The message loop is entirely capable of handling as many "main" windows as system and process resources will let you create. So, your process doesn't have a "main window". The best you can do in the general case is use EnumWindows()
to get all the non-child windows active on a given process and try to use some heuristics to figure out which one is the one you want. Luckily, most processes are only likely to have a single "main" window running most of the time, so you should get good results in most cases.
Browser jumps to <element id="abc" />
if there are http://site.com/#abc hash in the address and the element with id="abc" is visible. So, you just should hide the element by default: <element id="anchor" style="display: none" />
.
If there is no visible element with id=hash at the page, the browser would not jump.
Create a script that checks the hash in url, and then finds and shows the prrpopriate element (that is hidden by default).
Disable default "hash-like link" behaviour by binding an onclick event to a link and specify return false;
as a result of onclick event.
When I implemented tabs, I wrote something like that:
<script>
$(function () {
if (location.hash != "") {
selectPersonalTab(location.hash);
}
else {
selectPersonalTab("#cards");
}
});
function selectPersonalTab(hash) {
$("#personal li").removeClass("active");
$("a[href$=" + hash + "]").closest("li").addClass("active");
$("#personaldata > div").hide();
location.hash = hash;
$(hash).show();
}
$("#personal li a").click(function (e) {
var t = e.target;
if (t.href.indexOf("#") != -1) {
var hash = t.href.substr(t.href.indexOf("#"));
selectPersonalTab(hash);
return false;
}
});
</script>
Open the file in text wrangler or notepad ++ and show the formating e.g. in text wrangler you do show invisibles. That way you can see the new line or tabs characters Often excel will add all sorts of tabs in the wrong places and not a last new line character, but you need to show the symbols to see this.
Update: You can now just right click
Right click > Save as in the Console panel to save the logged messages to a file.
Original Answer:
You can use this devtools snippet shown below to create a console.save method. It creates a FileBlob from the input, and then automatically downloads it.
(function(console){
console.save = function(data, filename){
if(!data) {
console.error('Console.save: No data')
return;
}
if(!filename) filename = 'console.json'
if(typeof data === "object"){
data = JSON.stringify(data, undefined, 4)
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a')
a.download = filename
a.href = window.URL.createObjectURL(blob)
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
a.dispatchEvent(e)
}
})(console)
Source: http://bgrins.github.io/devtools-snippets/#console-save
In contribution to ellabeauty's answer. you can also use this dynamic percentage values
$('.bar').css('width', function(){ return ($(this).attr('data-percentage')+'%')});
And probably add custom easing to your css
.bar {
-webkit-transition: width 2.50s ease !important;
-moz-transition: width 2.50s ease !important;
-o-transition: width 2.50s ease !important;
transition: width 2.50s ease !important;
}
If you REALLY want to brute force it, try this, but it will take you a ridiculous amount of time:
your_list = 'abcdefghijklmnopqrstuvwxyz'
complete_list = []
for current in xrange(10):
a = [i for i in your_list]
for y in xrange(current):
a = [x+i for i in your_list for x in a]
complete_list = complete_list+a
On a smaller example, where list = 'ab' and we only go up to 5, this prints the following:
['a', 'b', 'aa', 'ba', 'ab', 'bb', 'aaa', 'baa', 'aba', 'bba', 'aab', 'bab', 'abb', 'bbb', 'aaaa', 'baaa', 'abaa', 'bbaa', 'aaba', 'baba', 'abba', 'bbba', 'aaab', 'baab', 'abab', 'bbab', 'aabb', 'babb', 'abbb', 'bbbb', 'aaaaa', 'baaaa', 'abaaa', 'bbaaa', 'aabaa', 'babaa', 'abbaa', 'bbbaa', 'aaaba','baaba', 'ababa', 'bbaba', 'aabba', 'babba', 'abbba', 'bbbba', 'aaaab', 'baaab', 'abaab', 'bbaab', 'aabab', 'babab', 'abbab', 'bbbab', 'aaabb', 'baabb', 'ababb', 'bbabb', 'aabbb', 'babbb', 'abbbb', 'bbbbb']
' Create The Object
Set FSO = CreateObject("Scripting.FileSystemObject")
' How To Write To A File
Set File = FSO.CreateTextFile("C:\foo\bar.txt",True)
File.Write "Example String"
File.Close
' How To Read From A File
Set File = FSO.OpenTextFile("C:\foo\bar.txt")
Do Until File.AtEndOfStream
Line = File.ReadLine
WScript.Echo(Line)
Loop
File.Close
' Another Method For Reading From A File
Set File = FSO.OpenTextFile("C:\foo\bar.txt")
Set Text = File.ReadAll
WScript.Echo(Text)
File.Close
If you are from the Java world, you can compare a closure with a member function of a class. Look at this example
var f=function(){
var a=7;
var g=function(){
return a;
}
return g;
}
The function g
is a closure: g
closes a
in. So g
can be compared with a member function, a
can be compared with a class field, and the function f
with a class.
Since scipy
's imread
is deprecated, use imageio.imread
.
pip install imageio
height, width, channels = imageio.imread(filepath).shape
Ruby has the tap
method (1.8.7, 1.9.3 and 2.1.0) that's very useful for stuff like this.
original_hash = { :a => 'a', :b => 'b' }
original_hash.clone.tap{ |h| h.each{ |k,v| h[k] = v.upcase } }
# => {:a=>"A", :b=>"B"}
original_hash # => {:a=>"a", :b=>"b"}
int
and unsigned int
are two distinct integer types. (int
can also be referred to as signed int
, or just signed
; unsigned int
can also be referred to as unsigned
.)
As the names imply, int
is a signed integer type, and unsigned int
is an unsigned integer type. That means that int
is able to represent negative values, and unsigned int
can represent only non-negative values.
The C language imposes some requirements on the ranges of these types. The range of int
must be at least -32767
.. +32767
, and the range of unsigned int
must be at least 0
.. 65535
. This implies that both types must be at least 16 bits. They're 32 bits on many systems, or even 64 bits on some. int
typically has an extra negative value due to the two's-complement representation used by most modern systems.
Perhaps the most important difference is the behavior of signed vs. unsigned arithmetic. For signed int
, overflow has undefined behavior. For unsigned int
, there is no overflow; any operation that yields a value outside the range of the type wraps around, so for example UINT_MAX + 1U == 0U
.
Any integer type, either signed or unsigned, models a subrange of the infinite set of mathematical integers. As long as you're working with values within the range of a type, everything works. When you approach the lower or upper bound of a type, you encounter a discontinuity, and you can get unexpected results. For signed integer types, the problems occur only for very large negative and positive values, exceeding INT_MIN
and INT_MAX
. For unsigned integer types, problems occur for very large positive values and at zero. This can be a source of bugs. For example, this is an infinite loop:
for (unsigned int i = 10; i >= 0; i --) [
printf("%u\n", i);
}
because i
is always greater than or equal to zero; that's the nature of unsigned types. (Inside the loop, when i
is zero, i--
sets its value to UINT_MAX
.)
If you want to keep all the style but change few details, you can use the default style defined on the Android and change what you want
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:textColor="@android:color/background_light"
android:paddingStart="?android:attr/listPreferredItemPaddingStart"
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
android:background="?android:attr/activatedBackgroundIndicator"
android:minHeight="?android:attr/listPreferredItemHeightSmall" />
Then set the adapter using:
setListAdapter(new ArrayAdapter<String>(getApplicationContext(),
R.layout.list_item_custom, mStringList));
It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.
Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:
SQL> select * from dba_directories;
... and if not, create one
SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
SQL> grant all on directory DATA_PUMP_DIR to myuser; -- DBAs dont need this grant
Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:
$ expdp system/manager schemas=user1 dumpfile=user1.dpdmp
Or specifying a specific directory, add directory=<directory name>
:
C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR
With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:
$ exp system/manager owner=user1 file=user1.dmp
Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.
Example for American UTF8 (UNIX):
$ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8
Windows uses SET, example using Japanese UTF8:
C:\> set NLS_LANG=Japanese_Japan.AL32UTF8
More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624
Within the AD every user has a property memberOf
. This contains a list of all groups he belongs to.
Here is a little code example:
// (replace "part_of_user_name" with some partial user name existing in your AD)
var userNameContains = "part_of_user_name";
var identity = WindowsIdentity.GetCurrent().User;
var allDomains = Forest.GetCurrentForest().Domains.Cast<Domain>();
var allSearcher = allDomains.Select(domain =>
{
var searcher = new DirectorySearcher(new DirectoryEntry("LDAP://" + domain.Name));
// Apply some filter to focus on only some specfic objects
searcher.Filter = String.Format("(&(&(objectCategory=person)(objectClass=user)(name=*{0}*)))", userNameContains);
return searcher;
});
var directoryEntriesFound = allSearcher
.SelectMany(searcher => searcher.FindAll()
.Cast<SearchResult>()
.Select(result => result.GetDirectoryEntry()));
var memberOf = directoryEntriesFound.Select(entry =>
{
using (entry)
{
return new
{
Name = entry.Name,
GroupName = ((object[])entry.Properties["MemberOf"].Value).Select(obj => obj.ToString())
};
}
});
foreach (var item in memberOf)
{
Debug.Print("Name = " + item.Name);
Debug.Print("Member of:");
foreach (var groupName in item.GroupName)
{
Debug.Print(" " + groupName);
}
Debug.Print(String.Empty);
}
}
Sure, use the .format method. E.g.,
print('{:10s} {:3d} {:7.2f}'.format('xxx', 123, 98))
print('{:10s} {:3d} {:7.2f}'.format('yyyy', 3, 1.0))
print('{:10s} {:3d} {:7.2f}'.format('zz', 42, 123.34))
will print
xxx 123 98.00
yyyy 3 1.00
zz 42 123.34
You can adjust the field sizes as desired. Note that .format
works independently of print
to format a string. I just used print to display the strings. Brief explanation:
10s
format a string with 10 spaces, left justified by default
3d
format an integer reserving 3 spaces, right justified by default
7.2f
format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.
There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.
Update for f-string mode. E.g.,
text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d} {other_number:7.2f}')
For right alignment
print(f'{text:>10} {number:3d} {other_number:7.2f}')
There's no need to use onAuthStateChanged() function in this scenario.
You can easily detect if the user is logged or not by executing:
var user = firebase.auth().currentUser;
For those who face the "returning null" issue, it's just because you are not waiting for the firebase call to complete.
Let's suppose you perform the login action on Page A and then you invoke Page B, on Page B you can call the following JS code to test the expected behavior:
var config = {
apiKey: "....",
authDomain: "...",
databaseURL: "...",
projectId: "..",
storageBucket: "..",
messagingSenderId: ".."
};
firebase.initializeApp(config);
$( document ).ready(function() {
console.log( "testing.." );
var user = firebase.auth().currentUser;
console.log(user);
});
If the user is logged then "var user" will contain the expected JSON payload, if not, then it will be just "null"
And that's all you need.
Regards
In JQuery you can call
$("form:first").trigger("submit")
Don't know if that is much better. I think form.submit(); is pretty universal.
Using writing-mode
and transform
.
.rotate {
writing-mode: vertical-lr;
-webkit-transform: rotate(-180deg);
-moz-transform: rotate(-180deg);
}
<span class="rotate">Hello</span>
Thew problem is because of spaces in the titles(Headers). Remove spaces in all headers and it works fine.
What about creating an additional wrapper class?
package com.naveen.research.sql;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public abstract class PreparedStatementWrapper implements AutoCloseable {
protected PreparedStatement stat;
public PreparedStatementWrapper(Connection con, String query, Object ... params) throws SQLException {
this.stat = con.prepareStatement(query);
this.prepareStatement(params);
}
protected abstract void prepareStatement(Object ... params) throws SQLException;
public ResultSet executeQuery() throws SQLException {
return this.stat.executeQuery();
}
public int executeUpdate() throws SQLException {
return this.stat.executeUpdate();
}
@Override
public void close() {
try {
this.stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Then in the calling class you can implement prepareStatement method as:
try (Connection con = DriverManager.getConnection(JDBC_URL, prop);
PreparedStatementWrapper stat = new PreparedStatementWrapper(con, query,
new Object[] { 123L, "TEST" }) {
@Override
protected void prepareStatement(Object... params) throws SQLException {
stat.setLong(1, Long.class.cast(params[0]));
stat.setString(2, String.valueOf(params[1]));
}
};
ResultSet rs = stat.executeQuery();) {
while (rs.next())
System.out.println(String.format("%s, %s", rs.getString(2), rs.getString(1)));
} catch (SQLException e) {
e.printStackTrace();
}
That is interesting subject.
You can play around with two lifecycle hooks to figure out how it works: ngOnChanges
and ngOnInit
.
Basically when you set default value to Input
that's mean it will be used only in case there will be no value coming on that component.
And the interesting part it will be changed before component will be initialized.
Let's say we have such components with two lifecycle hooks and one property coming from input
.
@Component({
selector: 'cmp',
})
export class Login implements OnChanges, OnInit {
@Input() property: string = 'default';
ngOnChanges(changes) {
console.log('Changed', changes.property.currentValue, changes.property.previousValue);
}
ngOnInit() {
console.log('Init', this.property);
}
}
Situation 1
Component included in html without defined property
value
As result we will see in console:
Init default
That's mean onChange
was not triggered. Init was triggered and property
value is default
as expected.
Situation 2
Component included in html with setted property <cmp [property]="'new value'"></cmp>
As result we will see in console:
Changed
new value
Object {}
Init
new value
And this one is interesting. Firstly was triggered onChange
hook, which setted property
to new value
, and previous value was empty object! And only after that onInit
hook was triggered with new value of property
.
This is the simplest answer:
<?php
$img = get_the_post_thumbnail_url($postID, 'post-thumbnail');
?>
ul
{
list-style-position:inside;
}
Definition and Usage
The list-style-position property specifies if the list-item markers should appear inside or outside the content flow.
Source: http://www.w3schools.com/cssref/pr_list-style-position.asp
As other answers mentioned you can use ajaxStop()
to wait until all ajax request are completed.
$(document).ajaxStop(function() {
// This function will be triggered every time any ajax request is requested and completed
});
If you want do it for an specific ajax()
request the best you can do is use complete()
method inside the certain ajax request:
$.ajax({
type: "POST",
url: "someUrl",
success: function(data) {
// This function will be triggered when ajax returns a 200 status code (success)
},
complete: function() {
// This function will be triggered always, when ajax request is completed, even it fails/returns other status code
},
error: function() {
// This will be triggered when ajax request fail.
}
});
But, If you need to wait only for a few and certain ajax request to be done? Use the wonderful javascript promises to wait until the these ajax you want to wait are done. I made a shortly, easy and readable example to show you how does promises works with ajax.
Please take a look to the next example. I used setTimeout
to clarify the example.
// Note:_x000D_
// resolve() is used to mark the promise as resolved_x000D_
// reject() is used to mark the promise as rejected_x000D_
_x000D_
$(document).ready(function() {_x000D_
$("button").on("click", function() {_x000D_
_x000D_
var ajax1 = new Promise((resolve, reject) => {_x000D_
$.ajax({_x000D_
type: "GET",_x000D_
url: "https://miro.medium.com/max/1200/0*UEtwA2ask7vQYW06.png",_x000D_
xhrFields: { responseType: 'blob'},_x000D_
success: function(data) {_x000D_
setTimeout(function() {_x000D_
$('#image1').attr("src", window.URL.createObjectURL(data));_x000D_
resolve(" Promise ajax1 resolved");_x000D_
}, 1000);_x000D_
},_x000D_
error: function() {_x000D_
reject(" Promise ajax1 rejected");_x000D_
},_x000D_
});_x000D_
});_x000D_
_x000D_
var ajax2 = new Promise((resolve, reject) => {_x000D_
$.ajax({_x000D_
type: "GET",_x000D_
url: "https://cdn1.iconfinder.com/data/icons/social-media-vol-1-1/24/_github-512.png",_x000D_
xhrFields: { responseType: 'blob' },_x000D_
success: function(data) {_x000D_
setTimeout(function() {_x000D_
$('#image2').attr("src", window.URL.createObjectURL(data));_x000D_
resolve(" Promise ajax2 resolved");_x000D_
}, 1500);_x000D_
},_x000D_
error: function() {_x000D_
reject(" Promise ajax2 rejected");_x000D_
},_x000D_
});_x000D_
});_x000D_
_x000D_
var ajax3 = new Promise((resolve, reject) => {_x000D_
$.ajax({_x000D_
type: "GET",_x000D_
url: "https://miro.medium.com/max/632/1*LUfpOf7teWvPdIPTBmYciA.png",_x000D_
xhrFields: { responseType: 'blob' },_x000D_
success: function(data) {_x000D_
setTimeout(function() {_x000D_
$('#image3').attr("src", window.URL.createObjectURL(data));_x000D_
resolve(" Promise ajax3 resolved");_x000D_
}, 2000);_x000D_
},_x000D_
error: function() {_x000D_
reject(" Promise ajax3 rejected");_x000D_
},_x000D_
});_x000D_
});_x000D_
_x000D_
Promise.all([ajax1, ajax2, ajax3]).then(values => {_x000D_
console.log("We waited until ajax ended: " + values);_x000D_
console.log("My few ajax ended, lets do some things!!")_x000D_
}, reason => {_x000D_
console.log("Promises failed: " + reason);_x000D_
});_x000D_
_x000D_
// Or if you want wait for them individually do it like this_x000D_
// ajax1.then(values => {_x000D_
// console.log("Promise 1 resolved: " + values)_x000D_
// }, reason => {_x000D_
// console.log("Promise 1 failed: " + reason)_x000D_
// });_x000D_
});_x000D_
_x000D_
});
_x000D_
img {_x000D_
max-width: 200px;_x000D_
max-height: 100px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<button>Make AJAX request</button>_x000D_
<div id="newContent">_x000D_
<img id="image1" src="">_x000D_
<img id="image2" src="">_x000D_
<img id="image3" src="">_x000D_
</div>
_x000D_
In my case, the padding was because of the sectionHeader and sectionFooter heights, where storyboard allowed me to change it to minimum 1. So in viewDidLoad method:
tableView.sectionHeaderHeight = 0
tableView.sectionFooterHeight = 0
Create a repository folder under your project. Let's take
${project.basedir}/src/main/resources/repo
Then, install your custom jar to this repo:
mvn install:install-file -Dfile=[FILE_PATH] \
-DgroupId=[GROUP] -DartifactId=[ARTIFACT] -Dversion=[VERS] \
-Dpackaging=jar -DlocalRepositoryPath=[REPO_DIR]
Lastly, add the following repo and dependency definitions to the projects pom.xml:
<repositories>
<repository>
<id>project-repo</id>
<url>file://${project.basedir}/src/main/resources/repo</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>[GROUP]</groupId>
<artifactId>[ARTIFACT]</artifactId>
<version>[VERS]</version>
</dependency>
</dependencies>
I asked the same question of the lodash maintainers a while back and they replied by mentioning the !=
operator can be used here:
if(newVal != null) {
// newVal is defined
}
This uses JavaScript's type coercion to check the value for undefined
or null
.
If you are using JSHint to lint your code, add the following comment blocks to tell it that you know what you are doing - most of the time !=
is considered bad.
/* jshint -W116 */
if(newVal != null) {
/* jshint +W116 */
// newVal is defined
}
Press Shift-zz. Saves changes and Quits. Escape didn't work for me.
I am using Git Bash in windows. And couldn't get past this either. My commit messages are simple so I dont want to add another editor atm.
When you decide between fixed width and fluid width you need to think in terms of your ENTIRE page. Generally, you want to pick one or the other, but not both. The examples you listed in your question are, in-fact, in the same fixed-width page. In other words, the Scaffolding page is using a fixed-width layout. The fixed grid and fluid grid on the Scaffolding page are not meant to be examples, but rather the documentation for implementing fixed and fluid width layouts.
The proper fixed width example is here. The proper fluid width example is here.
When observing the fixed width example, you should not see the content changing sizes when your browser is greater than 960px wide. This is the maximum (fixed) width of the page. Media queries in a fixed-width design will designate the minimum widths for particular styles. You will see this in action when you shrink your browser window and see the layout snap to a different size.
Conversely, the fluid-width layout will always stretch to fit your browser window, no matter how wide it gets. The media queries indicate when the styles change, but the width of containers are always a percentage of your browser window (rather than a fixed number of pixels).
The 'responsive' media queries are all ready to go. You just need to decide if you want to use a fixed width or fluid width layout for your page.
Previously, in bootstrap 2, you had to use row-fluid
inside a fluid container and row
inside a fixed container. With the introduction of bootstrap 3, row-fluid
was removed, do no longer use it.
EDIT: As per the comments, some jsFiddles for:
These fiddles are completely Bootstrap-free, based on pure CSS media queries, which makes them a good starting point, for anyone willing to craft similar solution without using Twitter Bootstrap.
You can store your find
output in array if you wish to use the output later as:
array=($(find . -name "*.txt"))
Now to print the each element in new line, you can either use for
loop iterating to all the elements of array, or you can use printf statement.
for i in ${array[@]};do echo $i; done
or
printf '%s\n' "${array[@]}"
You can also use:
for file in "`find . -name "*.txt"`"; do echo "$file"; done
This will print each filename in newline
To only print the find
output in list form, you can use either of the following:
find . -name "*.txt" -print 2>/dev/null
or
find . -name "*.txt" -print | grep -v 'Permission denied'
This will remove error messages and only give the filename as output in new line.
If you wish to do something with the filenames, storing it in array is good, else there is no need to consume that space and you can directly print the output from find
.
jQuery's .eq() can help you traverse through elements with an indexed approach.
var testimonialElements = $(".testimonial");
for(var i=0; i<testimonialElements.length; i++){
var element = testimonialElements.eq(i);
//do something with element
}
Public: https://mvnrepository.com/artifact/com.oracle.database.jdbc/ojdbc6/11.2.0.4
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.4</version>
</dependency>
One-liner. No transpose needed:
df.loc[~(df==0).all(axis=1)]
And for those who like symmetry, this also works...
df.loc[(df!=0).any(axis=1)]
Here's a one-liner:
int age = new DateTime(DateTime.Now.Subtract(birthday).Ticks).Year-1;
This is my solution which perfectly works starting from API 15. This solution keeps all default button click effects, like material RippleEffect
. I have not tested it on lower APIs, but it should work.
All you need to do, is:
1) Create a style which changes only colorAccent
:
<style name="Facebook.Button" parent="ThemeOverlay.AppCompat">
<item name="colorAccent">@color/com_facebook_blue</item>
</style>
I recommend using
ThemeOverlay.AppCompat
or your mainAppTheme
as parent, to keep the rest of your styles.
2) Add these two lines to your button
widget:
style="@style/Widget.AppCompat.Button.Colored"
android:theme="@style/Facebook.Button"
Sometimes your new
colorAccent
isn't showing in Android Studio Preview, but when you launch your app on the phone, the color will be changed.
<Button
android:id="@+id/sign_in_with_facebook"
style="@style/Widget.AppCompat.Button.Colored"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/sign_in_facebook"
android:textColor="@android:color/white"
android:theme="@style/Facebook.Button" />
To ensure that a cell will return a date value and not just a string that looks like a date, first you must set the NumberFormat property to a Date format, then put a real date into the cell's content.
Sub test_date_or_String()
Set c = ActiveCell
c.NumberFormat = "@"
c.Value = CDate("03/04/2014")
Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is a String
c.NumberFormat = "m/d/yyyy"
Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is still a String
c.Value = CDate("03/04/2014")
Debug.Print c.Value & " is a " & TypeName(c.Value) 'C is a date
End Sub
val.ToString("".PadLeft(length, '0'))
There is no single magic function to force a frame to a minimum or fixed size. However, you can certainly force the size of a frame by giving the frame a width and height. You then have to do potentially two more things: when you put this window in a container you need to make sure the geometry manager doesn't shrink or expand the window. Two, if the frame is a container for other widget, turn grid or pack propagation off so that the frame doesn't shrink or expand to fit its own contents.
Note, however, that this won't prevent you from resizing a window to be smaller than an internal frame. In that case the frame will just be clipped.
import Tkinter as tk
root = tk.Tk()
frame1 = tk.Frame(root, width=100, height=100, background="bisque")
frame2 = tk.Frame(root, width=50, height = 50, background="#b22222")
frame1.pack(fill=None, expand=False)
frame2.place(relx=.5, rely=.5, anchor="c")
root.mainloop()
Previous Table syntax:
CREATE TABLE apim_log_request (TransactionId varchar(50) DEFAULT NULL);
For changing the TransactionId to auto increment use this query
ALTER TABLE apim_log_request MODIFY COLUMN TransactionId INT auto_increment;
You need to git add my_project
to stage your new folder. Then git add my_project/*
to stage its contents. Then commit what you've staged using git commit
and finally push your changes back to the source using git push origin master
(I'm assuming you wish to push to the master branch).
public static byte[] ReadImageFile(string imageLocation)
{
byte[] imageData = null;
FileInfo fileInfo = new FileInfo(imageLocation);
long imageFileLength = fileInfo.Length;
FileStream fs = new FileStream(imageLocation, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
imageData = br.ReadBytes((int)imageFileLength);
return imageData;
}
Check out the .read() method of the File object:
http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects
You could do something like:
concat = ""
for file in files:
concat += open(file).read()
or a more 'elegant' python-way:
concat = ''.join([open(f).read() for f in files])
which, according to this article: http://www.skymind.com/~ocrow/python_string/ would also be the fastest.
Try one of these:
gdb -p 12271
gdb /path/to/exe 12271
gdb /path/to/exe
(gdb) attach 12271
If you're using .NET 4.5 you can use the new async/await framework to sleep without locking the thread.
How it works is that you mark the function in need of asynchronous operations, with the async
keyword. This is just a hint to the compiler. Then you use the await
keyword on the line where you want your code to run asynchronously and your program will wait without locking the thread or the UI. The method you call (on the await line) has to be marked with an async
keyword as well and is usually named ending with Async, as in ImportFilesAsync.
What you need to do in your example is:
async
keyword (see example below)using System.Threading.Tasks;
to your code.Your code is now ready to use the Task.Delay
method instead of the System.Threading.Thread.Sleep
method (it is possible to use await
on Task.Delay
because Task.Delay
is marked with async
in its definition).
private async void button1_Click(object sender, EventArgs e)
{
textBox1.Text += "\r\nThread Sleeps!";
await Task.Delay(3000);
textBox1.Text += "\r\nThread awakens!";
}
Here you can read more about Task.Delay and Await.
In case of .css method in jQuery for !important rule will not apply.
In this case we should use .attr function.
For Example:
If you want to add style as below:
<div id='voltaic_holder' style='position:absolute;top:-75px !important'>
You should use:
$("#voltaic_holder").attr("style", "position:absolute;top:-75px !important");
Hope it helps some one.
EDIT: This is a naive algorithm, modelling human conscious thought process, and gets very weak results compared to AI that search all possibilities since it only looks one tile ahead. It was submitted early in the response timeline.
I have refined the algorithm and beaten the game! It may fail due to simple bad luck close to the end (you are forced to move down, which you should never do, and a tile appears where your highest should be. Just try to keep the top row filled, so moving left does not break the pattern), but basically you end up having a fixed part and a mobile part to play with. This is your objective:
This is the model I chose by default.
1024 512 256 128
8 16 32 64
4 2 x x
x x x x
The chosen corner is arbitrary, you basically never press one key (the forbidden move), and if you do, you press the contrary again and try to fix it. For future tiles the model always expects the next random tile to be a 2 and appear on the opposite side to the current model (while the first row is incomplete, on the bottom right corner, once the first row is completed, on the bottom left corner).
Here goes the algorithm. Around 80% wins (it seems it is always possible to win with more "professional" AI techniques, I am not sure about this, though.)
initiateModel();
while(!game_over)
{
checkCornerChosen(); // Unimplemented, but it might be an improvement to change the reference point
for each 3 possible move:
evaluateResult()
execute move with best score
if no move is available, execute forbidden move and undo, recalculateModel()
}
evaluateResult() {
calculatesBestCurrentModel()
calculates distance to chosen model
stores result
}
calculateBestCurrentModel() {
(according to the current highest tile acheived and their distribution)
}
A few pointers on the missing steps. Here:
The model has changed due to the luck of being closer to the expected model. The model the AI is trying to achieve is
512 256 128 x
X X x x
X X x x
x x x x
And the chain to get there has become:
512 256 64 O
8 16 32 O
4 x x x
x x x x
The O
represent forbidden spaces...
So it will press right, then right again, then (right or top depending on where the 4 has created) then will proceed to complete the chain until it gets:
So now the model and chain are back to:
512 256 128 64
4 8 16 32
X X x x
x x x x
Second pointer, it has had bad luck and its main spot has been taken. It is likely that it will fail, but it can still achieve it:
Here the model and chain is:
O 1024 512 256
O O O 128
8 16 32 64
4 x x x
When it manages to reach the 128 it gains a whole row is gained again:
O 1024 512 256
x x 128 128
x x x x
x x x x
Seba Illingworth's code, In case you need time in your file name (it gives 2014-02-21_1035)
echo off
cls
echo -- BACKUP DATABASE --
set /p DATABASENAME=Enter database name:
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)
:: filename format Name-Date (eg MyDatabase-2009.5.19.bak)
set DATESTAMP=%mydate%_%mytime%
set BACKUPFILENAME=%CD%\%DATABASENAME%-%DATESTAMP%.bak
set SERVERNAME=.
echo.
sqlcmd -E -S %SERVERNAME% -d master -Q "BACKUP DATABASE [%DATABASENAME%] TO DISK = N'%BACKUPFILENAME%' WITH INIT , NOUNLOAD , NAME = N'%DATABASENAME% backup', NOSKIP , STATS = 10, NOFORMAT"
echo.
pause
For fields where NULL
is acceptable, you could use var_export($var, true)
to output the string
, integer
, or NULL
literal. Note that you would not surround the output with quotes because they will be automatically added or omitted.
For example:
mysql_query("insert into table2 (f1, f2) values ('{$row['string_field']}', ".var_export($row['null_field'], true).")");
You may also use defer. The main difference is that the promise is not going to resolve or reject eagerly.
You need to increase the memory size in Jdeveloper go to setDomainEnv.cmd.
set WLS_HOME=%WL_HOME%\server
set XMS_SUN_64BIT=256
set XMS_SUN_32BIT=256
set XMX_SUN_64BIT=3072
set XMX_SUN_32BIT=3072
set XMS_JROCKIT_64BIT=256
set XMS_JROCKIT_32BIT=256
set XMX_JROCKIT_64BIT=1024
set XMX_JROCKIT_32BIT=1024
if "%JAVA_VENDOR%"=="Sun" (
set WLS_MEM_ARGS_64BIT=-Xms256m -Xmx512m
set WLS_MEM_ARGS_32BIT=-Xms256m -Xmx512m
) else (
set WLS_MEM_ARGS_64BIT=-Xms512m -Xmx512m
set WLS_MEM_ARGS_32BIT=-Xms512m -Xmx512m
)
and
set MEM_PERM_SIZE_64BIT=-XX:PermSize=256m
set MEM_PERM_SIZE_32BIT=-XX:PermSize=256m
if "%JAVA_USE_64BIT%"=="true" (
set MEM_PERM_SIZE=%MEM_PERM_SIZE_64BIT%
) else (
set MEM_PERM_SIZE=%MEM_PERM_SIZE_32BIT%
)
set MEM_MAX_PERM_SIZE_64BIT=-XX:MaxPermSize=1024m
set MEM_MAX_PERM_SIZE_32BIT=-XX:MaxPermSize=1024m
{
"number" : ["1","2","3"],
"alphabet" : ["a", "b", "c"]
}
Tip: generate error.
declare @Day int, @Config_Node varchar(50)
set @Config_Node = 'value to trace'
set @Day = @Config_Node
You will get this message:
Conversion failed when converting the varchar value 'value to trace' to data type int.
Since you may have more than one legends in a plot, a way to selectively remove just one of the titles without leaving an empty space is to set the name
argument of the scale_
function to NULL
, i.e.
scale_fill_discrete(name = NULL)
(kudos to @pascal for a comment on another thread)
You should be using the json
module. json.dumps(string)
. It can also serialize other python data types.
import json
>>> s = 'my string with "double quotes" blablabla'
>>> json.dumps(s)
<<< '"my string with \\"double quotes\\" blablabla"'
This will work:
if 'A' in df:
But for clarity, I'd probably write it as:
if 'A' in df.columns:
I guess it would be best to fix the database startup script itself. But as a work around, you can add that line to /etc/rc.local
, which is executed about last in init phase.
As of now:
To add the bot to your channel:
* In some platforms like mac native telegram client it may look like that you can add bot as a member, but at the end it won't work.
** the bot doesn't need to be in your contact list.
Another solution to this old question is the new container string array
, introduced in Matlab 2016b. From what I read in the official Matlab docs, this container resembles a cell-array and most of the array-related functions should work out of the box. For your case, new solution would be:
a=repmat('Some text', 10, 1);
This solution resembles a Rich C's solution applied to string array.
Try to add the path to tnsnames.ora to the config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<oracle.manageddataaccess.client>
<version number="4.112.3.60">
<settings>
<setting name="TNS_ADMIN" value="C:\oracle\product\10.2.0\client_1\NETWORK\ADMIN\" />
</settings>
</version>
</oracle.manageddataaccess.client>
</configuration>
If you want to script all table rows then Go with Generate Scripts as described by Daniel Vassallo. You can’t go wrong here
Else Use third party tools such as ApexSQL Script or SSMS Toolpack for more advanced scripting that includes some preprocessing, selective scripting and more.
$this->load->helper('security');
$h=mysql_real_escape_string(strip_image_tags($comment));
If user inputs
<img src="#">
In the database table just insert character this #
Works for me
The problem is the location of the index file (index.php).You must create a symbolic link in the root of the project to public/index.php with the command "ln-s public/index.php index.php"
Call GoogleMap.setMyLocationEnabled(true)
in your Activity
, and add this 2 lines code in the Manifest
:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Honestly, the best way to limit files is on the server side. People can spoof file type on the client so taking in the full file name at server transfer time, parsing out the file type, and then returning a message is usually the best bet.
In my case I didn't add the http://
prefix. Potentially worth checking.
I posted a fiddle here, showing data, remote and local images embedded in SVG, inside an HTML page:
<!DOCTYPE html>
<html>
<head>
<title>SVG embedded bitmaps in HTML</title>
<style>
body{
background-color:#999;
color:#666;
padding:10px;
}
h1{
font-weight:normal;
font-size:24px;
margin-top:20px;
color:#000;
}
h2{
font-weight:normal;
font-size:20px;
margin-top:20px;
}
p{
color:#FFF;
}
svg{
margin:20px;
display:block;
height:100px;
}
</style>
</head>
<body>
<h1>SVG embedded bitmaps in HTML</h1>
<p>The trick appears to be ensuring the image has the correct width and height atttributes</p>
<h2>Example 1: Embedded data</h2>
<svg id="example1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<image x="0" y="0" width="5" height="5" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="/>
</svg>
<h2>Example 2: Remote image</h2>
<svg id="example2" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<image x="0" y="0" width="275" height="95" xlink:href="http://www.google.co.uk/images/srpr/logo3w.png" />
</svg>
<h2>Example 3: Local image</h2>
<svg id="example3" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<image x="0" y="0" width="136" height="23" xlink:href="/img/logo.png" />
</svg>
</body>
</html>
In my case div position was fixed , adding left position was not enough it started working only after adding display block
left:0;
display:block;
So, @Vivek has got the solution to the problem through a dialogue in the Comments rather than through an actual answer.
"The file is being created by user
oracle
just noticed this in our development database. i'm getting this error because, the directory where i try to create the file doesn't have write access forothers
and useroracle
comes underothers
category. "
Who says SO is a Q&A site not a forum? Er, me, amongst others. Anyway, in the absence of an accepted answer to this question I proffer a link to an answer of mine on the topic of UTL_FILE.FOPEN()
. Find it here.
P.S. I'm marking this answer Community Wiki, because it's not a proper answer to this question, just a redirect to somewhere else.
The best way is to check the type, because undefined
/null
/false
are a tricky thing in JS.
So:
if(typeof obj !== "undefined") {
// obj is a valid variable, do something here.
}
Note that typeof
always returns a string, and doesn't generate an error if the variable doesn't exist at all.
When you are in the context of a trigger you have access to the logical table INSERTED which contains all the rows that have just been inserted to the table. You can build your insert to the other table based on a select from Inserted.
Run a packet sniffer (e.g., Wireshark) also on the peer to see whether it's the peer who's sending the RST or someone in the middle.
It is interesting to note that getCanonicalName()
and getSimpleName()
can raise InternalError
when the class name is malformed. This happens for some non-Java JVM languages, e.g., Scala.
Consider the following (Scala 2.11 on Java 8):
scala> case class C()
defined class C
scala> val c = C()
c: C = C()
scala> c.getClass.getSimpleName
java.lang.InternalError: Malformed class name
at java.lang.Class.getSimpleName(Class.java:1330)
... 32 elided
scala> c.getClass.getCanonicalName
java.lang.InternalError: Malformed class name
at java.lang.Class.getSimpleName(Class.java:1330)
at java.lang.Class.getCanonicalName(Class.java:1399)
... 32 elided
scala> c.getClass.getName
res2: String = C
This can be a problem for mixed language environments or environments that dynamically load bytecode, e.g., app servers and other platform software.
You need to rearrange your curly brackets. Your first statement is complete, so R interprets it as such and produces syntax errors on the other lines. Your code should look like:
if (dsnt<0.05) {
wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else if (dst<0.05) {
wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else {
t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
}
To put it more simply, if you have:
if(condition == TRUE) x <- TRUE
else x <- FALSE
Then R reads the first line and because it is complete, runs that in its entirety. When it gets to the next line, it goes "Else? Else what?" because it is a completely new statement. To have R interpret the else as part of the preceding if statement, you must have curly brackets to tell R that you aren't yet finished:
if(condition == TRUE) {x <- TRUE
} else {x <- FALSE}
I had a similar problem and what worked for me was to make a new clone from my original repository