Use stopPropagation method, see an example:
$("#clickable a").click(function(e) {
e.stopPropagation();
});
As said by jQuery Docs:
stopPropagation
method prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
Keep in mind that it does not prevent others listeners to handle this event(ex. more than one click handler for a button), if it is not the desired effect, you must use stopImmediatePropagation
instead.
If you want to be able to add this to any elements without having to copy/paste the same code over and over again, you can make a directive to do this. It is as simple as below:
import {Directive, HostListener} from "@angular/core";
@Directive({
selector: "[click-stop-propagation]"
})
export class ClickStopPropagation
{
@HostListener("click", ["$event"])
public onClick(event: any): void
{
event.stopPropagation();
}
}
Then just add it to the element you want it on:
<div click-stop-propagation>Stop Propagation</div>
React uses event delegation with a single event listener on document for events that bubble, like 'click' in this example, which means stopping propagation is not possible; the real event has already propagated by the time you interact with it in React. stopPropagation on React's synthetic event is possible because React handles propagation of synthetic events internally.
stopPropagation: function(e){
e.stopPropagation();
e.nativeEvent.stopImmediatePropagation();
}
e.preventDefault();
It simply stops the default action of an element.
Instance Ex.:-
prevents the hyperlink from following the URL, prevents the submit button to submit the form. When you have many event handlers and you just want to prevent default event from occuring, & occuring from many times, for that we need to use in the top of the function().
Reason:-
The reason to use e.preventDefault();
is that in our code so something goes wrong in the code, then it will allow to execute the link or form to get submitted or allow to execute or allow whatever action you need to do. & link or submit button will get submitted & still allow further propagation of the event.
<!DOCTYPE html>_x000D_
<html lang="en" dir="ltr">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title></title>_x000D_
</head>_x000D_
<body>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<a href="https://www.google.com" onclick="doSomethingElse()">Preventsss page from redirect</a>_x000D_
<script type="text/javascript">_x000D_
function doSomethingElse(){_x000D_
console.log("This is Test...");_x000D_
}_x000D_
$("a").click(function(e){_x000D_
e.preventDefault(); _x000D_
});_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
return False;
It simply stops the execution of the function().
"return false;
" will end the whole execution of process.
Reason:-
The reason to use return false; is that you don't want to execute the function any more in strictly mode.
<!DOCTYPE html>_x000D_
<html lang="en" dir="ltr">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title></title>_x000D_
</head>_x000D_
<body>_x000D_
<a href="#" onclick="returnFalse();">Blah</a>_x000D_
<script type="text/javascript">_x000D_
function returnFalse(){_x000D_
console.log("returns false without location redirection....")_x000D_
return false;_x000D_
location.href = "http://www.google.com/";_x000D_
_x000D_
}_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
This actually works in AngularJS. Tested on Chrome and Firefox.
.directive('stopScroll', function () {
return {
restrict: 'A',
link: function (scope, element, attr) {
element.bind('mousewheel', function (e) {
var $this = $(this),
scrollTop = this.scrollTop,
scrollHeight = this.scrollHeight,
height = $this.height(),
delta = (e.type == 'DOMMouseScroll' ?
e.originalEvent.detail * -40 :
e.originalEvent.wheelDelta),
up = delta > 0;
var prevent = function() {
e.stopPropagation();
e.preventDefault();
e.returnValue = false;
return false;
};
if (!up && -delta > scrollHeight - height - scrollTop) {
// Scrolling down, but this will take us past the bottom.
$this.scrollTop(scrollHeight);
return prevent();
} else if (up && delta > scrollTop) {
// Scrolling up, but this will take us past the top.
$this.scrollTop(0);
return prevent();
}
});
}
};
})
When the left part is an object instance, you use ->
. Otherwise, you use ::
.
This means that ->
is mostly used to access instance members (though it can also be used to access static members, such usage is discouraged), while ::
is usually used to access static members (though in a few special cases, it's used to access instance members).
In general, ::
is used for scope resolution, and it may have either a class name, parent
, self
, or (in PHP 5.3) static
to its left. parent
refers to the scope of the superclass of the class where it's used; self
refers to the scope of the class where it's used; static
refers to the "called scope" (see late static bindings).
The rule is that a call with ::
is an instance call if and only if:
$this
exists and$this
is either the class of the method being called or a subclass of it.Example:
class A {
public function func_instance() {
echo "in ", __METHOD__, "\n";
}
public function callDynamic() {
echo "in ", __METHOD__, "\n";
B::dyn();
}
}
class B extends A {
public static $prop_static = 'B::$prop_static value';
public $prop_instance = 'B::$prop_instance value';
public function func_instance() {
echo "in ", __METHOD__, "\n";
/* this is one exception where :: is required to access an
* instance member.
* The super implementation of func_instance is being
* accessed here */
parent::func_instance();
A::func_instance(); //same as the statement above
}
public static function func_static() {
echo "in ", __METHOD__, "\n";
}
public function __call($name, $arguments) {
echo "in dynamic $name (__call)", "\n";
}
public static function __callStatic($name, $arguments) {
echo "in dynamic $name (__callStatic)", "\n";
}
}
echo 'B::$prop_static: ', B::$prop_static, "\n";
echo 'B::func_static(): ', B::func_static(), "\n";
$a = new A;
$b = new B;
echo '$b->prop_instance: ', $b->prop_instance, "\n";
//not recommended (static method called as instance method):
echo '$b->func_static(): ', $b->func_static(), "\n";
echo '$b->func_instance():', "\n", $b->func_instance(), "\n";
/* This is more tricky
* in the first case, a static call is made because $this is an
* instance of A, so B::dyn() is a method of an incompatible class
*/
echo '$a->dyn():', "\n", $a->callDynamic(), "\n";
/* in this case, an instance call is made because $this is an
* instance of B (despite the fact we are in a method of A), so
* B::dyn() is a method of a compatible class (namely, it's the
* same class as the object's)
*/
echo '$b->dyn():', "\n", $b->callDynamic(), "\n";
Output:
B::$prop_static: B::$prop_static value B::func_static(): in B::func_static $b->prop_instance: B::$prop_instance value $b->func_static(): in B::func_static $b->func_instance(): in B::func_instance in A::func_instance in A::func_instance $a->dyn(): in A::callDynamic in dynamic dyn (__callStatic) $b->dyn(): in A::callDynamic in dynamic dyn (__call)
This worked for me. It looks like a button and behaves like a link. You can bookmark it for example.
<a href="mypage.aspx?param1=1" style="text-decoration:none;">
<asp:Button PostBackUrl="mypage.aspx?param1=1" Text="my button-like link" runat="server" />
</a>
function get_input_tags($html)
{
$post_data = array();
// a new dom object
$dom = new DomDocument;
//load the html into the object
$dom->loadHTML($html);
//discard white space
$dom->preserveWhiteSpace = false;
//all input tags as a list
$input_tags = $dom->getElementsByTagName('input');
//get all rows from the table
for ($i = 0; $i < $input_tags->length; $i++)
{
if( is_object($input_tags->item($i)) )
{
$name = $value = '';
$name_o = $input_tags->item($i)->attributes->getNamedItem('name');
if(is_object($name_o))
{
$name = $name_o->value;
$value_o = $input_tags->item($i)->attributes->getNamedItem('value');
if(is_object($value_o))
{
$value = $input_tags->item($i)->attributes->getNamedItem('value')->value;
}
$post_data[$name] = $value;
}
}
}
return $post_data;
}
error_reporting(~E_WARNING);
$html = file_get_contents("https://accounts.google.com/ServiceLoginAuth");
print_r(get_input_tags($html));
Your regexp use ^
and $
so it tries to match the entire string. And if you want only a boolean as the result, use test
instead of match
.
var format = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+/;
if(format.test(string)){
return true;
} else {
return false;
}
Tested answer:
In the .view-row css, change:
display:table-row;
to:
display:table
and get rid of "float". Everything will work as expected.
As it has been suggested in the comments, there is no need for a wrapping table. CSS allows for omitting levels of the tree structure (in this case rows) that are implicit. The reason your code doesn't work is that "width" can only be interpreted at the table level, not at the table-row level. When you have a "table" and then "table-cell"s directly underneath, they're implicitly interpreted as sitting in a row.
Working example:
<div class="view">
<div>Type</div>
<div>Name</div>
</div>
with css:
.view {
width:100%;
display:table;
}
.view > div {
width:50%;
display: table-cell;
}
First check - is the working directory the directory that the application is running in:
If this isn't the problem, then ask if Autodesk.Navisworks.Timeliner.dll is requiring another DLL which is not there.
If Timeliner.dll is not a .NET assembly, you can determine the required imports using the command utility DUMPBIN
.
dumpbin /imports Autodesk.Navisworks.Timeliner.dll
If it is a .NET assembly, there are a number of tools that can check dependencies.
Reflector
has already been mentioned, and I use JustDecompile
from Telerik.
/**
* Take a screenshot and move to the given folder location.
*
* @param driver
* @param folderLocation
* @return screenShotFilePath
*/
public static String captureScreenshot(WebDriver driver, String folderLocation) {
// Variable to store screenshot's file path.
String screenShotFilePath = null;
// Generate unique id for screen shot name.
String uniqueId = UUID.randomUUID().toString().substring(31);
if (driver != null) {
// Generate screenshot as a file
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
// New screenshot file path with having file name
screenShotFilePath = folderLocation + File.separator + uniqueId + ".png";
// Move file to the destination location.
FileUtils.moveFile(scrFile, new File(screenShotFilePath));
}
return screenShotFilePath;
}
Number((6.688689).toFixed(1)); // 6.7
var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;
Use toFixed()
function.
(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"
Use this:
public static void wait(int ms)
{
try
{
Thread.sleep(ms);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
}
and, then you can call this method anywhere like:
wait(1000);
Easiest way would be to serve the multiple files bundled up into a ZIP file.
I suppose you could initiate multiple file downloads using a bunch of iframes or popups, but from a usability standpoint, a ZIP file is still better. Who wants to click through ten "Save As" dialogs that the browser will bring up?
I've been messing around with this for about four hours and decided to share this with you.
You can submit a form by clicking a checkbox but the weird thing is that when checking for the submission in php, you would expect the form to be set when you either check or uncheck the checkbox. But this is not true. The form only gets set when you actually check the checkbox, if you uncheck it it won't be set. the word checked at the end of a checkbox input type will cause the checkbox to display checked, so if your field is checked it will have to reflect that like in the example below. When it gets unchecked the php updates the field state which will cause the word checked the disappear.
You HTML should look like this:
<form method='post' action='#'>
<input type='checkbox' name='checkbox' onChange='submit();'
<?php if($page->checkbox_state == 1) { echo 'checked' }; ?>>
</form>
and the php:
if(isset($_POST['checkbox'])) {
// the checkbox has just been checked
// save the new state of the checkbox somewhere
$page->checkbox_state == 1;
} else {
// the checkbox has just been unchecked
// if you have another form ont the page which uses than you should
// make sure that is not the one thats causing the page to handle in input
// otherwise the submission of the other form will uncheck your checkbox
// so this this line is optional:
if(!isset($_POST['submit'])) {
$page->checkbox_state == 0;
}
}
This library works like a charm http://www.codeproject.com/KB/cs/tsnewlib.aspx
It allows you to manage Windows scheduled tasks directly through your .NET code.
continue
is a statement (like for, or if) and must appear standalone. It cannot be used as part of an expression. Partly because continue doesn't return a value, but in an expression every sub-expression must result in some value so the overall expression results in a value. That's the difference between a statement and an expression.
That means continue
cannot be used in a ternary statement or any statement that requires a return value.
Same goes for break;
of course. It's also not usable in expression context, but a strict statement (on the same level as foreach
or an if
block).
Now this might be more surprising for return
, but that's also just a block-level statement. It does return a value (or NULL) to the higher scope/function, but it does not evaluate as expression itself. ? That is: there's no point in doing return(return(false);;
There are below things to do.
git
command can be run successfully in CMDThat means you need to add git
to path when install git or add it to system environment later.
profile.json
Open Settings
, add following snippet inside the word profiles
:
{
"tabTitle": "Git Bash",
"acrylicOpacity" : 0.75,
"closeOnExit" : true,
"colorScheme" : "Campbell",
"commandline" : "C:/Program Files/Git/bin/bash.exe --login",
"cursorColor" : "#FFFFFF",
"cursorShape" : "bar",
"fontFace" : "Consolas",
"fontSize" : 12,
"guid" : "{14ad203f-52cc-4110-90d6-d96e0f41b64d}",
"historySize" : 9001,
"icon": "ms-appdata:///roaming/git-bash_32px.ico",
"name" : "Git Bash",
"padding" : "0, 0, 0, 0",
"snapOnInput" : true,
"useAcrylic" : true
}
The icon can be obtained here: git-bash_32px.ico
You can add icons for Tab to this location:
%LOCALAPPDATA%\packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\RoamingState
Put 32x32 PNG/icons in this folder, and then in profile.json
you can reference the image resource with the path starting with ms-appdata:// .
Note that, please make sure the Guid
is correct and it matches the corresponding correct configs.
Windows Terminal
Simply restate the target field & condition;
where (field like "*AA*" and field not like "*BB*")
Also, for posterity -- Clang (like GCC) accepts the -x
switch to set the language of the input files, for example,
$ clang -x c++ some_random_file.txt
This mailing list thread explains the difference between clang
and clang++
well: Difference between clang and clang++
Add !important
rule to display: table
of your .v-center
class.
.v-center {
display:table !important;
border:2px solid gray;
height:300px;
}
Your display property is being overridden by bootstrap to display: block
.
I implemented the following and it works well. Basically, I set the body dimensions according to the size of the iFrame content. It does mean that our non-iFrame menu can be scrolled off the screen, but otherwise, this makes our sites functional with iPad and iPhone. "workbox" is the ID of our iFrame.
// Configure for scrolling peculiarities of iPad and iPhone
if (navigator.userAgent.indexOf('iPhone') != -1 || navigator.userAgent.indexOf('iPad') != -1)
{
document.body.style.width = "100%";
document.body.style.height = "100%";
$("#workbox").load(function (){ // Wait until iFrame content is loaded before checking dimensions of the content
iframeWidth = $("#workbox").contents().width();
if (iframeWidth > 400)
document.body.style.width = (iframeWidth + 182) + 'px';
iframeHeight = $("#workbox").contents().height();
if (iframeHeight>200)
document.body.style.height = iframeHeight + 'px';
});
}
In my case 'await' never finished because of exception while executing the request, e.g. server not responding, etc. Surround it with try..catch to identify what happened, it'll also complete your 'await' gracefully.
public async Task<Stuff> GetStuff(string id)
{
string path = $"/api/v2/stuff/{id}";
try
{
HttpResponseMessage response = await client.GetAsync(path);
if (response.StatusCode == HttpStatusCode.OK)
{
string json = await response.Content.ReadAsStringAsync();
return JsonUtility.FromJson<Stuff>(json);
}
else
{
Debug.LogError($"Could not retrieve stuff {id}");
}
}
catch (Exception exception)
{
Debug.LogError($"Exception when retrieving stuff {exception}");
}
return null;
}
span { _x000D_
display:inline-block;_x000D_
width:50px;_x000D_
background:blue;_x000D_
font-size:30px;_x000D_
color:white; _x000D_
text-align:center;_x000D_
}
_x000D_
<p><span>Foo</span><span>Bar</span></p>
_x000D_
Give this a try:
$(document).ready(function(){
$("#topbar-show").toggle(function(){
$(this).animate({height:40},200);
},function(){
$(this).animate({height:10},200);
});
});
Please try this command node --version or node -v, either of which should return something like v4.4.5
.
I actually built a Chrome extension that does exactly this, and for all web pages. The source code is on GitHub.
I find three bugs with Trello's approach, which I know because I've faced them myself :)
The copy doesn't work in these scenarios:
I solved #1 by always having a hidden span, rather than creating one when user hits Ctrl/Cmd.
I solved #2 by temporarily clearing the zero-length selection, saving the caret position, doing the copy and restoring the caret position.
I haven't found a fix for #3 yet :) (For information, check the open issue in my GitHub project).
Swift 5 or above# make route view controller by this simple code.
If you are using xcode 11 or above first initialise var window: UIWindow?
in AppDelegate
let rootVC = mainStoryboard.instantiateViewController(withIdentifier: "YOURCONTROLLER") as! YOURCONTROLLER
navigationController.setNavigationBarHidden(true, animated: true)
UIApplication.shared.windows.first?.rootViewController = UINavigationController.init(rootViewController: rootVC)
UIApplication.shared.windows.first?.makeKeyAndVisible()
I would open another terminal on your laptop and do the scp from there, since you already know how to set that connection up.
scp username@remotecomputer:/path/to/file/you/want/to/copy where/to/put/file/on/laptop
The username@remotecomputer
is the same string you used with ssh initially.
The only way is to highlight the lines to comment and press
ctrl + k, ctrl + c
or after highlighted press the toolbar option to comment out the selected lines.
The icons look like this
You could use a generator expression with a default value and then next
it:
next((x for x in seq if predicate(x)), None)
Although for this one-liner you need to be using Python >= 2.6.
This rather popular article further discusses this issue: Cleanest Python find-in-list function?.
In a nutshell, ZooKeeper helps you build distributed applications.
You may describe ZooKeeper as a replicated synchronization service with eventual consistency. It is robust, since the persisted data is distributed between multiple nodes (this set of nodes is called an "ensemble") and one client connects to any of them (i.e., a specific "server"), migrating if one node fails; as long as a strict majority of nodes are working, the ensemble of ZooKeeper nodes is alive. In particular, a master node is dynamically chosen by consensus within the ensemble; if the master node fails, the role of master migrates to another node.
The master is the authority for writes: in this way writes can be guaranteed to be persisted in-order, i.e., writes are linear. Each time a client writes to the ensemble, a majority of nodes persist the information: these nodes include the server for the client, and obviously the master. This means that each write makes the server up-to-date with the master. It also means, however, that you cannot have concurrent writes.
The guarantee of linear writes is the reason for the fact that ZooKeeper does not perform well for write-dominant workloads. In particular, it should not be used for interchange of large data, such as media. As long as your communication involves shared data, ZooKeeper helps you. When data could be written concurrently, ZooKeeper actually gets in the way, because it imposes a strict ordering of operations even if not strictly necessary from the perspective of the writers. Its ideal use is for coordination, where messages are exchanged between the clients.
This is where ZooKeeper excels: reads are concurrent since they are served by the specific server that the client connects to. However, this is also the reason for the eventual consistency: the "view" of a client may be outdated, since the master updates the corresponding server with a bounded but undefined delay.
The replicated database of ZooKeeper comprises a tree of znodes, which are entities roughly representing file system nodes (think of them as directories). Each znode may be enriched by a byte array, which stores data. Also, each znode may have other znodes under it, practically forming an internal directory system.
Interestingly, the name of a znode can be sequential, meaning that the name the client provides when creating the znode is only a prefix: the full name is also given by a sequential number chosen by the ensemble. This is useful, for example, for synchronization purposes: if multiple clients want to get a lock on a resource, they can each concurrently create a sequential znode on a location: whoever gets the lowest number is entitled to the lock.
Also, a znode may be ephemeral: this means that it is destroyed as soon as the client that created it disconnects. This is mainly useful in order to know when a client fails, which may be relevant when the client itself has responsibilities that should be taken by a new client. Taking the example of the lock, as soon as the client having the lock disconnects, the other clients can check whether they are entitled to the lock.
The example related to client disconnection may be problematic if we needed to periodically poll the state of znodes. Fortunately, ZooKeeper offers an event system where a watch can be set on a znode. These watches may be set to trigger an event if the znode is specifically changed or removed or new children are created under it. This is clearly useful in combination with the sequential and ephemeral options for znodes.
A canonical example of Zookeeper usage is distributed-memory computation, where some data is shared between client nodes and must be accessed/updated in a very careful way to account for synchronization.
ZooKeeper offers the library to construct your synchronization primitives, while the ability to run a distributed server avoids the single-point-of-failure issue you have when using a centralized (broker-like) message repository.
ZooKeeper is feature-light, meaning that mechanisms such as leader election, locks, barriers, etc. are not already present, but can be written above the ZooKeeper primitives. If the C/Java API is too unwieldy for your purposes, you should rely on libraries built on ZooKeeper such as cages and especially curator.
Official documentation apart, which is pretty good, I suggest to read Chapter 14 of Hadoop: The Definitive Guide which has ~35 pages explaining essentially what ZooKeeper does, followed by an example of a configuration service.
It's better to create a new factor variable using cut(). I've added a few options using ggplot2 also.
df <- data.frame(
X1=seq(0, 5, by=0.001),
X2=rnorm(df$X1, mean = 3.5, sd = 1.5)
)
# Create new variable for plotting
df$Colour <- cut(df$X2, breaks = c(-Inf, 1, 3, +Inf),
labels = c("low", "medium", "high"),
right = FALSE)
### Base Graphics
plot(df$X1, df$X2,
col = df$Colour, ylim = c(0, 10), xlab = "POS",
ylab = "CS", main = "Plot Title", pch = 21)
plot(df$X1,df$X2,
col = df$Colour, ylim = c(0, 10), xlab = "POS",
ylab = "CS", main = "Plot Title", pch = 19, cex = 0.5)
# Using `with()`
with(df,
plot(X1, X2, xlab="POS", ylab="CS", col = Colour, pch=21, cex=1.4)
)
# Using ggplot2
library(ggplot2)
# qplot()
qplot(df$X1, df$X2, colour = df$Colour)
# ggplot()
p <- ggplot(df, aes(X1, X2, colour = Colour))
p <- p + geom_point() + xlab("POS") + ylab("CS")
p
p + facet_grid(Colour~., scales = "free")
lsof -n -i | awk '{ print $1,$9; }' | sort -u
This displays who's doing what. Remove -n to see hostnames (a bit slower).
Just be aware of TempData persistence, it's a bit tricky. For example if you even simply read TempData inside the current request, it would be removed and consequently you don't have it for the next request. Instead, you can use Peek
method. I would recommend reading this cool article:
this will return first match
@fathers.detect {|f| f["age"] > 35 }
As everyone noticed: you can't. But you can create a obj and assign every var you declare to that obj. That way you can easily check out your vars:
var v = {}; //put everything here
var f = function(a, b){//do something
}; v.f = f; //make's easy to debug
var a = [1,2,3];
v.a = a;
var x = 'x';
v.x = x; //so on...
console.log(v); //it's all there
I tried android:launchMode="singleTask"
, but it didn't help.
Worked for me using android:launchMode="singleInstance"
Random randomGenerator = new Random();
int i = randomGenerator.nextInt(256);
System.out.println((char)i);
Should take care of what you want, assuming you consider '0,'1','2'.. as characters.
You can also use the CSS calc() function to subtract the width of your padding from the percentage of your container's width.
An example:
width: calc((100%) - (32px))
Just be sure to make the subtracted width equal to the total padding, not just one half. If you pad both sides of the inner div with 16px, then you should subtract 32px from the final width, assuming that the example below is what you want to achieve.
.outer {_x000D_
width: 200px;_x000D_
height: 120px;_x000D_
background-color: black;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
height: 40px;_x000D_
top: 30px;_x000D_
position: relative;_x000D_
padding: 16px;_x000D_
background-color: teal;_x000D_
}_x000D_
_x000D_
#inner-1 {_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
#inner-2 {_x000D_
width: calc((100%) - (32px));_x000D_
}
_x000D_
<div class="outer" id="outer-1">_x000D_
<div class="inner" id="inner-1"> width of 100% </div>_x000D_
</div>_x000D_
_x000D_
<br>_x000D_
<br>_x000D_
_x000D_
<div class="outer" id="outer-2">_x000D_
<div class="inner" id="inner-2"> width of 100% - 16px </div>_x000D_
</div>
_x000D_
I actually found that calling fullScroll twice does the trick:
myScrollView.fullScroll(View.FOCUS_DOWN);
myScrollView.post(new Runnable() {
@Override
public void run() {
myScrollView.fullScroll(View.FOCUS_DOWN);
}
});
It may have something to do with the activation of the post() method right after performing the first (unsuccessful) scroll. I think this behavior occurs after any previous method call on myScrollView, so you can try replacing the first fullScroll() method by anything else that may be relevant to you.
git checkout HEAD~ path/to/file
git commit --amend
Well, you pretty much gave yourself the answer. In your CSS give the containing element a min-width. If you have to support IE6 you can use the min-width-trick:
#container {
min-width:800px;
width: auto !important;
width:800px;
}
That will effectively give you 800px min-width in IE6 and any up-to-date browsers.
somevar = tag.getArtist()
I think you want to specify
-H "Content-Type:text/xml"
with a colon, not an equals.
From W3schools and its cross browser back to the dark ages of IE!
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;
var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;
var x = document.getElementById("demo");
x.innerHTML = "Browser inner window width: " + w + ", height: " + h + ".";
alert("Browser inner window width: " + w + ", height: " + h + ".");
</script>
</body>
</html>
$("#button_id").click(function() {
$('#button_id').attr('disabled', 'true');
$('#myDiv').hide(function() { $('#button_id').removeAttr('disabled'); });
});
Don't use .attr()
to do the disabled, use .prop()
, it's better.
get_current_user_id()
will return the current user id (an integer), or will return 0 if the user is not logged in.
if (get_current_user_id()) {
// display navbar here
}
More details here get_current_user_id().
In general, I/O means Input or Output. Those methods throw the IOException
whenever an input or output operation is failed or interpreted. Note that this won't be thrown for reading or writing to memory as Java will be handling it automatically.
Here are some cases which result in IOException
.
Another way that the one described by danield is to have a child container width display inline, and the tipography color you want. The parent element width the text-decoration, and the color of underline you want. Like this:
div{text-decoration:underline;color:#ff0000;display:inline-block;width:50px}_x000D_
div span{color:#000;display:inline}
_x000D_
<div>_x000D_
<span>Hover me, i can have many lines</span>_x000D_
</div>
_x000D_
For local packages
npm list --depth=0
For Global packages
npm list -g --depth=0
The correct command to answer the posted question could be any of the following (assuming branch topic
is already checked out):
git rebase --onto B master
git rebase --onto master~1 master
git rebase --onto B A
git rebase --onto B C
git rebase --onto B
If topic
is not checked out, you simply append topic
to the command (except the last one) like so:
git rebase --onto B master topic
Alternatively, check out the branch first with:
git checkout topic
The basic form of the command we need, cribbed from the documentation, is:
git rebase --onto <Target> [<Upstream> [<Branch>]]
<Branch>
is optional and all it does is checks out the branch specified before executing the rest of the command. If you've already checked out the branch you want to rebase, then you don't need this. Note that you must have specified <Upstream>
in order to specify <Branch>
or git will think you are specifying <Upstream>
.
<Target>
is the commit we will attach our string of commits to. When providing a branch name, you are simply specifying the head commit of that branch. <Target>
can be any commit that won't be contained in the string of commits being moved. For example:
A --- B --- C --- D master
\
\-- X --- Y --- Z feature
To move the entire feature branch, you can not select X
, Y
, Z
, or feature
as the <Target>
since those all are commits inside the group being moved.
<Upstream>
is special because it can mean two different things. If it is a commit that is an ancestor of the checked out branch, then it serves as the cut point. In the example I provided, this would be anything that isn't C
, D
, or master
. All commits after <Upstream>
until the head of the checked out branch are the ones that will be moved.
However, if <Upstream>
is not an ancestor, then git backs up the chain from the specified commit until if finds a common ancestor with the checked out branch (and aborts if it can't find one). In our case, an <Upstream>
of B
, C
, D
, or master
will all result in commit B
serving as the cut point. <Upstream>
is itself an optional command and if it is not specified, then git looks at the parent of the checked out branch which is the equivalent of entering master
.
Now that git has selected the commits it will cut and move, it applies them in order to <Target>
, skipping any that are already applied to target.
Using this starting point:
A --- B --- C --- D --- E master
\
\-- X --- Y --- Z feature
git rebase --onto D A feature
Will apply commits B
, C
, X
, Y
, Z
to commit D
and end up skipping B
and C
because they already have been applied.
git rebase --onto C X feature
Will apply commits Y
and Z
to commit C
, effectively deleting commit X
If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.
Per the jQuery documentation:
Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".
You can handle your error accordingly then.
I created this fiddle that demonstrates this.
$.ajax({
url: "/ajax_json_echo/",
type: "GET",
dataType: "json",
timeout: 1000,
success: function(response) { alert(response); },
error: function(xmlhttprequest, textstatus, message) {
if(textstatus==="timeout") {
alert("got timeout");
} else {
alert(textstatus);
}
}
});?
With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.
Hope this helps!
For example, if you have a users
entity you want to store, with fields (firstname, lastname , email)
and you want autogenerated id, you do this.
@Entity(tableName = "users")
data class Users(
@PrimaryKey(autoGenerate = true)
val id: Long,
val firstname: String,
val lastname: String,
val email: String
)
Room will then autogenerate and auto-increment the id
field.
In percentage :
$('.your-class').click(function (e){
var $this = $(this); // or use $(e.target) in some cases;
var offset = $this.offset();
var width = $this.width();
var height = $this.height();
var posX = offset.left;
var posY = offset.top;
var x = e.pageX-posX;
x = parseInt(x/width*100,10);
x = x<0?0:x;
x = x>100?100:x;
var y = e.pageY-posY;
y = parseInt(y/height*100,10);
y = y<0?0:y;
y = y>100?100:y;
console.log(x+'% '+y+'%');
});
Two answers, both valid, depending on how sloppy you like to be:
1) No, it's not currently possible to inject audio into a phone conversation.
2) Yes, it's possible. It's also an ugly, ugly kludge. Turn on the hands free function of your phone. Create a media player, set the media source, set the volume to 1.0f (highest) and call player.start()
. If the microphone and speakers on the phone are of reasonable quality, the other party to the call will hear the music. He or she will also continue to hear anything you say, as well as ambient and other sounds in your immediate vicinity.
**EDITED for Swift 4.2:
As @Koen commented, swift 4.2 allows:
guard let self = self else {
return // Could not get a strong reference for self :`(
}
// Now self is a strong reference
self.doSomething()
P.S.: Since I am having some up-votes, I would like to recommend the reading about escaping closures.
EDITED: As @tim-vermeulen has commented, Chris Lattner said on Fri Jan 22 19:51:29 CST 2016, this trick should not be used on self, so please don't use it. Check the non escaping closures info and the capture list answer from @gbk.**
For those who use [weak self] in capture list, note that self could be nil, so the first thing I do is check that with a guard statement
guard let `self` = self else {
return
}
self.doSomething()
If you are wondering what the quote marks are around self
is a pro trick to use self inside the closure without needing to change the name to this, weakSelf or whatever.
In Xcode 7, what worked for me was:
Make sure that the Target > Scheme > Run
- is in Debug mode (was Release)
Make sure to check the option "Debug executable":
Solved with the following example:
public void CheckConsoleOutput()
{
Console.WriteLine("Hello, World!");
Trace.WriteLine("Trace Trace the World");
Debug.WriteLine("Debug Debug World");
Assert.IsTrue(true);
}
After running this test, under 'Test Passed', there is the option to view the output, which will bring up the output window.
Having trouble with a button onclick event in jsfiddle?
If so see Onclick event not firing on jsfiddle.net
TortoiseSVN has a command-line interface that can be used for TortoiseSVN GUI automation and it's different from the normal Subversion one.
You can find information about the command-line options of TortoiseSVN in the documentation:
Appendix D. Automating TortoiseSVN. The main program to work with here is TortoiseProc.exe
.
But a note pretty much at the top there already says:
Remember that TortoiseSVN is a GUI client, and this automation guide shows you how to make the TortoiseSVN dialogs appear to collect user input. If you want to write a script which requires no input, you should use the official Subversion command line client instead.
Another option would be that you install the Subversion binaries. Slik SVN is a nice build (and doesn't require a registration like Collabnet). Recent versions of TortoiseSVN also include the command-line client if you choose to install it.
I found another way without setting proxy. I'm currently using an antivirus which has a firewall program. Then, I turn off this firewall and now I can fetch that URL.
If still doesn't work, try to turn off Firewall on your PC, such as Windows Firewall.
That doesn't work because the second parameter should be a mapped entity and of course Integer is not a persistent class (since it doesn't have the @Entity annotation on it).
for you you should do the following:
Query q = em.createNativeQuery("select id from users where username = :username");
q.setParameter("username", "lt");
List<BigDecimal> values = q.getResultList();
or if you want to use HQL you can do something like this:
Query q = em.createQuery("select new Integer(id) from users where username = :username");
q.setParameter("username", "lt");
List<Integer> values = q.getResultList();
Regards.
If you are using forms authentication you could try the code below:
<authentication mode="Forms">
<forms name=".FORM" loginUrl="Login.aspx" defaultUrl="CreateThings.aspx" protection="All" timeout="30" path="/">
</forms>
</authentication>
Here is what you do in Excel 2003:
Here is what you do in Excel 2007:
Once this is done, the sheet is hidden and cannot be unhidden without the password. Make sense?
If you really need to keep some calculations secret, try this: use Access (or another Excel workbook or some other DB of your choice) to calculate what you need calculated, and export only the "unclassified" results to your Excel workbook.
I had this issue with a WinForms Project using VS 2015. My solution was:
ProjectCodeMeter counts LLOC (logical lines of code) exactly as you described (only effective lines). it integrates into eclipse as external code metrics tool, it's not real-time though, it generates a report.actually it counts many source code metrics such as complexity, arithmetic intricacy, hard coded strings, numeric constants.. even estimates development time in hours.
For converting date to string check this thread
Convert java.util.Date to String
And for converting string to date try this,
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class StringToDate
{
public static void main(String[] args) throws ParseException
{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
String strDate = "14/03/2003 08:05:10";
System.out.println("Date - " + sdf.parse(strDate));
}
}
Adding to slebetman answer:
When you say Node.JS
can handle 10,000 concurrent requests they are essentially non-blocking requests i.e. these requests are majorly pertaining to database query.
Internally, event loop
of Node.JS
is handling a thread pool
, where each thread handles a non-blocking request
and event loop continues to listen to more request after delegating work to one of the thread of the thread pool
. When one of the thread completes the work, it send a signal to the event loop
that it has finished aka callback
. Event loop
then process this callback and send the response back.
As you are new to NodeJS, do read more about nextTick
to understand how event loop works internally.
Read blogs on http://javascriptissexy.com, they were really helpful for me when I started with JavaScript/NodeJS.
"Stack Me 123 Heppa1 oeu".toCharArray()
?
Even though you've got your answer, for those that find this question, it is also possible to open an Excel spreadsheet as a JET data store. Borrowing the connection string from a project I've used it on, it will look kinda like this:
strExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & objFile.Path & ";Extended Properties=""Excel 8.0;HDR=Yes"""
strSQL = "SELECT * FROM [RegistrationList$] ORDER BY DateToRegister DESC"
Note that "RegistrationList" is the name of the tab in the workbook. There are a few tutorials floating around on the web with the particulars of what you can and can't do accessing a sheet this way.
Just thought I'd add. :)
There a 3 ways to implement validation:
Validation rule example:
public class NumericValidationRule : ValidationRule
{
public Type ValidationType { get; set; }
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
string strValue = Convert.ToString(value);
if (string.IsNullOrEmpty(strValue))
return new ValidationResult(false, $"Value cannot be coverted to string.");
bool canConvert = false;
switch (ValidationType.Name)
{
case "Boolean":
bool boolVal = false;
canConvert = bool.TryParse(strValue, out boolVal);
return canConvert ? new ValidationResult(true, null) : new ValidationResult(false, $"Input should be type of boolean");
case "Int32":
int intVal = 0;
canConvert = int.TryParse(strValue, out intVal);
return canConvert ? new ValidationResult(true, null) : new ValidationResult(false, $"Input should be type of Int32");
case "Double":
double doubleVal = 0;
canConvert = double.TryParse(strValue, out doubleVal);
return canConvert ? new ValidationResult(true, null) : new ValidationResult(false, $"Input should be type of Double");
case "Int64":
long longVal = 0;
canConvert = long.TryParse(strValue, out longVal);
return canConvert ? new ValidationResult(true, null) : new ValidationResult(false, $"Input should be type of Int64");
default:
throw new InvalidCastException($"{ValidationType.Name} is not supported");
}
}
}
XAML:
Very important: don't forget to set ValidatesOnTargetUpdated="True"
it won't work without this definition.
<TextBox x:Name="Int32Holder"
IsReadOnly="{Binding IsChecked,ElementName=CheckBoxEditModeController,Converter={converters:BooleanInvertConverter}}"
Style="{StaticResource ValidationAwareTextBoxStyle}"
VerticalAlignment="Center">
<!--Text="{Binding Converter={cnv:TypeConverter}, ConverterParameter='Int32', Path=ValueToEdit.Value, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"-->
<TextBox.Text>
<Binding Path="Name"
Mode="TwoWay"
UpdateSourceTrigger="PropertyChanged"
Converter="{cnv:TypeConverter}"
ConverterParameter="Int32"
ValidatesOnNotifyDataErrors="True"
ValidatesOnDataErrors="True"
NotifyOnValidationError="True">
<Binding.ValidationRules>
<validationRules:NumericValidationRule ValidationType="{x:Type system:Int32}"
ValidatesOnTargetUpdated="True" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
<!--NumericValidationRule-->
</TextBox>
INotifyDataErrorInfo example:
public abstract class ViewModelBase : INotifyPropertyChanged, INotifyDataErrorInfo
{
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
ValidateAsync();
}
#endregion
public virtual void OnLoaded()
{
}
#region INotifyDataErrorInfo
private ConcurrentDictionary<string, List<string>> _errors = new ConcurrentDictionary<string, List<string>>();
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
public void OnErrorsChanged(string propertyName)
{
var handler = ErrorsChanged;
if (handler != null)
handler(this, new DataErrorsChangedEventArgs(propertyName));
}
public IEnumerable GetErrors(string propertyName)
{
List<string> errorsForName;
_errors.TryGetValue(propertyName, out errorsForName);
return errorsForName;
}
public bool HasErrors
{
get { return _errors.Any(kv => kv.Value != null && kv.Value.Count > 0); }
}
public Task ValidateAsync()
{
return Task.Run(() => Validate());
}
private object _lock = new object();
public void Validate()
{
lock (_lock)
{
var validationContext = new ValidationContext(this, null, null);
var validationResults = new List<ValidationResult>();
Validator.TryValidateObject(this, validationContext, validationResults, true);
foreach (var kv in _errors.ToList())
{
if (validationResults.All(r => r.MemberNames.All(m => m != kv.Key)))
{
List<string> outLi;
_errors.TryRemove(kv.Key, out outLi);
OnErrorsChanged(kv.Key);
}
}
var q = from r in validationResults
from m in r.MemberNames
group r by m into g
select g;
foreach (var prop in q)
{
var messages = prop.Select(r => r.ErrorMessage).ToList();
if (_errors.ContainsKey(prop.Key))
{
List<string> outLi;
_errors.TryRemove(prop.Key, out outLi);
}
_errors.TryAdd(prop.Key, messages);
OnErrorsChanged(prop.Key);
}
}
}
#endregion
}
View Model Implementation:
public class MainFeedViewModel : BaseViewModel//, IDataErrorInfo
{
private ObservableCollection<FeedItemViewModel> _feedItems;
[XmlIgnore]
public ObservableCollection<FeedItemViewModel> FeedItems
{
get
{
return _feedItems;
}
set
{
_feedItems = value;
OnPropertyChanged("FeedItems");
}
}
[XmlIgnore]
public ObservableCollection<FeedItemViewModel> FilteredFeedItems
{
get
{
if (SearchText == null) return _feedItems;
return new ObservableCollection<FeedItemViewModel>(_feedItems.Where(x => x.Title.ToUpper().Contains(SearchText.ToUpper())));
}
}
private string _title;
[Required]
[StringLength(20)]
//[CustomNameValidationRegularExpression(5, 20)]
[CustomNameValidationAttribute(3, 20)]
public string Title
{
get { return _title; }
set
{
_title = value;
OnPropertyChanged("Title");
}
}
private string _url;
[Required]
[StringLength(200)]
[Url]
//[CustomValidation(typeof(MainFeedViewModel), "UrlValidation")]
/// <summary>
/// Validation of URL should be with custom method like the one that implemented below, or with
/// </summary>
public string Url
{
get { return _url; }
set
{
_url = value;
OnPropertyChanged("Url");
}
}
public MainFeedViewModel(string url, string title)
{
Title = title;
Url = url;
}
/// <summary>
///
/// </summary>
public MainFeedViewModel()
{
}
public MainFeedViewModel(ObservableCollection<FeedItemViewModel> feeds)
{
_feedItems = feeds;
}
private string _searchText;
[XmlIgnore]
public string SearchText
{
get { return _searchText; }
set
{
_searchText = value;
OnPropertyChanged("SearchText");
OnPropertyChanged("FilteredFeedItems");
}
}
#region Data validation local
/// <summary>
/// Custom URL validation method
/// </summary>
/// <param name="obj"></param>
/// <param name="context"></param>
/// <returns></returns>
public static ValidationResult UrlValidation(object obj, ValidationContext context)
{
var vm = (MainFeedViewModel)context.ObjectInstance;
if (!Uri.IsWellFormedUriString(vm.Url, UriKind.Absolute))
{
return new ValidationResult("URL should be in valid format", new List<string> { "Url" });
}
return ValidationResult.Success;
}
#endregion
}
XAML:
<UserControl x:Class="RssReaderTool.Views.AddNewFeedDialogView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="300">
<FrameworkElement.Resources>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate x:Name="TextErrorTemplate">
<DockPanel LastChildFill="True">
<AdornedElementPlaceholder>
<Border BorderBrush="Red"
BorderThickness="2" />
</AdornedElementPlaceholder>
<TextBlock FontSize="20"
Foreground="Red">*?*</TextBlock>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="Validation.HasError"
Value="True">
<Setter Property="ToolTip"
Value="{Binding RelativeSource=
{x:Static RelativeSource.Self},
Path=(Validation.Errors)[0].ErrorContent}"></Setter>
</Trigger>
</Style.Triggers>
</Style>
<!--<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="Validation.HasError"
Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=(Validation.Errors)[0].ErrorContent}" />
</Trigger>
</Style.Triggers>
</Style>-->
</FrameworkElement.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="5" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="5" />
<RowDefinition Height="Auto" />
<RowDefinition Height="5" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Text="Feed Name"
ToolTip="Display" />
<TextBox Text="{Binding MainFeedViewModel.Title,UpdateSourceTrigger=PropertyChanged,ValidatesOnNotifyDataErrors=True,ValidatesOnDataErrors=True}"
Grid.Column="2" />
<TextBlock Text="Feed Url"
Grid.Row="2" />
<TextBox Text="{Binding MainFeedViewModel.Url,UpdateSourceTrigger=PropertyChanged,ValidatesOnNotifyDataErrors=True,ValidatesOnDataErrors=True}"
Grid.Column="2"
Grid.Row="2" />
</Grid>
</UserControl>
IDataErrorInfo:
View Model:
public class OperationViewModel : ViewModelBase, IDataErrorInfo
{
private const int ConstCodeMinValue = 1;
private readonly IEventAggregator _eventAggregator;
private OperationInfoDefinition _operation;
private readonly IEntityFilterer _contextFilterer;
private OperationDescriptionViewModel _description;
public long Code
{
get { return _operation.Code; }
set
{
if (SetProperty(value, _operation.Code, o => _operation.Code = o))
{
UpdateDescription();
}
}
}
public string Description
{
get { return _operation.Description; }
set
{
if (SetProperty(value, _operation.Description, o => _operation.Description = o))
{
UpdateDescription();
}
}
}
public string FriendlyName
{
get { return _operation.FriendlyName; }
set
{
if (SetProperty(value, _operation.FriendlyName, o => _operation.FriendlyName = o))
{
UpdateDescription();
}
}
}
public int Timeout
{
get { return _operation.Timeout; }
set
{
if (SetProperty(value, _operation.Timeout, o => _operation.Timeout = o))
{
UpdateDescription();
}
}
}
public string Category
{
get { return _operation.Category; }
set
{
if (SetProperty(value, _operation.Category, o => _operation.Category = o))
{
UpdateDescription();
}
}
}
public bool IsManual
{
get { return _operation.IsManual; }
set
{
if (SetProperty(value, _operation.IsManual, o => _operation.IsManual = o))
{
UpdateDescription();
}
}
}
void UpdateDescription()
{
//some code
}
#region Validation
#region IDataErrorInfo
public ValidationResult Validate()
{
return ValidationService.Instance.ValidateNumber(Code, ConstCodeMinValue, long.MaxValue);
}
public string this[string columnName]
{
get
{
var validation = ValidationService.Instance.ValidateNumber(Code, ConstCodeMinValue, long.MaxValue);
return validation.IsValid ? null : validation.ErrorContent.ToString();
}
}
public string Error
{
get
{
var result = Validate();
return result.IsValid ? null : result.ErrorContent.ToString();
}
}
#endregion
#endregion
}
XAML:
<controls:NewDefinitionControl x:Class="DiagnosticsDashboard.EntityData.Operations.Views.NewOperationView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:views="clr-namespace:DiagnosticsDashboard.EntityData.Operations.Views"
xmlns:controls="clr-namespace:DiagnosticsDashboard.Core.Controls;assembly=DiagnosticsDashboard.Core"
xmlns:c="clr-namespace:DiagnosticsDashboard.Core.Validation;assembly=DiagnosticsDashboard.Core"
mc:Ignorable="d">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="40" />
<RowDefinition Height="40" />
<RowDefinition Height="40" />
<RowDefinition Height="40" />
<RowDefinition Height="40" />
<RowDefinition Height="40" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Label Grid.Column="0"
Grid.Row="0"
Margin="5">Code:</Label>
<Label Grid.Column="0"
Grid.Row="1"
Margin="5">Description:</Label>
<Label Grid.Column="0"
Grid.Row="2"
Margin="5">Category:</Label>
<Label Grid.Column="0"
Grid.Row="3"
Margin="5">Friendly Name:</Label>
<Label Grid.Column="0"
Grid.Row="4"
Margin="5">Timeout:</Label>
<Label Grid.Column="0"
Grid.Row="5"
Margin="5">Is Manual:</Label>
<TextBox Grid.Column="1"
Text="{Binding Code,UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}"
Grid.Row="0"
Margin="5"/>
<TextBox Grid.Column="1"
Grid.Row="1"
Margin="5"
Text="{Binding Description}" />
<TextBox Grid.Column="1"
Grid.Row="2"
Margin="5"
Text="{Binding Category}" />
<TextBox Grid.Column="1"
Grid.Row="3"
Margin="5"
Text="{Binding FriendlyName}" />
<TextBox Grid.Column="1"
Grid.Row="4"
Margin="5"
Text="{Binding Timeout}" />
<CheckBox Grid.Column="1"
Grid.Row="5"
Margin="5"
IsChecked="{Binding IsManual}"
VerticalAlignment="Center" />
</Grid>
</controls:NewDefinitionControl>
Clean will remove all intermediate and final files created by the build process, such as .obj files and .exe or .dll files.
It does not, however, remove the directories where those files get built. I don't see a compelling reason why you need the directories to be removed. Can you explain further?
If you look inside these directories before and after a "Clean", you should see your compiled output get cleaned up.
you can change
this.router.routeReuseStrategy.shouldReuseRoute = () => false;
at the component level in constructor like bellow
constructor(private router: Router) {
this.router.routeReuseStrategy.shouldReuseRoute = () => false;
}
def cube(x):
if 0<=x: return x**(1./3.)
return -(-x)**(1./3.)
print (cube(8))
print (cube(-8))
Here is the full answer for both negative and positive numbers.
>>>
2.0
-2.0
>>>
Or here is a one-liner;
root_cube = lambda x: x**(1./3.) if 0<=x else -(-x)**(1./3.)
In order to prove that a problem L is NP-complete, we need to do the following steps:
Having struggled with ImageIO
a lot in the past years, I think Andrew Taylor's solution is by far the best compromise (fast: not using ImageIO#read
, and versatile). Thanks man!!
But I was a little frustrated to be compelled to use a local file (File/String), especially in cases where you want to check image sizes coming from, say, a multipart/form-data request where you usually retrieve InputPart
/InputStream
's. So I quickly made a variant that accepts File
, InputStream
and RandomAccessFile
, based on the ability of ImageIO#createImageInputStream
to do so.
Of course, such a method with Object input
, may only remain private and you shall create as many polymorphic methods as needed, calling this one. You can also accept Path
with Path#toFile()
and URL
with URL#openStream()
prior to passing to this method:
private static Dimension getImageDimensions(Object input) throws IOException {
try (ImageInputStream stream = ImageIO.createImageInputStream(input)) { // accepts File, InputStream, RandomAccessFile
if(stream != null) {
IIORegistry iioRegistry = IIORegistry.getDefaultInstance();
Iterator<ImageReaderSpi> iter = iioRegistry.getServiceProviders(ImageReaderSpi.class, true);
while (iter.hasNext()) {
ImageReaderSpi readerSpi = iter.next();
if (readerSpi.canDecodeInput(stream)) {
ImageReader reader = readerSpi.createReaderInstance();
try {
reader.setInput(stream);
int width = reader.getWidth(reader.getMinIndex());
int height = reader.getHeight(reader.getMinIndex());
return new Dimension(width, height);
} finally {
reader.dispose();
}
}
}
throw new IllegalArgumentException("Can't find decoder for this image");
} else {
throw new IllegalArgumentException("Can't open stream for this image");
}
}
}
To create these constraints through the GUI you need the "indexes and keys" dialogue not the check constraints one.
But in your case you just need to run the piece of code you already have. It doesn't need to be entered into the expression dialogue at all.
Tray to add text with html value to textarea but it wil not works
value :
$(document).on('click', '.edit_targets_btn', function() {
$('#add_edit_targets').modal('show');
$('#add_edit_targets_form')[0].reset();
$('#targets_modal_title').text('Doel bijwerken');
$('#action').val('targets_update');
$('#targets_submit_btn').val('Opslaan');
$('#callcenter_targets_id').val($(this).attr("callcenter_targets_id"));
$('#targets_title').val($(this).attr("title"));
$("#targets_content").append($(this).attr("content"));
tinymce.init({
selector: '#targets_content',
setup: function (editor) {
editor.on('change', function () {
tinymce.triggerSave();
});
},
browser_spellcheck : true,
plugins: ['advlist autolink lists image charmap print preview anchor', 'searchreplace visualblocks code fullscreen', 'insertdatetime media table paste code help wordcount', 'autoresize'],
toolbar: 'undo redo | formatselect | ' + ' bold italic backcolor | alignleft aligncenter ' + ' alignright alignjustify | bullist numlist outdent indent |' + ' removeformat | image | help',
relative_urls : false,
remove_script_host : false,
image_list: [<?php $stmt = $db->query('SELECT * FROM images WHERE users_id = ' . $get_user_users_id); foreach ($stmt as $row) { ?>{title: '<?=$row['name']?>', value: '<?=$imgurl?>/image_uploads/<?=$row['src']?>'},<?php } ?>],
min_height: 250,
branding: false
});
});
Here's an example of the ImageCodecInfo suggestion (in VB):
Imports System.Drawing.Imaging
...
Dim ofd as new OpenFileDialog()
ofd.Filter = ""
Dim codecs As ImageCodecInfo() = ImageCodecInfo.GetImageEncoders()
Dim sep As String = String.Empty
For Each c As ImageCodecInfo In codecs
Dim codecName As String = c.CodecName.Substring(8).Replace("Codec", "Files").Trim()
ofd.Filter = String.Format("{0}{1}{2} ({3})|{3}", ofd.Filter, sep, codecName, c.FilenameExtension)
sep = "|"
Next
ofd.Filter = String.Format("{0}{1}{2} ({3})|{3}", ofd.Filter, sep, "All Files", "*.*")
And it looks like this:
I know this is old but if you do a split then join it will remove all occurrences of a particular character ie:
var str = theText.split('A').join('')
will remove all occurrences of 'A' from the string, obviously it's not case sensitive
The standard idiom for integer rounding up is:
int a = (59 + (4 - 1)) / 4;
You add the divisor minus one to the dividend.
I have created following class
@Configuration
public class ConfigUtility {
@Autowired
private Environment env;
public String getProperty(String pPropertyKey) {
return env.getProperty(pPropertyKey);
}
}
and called as follow to get application.properties value
@Autowired
private ConfigUtility configUtil;
public AppResponse getDetails() {
AppResponse response = new AppResponse();
String email = configUtil.getProperty("emailid");
return response;
}
unit tested, working as expected...
After a change of ip in our oracle virtual machine, the listener never worked again. Finally these command solved the problem (where 192.168.10.200 is the new ip)
[oracle@oracle admin]$ sqlplus / as sysdba
SQL*Plus: Release 11.2.0.1.0 Production on Tue May 10 12:57:37 2016
Copyright (c) 1982, 2009, Oracle. All rights reserved.
Connected to: Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production With the Partitioning, OLAP, Data Mining and Real Application Testing options
SQL> alter system set local_listener='(ADDRESS=(PROTOCOL=tcp)(HOST=192.168.10.200)(PORT=1521))' scope=both;
System altered.
SQL> alter system register;
System altered.
SQL> exit
If you need to fetch an object's property dynamically, use the getattr() function: getattr(user, "fullName")
- or to elaborate:
user = User()
property = "fullName"
name = getattr(user, property)
Otherwise just use user.fullName
.
import pygame, sys
from pygame.locals import *
def main():
pygame.init()
DISPLAY=pygame.display.set_mode((500,400),0,32)
WHITE=(255,255,255)
BLUE=(0,0,255)
DISPLAY.fill(WHITE)
pygame.draw.rect(DISPLAY,BLUE,(200,150,100,50))
while True:
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
main()
This creates a simple window 500 pixels by 400 pixels that is white. Within the window will be a blue rectangle. You need to use the pygame.draw.rect
to go about this, and you add the DISPLAY
constant to add it to the screen, the variable blue to make it blue (blue is a tuple that values which equate to blue in the RGB values and it's coordinates.
Look up pygame.org for more info
Just use contains
myFunction(strings.contains(myString))
If you want to retrieve the item selected from listbox, here is the code...
String SelectedItem = listBox1.SelectedItem.Value;
To specify the coordinates within the SVG image independently of the scaled size of the image, use the viewBox
attribute on the SVG element to define what the bounding box of the image is in the coordinate system of the image, and use the width
and height
attributes to define what the width or height are with respect to the containing page.
For instance, if you have the following:
<svg>
<polygon fill=red stroke-width=0
points="0,10 20,10 10,0" />
</svg>
It will render as a 10px by 20px triangle:
Now, if you set only the width and height, that will change the size of the SVG element, but not scale the triangle:
<svg width=100 height=50>
<polygon fill=red stroke-width=0
points="0,10 20,10 10,0" />
</svg>
If you set the view box, that causes it to transform the image such that the given box (in the coordinate system of the image) is scaled up to fit within the given width and height (in the coordinate system of the page). For instance, to scale up the triangle to be 100px by 50px:
<svg width=100 height=50 viewBox="0 0 20 10">
<polygon fill=red stroke-width=0
points="0,10 20,10 10,0" />
</svg>
If you want to scale it up to the width of the HTML viewport:
<svg width="100%" viewBox="0 0 20 10">
<polygon fill=red stroke-width=0
points="0,10 20,10 10,0" />
</svg>
Note that by default, the aspect ratio is preserved. So if you specify that the element should have a width of 100%, but a height of 50px, it will actually only scale up to the height of 50px (unless you have a very narrow window):
<svg width="100%" height="50px" viewBox="0 0 20 10">
<polygon fill=red stroke-width=0
points="0,10 20,10 10,0" />
</svg>
If you actually want it to stretch horizontally, disable aspect ratio preservation with preserveAspectRatio=none
:
<svg width="100%" height="50px" viewBox="0 0 20 10" preserveAspectRatio="none">
<polygon fill=red stroke-width=0
points="0,10 20,10 10,0" />
</svg>
(note that while in my examples I use syntax that works for HTML embedding, to include the examples as an image in StackOverflow I am instead embedding within another SVG, so I need to use valid XML syntax)
What would be useful here would be a LIKE ANY
predicate as is available in PostgreSQL
SELECT *
FROM tbl
WHERE my_col LIKE ANY (ARRAY['%val1%', '%val2%', '%val3%', ...])
Unfortunately, that syntax is not available in Oracle. You can expand the quantified comparison predicate using OR
, however:
SELECT *
FROM tbl
WHERE my_col LIKE '%val1%' OR my_col LIKE '%val2%' OR my_col LIKE '%val3%', ...
Or alternatively, create a semi join using an EXISTS
predicate and an auxiliary array data structure (see this question for details):
SELECT *
FROM tbl t
WHERE EXISTS (
SELECT 1
-- Alternatively, store those values in a temp table:
FROM TABLE (sys.ora_mining_varchar2_nt('%val1%', '%val2%', '%val3%'/*, ...*/))
WHERE t.my_col LIKE column_value
)
For true full-text search, you might want to look at Oracle Text: http://www.oracle.com/technetwork/database/enterprise-edition/index-098492.html
Its simple, just make sure the data type in your columns are the same. For e.g. I faced the same error, that and an another error:
Error in
contrasts<-
(*tmp*
, value = contr.funs[1 + isOF[nn]]) : contrasts can be applied only to factors with 2 or more levels
So, I went back to my excel file or csv file, set a filter on the variable throwing me an error and checked if the distinct datatypes are the same. And... Oh! it had numbers and strings, so I converted numbers to string and it worked just fine for me.
In my dockercontainer (being minimal the problem of not finding java) was, that "which" was not installed. Comipling a project using gradlew used which in ./gradlew to find java Installing which solved the problem.
int value = 3;
var array = Convert.ToString(value, 2).PadLeft(8, '0').ToArray();
Ecu, if you do myObj.a
, then it looks for the property named a of myObj.
If you do myObj[a] =b
then it looks for the a.valueOf()
property of myObj.
Fastest that I found here for PHP 7.2
on Ububntu 18.04
preg_replace('/^(\w+\\\)*/', '', static::class)
class Second:
def __init__(self, data):
self.data = data
class First:
def SecondClass(self, data):
return Second(data)
FirstClass = First()
SecondClass = FirstClass.SecondClass('now you see me')
print SecondClass.data
use git bash in windows. Git Bash processes commands differently than cmd.
Most Windows command prompts will choke when you set environment variables with NODE_ENV=production like that. (The exception is Bash on Windows, which uses native Bash.) Similarly, there's a difference in how windows and POSIX commands utilize environment variables. With POSIX, you use: $ENV_VAR and on windows you use %ENV_VAR%. - cross-env doc
{
...
"scripts": {
"help": "tagove help",
"start": "env NODE_ENV=production tagove start"
}
...
}
use dotenv package to declare the env variables
Another solution:
position: absolute;
top: 0;
left: 0;
just change the top/right/bottom/left to your case.
$time = '09:15 AM';
$chunks = explode(':', $time);
if (strpos( $time, 'AM') === false && $chunks[0] !== '12') {
$chunks[0] = $chunks[0] + 12;
} else if (strpos( $time, 'PM') === false && $chunks[0] == '12') {
$chunks[0] = '00';
}
echo preg_replace('/\s[A-Z]+/s', '', implode(':', $chunks));
In case that you're interested in specific lines, use a result-array:
declare RESULT=($(./myscript)) # (..) = array
echo "First line: ${RESULT[0]}"
echo "Second line: ${RESULT[1]}"
echo "N-th line: ${RESULT[N]}"
It is a memory protection concept. In this compiler creates extra copy to modify data in child and this updated data not reflect in parents data.
Figured it out by testing all the stuff by myself. Couldn't find any topics about it tho, so I'll just leave the solution here. This might not be the only or even the best solution, but it works for my purposes (within getch's limits) and is better than nothing.
Note: proper keyDown()
which would recognize all the keys and actual key presses, is still valued.
Solution: using ord()
-function to first turn the getch()
into an integer (I guess they're virtual key codes, but not too sure) works fine, and then comparing the result to the actual number representing the wanted key. Also, if I needed to, I could add an extra chr()
around the number returned so that it would convert it to a character. However, I'm using mostly down arrow, esc, etc. so converting those to a character would be stupid. Here's the final code:
from msvcrt import getch
while True:
key = ord(getch())
if key == 27: #ESC
break
elif key == 13: #Enter
select()
elif key == 224: #Special keys (arrows, f keys, ins, del, etc.)
key = ord(getch())
if key == 80: #Down arrow
moveDown()
elif key == 72: #Up arrow
moveUp()
Also if someone else needs to, you can easily find out the keycodes from google, or by using python and just pressing the key:
from msvcrt import getch
while True:
print(ord(getch()))
1- If you don't have bash-completion ... : sudo apt-get install bash-completion
2- Edit your .bashrc file and check (or add) :
if [ -f /etc/bash_completion ]; then
. /etc/bash_completion
fi
3- ... before your prompt line : export PS1='$(__git_ps1) \w\$ '
(__git_ps1 will show your git branch)
4- do source .bashrc
EDIT :
Further readings : Don’t Reinvent the Wheel
If you are creating new array then try this :
$arr = ['key' => 'value'];
And if array is already created then try this :
$arr['key'] = 'value';
Use it ...
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.headless = True
driver = webdriver.Chrome(CHROMEDRIVER_PATH, chrome_options=options)
you should use
select FLOOR(DATEDIFF(CURDATE(),DATE(DOB))/365.25) from table_name;
here CURDATE() uses current date you can give own date in 'yyyy-mm-dd' format
DATE(DOB) extract yyyy-mm-dd year from your column which is in DATETIME format
here DOB is your column name (but you should alter table to modify the data type to be DATETIME in your case which is nvarchar)
Note-
this query is used in mysql
this return age in whole year
Some of the solutions here are overly complex. Here's one with 4 lines of code, no batch files, no external apps and all self-contained in the SQL server.
In this example, my table is named "MyTable" and it has two columns named Column1 and Column2. Column2 is an integer, so we need to CAST it to varchar for the export:
DECLARE @FileName varchar(100)
DECLARE @BCPCommand varchar(8000)
DECLARE @ColumnHeader varchar(8000)
SET @FileName = 'C:\Temp\OutputFile.csv'
SELECT @ColumnHeader = COALESCE(@ColumnHeader+',' ,'')+ ''''+column_name +'''' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='MyTable'
SET @BCPCommand = 'bcp "SELECT '+ @ColumnHeader +' UNION ALL SELECT Column1, CAST(Column2 AS varchar(100)) AS Column2 FROM MyTable" queryout "' + @FileName + '" -c -t , -r \n -S . -T'
EXEC master..xp_cmdshell @BCPCommand
You could add this to a stored procedure to fully automate your .CSV file (with header row) creation.
I encountered this using it in Mac, resolved it by using --ignore-platform-reqs
option.
composer install --ignore-platform-reqs
I just used =COUNTIF(Range, "<>")
and it counted non-empty cells for me.
Asset.objects.filter( project__name__contains="Foo" )
function call asStartOfDay()
on java.time.LocalDate
object returns a java.time.LocalDateTime
object
A very minimal light weight plugin: vim-commentary.
gcc to comment a line
gcgc to uncomment. check out the plugin page for more.
v+k/j highlight the block then gcc to comment that block.
Yes, it's built in to jQuery. See the docs at jquery documentation.
ajaxError may be what you want.
Whenever I attempt to remove the constraints that the system had to break, my constraints are no longer enough to satisfy the IB (ie "missing constraints" shows in the IB, which means they're incomplete and won't be used). I actually got around this by setting the constraint it wants to break to low priority, which (and this is an assumption) allows the system to break the constraint gracefully. It's probably not the best solution, but it solved my problem and the resulting constraints worked perfectly.
It's called a Favicon, have a read.
<link rel="shortcut icon" href="http://www.example.com/myicon.ico"/>
You can use this neat tool to generate cross-browser compatible Favicons.
What if you do this (as was suggested earlier):
new_time = dfs['XYF']['TimeUS'].astype(float)
new_time_F = new_time / 1000000
Or just use $json as an object:
$json->$user = array("first" => $first, "last" => $last);
This is how it is returned without the second parameter (as an instance of stdClass).
First, convert the timespan to a string, then to DateTime, then back to a string:
Convert.ToDateTime(timespan.SelectedTime.ToString()).ToShortTimeString();
SSL development libraries have to be installed
CentOS:
$ yum install openssl-devel libffi-devel
Ubuntu:
$ apt-get install libssl-dev libffi-dev
OS X (with Homebrew installed):
$ brew install openssl
public class MyException extends Exception {
// special exception code goes here
}
Throw it as:
throw new MyException ("Something happened")
Catch as:
catch (MyException e)
{
// something
}
Yes, you can use mysqldump
with the --no-data
option:
mysqldump -u user -h localhost --no-data -p database > database.sql
ulimit -s unlimited
lets the stack grow unlimited.
This may prevent your program from crashing if you write programs by recursion, especially if your programs are not tail recursive (compilers can "optimize" those), and the depth of recursion is large.
Not sure about the performance implications, but it seems a possible compromise, at least during development, would be to include both the auto-incremented, integer "surrogate" key, as well as your intended, unique, "natural" key. This would give you the opportunity to evaluate performance, as well as other possible issues, including the changeability of natural keys.
I made my solution based on the posts I found here with Google. And I thought there is no harm to post mine as well even if it is an old thread.
The only plus this code gives is that it can iterate through sub-directories as well.
import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.WildcardFileFilter;
Method is as follows:
List <File> exploreThis(String dirPath){
File topDir = new File(dirPath);
List<File> directories = new ArrayList<>();
directories.add(topDir);
List<File> textFiles = new ArrayList<>();
List<String> filterWildcards = new ArrayList<>();
filterWildcards.add("*.txt");
filterWildcards.add("*.doc");
FileFilter typeFilter = new WildcardFileFilter(filterWildcards);
while (directories.isEmpty() == false)
{
List<File> subDirectories = new ArrayList();
for(File f : directories)
{
subDirectories.addAll(Arrays.asList(f.listFiles((FileFilter)DirectoryFileFilter.INSTANCE)));
textFiles.addAll(Arrays.asList(f.listFiles(typeFilter)));
}
directories.clear();
directories.addAll(subDirectories);
}
return textFiles;
}
In C, using a previously undeclared function constitutes an implicit declaration of the function. In an implicit declaration, the return type is int
if I recall correctly. Now, GCC has built-in definitions for some standard functions. If an implicit declaration does not match the built-in definition, you get this warning.
To fix the problem, you have to declare the functions before using them; normally you do this by including the appropriate header. I recommend not to use the -fno-builtin-*
flags if possible.
Instead of stdlib.h, you should try:
#include <string.h>
That's where strcpy
and strncpy
are defined, at least according to the strcpy
(2) man page.
The exit
function is defined in stdlib.h, though, so I don't know what's going on there.
Query all users and filter by the list from your text file:
$Users = Get-Content 'C:\scripts\Users.txt'
Get-ADUser -Filter '*' -Properties DisplayName,Office |
Where-Object { $Users -contains $_.SamAccountName } |
Select-Object DisplayName, Office |
Export-Csv 'C:\path\to\your.csv' -NoType
Get-ADUser -Filter '*'
returns all AD user accounts. This stream of user objects is then piped into a Where-Object
filter, which checks for each object if its SamAccountName
property is contained in the user list from your input file ($Users
). Only objects with a matching account name are passed forward to the next step of the pipeline. The output can be limited by selecting the relevant properties before exporting the data.
You can further optimize the code by replacing the -contains
operator with hashtable lookups:
$Users = @{}
Get-Content 'C:\scripts\Users.txt' | ForEach-Object { $Users[$_] = $true }
Get-ADUser -Filter '*' -Properties DisplayName,Office |
Where-Object { $Users.ContainsKey($_.SamAccountName) } |
Select-Object DisplayName, Office |
Export-Csv 'C:\path\to\your.csv' -NoType
In the latest IntelliJ IDEA version (2020.1.3 Ultimate Edition), You need to to click this little guy that appears on the top right of the editor window after you make a change to the pom.xml
This little guy is too small and in an unnoticeable position. I liked the previous versions where an alert shows up in the bottom right. Still can't find the option to enable auto import in this version.
Following @Sam Lu's answer,
Indeed Android 4.x blocks certain types from listening to outside touch events, but some types, such as TYPE_SYSTEM_ALERT
, still do the job.
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT);
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View myView = inflater.inflate(R.layout.my_view, null);
myView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.d(TAG, "touch me");
return true;
}
});
// Add layout to window manager
wm.addView(myView, params);
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
If the purpose of reading environment variable is to override the values in the appsetting.json or any other config file, you can archive it through EnvironmentVariablesExtensions.
var builder = new ConfigurationBuilder()
.AddJsonFile("appSettings.json")
.AddEnvironmentVariables(prefix: "ABC_")
var config = builder.Build();
According to this example, Url for the environment is read from the appsettings.json. but when the AddEnvironmentVariables(prefix: "ABC_")
line is added to the ConfigurationBuilder the value appsettings.json will be override by in the environement varibale value.
Look at how Runtime.getRuntime().exec()
passes the String command to the ProcessBuilder
. It uses a tokenizer and explodes the command into individual tokens, then invokes exec(String[] cmdarray, ......)
which constructs a ProcessBuilder
.
If you construct the ProcessBuilder
with an array of strings instead of a single one, you'll get to the same result.
The ProcessBuilder
constructor takes a String...
vararg, so passing the whole command as a single String has the same effect as invoking that command in quotes in a terminal:
shell$ "command with args"
You are not doing error checking after the call to mysql_query:
$result = mysql_query("SELECT * FROM student WHERE IDNO=".$_GET['id']);
if (!$result) { // add this check.
die('Invalid query: ' . mysql_error());
}
In case mysql_query
fails, it returns false
, a boolean
value. When you pass this to mysql_fetch_array
function (which expects a mysql result object
) we get this error.
grep -nr "search string" directory
This gives you the line with the line number.
If you look in the ISAPI And CGI Restrictions, and everything is already set to Allowed, and the ASP.NET installed is v4.0.30319, then in the right, at the "Actions" panel click in the "Edit Feature Settings..." and check both boxes. In my case, they were not.
ArrayList<String> al[] = new ArrayList[n+1];
for(int i = 0;i<n;i++){
al[i] = new ArrayList<String>();
}
Looking at the Eclipse plugin docs I found some useful tasks that rebuilt my classpath and updated the required dependencies.
gradle cleanEclipse
to clean the Eclipse configuration completely. If this doesn;t work you may try more specific tasks:
gradle cleanEclipseProject
to remove the .project filegradle cleanEclipseClasspath
to empty the project's classpathgradle eclipse
to rebuild the Eclipse configurationCalling readOnly=false from readOnly=true doesn't work since the previous transaction continues.
In your example, the handle() method on your service layer is starting a new read-write transaction. If the handle method in turn calls service methods that annotated read-only, the read-only will take no effect as they will participate in the existing read-write transaction instead.
If it is essential for those methods to be read-only, then you can annotate them with Propagation.REQUIRES_NEW, and they will then start a new read-only transaction rather than participate in the existing read-write transaction.
Here is a worked example, CircuitStateRepository is a spring-data JPA repository.
BeanS calls a transactional=read-only Bean1, which does a lookup and calls transactional=read-write Bean2 which saves a new object.
31 09:39:44.199 [pool-1-thread-1] DEBUG o.s.orm.jpa.JpaTransactionManager - Creating new transaction with name [nz.co.vodafone.wcim.business.Bean1.startSomething]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
Bean 2 pariticipates in it.
31 09:39:44.230 [pool-1-thread-1] DEBUG o.s.orm.jpa.JpaTransactionManager - Participating in existing transaction
Nothing is committed to the database.
Now change Bean2 @Transactional
annotation to add propagation=Propagation.REQUIRES_NEW
Bean1 starts a read-only tx.
31 09:31:36.418 [pool-1-thread-1] DEBUG o.s.orm.jpa.JpaTransactionManager - Creating new transaction with name [nz.co.vodafone.wcim.business.Bean1.startSomething]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
Bean2 starts a new read-write tx
31 09:31:36.449 [pool-1-thread-1] DEBUG o.s.orm.jpa.JpaTransactionManager - Suspending current transaction, creating new transaction with name [nz.co.vodafone.wcim.business.Bean2.createSomething]
And the changes made by Bean2 are now committed to the database.
Here's the example, tested with spring-data, hibernate and oracle.
@Named
public class BeanS {
@Inject
Bean1 bean1;
@Scheduled(fixedRate = 20000)
public void runSomething() {
bean1.startSomething();
}
}
@Named
@Transactional(readOnly = true)
public class Bean1 {
Logger log = LoggerFactory.getLogger(Bean1.class);
@Inject
private CircuitStateRepository csr;
@Inject
private Bean2 bean2;
public void startSomething() {
Iterable<CircuitState> s = csr.findAll();
CircuitState c = s.iterator().next();
log.info("GOT CIRCUIT {}", c.getCircuitId());
bean2.createSomething(c.getCircuitId());
}
}
@Named
@Transactional(readOnly = false)
public class Bean2 {
@Inject
CircuitStateRepository csr;
public void createSomething(String circuitId) {
CircuitState c = new CircuitState(circuitId + "-New-" + new DateTime().toString("hhmmss"), new DateTime());
csr.save(c);
}
}
As it is being mentioned in pir's comment - the .apply(lambda el: scale.fit_transform(el))
method will produce the following warning:
DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and will raise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.
Converting your columns to numpy arrays should do the job (I prefer StandardScaler):
from sklearn.preprocessing import StandardScaler
scale = StandardScaler()
dfTest[['A','B','C']] = scale.fit_transform(dfTest[['A','B','C']].as_matrix())
-- Edit Nov 2018 (Tested for pandas 0.23.4)--
As Rob Murray mentions in the comments, in the current (v0.23.4) version of pandas .as_matrix()
returns FutureWarning
. Therefore, it should be replaced by .values
:
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit_transform(dfTest[['A','B']].values)
-- Edit May 2019 (Tested for pandas 0.24.2)--
As joelostblom mentions in the comments, "Since 0.24.0
, it is recommended to use .to_numpy()
instead of .values
."
Updated example:
import pandas as pd
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
dfTest = pd.DataFrame({
'A':[14.00,90.20,90.95,96.27,91.21],
'B':[103.02,107.26,110.35,114.23,114.68],
'C':['big','small','big','small','small']
})
dfTest[['A', 'B']] = scaler.fit_transform(dfTest[['A','B']].to_numpy())
dfTest
A B C
0 -1.995290 -1.571117 big
1 0.436356 -0.603995 small
2 0.460289 0.100818 big
3 0.630058 0.985826 small
4 0.468586 1.088469 small
For example :
<div style="height:100px; width:100px; background:#000000"></div>
_x000D_
here.
you give css to div of height and width having 100px and background as black.
PS : try to avoid inline-css you can make external CSS and import in your html file.
you can refer here for CSS
hope this helps.
In addition to the previous answers, here is a way to calculate the distance inside a SELECT:
CREATE FUNCTION Get_Distance
(
@La1 float , @Lo1 float , @La2 float, @Lo2 float
)
RETURNS TABLE
AS
RETURN
-- Distance in Meters
SELECT GEOGRAPHY::Point(@La1, @Lo1, 4326).STDistance(GEOGRAPHY::Point(@La2, @Lo2, 4326))
AS Distance
GO
Usage:
select Distance
from Place P1,
Place P2,
outer apply dbo.Get_Distance(P1.latitude, P1.longitude, P2.latitude, P2.longitude)
Scalar functions also work but they are very inefficient when computing large amount of data.
I hope this might help someone.
I use ajaxcontrol toolkit's AutoComplete
Uri uri = null;
if (!Uri.TryCreate(url, UriKind.Absolute, out uri) || null == uri)
return false;
else
return true;
Here url
is the string you have to test.
If you wish to mutate the same object rather than create a new one.
The following example will delete all 0 or empty values:
const sev = { a: 1, b: 0, c: 3 };
const deleteKeysBy = (obj, predicate) =>
Object.keys(obj)
.forEach( (key) => {
if (predicate(obj[key])) {
delete(obj[key]);
}
});
deleteKeysBy(sev, val => !val);
I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.
Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled
Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is
Here is the xmlns reference:
xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI"
Then the ad itself:
<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480" AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/>
Do this in your .profile -
export JAVA_HOME=`/usr/libexec/java_home`
(backticks make sure to execute the command and place its value in JAVA_HOME)
Better late than never. Your original code used enumerate()
, but you only used the i
index to check if it's the last item in a list. Here's an simpler alternative (if you don't need enumerate()
) using negative indexing:
for data in data_list:
code_that_is_done_for_every_element
if data != data_list[-1]:
code_that_is_done_between_elements
if data != data_list[-1]
checks if the current item in the iteration is NOT the last item in the list.
Hope this helps, even nearly 11 years later.
In my case, the MissingMethodException was for a method that was in the same file!
However, I had just added a NuGet package that uses .Net Standard2 to my 4.7.1-targeting project, which caused a version conflict for System.Net.Http (4.7.1: version 4.0.0.0, the NuGet package using .NET Standard 2 wants 4.2.0.0). This seem to be known issues that should be better in 4.7.2 (see note 2).
I had used a binding redirect like this in all other my projects, because there were exceptions as soon as it tried to load the 4.2.0.0 which I didn't have:
<dependentAssembly>
<assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
Except in this one project, where it seems it tries to load System.Net.Http only while calling a local function that uses a System.Net.Http.HttpResponseMessage as it's parameter or return type (parameter during debugging, return type when I run the tests without the debugger, also a bit strange). And instead of showing a message that it could not load the 4.2.0.0 version of System.Net.Http, it returns this exception.
Your server needs to have the php modules installed so it can parse php code.
If you are on ubuntu you can do this easily with
sudo apt-get install apache2
sudo apt-get install php5
sudo apt-get install libapache2-mod-php5
sudo /etc/init.d/apache2 restart
Otherwise you may compile apache with php: http://dan.drydog.com/apache2php.html
Specifying your server OS will help others to answer more specifically.
Much like the manual, use an equals (=
) sign in your definition of the parameters:
function dosomething($var1, $var2, $var3 = 'somevalue'){
// Rest of function here...
}
npm install --global yarn
npm upgrade --global yarn
This should work.
default_scope
This works for Rails 4+:
class Book < ActiveRecord::Base
default_scope { order(created_at: :desc) }
end
For Rails 2.3, 3, you need this instead:
default_scope order('created_at DESC')
For Rails 2.x:
default_scope :order => 'created_at DESC'
Where created_at
is the field you want the default sorting to be done on.
Note: ASC is the code to use for Ascending and DESC is for descending (desc
, NOT dsc
!).
scope
Once you're used to that you can also use scope
:
class Book < ActiveRecord::Base
scope :confirmed, :conditions => { :confirmed => true }
scope :published, :conditions => { :published => true }
end
For Rails 2 you need named_scope
.
:published
scope gives you Book.published
instead of
Book.find(:published => true)
.
Since Rails 3 you can 'chain' those methods together by concatenating them with periods between them, so with the above scopes you can now use Book.published.confirmed
.
With this method, the query is not actually executed until actual results are needed (lazy evaluation), so 7 scopes could be chained together but only resulting in 1 actual database query, to avoid performance problems from executing 7 separate queries.
You can use a passed in parameter such as a date or a user_id (something that will change at run-time and so will need that 'lazy evaluation', with a lambda, like this:
scope :recent_books, lambda
{ |since_when| where("created_at >= ?", since_when) }
# Note the `where` is making use of AREL syntax added in Rails 3.
Finally you can disable default scope with:
Book.with_exclusive_scope { find(:all) }
or even better:
Book.unscoped.all
which will disable any filter (conditions) or sort (order by).
Note that the first version works in Rails2+ whereas the second (unscoped) is only for Rails3+
So
... if you're thinking, hmm, so these are just like methods then..., yup, that's exactly what these scopes are!
They are like having def self.method_name ...code... end
but as always with ruby they are nice little syntactical shortcuts (or 'sugar') to make things easier for you!
In fact they are Class level methods as they operate on the 1 set of 'all' records.
Their format is changing however, with rails 4 there are deprecation warning when using #scope without passing a callable object. For example scope :red, where(color: 'red') should be changed to scope :red, -> { where(color: 'red') }
.
As a side note, when used incorrectly, default_scope can be misused/abused.
This is mainly about when it gets used for actions like where
's limiting (filtering) the default selection (a bad idea for a default) rather than just being used for ordering results.
For where
selections, just use the regular named scopes. and add that scope on in the query, e.g. Book.all.published
where published
is a named scope.
In conclusion, scopes are really great and help you to push things up into the model for a 'fat model thin controller' DRYer approach.
You can use the following command:
git checkout filename
If you have a branch with the same file name you have to use this command:
git checkout -- filename
This worked for me too, but with an addition (below).
protected void Page_Load(object sender, EventArgs e) {
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
scriptManager.RegisterPostBackControl(this.btnExcelExport);
//Further code goes here....
}
I was registering a script on my button to click on another button after its event was finished processing. In order for it to work, I had to remove the other button from the Update Panel (just in case somebody faces the same problem).
Just enable NuGet Package Restore. Right click your solution > choose 'Enable NuGet Package Restore'.
This will create the .nuget folder with NuGet.Config file and fixed my problem.
If the images are in an array and you want to iterate through each element and print it, you can write the code as follows:
plt.figure(figsize=(10,10)) # specifying the overall grid size
for i in range(25):
plt.subplot(5,5,i+1) # the number of images in the grid is 5*5 (25)
plt.imshow(the_array[i])
plt.show()
Also note that I used subplot and not subplots. They're both different
The shape of your matrix C
is wrong; it's the transpose of what you actually want it to be. (But I agree with ulmangt: the Right Thing is almost certainly to use numpy, really.)
You will want to look into the nl2br() function along with the trim().
The nl2br()
will insert <br />
before the newline character (\n
) and the trim()
will remove any ending \n
or whitespace characters.
$text = trim($_POST['textareaname']); // remove the last \n or whitespace character
$text = nl2br($text); // insert <br /> before \n
That should do what you want.
UPDATE
The reason the following code will not work is because in order for \n
to be recognized, it needs to be inside double quotes since double quotes parse data inside of them, where as single quotes takes it literally, IE "\n"
$text = str_replace('\n', '<br />', $text);
To fix it, it would be:
$text = str_replace("\n", '<br />', $text);
But it is still better to use the builtin nl2br()
function, PHP provides.
EDIT
Sorry, I figured the first question was so you could add the linebreaks in, indeed this will change the answer quite a bit, as anytype of explode()
will remove the line breaks, but here it is:
$text = trim($_POST['textareaname']);
$textAr = explode("\n", $text);
$textAr = array_filter($textAr, 'trim'); // remove any extra \r characters left behind
foreach ($textAr as $line) {
// processing here.
}
If you do it this way, you will need to append the <br />
onto the end of the line before the processing is done on your own, as the explode()
function will remove the \n
characters.
Added the array_filter()
to trim()
off any extra \r
characters that may have been lingering.
This depends on what content do you have. You need to initialize your requestMessage.Content
property with new HttpContent. For example:
...
// Add request body
if (isPostRequest)
{
requestMessage.Content = new ByteArrayContent(content);
}
...
where content
is your encoded content. You also should include correct Content-type header.
Oh, it can be even nicer (from this answer):
requestMessage.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}", Encoding.UTF8, "application/json");
Try this:
fname = "feed.txt"
num_lines = 0
num_words = 0
num_chars = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
num_lines += 1
num_words += len(words)
num_chars += len(line)
Back to your code:
fname = "feed.txt"
fname = open('feed.txt', 'r')
what's the point of this? fname
is a string first and then a file object. You don't really use the string defined in the first line and you should use one variable for one thing only: either a string or a file object.
for line in feed:
lines = line.split('\n')
line
is one line from the file. It does not make sense to split('\n')
it.
It's Very Easy To Install By Following Below Steps In Eclipse JUNO version
Help-->Eclipse Marketplace-->Find: beside Textbox u can type "Egit"-->select Egit-git team provider intall button-->follow next steps and finally click finish
No plugin necessary for just this task. Cobbled this together from a couple other scripts:
$('INPUT[type="file"]').change(function () {
var ext = this.value.match(/\.(.+)$/)[1];
switch (ext) {
case 'jpg':
case 'jpeg':
case 'png':
case 'gif':
$('#uploadButton').attr('disabled', false);
break;
default:
alert('This is not an allowed file type.');
this.value = '';
}
});
The trick here is to set the upload button to disabled unless and until a valid file type is selected.
Since you want to pivot multiple columns of data, I would first suggest unpivoting the result
, score
and grade
columns so you don't have multiple columns but you will have multiple rows.
Depending on your version of SQL Server you can use the UNPIVOT function or CROSS APPLY. The syntax to unpivot the data will be similar to:
select ratio, col, value
from GRAND_TOTALS
cross apply
(
select 'result', cast(result as varchar(10)) union all
select 'score', cast(score as varchar(10)) union all
select 'grade', grade
) c(col, value)
See SQL Fiddle with Demo. Once the data has been unpivoted, then you can apply the PIVOT function:
select ratio = col,
[current ratio], [gearing ratio], [performance ratio], total
from
(
select ratio, col, value
from GRAND_TOTALS
cross apply
(
select 'result', cast(result as varchar(10)) union all
select 'score', cast(score as varchar(10)) union all
select 'grade', grade
) c(col, value)
) d
pivot
(
max(value)
for ratio in ([current ratio], [gearing ratio], [performance ratio], total)
) piv;
See SQL Fiddle with Demo. This will give you the result:
| RATIO | CURRENT RATIO | GEARING RATIO | PERFORMANCE RATIO | TOTAL |
|--------|---------------|---------------|-------------------|-----------|
| grade | Good | Good | Satisfactory | Good |
| result | 1.29400 | 0.33840 | 0.04270 | (null) |
| score | 60.00000 | 70.00000 | 50.00000 | 180.00000 |
Make sure /webapps/ROOT file is there and it has all the icons, WEB-INF, and index.jsp is in the folder.
When you startup Tomcat, it will run this code in <Tomcat-Directory>/conf/web.xml
directory:
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
The location of index.jsp is in <Tomcat-Directory>/webapps/ROOT/index.jsp
Also, try running tomcat from the /bin directory using ./catalina.sh start
instead of ./startup.sh
. For some reason, ./startup.sh
isn't as reliable.
Like this?
[bool]($myObject.PSobject.Properties.name -match "myPropertyNameToTest")
I think there's proper solution. Configure the yii\data\Sort
object:
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort'=> ['defaultOrder' => ['topic_order' => SORT_ASC]],
]);
If you have this problem in Windows 10, and you know you have premisions on folder (You could write before but it just started to print exception PermissionError recently).. You will need to install Windows updates... I hope someone will help this info.
Even more slower one
public int slowerLength(String myString) {
String[] str = myString.split("");
int lol=0;
for(String s:str){
lol++;
}
return (lol-1)
}
Or even slower,
public int slowerLength(String myString) {
String[] str = myString.split("");
int lol=0;
for(String s:str){
lol += s.toCharArray().length;
}
return lol
}
Use below code for HTML5 validation pattern alphanumeric without / with space :-
for HTML5 validation pattern alphanumeric without space :- onkeypress="return event.charCode >= 48 && event.charCode <= 57 || event.charCode >= 97 && event.charCode <= 122 || event.charCode >= 65 && event.charCode <= 90"
for HTML5 validation pattern alphanumeric with space :-
onkeypress="return event.charCode >= 48 && event.charCode <= 57 || event.charCode >= 97 && event.charCode <= 122 || event.charCode >= 65 && event.charCode <= 90 || event.charCode == 32"
If you need to iterate a queue ... queue isn't the container you need.
Why did you pick a queue?
Why don't you take a container that you can iterate over?
1.if you pick a queue then you say you want to wrap a container into a 'queue' interface: - front - back - push - pop - ...
if you also want to iterate, a queue has an incorrect interface. A queue is an adaptor that provides a restricted subset of the original container
2.The definition of a queue is a FIFO and by definition a FIFO is not iterable
There are two ways to fix these issues,
1st is simple without code change that is
run your script by Python3,
if you still want to run on python2 then
after running your python script, when you are entering the input keep in mind
string
then just start typing down with "input goes with double-quote" and it will work in python2.7 and 2nd way is with code changes
use the below import and run with any version of python
from six.moves import input
raw_input()
function instead of input()
function in your code with any importstr()
function like str(input())
and then assign to any variableAs error implies:
name 'dude' is not defined
i.e. for python 'dude' become variable here and it's not having any value of python defined type assigned
so only its crying like baby so if we define a 'dude' variable and assign any value and pass to it, it will work but that's not what we want as we don't know what user will enter and moreover we want to capture the user input.
Fact about these method:
input()
function: This function takes the value and type of the input you enter as it is without modifying it type.
raw_input()
function: This function explicitly converts the input you give into type string,Note:
The vulnerability in input() method lies in the fact that the variable accessing the value of input can be accessed by anyone just by using the name of variable or method.
You can use the .hide()
function bound to a click
handler:
$('#Comanda').click(function() {
$(this).hide();
});
checked :
public Constructor(Class<E> c, int length) {
elements = (E[]) Array.newInstance(c, length);
}
or unchecked :
public Constructor(int s) {
elements = new Object[s];
}
You should try :
<?php
echo CI_VERSION;
?>
Or check the file system/core/CodeIgniter.php
You could do something along this lines:
def static_example():
if not hasattr(static_example, "static_var"):
static_example.static_var = 0
static_example.static_var += 1
return static_example.static_var
print static_example()
print static_example()
print static_example()
I would say in some cases it's ok to do nothing. Probably not something you should be doing by default, but in case there should be no way for the interrupt to happen, I'm not sure what else to do (probably logging error, but that does not affect program flow).
One case would be in case you have a task (blocking) queue. In case you have a daemon Thread handling these tasks and you do not interrupt the Thread by yourself (to my knowledge the jvm does not interrupt daemon threads on jvm shutdown), I see no way for the interrupt to happen, and therefore it could be just ignored. (I do know that a daemon thread may be killed by the jvm at any time and therefore are unsuitable in some cases).
EDIT: Another case might be guarded blocks, at least based on Oracle's tutorial at: http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html
Or you may do the following
$(this).animate({color:'black'},1000);
But you need to download the color plugin from here.
You don't. The whole reason for using the SecureString object is to avoid creating a string object (which is loaded into memory and kept there in plaintext until garbage collection). However, you can add characters to a SecureString by appending them.
var s = new SecureString();
s.AppendChar('d');
s.AppendChar('u');
s.AppendChar('m');
s.AppendChar('b');
s.AppendChar('p');
s.AppendChar('a');
s.AppendChar('s');
s.AppendChar('s');
s.AppendChar('w');
s.AppendChar('d');
Update 2019-10:
As stated in the issue tracker, Google has been working on a new SDK tools release that runs on current JVMs (9+)!
You can download and use the new Android SDK Command-line Tools (1.0.0) inside Android Studio or by manually downloading them from the Google servers:
For the latest versions check the URLs inside the repository.xml.
If you manually unpack the command line tools, take care of placing them in a subfolder inside your $ANDROID_HOME
(e.g. $ANDROID_HOME/cmdline-tools/...
).
in your server side the code looks like:
var request = require('request');
app.post('/add', function(req, res){
console.log(req.body);
request.post(
{
url:'http://localhost:6001/add',
json: {
unit_name:req.body.unit_name,
unit_price:req.body.unit_price
},
headers: {
'Content-Type': 'application/json'
}
},
function(error, response, body){
// console.log(error);
// console.log(response);
console.log(body);
res.send(body);
});
// res.send("body");
});
in receiving end server code looks like:
app.post('/add', function(req, res){
console.log('received request')
console.log(req.body);
let adunit = new AdUnit(req.body);
adunit.save()
.then(game => {
res.status(200).json({'adUnit':'AdUnit is added successfully'})
})
.catch(err => {
res.status(400).send('unable to save to database');
})
});
Schema is just two properties unit_name and unit_price.
The problem is that you are trying to access a collection in an object that is detached. You need to re-attach the object before accessing the collection to the current session. You can do that through
session.update(object);
Using lazy=false
is not a good solution because you are throwing away the Lazy Initialization feature of hibernate. When lazy=false
, the collection is loaded in memory at the same time that the object is requested. This means that if we have a collection with 1000 items, they all will be loaded in memory, despite we are going to access them or not. And this is not good.
Please read this article where it explains the problem, the possible solutions and why is implemented this way. Also, to understand Sessions and Transactions you must read this other article.
Classic mode (the only mode in IIS6 and below) is a mode where IIS only works with ISAPI extensions and ISAPI filters directly. In fact, in this mode, ASP.NET is just an ISAPI extension (aspnet_isapi.dll) and an ISAPI filter (aspnet_filter.dll). IIS just treats ASP.NET as an external plugin implemented in ISAPI and works with it like a black box (and only when it's needs to give out the request to ASP.NET). In this mode, ASP.NET is not much different from PHP or other technologies for IIS.
Integrated mode, on the other hand, is a new mode in IIS7 where IIS pipeline is tightly integrated (i.e. is just the same) as ASP.NET request pipeline. ASP.NET can see every request it wants to and manipulate things along the way. ASP.NET is no longer treated as an external plugin. It's completely blended and integrated in IIS. In this mode, ASP.NET HttpModule
s basically have nearly as much power as an ISAPI filter would have had and ASP.NET HttpHandler
s can have nearly equivalent capability as an ISAPI extension could have. In this mode, ASP.NET is basically a part of IIS.
When using with a reactive bootstrap table, i did not find that the
table.classname td {
syntax worked as there was no <table>
tag at all. Often modules like this don't use the outer tag but just dive right in maybe using <thead>
and <tbody>
for grouping at most.
Simply specifying like this worked great though
td.classname {
max-width: 500px;
text-overflow: initial;
white-space: wrap;
word-wrap: break-word;
}
as it directly overrides the <td>
and can be used only on the elements you want to change. Maybe in your case use
thead.medium td {
font-size: 40px;
}
tbody.small td {
font-size:25px;
}
for consistent font sizing with a bigger header.
If you can avoid the need for concurrent writes to a single file, it sounds like you do not need a database to store the chat messages.
Just append the conversation to a text file (1 file per user\conversation). and have a directory/ file structure
Here's a simplified view of the file structure:
chat-1-bob.txt
201101011029, hi
201101011030, fine thanks.
chat-1-jen.txt
201101011030, how are you?
201101011035, have you spoken to bill recently?
chat-2-bob.txt
201101021200, hi
201101021222, about 12:22
chat-2-bill.txt
201101021201, Hey Bob,
201101021203, what time do you call this?
You would then only need to store the userid, conversation id (guid ?) & a reference to the file name.
I think you will find it hard to get a more simple scaleable solution.
You can use LOAD_FILE
to get the data too see: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html
If you have a requirement to rebuild a conversation you will need to put a value (date time) alongside your sent chat message (in the file) to allow you to merge & sort the files, but at this point it is probably a good idea to consider using a database.
Perhaps I am misunderstanding the question, by why exactly would you not want to use atoi? I see no point in reinventing the wheel.
Am I just missing the point here?
You should use the OpenFileDialog class like this
Dim fd As OpenFileDialog = New OpenFileDialog()
Dim strFileName As String
fd.Title = "Open File Dialog"
fd.InitialDirectory = "C:\"
fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
fd.FilterIndex = 2
fd.RestoreDirectory = True
If fd.ShowDialog() = DialogResult.OK Then
strFileName = fd.FileName
End If
Then you can use the File class.
My problem was solved by changing the build variant as suggested by Stéphane , if anyone was struggling to find the "Build variants" as I did here is a screenshot where you can find it .
In addition to dumping the ordered list of keys alongside the dictionary, another low-tech solution, which has the advantage of being explicit, is to dump the (ordered) list of key-value pairs ordered_dict.items()
; loading is a simple OrderedDict(<list of key-value pairs>)
. This handles an ordered dictionary despite the fact that JSON does not have this concept (JSON dictionaries have no order).
It is indeed nice to take advantage of the fact that json
dumps the OrderedDict in the correct order. However, it is in general unnecessarily heavy and not necessarily meaningful to have to read all JSON dictionaries as an OrderedDict (through the object_pairs_hook
argument), so an explicit conversion of only the dictionaries that must be ordered makes sense too.
If you have to ask an user to give input and then you have to count how many numbers are there then you can follow this:
count_number = input('Please enter a number\t')
print(len(count_number))
Note: Never take an int as user input.
I used to do the same until I started using libraries that are compiled differently depending on the environment such as PyCrypto. My PyCrypto mac wouldn't work on Cygwin wouldn't work on Ubuntu.
It becomes an utter nightmare to manage the repository.
Either way I found it easier to manage the pip freeze & a requirements file than having it all in git. It's cleaner too since you get to avoid the commit spam for thousands of files as those libraries get updated...
Note that Visual C++ compilers are removed when you upgrade Visual Studio 2010 Professional or Visual Studio 2010 Express to Visual Studio 2010 SP1 if Windows SDK v7.1 is installed.
For instructions on resolving this, see KB2519277 on the Microsoft Support site.
Empty strings and nulls are fundamentally different. A null is an absence of a value and an empty string is a value that is empty.
The programming language making assumptions about the "value" of a variable, in this case an empty string, will be as good as initiazing the string with any other value that will not cause a null reference problem.
Also, if you pass the handle to that string variable to other parts of the application, then that code will have no ways of validating whether you have intentionally passed a blank value or you have forgotten to populate the value of that variable.
Another occasion where this would be a problem is when the string is a return value from some function. Since string is a reference type and can technically have a value as null and empty both, therefore the function can also technically return a null or empty (there is nothing to stop it from doing so). Now, since there are 2 notions of the "absence of a value", i.e an empty string and a null, all the code that consumes this function will have to do 2 checks. One for empty and the other for null.
In short, its always good to have only 1 representation for a single state. For a broader discussion on empty and nulls, see the links below.
https://softwareengineering.stackexchange.com/questions/32578/sql-empty-string-vs-null-value
I got the same issue since I was referring old- Microsoft.EntityFrameworkCore.Tools.DotNet
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
After upgrading to the newer version it got resolved
you can do this as well
$path = "/public";
$objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);
foreach ($objects as $name => $object) {
if ('.' === $object) continue;
if ('..' === $object) continue;
str_replace('/public/', '/', $object->getPathname());
// for example : /public/admin/image.png => /admin/image.png
Columns of data frames are already vectors, you just have to pull them out. Note that you place the column you want after the comma, not before it:
> newV <- df[,1]
> newV
[1] 1 2 4 2
If you actually want a row, then do what Ben said and please use words correctly in the future.
Solution below:
SELECT GROUP_CONCAT(field_attr_best_weekday_value)as RAVI
FROM content_field_attr_best_weekday LEFT JOIN content_type_attraction
on content_field_attr_best_weekday.nid = content_type_attraction.nid
GROUP BY content_field_attr_best_weekday.nid
Use this, you also can change the Joins
Just for kicks:
var elmt = [0, 1, 2,3, 4, 7, 8, 9, 10, 11], l = elmt.length, i = -1, sum = 0;
for (; ++i < l; sum += elmt[i])
;
document.body.appendChild(document.createTextNode('The sum of all the elements is: ' + sum + ' The average of all the elements is: ' + (sum / l)));
I know this is not fully relevant, but since this answer is ranked first many a times when you search 'how to display images in Jupyter', please consider this answer as well.
You could use matplotlib to show an image as follows.
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
image = mpimg.imread("your_image.png")
plt.imshow(image)
plt.show()
You shouldn't be using the BinaryFormatter
for this - that's for serializing .Net types to a binary file so they can be read back again as .Net types.
If it's stored in the database, hopefully, as a varbinary
- then all you need to do is get the byte array from that (that will depend on your data access technology - EF and Linq to Sql, for example, will create a mapping that makes it trivial to get a byte array) and then write it to the file as you do in your last line of code.
With any luck - I'm hoping that fileContent
here is the byte array? In which case you can just do
System.IO.File.WriteAllBytes("hello.pdf", fileContent);
For only a small amount of objects the update_or_create works well, but if you're doing over a large collection it won't scale well. update_or_create always first runs a SELECT and thereafter an UPDATE.
for the_bar in bars:
updated_rows = SomeModel.objects.filter(bar=the_bar).update(foo=100)
if not updated_rows:
# if not exists, create new
SomeModel.objects.create(bar=the_bar, foo=100)
This will at best only run the first update-query, and only if it matched zero rows run another INSERT-query. Which will greatly increase your performance if you expect most of the rows to actually be existing.
It all comes down to your use case though. If you are expecting mostly inserts then perhaps the bulk_create() command could be an option.
I had the same problem. I made a simple UIView category that fixes that.
.h
#import <UIKit/UIKit.h>
@interface UIView (GCLibrary)
@property (nonatomic, assign) CGFloat height;
@property (nonatomic, assign) CGFloat width;
@property (nonatomic, assign) CGFloat x;
@property (nonatomic, assign) CGFloat y;
@end
.m
#import "UIView+GCLibrary.h"
@implementation UIView (GCLibrary)
- (CGFloat) height {
return self.frame.size.height;
}
- (CGFloat) width {
return self.frame.size.width;
}
- (CGFloat) x {
return self.frame.origin.x;
}
- (CGFloat) y {
return self.frame.origin.y;
}
- (CGFloat) centerY {
return self.center.y;
}
- (CGFloat) centerX {
return self.center.x;
}
- (void) setHeight:(CGFloat) newHeight {
CGRect frame = self.frame;
frame.size.height = newHeight;
self.frame = frame;
}
- (void) setWidth:(CGFloat) newWidth {
CGRect frame = self.frame;
frame.size.width = newWidth;
self.frame = frame;
}
- (void) setX:(CGFloat) newX {
CGRect frame = self.frame;
frame.origin.x = newX;
self.frame = frame;
}
- (void) setY:(CGFloat) newY {
CGRect frame = self.frame;
frame.origin.y = newY;
self.frame = frame;
}
@end
Edit config file for IDEA: IDEA_HOME/bin/idea.properties
# Maximum file size (kilobytes) IDE should provide code assistance for.
idea.max.intellisense.filesize=60000
# Maximum file size (kilobytes) IDE is able to open.
idea.max.content.load.filesize=60000
Save and restart IDEA
In plist add ----
View controller-based status bar appearance --- NO
In each viewController write
- (void) viewDidLayoutSubviews
{
CGRect viewBounds = self.view.bounds;
CGFloat topBarOffset = 20.0;
viewBounds.origin.y = -topBarOffset;
self.view.bounds = viewBounds;
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];//for status bar style
}
For status bar issue in iOS 7 but target should be 5.1 and above for the app