The Angular6 equivalent code should be:
app.component.html
<div (mouseover)="changeText=true" (mouseout)="changeText=false">
<span *ngIf="!changeText">Hide</span>
<span *ngIf="changeText">Show</span>
</div>
app.component.ts
@Component({
selector: 'app-main',
templateUrl: './app.component.html'
})
export class AppComponent {
changeText: boolean;
constructor() {
this.changeText = false;
}
}
Notice that there is no such thing as $scope
anymore as it existed in AngularJS. Its been replaced with member variables from the component class. Also, there is no scope resolution algorithm based on prototypical inheritance either - it either resolves to a component class member, or it doesn't.
To still be able to scroll this worked for me
if (e.changedTouches.length > 1) e.preventDefault();
I personally use Style It for inline-style in React or keep my style separately in a CSS or SASS file...
But if you are really interested doing it inline, look at the library, I share some of the usages below:
In the component:
import React from 'react';
import Style from 'style-it';
class Intro extends React.Component {
render() {
return (
<Style>
{`
.intro {
font-size: 40px;
}
`}
<p className="intro">CSS-in-JS made simple -- just Style It.</p>
</Style>
);
}
}
export default Intro;
Output:
<p class="intro _scoped-1">
<style type="text/css">
._scoped-1.intro {
font-size: 40px;
}
</style>
CSS-in-JS made simple -- just Style It.
</p>
Also you can use JavaScript variables with hover in your CSS as below :
import React from 'react';
import Style from 'style-it';
class Intro extends React.Component {
render() {
const fontSize = 13;
return Style.it(`
.intro {
font-size: ${ fontSize }px; // ES2015 & ES6 Template Literal string interpolation
}
.package {
color: blue;
}
.package:hover {
color: aqua;
}
`,
<p className="intro">CSS-in-JS made simple -- just Style It.</p>
);
}
}
export default Intro;
And the result as below:
<p class="intro _scoped-1">
<style type="text/css">
._scoped-1.intro {
font-size: 13px;
}
._scoped-1 .package {
color: blue;
}
._scoped-1 .package:hover {
color: aqua;
}
</style>
CSS-in-JS made simple -- just Style It.
</p>
I think onMouseEnter and onMouseLeave are the ways to go, but I don't see the need for an additional wrapper component. Here is how I implemented it:
var Link = React.createClass({
getInitialState: function(){
return {hover: false}
},
toggleHover: function(){
this.setState({hover: !this.state.hover})
},
render: function() {
var linkStyle;
if (this.state.hover) {
linkStyle = {backgroundColor: 'red'}
} else {
linkStyle = {backgroundColor: 'blue'}
}
return(
<div>
<a style={linkStyle} onMouseEnter={this.toggleHover} onMouseLeave={this.toggleHover}>Link</a>
</div>
)
}
You can then use the state of hover (true/false) to change the style of the link.
Here is example with only CSS for that. In example I'm using SASS and SLIM.
https://codepen.io/Darex1991/pen/zBxPxe
Slim:
a.btn.btn--joined-state
span joined
span leave
SASS:
=animate($property...)
@each $vendor in ('-webkit-', '')
#{$vendor}transition-property: $property
#{$vendor}transition-duration: .3s
#{$vendor}transition-timing-function: ease-in
=visible
+animate(opacity, max-height, visibility)
max-height: 150px
opacity: 1
visibility: visible
=invisible
+animate(opacity, max-height, visibility)
max-height: 0
opacity: 0
visibility: hidden
=transform($var)
@each $vendor in ('-webkit-', '-ms-', '')
#{$vendor}transform: $var
.btn
border: 1px solid blue
&--joined-state
position: relative
span
+animate(opacity)
span:last-of-type
+invisible
+transform(translateX(-50%))
position: absolute
left: 50%
&:hover
span:first-of-type
+invisible
span:last-of-type
+visible
border-color: blue
This worked for me, curly braces are not required.
ng-style="{'background-image':'url(../../../app/img/notification/'+notification.icon+'.png)'}"
notification.icon here is scope variable.
Vikas answer works perfectly for me, here I also add support for the delay (show / hide).
var popover = $('#example');
var options = {
animation : true,
html: true,
trigger: 'manual',
placement: 'right',
delay: {show: 500, hide: 100}
};
popover
.popover(options)
.on("mouseenter", function () {
var t = this;
var popover = $(this);
setTimeout(function () {
if (popover.is(":hover")) {
popover.popover("show");
popover.siblings(".popover").on("mouseleave", function () {
$(t).popover('hide');
});
}
}, options.delay.show);
})
.on("mouseleave", function () {
var t = this;
var popover = $(this);
setTimeout(function () {
if (popover.siblings(".popover").length && !popover.siblings(".popover").is(":hover")) {
$(t).popover("hide")
}
}, options.delay.hide);
});
Also please pay attention I changed:
if (!$(".popover:hover").length) {
with:
if (popover.siblings(".popover").length && !popover.siblings(".popover").is(":hover")) {
so that it references exactly at that opened popover, and not any other (since now, through the delay, more than 1 could be open at the same time)
I learned something really useful and fundamental from here.
chaining functions is very usefull in this case which works on most jQuery Functions including on function output too.
It works because output of most jQuery functions are the input objects sets so you can use them right away and make it shorter and smarter
function showPhotos() {
$(this).find("span").slideToggle();
}
$(".photos")
.on("mouseenter", "li", showPhotos)
.on("mouseleave", "li", showPhotos);
I really wanted a pure css
solution to this myself, since sprinkling a weighty javascript solution around all of my views seemed like an unpleasant option. Finally found the @media.hover query, which can detect "whether the primary input mechanism allows the user to hover over elements." This avoids touch devices where "hovering" is more of an emulated action than a direct capability of the input device.
So for example, if I have a link:
<a href="/" class="link">Home</a>
Then I can safely style it to only :hover
when the device easily supports it with this css
:
@media (hover: hover) {
.link:hover { /* hover styles */ }
}
While most modern browsers support interaction media feature queries, some popular browsers such as IE and Firefox do not. In my case this works fine, since I only intended to support Chrome on desktop and Chrome and Safari on mobile.
Here is my solution I've used in applications.
I disabled the body overflow and placed the entire website html inside container div's. The website containers have overflow and therefore the user may scroll the page as expected.
I then created a sibling div (#Prevent) with a higher z-index that covers the entire website. Since #Prevent has a higher z-index, it overlaps the website container. When #Prevent is visible the mouse is no longer hovering the website containers, so scrolling isn't possible.
You may of course place another div, such as your modal, with a higher z-index than #Prevent in the markup. This allows you to create pop-up windows that don't suffer from scrolling issues.
This solution is better because it doesn't hide the scrollbars (jumping affect). It doesn't require event listeners and it's easy to implement. It works in all browsers, although with IE7 & 8 you have to play around (depends on your specific code).
html
<body>
<div id="YourModal" style="display:none;"></div>
<div id="Prevent" style="display:none;"></div>
<div id="WebsiteContainer">
<div id="Website">
website goes here...
</div>
</div>
</body>
css
body { overflow: hidden; }
#YourModal {
z-index:200;
/* modal styles here */
}
#Prevent {
z-index:100;
position:absolute;
left:0px;
height:100%;
width:100%;
background:transparent;
}
#WebsiteContainer {
z-index:50;
overflow:auto;
position: absolute;
height:100%;
width:100%;
}
#Website {
position:relative;
}
jquery/js
function PreventScroll(A) {
switch (A) {
case 'on': $('#Prevent').show(); break;
case 'off': $('#Prevent').hide(); break;
}
}
disable/enable the scroll
PreventScroll('on'); // prevent scrolling
PreventScroll('off'); // allow scrolling
I was struggling with a similar problem yesterday. I already had a "working" solution using jQuery UI's draggable together with jQuery Touch Punch, which are mentioned in other answers. However, using this method was causing weird bugs in some Android devices for me, and therefore I decided to write a small jQuery plugin that can make HTML elements draggable by using touch events instead of using a method that emulates fake mouse events.
The result of this is jQuery Draggable Touch which is a simple jQuery plugin for making elements draggable, that has touch devices as it's main target by using touch events (like touchstart, touchmove, touchend, etc.). It still has a fallback that uses mouse events if the browser/device doesn't support touch events.
The stopPropagation
options are bad because they can interfere with other event handlers including other menus that might have attached close handlers to the HTML element.
Here is a simple solution based on user2989143's answer:
$('html').click(function(event) {
if ($(event.target).closest('#menu-container, #menu-activator').length === 0) {
$('#menu-container').hide();
}
});
in my case I was using below dependency
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.42</version>
</dependency>
and getting the same exception of Auth fail, but updated dependency to below version and problem get resolved.
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
I believe telnet 74.255.12.25 8089
. Why don't u try both
The easiest way I have see no achieve most of the same thing at least for one column which is similar to Anamika's answer just with the tuple syntax for the aggregate function.
df.groupby('a').agg(b=('b','unique'), c=('c','unique'))
The syntax is wrong, it should instead be
svn merge <what(the range)> <from(your dev branch)> <to(trunk/trunk local copy)>
Note that use strict
was introduced in EcmaScript 5 and was kept since then.
Below are the conditions to trigger strict mode in ES6 and ES7:
- Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
- Module code is always strict mode code.
- All parts of a ClassDeclaration or a ClassExpression are strict mode code.
- Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
- Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
- Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.
If you want the quick and dirty way and don't worry about XSS attack, use params.merge
to keep previous parameters. e.g.
<%= link_to 'Link', params.merge({:per_page => 20}) %>
see: https://stackoverflow.com/a/4174493/445908
Otherwise , check this answer: params.merge and cross site scripting
One work-around is to right-click on the result set and select "Save Results As...". This exports it to a CSV file with the entire contents of the column. Not perfect but worked well enough for me.
Do not use @@fetch_status - this will return status from the last cursor in the current connection. Use the example below:
declare @sqCur cursor;
declare @data varchar(1000);
declare @i int = 0, @lastNum int, @rowNum int;
set @sqCur = cursor local static read_only for
select
row_number() over (order by(select null)) as RowNum
,Data -- you fields
from YourIntTable
open @cur
begin try
fetch last from @cur into @lastNum, @data
fetch absolute 1 from @cur into @rowNum, @data --start from the beginning and get first value
while @i < @lastNum
begin
set @i += 1
--Do your job here
print @data
fetch next from @cur into @rowNum, @data
end
end try
begin catch
close @cur --|
deallocate @cur --|-remove this 3 lines if you do not throw
;throw --|
end catch
close @cur
deallocate @cur
I never liked using Robot, so I made my own simple method for making screenshots of JFrame objects:
public static final void makeScreenshot(JFrame argFrame) {
Rectangle rec = argFrame.getBounds();
BufferedImage bufferedImage = new BufferedImage(rec.width, rec.height, BufferedImage.TYPE_INT_ARGB);
argFrame.paint(bufferedImage.getGraphics());
try {
// Create temp file
File temp = File.createTempFile("screenshot", ".png");
// Use the ImageIO API to write the bufferedImage to a temporary file
ImageIO.write(bufferedImage, "png", temp);
// Delete temp file when program exits
temp.deleteOnExit();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
The default behaviour of divs is to take the full width available in their parent container.
This is the same as if you'd give the inner divs a width of 100%.
By floating the divs, they ignore their default and size their width to fit the content. Everything behind it (in the HTML), is placed under the div (on the rendered page).
This is the reason that they align theirselves next to each other.
The float CSS property specifies that an element should be taken from the normal flow and placed along the left or right side of its container, where text and inline elements will wrap around it. A floating element is one where the computed value of float is not none.
Source: https://developer.mozilla.org/en-US/docs/Web/CSS/float
Get rid of the float, and the divs will be aligned under each other.
If this does not happen, you'll have some other css on divs or children of wrapper defining a floating behaviour or an inline display.
If you want to keep the float, for whatever reason, you can use clear
on the 2nd div to reset the floating properties of elements before that element.
clear
has 5 valid values: none | left | right | both | inherit
. Clearing no floats (used to override inherited properties), left or right floats or both floats. Inherit means it'll inherit the behaviour of the parent element
Also, because of the default behaviour, you don't need to set the width and height on auto.
You only need this is you want to set a hardcoded height/width. E.g. 80% / 800px / 500em / ...
<div id="wrapper">
<div id="inner1"></div>
<div id="inner2"></div>
</div>
CSS is
#wrapper{
margin-left:auto;
margin-right:auto;
height:auto; // this is not needed, as parent container, this div will size automaticly
width:auto; // this is not needed, as parent container, this div will size automaticly
}
/*
You can get rid of the inner divs in the css, unless you want to style them.
If you want to style them identicly, you can use concatenation
*/
#inner1, #inner2 {
border: 1px solid black;
}
You actually do not have to wait a full second for each request. I found that if I wait 200 miliseconds between each request I am able to avoid the OVER_QUERY_LIMIT response and the user experience is passable. With this solution you can load 20 items in 4 seconds.
$(items).each(function(i, item){
setTimeout(function(){
geoLocate("my address", function(myLatlng){
...
});
}, 200 * i);
}
The default PostgreSQL port is 5432
. The host that the database is operating on should have been provided by your hosting provider; I'd guess it would be the same host as the web server if one wasn't specified. Typically this would be configured as localhost, assuming your web server and database server are on the same host.
This may be because, when both functions are compiled to JavaScript, their signature is totally identical. As JavaScript doesn't have types, we end up creating two functions taking same number of arguments. So, TypeScript restricts us from creating such functions.
TypeScript supports overloading based on number of parameters, but the steps to be followed are a bit different if we compare to OO languages. In answer to another SO question, someone explained it with a nice example: Method overloading?.
Basically, what we are doing is, we are creating just one function and a number of declarations so that TypeScript doesn't give compile errors. When this code is compiled to JavaScript, the concrete function alone will be visible. As a JavaScript function can be called by passing multiple arguments, it just works.
I found this solution in "Super useful bits of PHP, Form and JavaScript code" at Skytopia.
Inside "page1.php" or "page1.html":
// Send the variables myNumber=1 and myFruit="orange" to the new PHP page...
<a href="page2c.php?myNumber=1&myFruit=orange">Send variables via URL!</a>
//or as I needed it.
<a href='page2c.php?myNumber={$row[0]}&myFruit={$row[1]}'>Send variables</a>
Inside "page2c.php":
<?php
// Retrieve the URL variables (using PHP).
$num = $_GET['myNumber'];
$fruit = $_GET['myFruit'];
echo "Number: ".$num." Fruit: ".$fruit;
?>
You can try the following code:
$("input[name=cols][value=" + value + "]").attr('checked', 'checked');
This will set the attribute checked for the radio columns and value as specified.
There might be a cleverer way to go about this, but
intersect(intersect(a,b),c)
will do the job.
EDIT: More cleverly, and more conveniently if you have a lot of arguments:
Reduce(intersect, list(a,b,c))
pthread_exit()
will terminate the calling thread and exit from that(but resources used by calling thread is not released to operating system if it is not detached from main thread.)
pthrade_join()
will wait or block the calling thread until target thread is not terminated.
In simple word it will wait for to exit the target thread.
In your code, if you put sleep(or delay) in PrintHello
function before pthread_exit()
, then main thread may be exit and terminate full process, Although your PrintHello
function is not completed it will terminate. If you use pthrade_join()
function in main before calling pthread_exit()
from main it will block main thread and wait to complete your calling thread (PrintHello
).
set -x
Prints a trace of simple commands, for commands, case commands, select commands, and arithmetic for commands and their arguments or associated word lists after they are expanded and before they are executed. The value of the PS4 variable is expanded and the resultant value is printed before the command and its expanded arguments.
[source]
set -x
echo `expr 10 + 20 `
+ expr 10 + 20
+ echo 30
30
set +x
echo `expr 10 + 20 `
30
Above example illustrates the usage of set -x
. When it is used, above arithmetic expression has been expanded. We could see how a singe line has been evaluated step by step.
expr
has been evaluated.echo
has been evaluated.To know more about set ? visit this link
when it comes to your shell script,
[ "$DEBUG" == 'true' ] && set -x
Your script might have been printing some additional lines of information when the execution mode selected as DEBUG
. Traditionally people used to enable debug mode when a script called with optional argument such as -d
Add this to an htaccess file (and see edit notes added below):
<IfModule mod_php5.c>
php_value post_max_size 200M
php_value upload_max_filesize 200M
php_value memory_limit 300M
php_value max_execution_time 259200
php_value max_input_time 259200
php_value session.gc_maxlifetime 1200
</IfModule>
Additional resources and information:
2021 EDIT:
As PHP and Apache evolve and grow, I think it is important for me to take a moment to mention a few things to consider and possible "gotchas" to consider:
<IfModule
is loaded.mod_php5.c
in the first line. If you are using PHP 7, you would replace that with mod_php7.c
.php.ini
config file(s). This method is usually only useful in the event your hosting provider does not give you access to change those files. In circumstances where you can edit the PHP configuration, it is recommended that you apply these settings there.In your xampppath\apache\conf\extra open file httpd-xampp.conf and find the below tag:
# Close XAMPP sites here
<LocationMatch "^/(?i:(?:xampp|licenses|phpmyadmin|webalizer|server-status|server-info))">
Order deny,allow
Deny from all
Allow from ::1 127.0.0.0/8
ErrorDocument 403 /error/HTTP_XAMPP_FORBIDDEN.html.var
</LocationMatch>
and add
"Allow from all"
after Allow from ::1 127.0.0.0/8 {line}
Restart xampp, and you are done.
In later versions of Xampp
...you can simply remove this part
#
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
Require local
ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>
from the same file and it should work over the local network.
This will give you the current element name (tag name)
<xsl:value-of select ="name(.)"/>
OP-Edit: This will also do the trick:
<xsl:value-of select ="local-name()"/>
Here's a poor man's Linux/Python/Expect-like example based on this blog post: Upgrading simple shells to fully interactive TTYs. I needed this for old machines where I can't install Expect or add modules to Python.
Code:
(
echo 'scp [email protected]:./install.sh .'
sleep 5
echo 'scp-passwd'
sleep 5
echo 'exit'
) |
python -c 'import pty; pty.spawn("/usr/bin/bash")'
Output:
scp [email protected]:install.sh .
bash-4.2$ scp [email protected]:install.sh .
Password:
install.sh 100% 15KB 236.2KB/s 00:00
bash-4.2$ exit
exit
You probably want os.makedirs as it will create intermediate directories as well, if needed.
import os
#dir is not keyword
def makemydir(whatever):
try:
os.makedirs(whatever)
except OSError:
pass
# let exception propagate if we just can't
# cd into the specified directory
os.chdir(whatever)
I would really recommend to:
push only to the main repo
make sure that main repo is a bare repo, in order to never have any problem with the main repo working tree being not in sync with its .git
base. See "How to push a local git repository to another computer?"
If you do have to make modification in the main (bare) repo, clone it (on the main server), do your modification and push back to it
In other words, keep a bare repo accessible both from the main server and the local computer, in order to have a single upstream repo from/to which to pull/pull.
Similar to C# casting to (int)
with just using standard lib:
Math.trunc(1.6) // 1
Math.trunc(-1.6) // -1
You can use date function to format it by using the code below:
echo date("g:i a", strtotime("13:30:30 UTC"));
output: 1:30 pm
I open files "directly" from WinSCP which opens the files in Notepad++ I had a php files on my linux server which always opened in Mac format no matter what I did :-(
If I downloaded the file and then opened it from local (windows) it was open as Dos/Windows....hmmm
The solution was to EOL-convert the local file to "UNIX/OSX Format", save it and then upload it.
Now when I open the file directly from the server it's open as "Dos/Windows" :-)
BLOB is for binary data (videos, images, documents, other)
CLOB is for large text data (text)
Maximum size on MySQL 2GB
Maximum size on Oracle 128TB
It's impossible. You can only find and access views that are currently running. If you want to check the value of ex. TextView used in previus activity you must save the value is SharedPreferences, database, file or pass by Intent.
u = urllib2.urlopen('http://myserver/inout-tracker', data)
h.request('POST', '/inout-tracker/index.php', data, headers)
Using the path /inout-tracker
without a trailing /
doesn't fetch index.php
. Instead the server will issue a 302
redirect to the version with the trailing /
.
Doing a 302 will typically cause clients to convert a POST to a GET request.
Say you have defined your class like this:
@Data
@AllArgsConstructor(staticName = "of")
private class Pair<P,Q> {
public P first;
public Q second;
}
So when you will need to create a new instance, it will need to take the parameters and you will provide it like this as defined in the annotation.
Pair<Integer, String> pair = Pair.of(menuItemId, category);
If you define it like this, you will get the error asked for.
Pair<Integer, String> pair = new Pair(menuItemId, category);
If git config --global user.email "[email protected]"
git config --global user.name "github_username"
Dont work like in my case, you can use:
git config --replace-all user.email "[email protected]"
git config --replace-all user.name "github_username"
I believe that the best way to solve this problem is by using Ben Alman's plugin jQuery throttle / debounce. In my opinion there is no need to delay the events of every single field in your form.
Just wrap your $scope.$watch handling function in $.debounce like this:
$scope.$watch("searchText", $.debounce(1000, function() {
console.log($scope.searchText);
}), true);
Use the \n
for a newline character.
document.write("\n");
You can also have more than one:
document.write("\n\n\n"); // 3 new lines! My oh my!
However, if this is rendering to HTML, you will want to use the HTML tag for a newline:
document.write("<br>");
The string Hello\n\nTest
in your source will look like this:
Hello!
Test
The string Hello<br><br>Test
will look like this in HTML source:
Hello<br><br>Test
The HTML one will render as line breaks for the person viewing the page, the \n
just drops the text to the next line in the source (if it's on an HTML page).
String val = "hi hello prince";
String arr[] = val.split(" ");
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i]);
}
I had the same issue too and this worked for me try:
this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
subscribe((res) => {
let resSTR = JSON.stringify(res);
let resJSON = JSON.parse(resStr);
console.log(resJSON._body);
})
SOAPpy is now obsolete, AFAIK, replaced by ZSL. It's a moot point, because I can't get either one to work, much less compile, on either Python 2.5 or Python 2.6
Change background color of status bar: Swift:
let proxyViewForStatusBar : UIView = UIView(frame: CGRectMake(0, 0,self.view.frame.size.width, 20))
proxyViewForStatusBar.backgroundColor=UIColor.whiteColor()
self.view.addSubview(proxyViewForStatusBar)
Express makes this kind of stuff really intuitive. The syntax looks like below :
var app = require('express').createServer();
app.get("/string", function(req, res) {
var strings = ["rad", "bla", "ska"]
var n = Math.floor(Math.random() * strings.length)
res.send(strings[n])
})
app.listen(8001)
If you're using jQuery on the client side you can do something like this:
$.get("/string", function(string) {
alert(string)
})
try
DOCS="/cygdrive/c/Users/my\ dir/Documents";
cd "$DOCS"
Just to elaborate a bit on the meta-tag thing. I've heard a talk, where a statement was made, one should always insert the "no-sniff" meta tag in the html to prevent browser sniffing (just like OP did):
<meta content="text/html; charset=UTF-8; X-Content-Type-Options=nosniff" http-equiv="Content-Type" />
However, this is not a valid method for w3c compliant websites, the validator will raise an error:
Bad value text/html; charset=UTF-8; X-Content-Type-Options=nosniff for attribute content on element meta: The legacy encoding contained ;, which is not a valid character in an encoding name.
And there is no fixing this. To rightly turn off no-sniff, one has to go to the server settings and turn it off there. Because the "no-sniff" option is something from the HTTP header, not from the HTML file which is attached at the HTTP response.
To check if the no-sniff option is disabled, one can enable the developer console, networks tab and then inspect the HTTP response header:
IMPORTANT:
We have been using the function as provided above by LPG.
However, this contains a bug you might encounter when you start a process that generates a lot of output. Due to this you might end up with a deadlock when using this function. Instead use the adapted version below:
Function Execute-Command ($commandTitle, $commandPath, $commandArguments)
{
Try {
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = $commandPath
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.Arguments = $commandArguments
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
[pscustomobject]@{
commandTitle = $commandTitle
stdout = $p.StandardOutput.ReadToEnd()
stderr = $p.StandardError.ReadToEnd()
ExitCode = $p.ExitCode
}
$p.WaitForExit()
}
Catch {
exit
}
}
Further information on this issue can be found at MSDN:
A deadlock condition can result if the parent process calls p.WaitForExit before p.StandardError.ReadToEnd and the child process writes enough text to fill the redirected stream. The parent process would wait indefinitely for the child process to exit. The child process would wait indefinitely for the parent to read from the full StandardError stream.
An alternative way to get only one character.
$str = 'abcdefghij';
echo $str{5};
I would particularly not use this, but for the purpose of education. We can use that to answer the question:
$newString = '';
for ($i = 0; $i < 5; $i++) {
$newString .= $str{$i};
}
echo $newString;
For anyone using that. Bear in mind curly brace syntax for accessing array elements and string offsets is deprecated from PHP 7.4
More information: https://wiki.php.net/rfc/deprecate_curly_braces_array_access
Probably the shortest version:
[System.Collections.ArrayList]$someArray
It is also faster because it does not call relatively expensive New-Object
.
If elem.find()
is not working for you, check that you are including JQuery script before angular script....
"Rounded" down as in your example. This will return a varchar value of the date.
DECLARE @date As DateTime2
SET @date = '2007-09-22 15:07:38.850'
SELECT CONVERT(VARCHAR(16), @date, 120) --2007-09-22 15:07
SELECT CONVERT(VARCHAR(13), @date, 120) --2007-09-22 15
How about:
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
public class Demo {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(new File("input.xml"));
NodeList nodeList = document.getElementsByTagName("Item");
for(int x=0,size= nodeList.getLength(); x<size; x++) {
System.out.println(nodeList.item(x).getAttributes().getNamedItem("name").getNodeValue());
}
}
}
Additional hint: If you have multiple projects with different toolchains open, check the build console header for the failing project's path.
I've just spent half an hour trying to fix a build that showed this error because another project with hopelessly outdated toolchain settings was open in the same workbench. Closing the other project re-enabled the build.
The yum install php-soap
command will install the Soap module for php 5.x
For installing the correct version for your environment I recommend to create a file info.php
and put this code: <?php echo phpinfo(); ?>
In the header you'll see the version you're using:
Now that you know the correct version you can run this command: yum search php-soap
This command will return the avaliable versions:
php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php54-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php55-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php56-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php70-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php71-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php72-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php73-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php74-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
rh-php70-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
rh-php71-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
rh-php72-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
Now you just need to choose the correct module to your php version.
For this example, you should run this command php72-php-soap.x86_64
This will convert it to an int:
char foo = '2';
int bar = foo - '0';
This works because each character is internally represented by a number. The characters '0' to '9' are represented by consecutive numbers, so finding the difference between the characters '0' and '2' results in the number 2.
The .BAK files from SQL server are in Microsoft Tape Format (MTF) ref: http://www.fpns.net/willy/msbackup.htm
The bak file will probably contain the LDF and MDF files that SQL server uses to store the database.
You will need to use SQL server to extract these. SQL Server Express is free and will do the job.
So, install SQL Server Express edition, and open the SQL Server Powershell. There execute sqlcmd -S <COMPUTERNAME>\SQLExpress
(whilst logged in as administrator)
then issue the following command.
restore filelistonly from disk='c:\temp\mydbName-2009-09-29-v10.bak';
GO
This will list the contents of the backup - what you need is the first fields that tell you the logical names - one will be the actual database and the other the log file.
RESTORE DATABASE mydbName FROM disk='c:\temp\mydbName-2009-09-29-v10.bak'
WITH
MOVE 'mydbName' TO 'c:\temp\mydbName_data.mdf',
MOVE 'mydbName_log' TO 'c:\temp\mydbName_data.ldf';
GO
At this point you have extracted the database - then install Microsoft's "Sql Web Data Administrator". together with this export tool and you will have an SQL script that contains the database.
It no longer suffices to start Chrome with --user-data-dir=/root/.config/google-chrome
. It simply prints Aborted
and ends (Chrome 48 on Ubuntu 12.04).
You need actually to run it as a non-root user. This you can do with
gksu -wu chrome-user google-chrome
where chrome-user
is some user you've decided should be the one to run Chrome. Your Chrome user profile will be found at ~chrome-user/.config/google-chrome
.
BTW, the old hack of changing all occurrences of geteuid
to getppid
in the chrome
binary no longer works.
Not sure exactly what all the code you posted does, but to answer the question posed in the title, you can use + as the normal string concat function as well as str().
"hello " + str(10) + " world" = "hello 10 world"
Hope that helps!
To update this for Python-3 you can do this
"{} {}".format(True, False)
However if you want to actually format the string (e.g. add white space), you encounter Python casting the boolean into the underlying C value (i.e. an int), e.g.
>>> "{:<8} {}".format(True, False)
'1 False'
To get around this you can cast True
as a string, e.g.
>>> "{:<8} {}".format(str(True), False)
'True False'
Much like leonardocsouza, I had the same problem. To clarify a bit, this is what my folder structure looked like when I ran node server.js
node_modules/
app/
index.html
server.js
After printing out the __dirname
path, I realized that the __dirname
path was where my server was running (app/
).
So, the answer to your question is this:
If your server.js
file is in the same folder as the files you are trying to render, then
app.use( express.static( path.join( application_root, 'site') ) );
should actually be
app.use(express.static(application_root));
The only time you would want to use the original syntax that you had would be if you had a folder tree like so:
app/
index.html
node_modules
server.js
where index.html
is in the app/
directory, whereas server.js
is in the root directory (i.e. the same level as the app/
directory).
Side note: Intead of calling the path
utility, you can use the syntax application_root + 'site'
to join a path.
Overall, your code could look like:
// Module dependencies.
var application_root = __dirname,
express = require( 'express' ), //Web framework
mongoose = require( 'mongoose' ); //MongoDB integration
//Create server
var app = express();
// Configure server
app.configure( function() {
//Don't change anything here...
//Where to serve static content
app.use( express.static( application_root ) );
//Nothing changes here either...
});
//Start server --- No changes made here
var port = 5000;
app.listen( port, function() {
console.log( 'Express server listening on port %d in %s mode', port, app.settings.env );
});
There is a difference between initialization and assignment. What you want to do is not initialization, but assignment. But such assignment to array is not possible in C++.
Here is what you can do:
#include <algorithm>
int array [] = {1,3,34,5,6};
int newarr [] = {34,2,4,5,6};
std::copy(newarr, newarr + 5, array);
However, in C++0x, you can do this:
std::vector<int> array = {1,3,34,5,6};
array = {34,2,4,5,6};
Of course, if you choose to use std::vector
instead of raw array.
Do your groupby, and use reset_index() to make it back into a DataFrame. Then sort.
grouped = df.groupby('mygroups').sum().reset_index()
grouped.sort_values('mygroups', ascending=False)
If you're using Swift, you can create a UILabel extension:
extension UILabel {
@objc var substituteFontName : String {
get { return self.font.fontName }
set { self.font = UIFont(name: newValue, size: self.font.pointSize) }
}
}
And then where you do your appearance proxying:
UILabel.appearance().substituteFontName = applicationFont
There is equivalent Objective-C code using UI_APPEARANCE_SELECTOR
on a property with the name substituteFontName
.
Addition
For the case where you'd want to set bold and regular fonts separately:
extension UILabel {
@objc var substituteFontName : String {
get { return self.font.fontName }
set {
if self.font.fontName.range(of:"Medium") == nil {
self.font = UIFont(name: newValue, size: self.font.pointSize)
}
}
}
@objc var substituteFontNameBold : String {
get { return self.font.fontName }
set {
if self.font.fontName.range(of:"Medium") != nil {
self.font = UIFont(name: newValue, size: self.font.pointSize)
}
}
}
}
Then for your UIAppearance proxies:
UILabel.appearance().substituteFontName = applicationFont
UILabel.appearance().substituteFontNameBold = applicationFontBold
Note: if you're finding that the bold substitution isn't working, it's possible the default font name doesn't contain "Medium". Switch out that string for another match as needed (thanks to Mason in the comments below) .
The only way I could get this to work is to pass the JSON as a string and then deserialise it using JavaScriptSerializer.Deserialize<T>(string input)
, which is pretty strange if that's the default deserializer for MVC 4.
My model has nested lists of objects and the best I could get using JSON data is the uppermost list to have the correct number of items in it, but all the fields in the items were null.
This kind of thing should not be so hard.
$.ajax({
type: 'POST',
url: '/Agri/Map/SaveSelfValuation',
data: { json: JSON.stringify(model) },
dataType: 'text',
success: function (data) {
[HttpPost]
public JsonResult DoSomething(string json)
{
var model = new JavaScriptSerializer().Deserialize<Valuation>(json);
If this happens always, it literally means that the machine exists but that it has no services listening on the specified port, or there is a firewall stopping you.
If it happens occasionally - you used the word "sometimes" - and retrying succeeds, it is likely because the server has a full 'backlog'.
When you are waiting to be accept
ed on a listening socket, you are placed in a backlog. This backlog is finite and quite short - values of 1, 2 or 3 are not unusual - and so the OS might be unable to queue your request for the 'accept' to consume.
The backlog is a parameter on the listen
function - all languages and platforms have basically the same API in this regard, even the C# one. This parameter is often configurable if you control the server, and is likely read from some settings file or the registry. Investigate how to configure your server.
If you wrote the server, you might have heavy processing in the accept of your socket, and this can be better moved to a separate worker-thread so your accept is always ready to receive connections. There are various architecture choices you can explore that mitigate queuing up clients and processing them sequentially.
Regardless of whether you can increase the server backlog, you do need retry logic in your client code to cope with this issue - as even with a long backlog the server might be receiving lots of other requests on that port at that time.
There is a rare possibility where a NAT router would give this error should its ports for mappings be exhausted. I think we can discard this possibility as too much of a long shot though, since the router has 64K simultaneous connections to the same destination address/port before exhaustion.
Try this one:
Data objt = new Data(name, address, contact);
Contacts.add(objt);
I figured that the DJANGO_SETTINGS_MODULE had to be set some way, so I looked at the documentation (link updated) and found:
export DJANGO_SETTINGS_MODULE=mysite.settings
Though that is not enough if you are running a server on heroku, you need to specify it there, too. Like this:
heroku config:set DJANGO_SETTINGS_MODULE=mysite.settings --account <your account name>
In my specific case I ran these two and everything worked out:
export DJANGO_SETTINGS_MODULE=nirla.settings
heroku config:set DJANGO_SETTINGS_MODULE=nirla.settings --account personal
Edit
I would also like to point out that you have to re-do this every time you close or restart your virtual environment. Instead, you should automate the process by going to venv/bin/activate and adding the line: set DJANGO_SETTINGS_MODULE=mysite.settings
to the bottom of the code. From now on every time you activate the virtual environment, you will be using that app's settings.
A singleton service
is a service for which only one instance exists in an app.
There are (2) ways to provide a singleton service for your application.
use the providedIn
property, or
provide the module directly in the AppModule
of the application
Using providedIn
Beginning with Angular 6.0, the preferred way to create a singleton service is to set providedIn
to root on the service's @Injectable()
decorator. This tells Angular to provide the service in the application root.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class UserService {
}
NgModule providers array
In apps built with Angular versions prior to 6.0, services are registered NgModule providers arrays as follows:
@NgModule({
...
providers: [UserService],
...
})
If this NgModule
were the root AppModule
, the UserService would be a singleton and available throughout the app. Though you may see it coded this way, using the providedIn
property of the @Injectable()
decorator on the service itself is preferable as of Angular 6.0 as it makes your services tree-shakable.
As others said the convenient jQuery prepend functionality can be emulated:
var html = '<div>Hello prepended</div>';
document.body.innerHTML = html + document.body.innerHTML;
While some say it is better not to "mess" with innerHTML, it is reliable in many use cases, if you know this:
If a
<div>
,<span>
, or<noembed>
node has a child text node that includes the characters (&
), (<
), or (>
), innerHTML returns these characters as&
,<
and>
respectively. UseNode.textContent
to get a correct copy of these text nodes' contents.
https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML
Or:
var html = '<div>Hello prepended</div>';
document.body.insertAdjacentHTML('afterbegin', html)
insertAdjacentHTML
is probably a good alternative: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
After losing hours trying to find my error, the problem is your formula:
sigma = sum(y*(x-mean)**2)/n
This previous formula is wrong, the correct formula is the square root of this!;
sqrt(sum(y*(x-mean)**2)/n)
Hope this helps
ssh -t 'command; bash -l'
will execute the command and then start up a login shell when it completes. For example:
ssh -t [email protected] 'cd /some/path; bash -l'
There is a trick that allows anonymous class to update data in the outer scope.
private void f(Button b, final int a) {
final int[] res = new int[1];
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
res[0] = a * 5;
}
});
// But at this point handler is most likely not executed yet!
// How should we now res[0] is ready?
}
However, this trick is not very good due to the synchronization issues. If handler is invoked later, you need to 1) synchronize access to res if handler was invoked from the different thread 2) need to have some sort of flag or indication that res was updated
This trick works OK, though, if anonymous class is invoked in the same thread immediately. Like:
// ...
final int[] res = new int[1];
Runnable r = new Runnable() { public void run() { res[0] = 123; } };
r.run();
System.out.println(res[0]);
// ...
Here is a code example that proves the fault in the class. I've checked: the problem occurs when using parse and also when you are only using format.
Just had a similar issue
Resolved it by checking in httpd.conf
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride All <--- make sure this is not set to "None"
It is worth bearing in mind I tried (from Mark's answer) the "put garbage in the .htaccess" which did give a server error - but even though it was being read, it wasn't being acted on due to no overrides allowed.
Using the Thread.sleep(millis)
method.
I applied CSS styling to an anchored HREF attribute fully emulating the push button behaviors I needed (hover, active, background-color, etc., etc.). HTML markup is much simpler a-n-d eliminates the get/post complexity associated with using a form-based approach.
<a class="GYM" href="http://www.spufalcons.com/index.aspx?tab=gymnastics&path=gym">Gymnastics</a>
#include <iostream>
#include <iomanip>
using namespace std;
You can enter the line using namespace std;
for your convenience. Otherwise, you'll have to explicitly add std::
every time you wish to use cout
, fixed
, showpoint
, setprecision(2)
and endl
int main()
{
double num1 = 3.12345678;
cout << fixed << showpoint;
cout << setprecision(2);
cout << num1 << endl;
return 0;
}
Or simply Use union, for simple array.
_.union([1,2,3,3], [3,5])
// [1,2,3,5]
Show changes between the working tree and the index or a tree, changes between the index and a tree, changes between two trees, or changes between two files on disk.
This prints all elements that contain sub:
for s in filter (lambda x: sub in x, list): print (s)
A good practice is write text inside String.xml
example:
String.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="yellow">Yellow</string>
</resources>
and inside layout:
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/yellow" />
/**
* Copy the local DB file of an application to the root of external storage directory
* @param context the Context of application
* @param dbName The name of the DB
*/
private void copyDbToExternalStorage(Context context , String dbName){
try {
File name = context.getDatabasePath(dbName);
File sdcardFile = new File(Environment.getExternalStorageDirectory() , "test.db");//The name of output file
sdcardFile.createNewFile();
InputStream inputStream = null;
OutputStream outputStream = null;
inputStream = new FileInputStream(name);
outputStream = new FileOutputStream(sdcardFile);
byte[] buffer = new byte[1024];
int read;
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
inputStream.close();
outputStream.flush();
outputStream.close();
}
catch (Exception e) {
Log.e("Exception" , e.toString());
}
}
Following below command worked for me
[root@sandbox ~]# pip install google-api-python-client==1.6.4
You can combine attribute selectors this way:
$("[attr1=val][attr2=val]")...
so that an element has to satisfy both conditions. Of course you can use this for more than two. Also, don't do [type=checkbox]
. jQuery has a selector for that, namely :checkbox
so the end result is:
$("input:checkbox[name=ProductCode]")...
Attribute selectors are slow however so the recommended approach is to use ID and class selectors where possible. You could change your markup to:
<input type="checkbox" class="ProductCode" name="ProductCode"value="396P4">
<input type="checkbox" class="ProductCode" name="ProductCode"value="401P4">
<input type="checkbox" class="ProductCode" name="ProductCode"value="F460129">
allowing you to use the much faster selector of:
$("input.ProductCode")...
You can also use this code to get LayoutInflater:
LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)
After typing "prop" + Tab + Tab as suggested by Amra,
you can immediately type the property's type (which will replace the default int
), type another tab and type the property name (which will replace the default MyProperty). Finish by pressing Enter.
You can do this all within your controller by using the $window service here. $window is a wrapper around the global browser object window.
To make this work inject $window into you controller as follows
.controller('exampleCtrl', ['$scope', '$window',
function($scope, $window) {
$scope.redirectToGoogle = function(){
$window.open('https://www.google.com', '_blank');
};
}
]);
this works well when redirecting to dynamic routes
I know this post is ancient but, I found it useful.
It didn't resolve my issue of returning the record with a non empty text field so I thought I would add my solution.
This is the where clause that worked for me.
WHERE xyz LIKE CAST('% %' as text)
delete build folder projectfile\android\app\build
and run project
Create Drawable file in Drawable foloder
<item android:drawable="@color/SelectedColor" android:state_pressed="true"></item>
<item android:drawable="@color/SelectedColor" android:state_selected="true"></item>
<item android:drawable="@color/DefultColor"></item>
And in xml file
android:background="@drawable/Drawable file"
In RecyclerView onBindViewHolder
holder.button.setSelected(holder.button.isSelected()?true:false);
Like toggle button
Using typescript and fs/promises in node14
import * as fsp from 'fs/promises';
try{
const = await fsp.readFile(fullFileName)
...
} catch(e) { ...}
It is better to use fsp.readFile
than fsp.stat
or fsp.access
for two reasons:
fsp.stat
and fsp.readFile
would give different answers. Either due to subtle differences in the questions they ask, or because the files status changed between the calls. So the coder would have to code for two conditional branches instead of one, and the user might see more behaviors.Using "groupby" and list comprehension:
Storing all the split dataframe in list variable and accessing each of the seprated dataframe by their index.
DF = pd.DataFrame({'chr':["chr3","chr3","chr7","chr6","chr1"],'pos':[10,20,30,40,50],})
ans = [pd.DataFrame(y) for x, y in DF.groupby('chr', as_index=False)]
accessing the separated DF like this:
ans[0]
ans[1]
ans[len(ans)-1] # this is the last separated DF
accessing the column value of the separated DF like this:
ansI_chr=ans[i].chr
In Angular 2 this is how we can set the default value for radio button:
HTML:
<label class="form-check-label">
<input type="radio" class="form-check-input" name="gender"
[(ngModel)]="gender" id="optionsRadios1" value="male">
Male
</label>
In the Component Class set the value of 'gender' variable equal to the value of radio button:
gender = 'male';
To move all existing properties of a stdClass
to a new object of a specified class name:
/**
* recast stdClass object to an object with type
*
* @param string $className
* @param stdClass $object
* @throws InvalidArgumentException
* @return mixed new, typed object
*/
function recast($className, stdClass &$object)
{
if (!class_exists($className))
throw new InvalidArgumentException(sprintf('Inexistant class %s.', $className));
$new = new $className();
foreach($object as $property => &$value)
{
$new->$property = &$value;
unset($object->$property);
}
unset($value);
$object = (unset) $object;
return $new;
}
Usage:
$array = array('h','n');
$obj=new stdClass;
$obj->action='auth';
$obj->params= &$array;
$obj->authKey=md5('i');
class RestQuery{
public $action;
public $params=array();
public $authKey='';
}
$restQuery = recast('RestQuery', $obj);
var_dump($restQuery, $obj);
Output:
object(RestQuery)#2 (3) {
["action"]=>
string(4) "auth"
["params"]=>
&array(2) {
[0]=>
string(1) "h"
[1]=>
string(1) "n"
}
["authKey"]=>
string(32) "865c0c0b4ab0e063e5caa3387c1a8741"
}
NULL
This is limited because of the new
operator as it is unknown which parameters it would need. For your case probably fitting.
A Dockerfile is a simple text file that contains the commands a user could call to assemble an image.
Example, Dockerfile
FROM ubuntu:latest
MAINTAINER john doe
RUN apt-get update
RUN apt-get install -y python python-pip wget
RUN pip install Flask
ADD hello.py /home/hello.py
WORKDIR /home
Docker Compose
is a tool for defining and running multi-container Docker applications.
define the services that make up your app in docker-compose.yml
so they can be run together in an isolated environment.
get an app running in one command by just running docker-compose up
Example, docker-compose.yml
version: "3"
services:
web:
build: .
ports:
- '5000:5000'
volumes:
- .:/code
- logvolume01:/var/log
links:
- redis
redis:
image: redis
volumes:
logvolume01: {}
For symfony 2.6 and above we can use
{{ app.user.getFirstname() }}
as app.security global variable for Twig template has been deprecated and will be removed from 3.0
more info:
http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements
and see the global variables in
http://symfony.com/doc/current/reference/twig_reference.html
Does SQL Server support analytic functions?
select rowint,
value,
value - lag(value) over (order by rowint) diff
from myTable
order by rowint
/
I had the same issue and this is what I did and I was able to solve my issue:
Gradle file was updated from classpath 'com.android.tools.build:gradle:3.6.1' to
classpath 'com.android.tools.build:gradle:3.1.3'
Then distribution URL in gradle-wrapper.properties file was updated from distributionUrl=https://services.gradle.org/distributions/gradle-5.6.4-all.zip to
distributionUrl=https://services.gradle.org/distributions/gradle-5.4.1-all.zip
Gradle was then synched.
There's also the QueryString module's parse()
method:
var http = require('http'),
queryString = require('querystring');
http.createServer(function (oRequest, oResponse) {
var oQueryParams;
// get query params as object
if (oRequest.url.indexOf('?') >= 0) {
oQueryParams = queryString.parse(oRequest.url.replace(/^.*\?/, ''));
// do stuff
console.log(oQueryParams);
}
oResponse.writeHead(200, {'Content-Type': 'text/plain'});
oResponse.end('Hello world.');
}).listen(1337, '127.0.0.1');
you should run standlone.bat or .sh with -c standalone-full.xml switch may be work.
Like so?
>>>> [path for path in os.listdir(os.getcwd()) if os.path.isdir(path)]
I discover very simple way to redirect Login Page When session end in MVC. I have already tested it and this works without problems.
In short, I catch session end in _Layout 1 minute before and make redirection.
I try to explain everything step by step.
If we want to session end 30 minute after and redirect to loginPage see this steps:
Change the web config like this (set 31 minute):
<system.web>
<sessionState timeout="31"></sessionState>
</system.web>
Add this JavaScript in _Layout
(when session end 1 minute before this code makes redirect, it makes count time after user last action, not first visit on site)
<script>
//session end
var sessionTimeoutWarning = @Session.Timeout- 1;
var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
setTimeout('SessionEnd()', sTimeout);
function SessionEnd() {
window.location = "/Account/LogOff";
}
</script>
Here is my LogOff Action, which makes only LogOff and redirect LoginIn Page
public ActionResult LogOff()
{
Session["User"] = null; //it's my session variable
Session.Clear();
Session.Abandon();
FormsAuthentication.SignOut(); //you write this when you use FormsAuthentication
return RedirectToAction("Login", "Account");
}
I hope this is a very useful code for you.
Look into re-indexing tables in your database.
You can first find out the fragmentation level - and if it's above 10% or so you could benefit from re-indexing. If it's very high it's likely this is creating a significant performance bottle neck.
This should be done regularly.
Here is a simple approach which will print the 2 different elapsed time for each query.
DECLARE @t1 DATETIME;
DECLARE @t2 DATETIME;
SET @t1 = GETDATE();
SELECT DISTINCT u.profession FROM users u; --Query with DISTINCT
SET @t2 = GETDATE();
PRINT 'Elapsed time (ms): ' + CAST(DATEDIFF(millisecond, @t1, @t2) AS varchar);
SET @t1 = GETDATE();
SELECT u.profession FROM users u GROUP BY u.profession; --Query with GROUP BY
SET @t2 = GETDATE();
PRINT 'Elapsed time (ms): ' + CAST(DATEDIFF(millisecond, @t1, @t2) AS varchar);
OR try SET STATISTICS TIME (Transact-SQL)
SET STATISTICS TIME ON;
SELECT DISTINCT u.profession FROM users u; --Query with DISTINCT
SELECT u.profession FROM users u GROUP BY u.profession; --Query with GROUP BY
SET STATISTICS TIME OFF;
It simply displays the number of milliseconds required to parse, compile, and execute each statement as below:
SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 2 ms.
The answers provided so far using Jackson are so good, but still you could have a util function to help you convert different POJO
s as follows:
public static <T> T convert(Map<String, Object> aMap, Class<T> t) {
try {
return objectMapper
.convertValue(aMap, objectMapper.getTypeFactory().constructType(t));
} catch (Exception e) {
log.error("converting failed! aMap: {}, class: {}", getJsonString(aMap), t.getClass().getSimpleName(), e);
}
return null;
}
According to the documentation:
Thrown to indicate that the code has attempted to cast an Object
to a subclass
of which it is not an instance. For example, the following code generates a ClassCastException
:
Object x = new Integer(0);
System.out.println((String)x);
let prices = {_x000D_
"apple": 100,_x000D_
"banana": 300,_x000D_
"orange": 250_x000D_
};_x000D_
_x000D_
let sum = 0;_x000D_
for (let price of Object.values(prices)) {_x000D_
sum += price;_x000D_
}_x000D_
_x000D_
alert(sum)
_x000D_
If your PHP app is holding open many SQL Server connections, then, as you may know, you have a problem with your app's database code. It should be releasing/disposing those connections after use and using connection pooling. Have a look here for a decent article on the topic...
http://www.c-sharpcorner.com/UploadFile/dsdaf/ConnPooling07262006093645AM/ConnPooling.aspx
I use this solution
int G = 0;
private void toolStripMenuItem17_Click(object sender, EventArgs e)
{
Directory.CreateDirectory("picture");// ??? ??????? ????? ???? ?? ???? ???? ????????
G = G + 1;
FormScreen();
memoryImage1.Save("picture\\picture" + G.ToString() + ".jpg");
pictureBox1.Image = Image.FromFile("picture\\picture" + G.ToString() + ".jpg");
}
In my travels I have found that if you try either of the following while you are recording audio, the device will not vibrate even if it is enabled.
1) AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
2) AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
My method was called at a specific time in the measurement of the devices movements. I had to stop the recording and then restart it after the vibration had occurred.
It looked like this.
-(void)vibrate {
[recorder stop];
AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);
[recorder start];
}
recorder
is an AVRecorder instance.
Hope this helps others that have had the same problem before.
Where does pip installations happen in python?
I will give a windows solution which I was facing and took a while to solve.
First of all, in windows (I will be taking Windows as the OS here), if you do pip install <package_name>
, it will be by default installed globally (if you have not activated a virtual enviroment).
Once you activate a virtual enviroment and you are inside it, all pip installations will be inside that virtual enviroment.
pip is installing the said packages but not I cannot use them?
For this pip might be giving you a warning that the pip executables like pip3.exe
, pip.exe
are not on your path variable.
For this you might add this path ( usually - C:\Users\<your_username>\AppData\Roaming\Programs\Python\
) to your enviromental variables.
After this restart your cmd
, and now try to use your installed python package. It should work now.
Use below code to get all attributes with details
global $wpdb;
$attribute_taxonomies = $wpdb->get_results( "SELECT * FROM " . $wpdb->prefix . "woocommerce_attribute_taxonomies WHERE attribute_name != '' ORDER BY attribute_name ASC;" );
set_transient( 'wc_attribute_taxonomies', $attribute_taxonomies );
$attribute_taxonomies = array_filter( $attribute_taxonomies ) ;
prin_r($attribute_taxonomies);
Code for A Breadth First Search to make sure both nodes are in the tree. Only then move forward with the LCA search. Please comment if you have any suggestions to improve. I think we can probably mark them visited and restart the search at a certain point where we left off to improve for the second node (if it isn't found VISITED)
public class searchTree {
static boolean v1=false,v2=false;
public static boolean bfs(Treenode root, int value){
if(root==null){
return false;
}
Queue<Treenode> q1 = new LinkedList<Treenode>();
q1.add(root);
while(!q1.isEmpty())
{
Treenode temp = q1.peek();
if(temp!=null) {
q1.remove();
if (temp.value == value) return true;
if (temp.left != null) q1.add(temp.left);
if (temp.right != null) q1.add(temp.right);
}
}
return false;
}
public static Treenode lcaHelper(Treenode head, int x,int y){
if(head==null){
return null;
}
if(head.value == x || head.value ==y){
if (head.value == y){
v2 = true;
return head;
}
else {
v1 = true;
return head;
}
}
Treenode left = lcaHelper(head.left, x, y);
Treenode right = lcaHelper(head.right,x,y);
if(left!=null && right!=null){
return head;
}
return (left!=null) ? left:right;
}
public static int lca(Treenode head, int h1, int h2) {
v1 = bfs(head,h1);
v2 = bfs(head,h2);
if(v1 && v2){
Treenode lca = lcaHelper(head,h1,h2);
return lca.value;
}
return -1;
}
}
I had the same problem in my JSF application which was having a comment line containing some special characters in the XMHTL page. When I compared the previous version in my eclipse it had a comment,
//Some ? ? special characters found
Removed those characters and the page loaded fine. Mostly it is related to XML files, so please compare it with the working version.
This may be a little late but going back to your example I thought I would extend the answer just a tad.
D1 <- data.frame(Y1=c(1,2,3), Y2=c(4,5,6))
D2 <- data.frame(Y1=c(3,2,1), Y2=c(6,5,4))
D3 <- data.frame(Y1=c(6,5,4), Y2=c(3,2,1))
D4 <- data.frame(Y1=c(9,9,9), Y2=c(8,8,8))
Then you make your list easily:
mylist <- list(D1,D2,D3,D4)
Now you have a list but instead of accessing the list the old way such as
mylist[[1]] # to access 'd1'
you can use this function to obtain & assign the dataframe of your choice.
GETDF_FROMLIST <- function(DF_LIST, ITEM_LOC){
DF_SELECTED <- DF_LIST[[ITEM_LOC]]
return(DF_SELECTED)
}
Now get the one you want.
D1 <- GETDF_FROMLIST(mylist, 1)
D2 <- GETDF_FROMLIST(mylist, 2)
D3 <- GETDF_FROMLIST(mylist, 3)
D4 <- GETDF_FROMLIST(mylist, 4)
Hope that extra bit helps.
Cheers!
Here's what I'd do :
Put the data in a standard form (with no runat="server" attribute) and set the action of the form to post to the target off-site page. Before submitting I would submit the data to my server using an XmlHttpRequest and analyze the response. If the response means you should go ahead with the offsite POSTing then I (the JavaScript) would proceed with the post otherwise I would redirect to a page on my site
Copy-pasted from here: Incrementing a date in JavaScript
Three options for you:
Using just JavaScript's Date object (no libraries):
var today = new Date(); var tomorrow = new Date(today.getTime() + (24 * 60 * 60 * 1000));
Or if you don't mind changing the date in place (rather than creating a new date):
var dt = new Date(); dt.setTime(dt.getTime() + (24 * 60 * 60 * 1000));
Edit: See also Jigar's answer and David's comment below: var tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1);
Using MomentJS:
var today = moment(); var tomorrow = moment(today).add(1, 'days');
(Beware that add modifies the instance you call it on, rather than returning a new instance, so today.add(1, 'days') would modify today. That's why we start with a cloning op on var tomorrow = ....)
Using DateJS, but it hasn't been updated in a long time:
var today = new Date(); // Or Date.today() var tomorrow = today.add(1).day();
The If
style component is dangerous because the code block is always executed regardless of the condition. For example, this would cause a null exception if banner
is null
:
//dangerous
render: function () {
return (
<div id="page">
<If test={this.state.banner}>
<img src={this.state.banner.src} />
</If>
<div id="other-content">
blah blah blah...
</div>
</div>
);
}
Another option is to use an inline function (especially useful with else statements):
render: function () {
return (
<div id="page">
{function(){
if (this.state.banner) {
return <div id="banner">{this.state.banner}</div>
}
}.call(this)}
<div id="other-content">
blah blah blah...
</div>
</div>
);
}
Another option from react issues:
render: function () {
return (
<div id="page">
{ this.state.banner &&
<div id="banner">{this.state.banner}</div>
}
<div id="other-content">
blah blah blah...
</div>
</div>
);
}
The values()
method returns a QuerySet containing dictionaries:
<QuerySet [{'comment_id': 1}, {'comment_id': 2}]>
The values_list()
method returns a QuerySet containing tuples:
<QuerySet [(1,), (2,)]>
If you are using values_list()
with a single field, you can use flat=True
to return a QuerySet of single values instead of 1-tuples:
<QuerySet [1, 2]>
You can use netstat this way for much faster results:
On Linux:
netstat -lnt | awk '$6 == "LISTEN" && $4 ~ /\.445$/'
On Mac:
netstat -anp tcp | awk '$6 == "LISTEN" && $4 ~ /\.445$/'
This will output a list of processes listening on the port (445 in this example) or it will output nothing if the port is free.
<sup>
and <sub>
tags work and are your only good solution for arbitrary text. Other solutions include:
Unicode
If the superscript (or subscript) you need is of a mathematical nature, Unicode may well have you covered.
I've compiled a list of all the Unicode super and subscript characters I could identify in this gist. Some of the more common/useful ones are:
°
SUPERSCRIPT ZERO (U+2070)¹
SUPERSCRIPT ONE (U+00B9)²
SUPERSCRIPT TWO (U+00B2)³
SUPERSCRIPT THREE (U+00B3)n
SUPERSCRIPT LATIN SMALL LETTER N (U+207F)People also often reach for <sup>
and <sub>
tags in an attempt to render specific symbols like these:
™
TRADE MARK SIGN (U+2122)®
REGISTERED SIGN (U+00AE)?
SERVICE MARK (U+2120)Assuming your editor supports Unicode, you can copy and paste the characters above directly into your document.
Alternatively, you could use the hex values above in an HTML character escape. Eg, ²
instead of ²
. This works with GitHub (and should work anywhere else your Markdown is rendered to HTML) but is less readable when presented as raw text/Markdown.
Images
If your requirements are especially unusual, you can always just inline an image. The GitHub supported syntax is:
![Alt text goes here, if you'd like](path/to/image.png)
You can use a full path (eg. starting with https://
or http://
) but it's often easier to use a relative path, which will load the image from the repo, relative to the Markdown document.
If you happen to know LaTeX (or want to learn it) you could do just about any text manipulation imaginable and render it to an image. Sites like Quicklatex make this quite easy.
Function ExtSql(ByVal sql As String) As Boolean
Dim cnn As SqlConnection
Dim cmd As SqlCommand
cnn = New SqlConnection(My.Settings.mySqlConnectionString)
Try
cnn.Open()
cmd = New SqlCommand
cmd.Connection = cnn
cmd.CommandType = CommandType.Text
cmd.CommandText = sql
cmd.ExecuteNonQuery()
cnn.Close()
cmd.Dispose()
Catch ex As Exception
cnn.Close()
Return False
End Try
Return True
End Function
You could try:
#!/bin/bash
### $1 == the first args to this script
### usage: script.sh /path/to/dir/
for f in `find . -maxdepth 1 -mindepth 1 -type d`; do
cd "$f"
<your job here>
done
or similar...
Explanation:
find . -maxdepth 1 -mindepth 1 -type d
:
Only find directories with a maximum recursive depth of 1 (only the subdirectories of $1) and minimum depth of 1 (excludes current folder .
)
use this in css
.logo-center{
border:inherit 8px #000000;
-moz-border-radius-topleft: 75px;
-moz-border-radius-topright:75px;
-moz-border-radius-bottomleft:75px;
-moz-border-radius-bottomright:75px;
-webkit-border-top-left-radius:75px;
-webkit-border-top-right-radius:75px;
-webkit-border-bottom-left-radius:75px;
-webkit-border-bottom-right-radius:75px;
border-top-left-radius:75px;
border-top-right-radius:75px;
border-bottom-left-radius:75px;
border-bottom-right-radius:75px;
}
<img class="logo-center" src="NBC-Logo.png" height="60" width="60">
For the current MS SQL JDBC driver (6.4.0) tested under Windows 7 from within DataGrip:
server.your.domain
not just server
; the documentation also mentions the possibility to specify serverSpn=MSSQLSvc/fqdn:port@REALM
, but I can not provide you with details on how to use this. When specifying a fqdn as host the spn is auto-generated.authenticationScheme=JavaKerberos
integratedSecurity=true
As this is using JavaKerberos I would appreciate feedback on whether or not this works from outside Windows. I believe that no .dll is needed, but as I used DataGrip to create the connection I am uncertain; I would also appreciate Feedback on this!
try this
var fun = (function() {
var called = false;
return function() {
if (!called) {
console.log("I called");
called = true;
}
}
})()
This is a simpler way using iloc to select which columns to sum:
df['f']=df.iloc[:,0:2].sum(axis=1)
df['g']=df.iloc[:,[0,1]].sum(axis=1)
df['h']=df.iloc[:,[0,3]].sum(axis=1)
Produces:
a b c d e f g h
0 1 2 dd 5 8 3 3 6
1 2 3 ee 9 14 5 5 11
2 3 4 ff 1 8 7 7 4
I can't find a way to combine a range and specific columns that works e.g. something like:
df['i']=df.iloc[:,[[0:2],3]].sum(axis=1)
df['i']=df.iloc[:,[0:2,3]].sum(axis=1)
Here is a small hint that I hope might be useful to other poor saps that experienced the same issue as I did.
My Setup: Host: Windows 7 Enterprise - build 7601 SP 1 VM: VMware® Workstation 12 Player 12.1.1 build-3770994 (free) Guest: Fedora release 23
I naively failed to install open-vm-tools-desktop. I say naively because I had no idea such a thing existed, nor do I understand why instructions to install open-vm-tools do not (or at least where I read them, do not) include mentions of this package.
Installing open-vm-tools on its own appears to be nearly useless - the desktop package makes the copy and paste function - probably the single most important function of VMTools - work.
So, there you go. Install open-vm-tools-desktop, and copy-paste should work
If you downloaded bootstrap, go to bootstrap-4.4.1-dist/css/bootstrap.min.css
find the .navbar-light .navbar-toggler-icon
or the .navbar-dark .navbar-toggler-icon
selector
select the background-image
attribute and its value. The snippet looks like this:
.navbar-light .navbar-toggler-icon {
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' width='30' height='30' viewBox='0 0 30 30'%3e%3cpath stroke='rgba(0, 0, 0, 0.5)' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e");
}
copy the snippet and paste it in your custom CSS
change the stroke='rgba(0, 0, 0, 0.5)'
value to your preferred rgba value
Python has many variations off of the main three modes, these three modes are:
'w' write text
'r' read text
'a' append text
So to append to a file it's as easy as:
f = open('filename.txt', 'a')
f.write('whatever you want to write here (in append mode) here.')
Then there are the modes that just make your code fewer lines:
'r+' read + write text
'w+' read + write text
'a+' append + read text
Finally, there are the modes of reading/writing in binary format:
'rb' read binary
'wb' write binary
'ab' append binary
'rb+' read + write binary
'wb+' read + write binary
'ab+' append + read binary
A word of caution. Stringing together several not
selectors increases the specificity of the resulting selector, which makes it harder to override: you'll basically need to find the selector with all the nots and copy-paste it into your new selector.
A not(X or Y)
selector would be great to avoid inflating specificity, but I guess we'll have to stick to combining the opposites, like in this answer.
TL;DR
useEffect(yourCallback, [])
- will trigger the callback only after the first render.
Detailed explanation
useEffect
runs by default after every render of the component (thus causing an effect).
When placing useEffect
in your component you tell React you want to run the callback as an effect. React will run the effect after rendering and after performing the DOM updates.
If you pass only a callback - the callback will run after each render.
If passing a second argument (array), React will run the callback after the first render and every time one of the elements in the array is changed. for example when placing useEffect(() => console.log('hello'), [someVar, someOtherVar])
- the callback will run after the first render and after any render that one of someVar
or someOtherVar
are changed.
By passing the second argument an empty array, React will compare after each render the array and will see nothing was changed, thus calling the callback only after the first render.
package secondhighestno;
import java.util.Scanner;
/**
*
* @author Laxman
*/
public class SecondHighestno {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner sc=new Scanner(System.in);
int n =sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
}
int max1=a[0],max2=a[0];
for(int j=0;j<n;j++){
if(a[j]>max1){
max1=a[j];
}
}
for(int k=0;k<n;k++){
if(a[k]>max2 && max1>a[k]){
max2=a[k];
}
}
System.out.println(max1+" "+max2);
}
}
In this case you need to go up to the <tr>
then use .next()
, like this:
$(obj).closest('tr').next().find('.class');
Or if there may be rows in-between without the .class
inside, you can use .nextAll()
, like this:
$(obj).closest('tr').nextAll(':has(.class):first').find('.class');
I'm late to this party but I'd like to add one bit to user756519's thorough, excellent answer. I don't believe the "RetainSameConnection on the Connection Manager" property is relevant in this instance based on my recent experience. In my case, the relevant point was their advice to set "ValidateExternalMetadata" to False.
I'm using a temp table to facilitate copying data from one database (and server) to another, hence the reason "RetainSameConnection" was not relevant in my particular case. And I don't believe it is important to accomplish what is happening in this example either, as thorough as it is.
In Spring 5
@PostMapping( "some/request/path" )
public void someControllerMethod( @RequestParam MultiValueMap body ) {
// import org.springframework.util.MultiValueMap;
String datax = (String) body .getFirst("datax");
}
You can use easy_date to make it easy:
import date_converter
converted_date = date_converter.string_to_datetime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
As of Mongoose 3.8.x:
model.find({ ... }).sort({ field : criteria}).exec(function(err, model){ ... });
Where:
criteria
can be asc
, desc
, ascending
, descending
, 1
, or -1
Note: Use quotation marks or double quote
use "asc"
, "desc"
, "ascending"
, "descending"
, 1
, or -1
Assuming the first byte is the least significant byte:
long value = 0;
for (int i = 0; i < by.length; i++)
{
value += ((long) by[i] & 0xffL) << (8 * i);
}
Is the first byte the most significant, then it is a little bit different:
long value = 0;
for (int i = 0; i < by.length; i++)
{
value = (value << 8) + (by[i] & 0xff);
}
Replace long with BigInteger, if you have more than 8 bytes.
Thanks to Aaron Digulla for the correction of my errors.
I had the same problem. It was resolved by setting "USB computer connection" to "Camera (PTP)" instead of "Media Device (MTP)
Instead of using a collector try using findFirst
or findAny
.
Optional<Person> matchingObject = objects.stream().
filter(p -> p.email().equals("testemail")).
findFirst();
This returns an Optional
since the list might not contain that object.
If you're sure that the list always contains that person you can call:
Person person = matchingObject.get();
Be careful though! get
throws NoSuchElementException
if no value is present. Therefore it is strongly advised that you first ensure that the value is present (either with isPresent
or better, use ifPresent
, map
, orElse
or any of the other alternatives found in the Optional
class).
If you're okay with a null
reference if there is no such person, then:
Person person = matchingObject.orElse(null);
If possible, I would try to avoid going with the null
reference route though. Other alternatives methods in the Optional class (ifPresent
, map
etc) can solve many use cases. Where I have found myself using orElse(null)
is only when I have existing code that was designed to accept null
references in some cases.
Optionals have other useful methods as well. Take a look at Optional javadoc.
As pgb said, there are no "class variables," only "instance variables." The objective-c way of doing class variables is a static global variable inside the .m file of the class. The "static" ensures that the variable can not be used outside of that file (i.e. it can't be extern).
For the replacement portion, Python uses \1
the way sed and vi do, not $1
the way Perl, Java, and Javascript (amongst others) do. Furthermore, because \1
interpolates in regular strings as the character U+0001, you need to use a raw string or \escape it.
Python 3.2 (r32:88445, Jul 27 2011, 13:41:33)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> method = 'images/:id/huge'
>>> import re
>>> re.sub(':([a-z]+)', r'<span>\1</span>', method)
'images/<span>id</span>/huge'
>>>
Here is the right anwser:
ADD_EXECUTABLE(your_executable ${source_files})
TARGET_LINK_LIBRARIES( your_executable
pthread
)
equivalent to
-lpthread
After I read that this particular issue was fixed in the roslyn compiler (see this issue at GitHub), I updated Visual Studio from version 15.0.x to 15.3.1. It works like a charm now.
From php.net
@Alexandre - short solution
<?php
function vname(&$var, $scope=0)
{
$old = $var;
if (($key = array_search($var = 'unique'.rand().'value', !$scope ? $GLOBALS : $scope)) && $var = $old) return $key;
}
?>
@Lucas - usage
<?php
//1. Use of a variable contained in the global scope (default):
$my_global_variable = "My global string.";
echo vname($my_global_variable); // Outputs: my_global_variable
//2. Use of a local variable:
function my_local_func()
{
$my_local_variable = "My local string.";
return vname($my_local_variable, get_defined_vars());
}
echo my_local_func(); // Outputs: my_local_variable
//3. Use of an object property:
class myclass
{
public function __constructor()
{
$this->my_object_property = "My object property string.";
}
}
$obj = new myclass;
echo vname($obj->my_object_property, $obj); // Outputs: my_object_property
?>
1) for example HTML code:
<ul>
<li>
<a href="#">firstlink</a>
<span><a href="#">second link</a>
</li>
</ul>
and css rules:
1) ul li a {color:red;}
2) ul > li > a {color:blue;}
">" - symbol mean that that will be searching only child selector (parentTag > childTag)
so first css rule will apply to all links (first and second) and second rule will apply anly to first link
2) As for efficiency - I think second will be more fast - as in case with JavaScript selectors. This rule read from right to left, this mean that when rule will parse by browser, it get all links on page: - in first case it will find all parent elements for each link on page and filter all links where exist parent tags "ul" and "li" - in second case it will check only parent node of link if it is "li" tag then -> check if parent tag of "li" is "ul"
some thing like this. Hope I describe all properly for you
Use Split-Path
$filePath = "C:\PS\Test.Documents\myTestFile.txt";
$fileName = (Split-Path -Path $filePath -Leaf).Split(".")[0];
$extension = (Split-Path -Path $filePath -Leaf).Split(".")[1];
For linking against libraries see Andre's answer.
For linker flags - the following 4 CMake variables:
CMAKE_EXE_LINKER_FLAGS
CMAKE_MODULE_LINKER_FLAGS
CMAKE_SHARED_LINKER_FLAGS
CMAKE_STATIC_LINKER_FLAGS
can be easily manipulated for different configs (debug, release...) with the ucm_add_linker_flags macro of ucm
Nicely explained above!
For all those who may suffer like me to get this working in a localized Windows (mine is XP in Slovak), you may try to replace the %
with a !
So:
SET TEXT=Hello World
SET SUBSTRING=!TEXT:~3,5!
ECHO !SUBSTRING!
You can't do insert into to insert single record. It's not supported by Hive. You may place all new records that you want to insert in a file and load that file into a temp table in Hive. Then using insert overwrite..select command insert those rows into a new partition of your main Hive table. The constraint here is your main table will have to be pre partitioned. If you don't use partition then your whole table will be replaced with these new records.
Another approach (based on docker-postgresql-workflow)
Local running database (not in docker, but same approach would work) to export:
pg_dump -F c -h localhost mydb -U postgres export.dmp
Container database to import:
docker run -d -v /local/path/to/postgres:/var/lib/postgresql/data postgres #ex runs container as `CONTAINERNAME` #find via `docker ps`
docker run -it --link CONTAINERNAME:postgres --volume $PWD/:/tmp/ postgres bash -c 'exec pg_restore -h postgres -U postgres -d mydb -F c /tmp/sonar.dmp'
What do you mean with "without iterating"?
You can use map.entrySet().iterator().next()
and you wouldn't iterate through map (in the meaning of "touching each object"). You can't get hold of an Entry<K, V>
without using an iterator though. The Javadoc of Map.Entry says:
The Map.entrySet method returns a collection-view of the map, whose elements are of this class. The only way to obtain a reference to a map entry is from the iterator of this collection-view. These Map.Entry objects are valid only for the duration of the iteration.
Can you explain in more detail, what you are trying to accomplish? If you want to handle objects first, that match a specific criterion (like "have a particular key") and fall back to the remaining objects otherwise, then look at a PriorityQueue. It will order your objects based on natural order or a custom-defined Comparator
that you provide.
If you are pushing from one remote origin to another, you can use this:
git push newremote refs/remotes/oldremote/*:refs/heads/*
This worked for me. Reffer to this: https://www.metaltoad.com/blog/git-push-all-branches-new-remote
You can enable SSL on XAMPP by creating self signed certificates and then installing those certificates. Type the below commands to generate and move the certificates to ssl folders.
openssl genrsa -des3 -out server.key 1024
openssl req -new -key server.key -out server.csr
cp server.key server.key.org
openssl rsa -in server.key.org -out server.key
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
cp server.crt /opt/lampp/etc/ssl.crt/domainname.crt
cp server.key /opt/lampp/etc/ssl.key/domainname.key
(Use sudo with each command if you are not the super user)
Now, Check that mod_ssl is enabled in [XAMPP_HOME]/etc/httpd.conf:
LoadModule ssl_module modules/mod_ssl.so
Add a virtual host, in this example "localhost.domainname.com" by editing [XAMPP_HOME]/etc/extra/httpd-ssl.conf as follows:
<virtualhost 127.0.1.4:443>
ServerName localhost.domainname.com
ServerAlias localhost.domainname.com *.localhost.domainname.com
ServerAdmin admin@localhost
DocumentRoot "/opt/lampp/htdocs/"
DirectoryIndex index.php
ErrorLog /opt/lampp/logs/domainname.local.error.log
CustomLog /opt/lampp/logs/domainname.local.access.log combined
SSLEngine on
SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL
SSLCertificateFile /opt/lampp/etc/ssl.crt/domainname.crt
SSLCertificateKeyFile /opt/lampp/etc/ssl.key/domainname.key
<directory /opt/lampp/htdocs/>
Options Indexes FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
</directory>
BrowserMatch ".*MSIE.*" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0
</virtualhost>
Add the following entry to /etc/hosts:
127.0.1.4 localhost.domainname.com
Now, try installing the certificate/ try importing certificate to browser. I have checked this and this worked on Ubuntu.
Since seaborn also uses matplotlib to do its plotting you can easily combine the two. If you only want to adopt the styling of seaborn the set_style
function should get you started:
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
sns.set_style("darkgrid")
plt.plot(np.cumsum(np.random.randn(1000,1)))
plt.show()
Result:
fn
literally refers to the jquery prototype
.
This line of code is in the source code:
jQuery.fn = jQuery.prototype = {
//list of functions available to the jQuery api
}
But the real tool behind fn
is its availability to hook your own functionality into jQuery. Remember that jquery will be the parent scope to your function, so this
will refer to the jquery object.
$.fn.myExtension = function(){
var currentjQueryObject = this;
//work with currentObject
return this;//you can include this if you would like to support chaining
};
So here is a simple example of that. Lets say I want to make two extensions, one which puts a blue border, and which colors the text blue, and I want them chained.
jsFiddle Demo
$.fn.blueBorder = function(){
this.each(function(){
$(this).css("border","solid blue 2px");
});
return this;
};
$.fn.blueText = function(){
this.each(function(){
$(this).css("color","blue");
});
return this;
};
Now you can use those against a class like this:
$('.blue').blueBorder().blueText();
(I know this is best done with css such as applying different class names, but please keep in mind this is just a demo to show the concept)
This answer has a good example of a full fledged extension.
This has bugged me for some time. What I usually end up doing is rebuilding my external library using debug mode, then copy both .dll and the .pdb file to the bin of my website. This allows me to step into the libarary code.
You can also use onBackPressed by following ways using customized Toast:
customized_toast.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/txtMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableStart="@drawable/ic_white_exit_small"
android:drawableLeft="@drawable/ic_white_exit_small"
android:drawablePadding="8dp"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:gravity="center"
android:textColor="@android:color/white"
android:textSize="16sp"
android:text="Press BACK again to exit.."
android:background="@drawable/curve_edittext"/>
MainActivity.java
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
android.os.Process.killProcess(Process.myPid());
System.exit(1);
return;
}
this.doubleBackToExitPressedOnce = true;
Toast toast = new Toast(Dashboard.this);
View view = getLayoutInflater().inflate(R.layout.toast_view,null);
toast.setView(view);
toast.setDuration(Toast.LENGTH_SHORT);
int margin = getResources().getDimensionPixelSize(R.dimen.toast_vertical_margin);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_VERTICAL, 0, margin);
toast.show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
With the Material Components library you can use the CircularProgressIndicator
:
Something like:
<com.google.android.material.progressindicator.CircularProgressIndicator
android:indeterminate="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:indicatorColor="@array/progress_colors"
app:indicatorSize="xxdp"
app:showAnimationBehavior="inward"/>
where array/progress_colors
is an array with the colors:
<integer-array name="progress_colors">
<item>@color/yellow_500</item>
<item>@color/blue_700</item>
<item>@color/red_500</item>
</integer-array>
Note: it requires at least the version 1.3.0
The third inet_pton
parameter is a pointer to an in_addr
structure. After a successful inet_pton
call, the in_addr
structure will be populated with the address information. The structure's S_addr
field contains the IP address in network byte order (reverse order).
Example :
#include <arpa/inet.h>
uint32_t NodeIpAddress::getIPv4AddressInteger(std::string IPv4Address) {
int result;
uint32_t IPv4Identifier = 0;
struct in_addr addr;
// store this IP address in sa:
result = inet_pton(AF_INET, IPv4Address.c_str(), &(addr));
if (result == -1) {
gpLogFile->Write(LOGPREFIX, LogFile::LOGLEVEL_ERROR, _T("Failed to convert IP %hs to IPv4 Address. Due to invalid family of %d. WSA Error of %d"), IPv4Address.c_str(), AF_INET, result);
}
else if (result == 0) {
gpLogFile->Write(LOGPREFIX, LogFile::LOGLEVEL_ERROR, _T("Failed to convert IP %hs to IPv4"), IPv4Address.c_str());
}
else {
IPv4Identifier = ntohl(*((uint32_t *)&(addr)));
}
return IPv4Identifier;
}
I found that following these instructions helped with finding what the problem was. For me, that was the killer, not knowing what was broken.
Quoting from the link
In Tomcat 6 or above, the default logger is the”java.util.logging” logger and not Log4J. So if you are trying to add a “log4j.properties” file – this will NOT work. The Java utils logger looks for a file called “logging.properties” as stated here: http://tomcat.apache.org/tomcat-6.0-doc/logging.html
So to get to the debugging details create a “logging.properties” file under your”/WEB-INF/classes” folder of your WAR and you’re all set.
And now when you restart your Tomcat, you will see all of your debugging in it’s full glory!!!
Sample logging.properties file:
org.apache.catalina.core.ContainerBase.[Catalina].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].handlers = java.util.logging.ConsoleHandler
I've found a more reliable method (at least on Excel 2016 for Mac) is:
Assuming your long list is in column A, and the list of things to be removed from this is in column B, then paste this into all the rows of column C:
= IF(COUNTIF($B$2:$B$99999,A2)>0,"Delete","Keep")
Then just sort the list by column C to find what you have to delete.
Simply type start
in the command prompt:
start
This will open up new cmd
windows.
As others have pointed out, params
values can come from the query string of a GET request, or the form data of a POST request, but there's also a third place they can come from: The path of the URL.
As you might know, Rails uses something called routes to direct requests to their corresponding controller actions. These routes may contain segments that are extracted from the URL and put into params
. For example, if you have a route like this:
match 'products/:id', ...
Then a request to a URL like http://example.com/products/42
will set params[:id]
to 42
.
I am not sure why no one has yet suggested bindToController
which removes all these ugly scopes and $watches.
If You are using Angular 1.4
Below is a sample DOM:
<div ng-app="app">
<div ng-controller="MainCtrl as vm">
{{ vm.name }}
<foo-directive name="vm.name"></foo-directive>
<button ng-click="vm.changeScopeValue()">
changeScopeValue
</button>
</div>
</div>
Follows the controller
code:
angular.module('app', []);
// main.js
function MainCtrl() {
this.name = 'Vinoth Initial';
this.changeScopeValue = function(){
this.name = "Vinoth has Changed"
}
}
angular
.module('app')
.controller('MainCtrl', MainCtrl);
// foo.js
function FooDirCtrl() {
}
function fooDirective() {
return {
restrict: 'E',
scope: {
name: '='
},
controller: 'FooDirCtrl',
controllerAs: 'vm',
template:'<div><input ng-model="name"></div>',
bindToController: true
};
}
angular
.module('app')
.directive('fooDirective', fooDirective)
.controller('FooDirCtrl', FooDirCtrl);
A Fiddle to play around, here we are changing the scope value in the controller
and automatically the directive updates on scope change
.
http://jsfiddle.net/spechackers/1ywL3fnq/
There are a few efficient ways to implement this. Let's start with required imports:
from pyspark.sql.functions import col, expr, when
You can use Hive IF
function inside expr:
new_column_1 = expr(
"""IF(fruit1 IS NULL OR fruit2 IS NULL, 3, IF(fruit1 = fruit2, 1, 0))"""
)
or when
+ otherwise
:
new_column_2 = when(
col("fruit1").isNull() | col("fruit2").isNull(), 3
).when(col("fruit1") == col("fruit2"), 1).otherwise(0)
Finally you could use following trick:
from pyspark.sql.functions import coalesce, lit
new_column_3 = coalesce((col("fruit1") == col("fruit2")).cast("int"), lit(3))
With example data:
df = sc.parallelize([
("orange", "apple"), ("kiwi", None), (None, "banana"),
("mango", "mango"), (None, None)
]).toDF(["fruit1", "fruit2"])
you can use this as follows:
(df
.withColumn("new_column_1", new_column_1)
.withColumn("new_column_2", new_column_2)
.withColumn("new_column_3", new_column_3))
and the result is:
+------+------+------------+------------+------------+
|fruit1|fruit2|new_column_1|new_column_2|new_column_3|
+------+------+------------+------------+------------+
|orange| apple| 0| 0| 0|
| kiwi| null| 3| 3| 3|
| null|banana| 3| 3| 3|
| mango| mango| 1| 1| 1|
| null| null| 3| 3| 3|
+------+------+------------+------------+------------+
This works just fine, set the proxy string to ""
curl -x "" http://www.stackoverflow.com
Oops! Looks like they don't have Windows wheels on PyPI.
In the meantime, installing from source probably works or try downloading MSVC++ 14 as suggested in the error message and by others on this page.
Christoph's site also has unofficial Windows Binaries for Python Extension Packages (.whl files).
Follow steps mentioned in following links to install binaries :
Also check :
If you're on node 12 and want to downgrade to node 10, just remove node and follow the instructions for the desired version:
# Remove the version that is currently installed
sudo apt remove -y nodejs
# Setup sources for the version you want
curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -
# (Re-)Install Node
sudo apt-get install -y nodejs
I found myself wanting to downgrade to LTS on Windows from the bleeding edge. If you're not using a package manager like Chocolatey or a node version manager like nvm or n, just download the .msi
for the version you want and install it. You might want to remove the currently installed version via "Add or remove programs" tool in Windows.
I highly recommend chocolatey for keeping installations up to date easily and it is a common way to install Node.js on Windows. I had to remove the bleeding edge version before installing the LTS version:
choco uninstall nodejs
choco install nodejs-lts
package.json
- The Maintainable and Portable Way You can add node
as a dependency in package.json
and control which version is used for a particular project. Upon executing a package.json
"script", npm
(and yarn
) will use that version to run the script instead of the globally installed Node.js.
The node
package accomplishes this by downloading a node
binary for your local system and puts it into the node_modules/.bin
directory.
While not very portable or easily maintainable, some developers like manually switching which global version of node is active at any given point in time and think the official ways of doing this are too slow. There are two popular npm packages that provide helpful CLI interfaces for selecting (and automatically installing) whichever version you want for your system: nvm
and n
. Using either is beyond the scope of this answer.
You might also consider trying one of these approaches, since larger tables aren't exactly friendly on mobile even if it works:
http://elvery.net/demo/responsive-tables/
I'm partial to 'No More Tables' but that obviously depends on your application.
First of all, thank you all for your inputs. I tweak my Query - 1
and got my desired result. Gordon Linoff is right, PRINT
was messing up my query so I modified it as following:
Modified Query - 1:
SET ROWCOUNT 5
WHILE (1 = 1)
BEGIN
BEGIN TRANSACTION
UPDATE TableName
SET Value = 'abc1'
WHERE Parameter1 = 'abc' AND Parameter2 = 123
IF @@ROWCOUNT = 0
BEGIN
COMMIT TRANSACTION
BREAK
END
COMMIT TRANSACTION
END
SET ROWCOUNT 0
Output:
(5 row(s) affected)
(5 row(s) affected)
(4 row(s) affected)
(0 row(s) affected)
Annotate the property like below
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
To use identity columns for all value-generated properties on a new model, simply place the following in your context's OnModelCreating():
builder.ForNpgsqlUseIdentityColumns();
This will create make all keys and other properties which have .ValueGeneratedOnAdd() have Identity by default. You can use ForNpgsqlUseIdentityAlwaysColumns() to have Identity always, and you can also specify identity on a property-by-property basis with UseNpgsqlIdentityColumn() and UseNpgsqlIdentityAlwaysColumn().
you can use an object
var days = {
'Mon': 'Monday',
'etc..': 'etc..',
'Fri': 'Friday'
}
var date = new Date().toString().split(' ')[0]; //get day abreviation first
console.log(days[date]);
git reset
does know five "modes": soft, mixed, hard, merge and keep. I will start with the first three, since these are the modes you'll usually encounter. After that you'll find a nice little a bonus, so stay tuned.
When using git reset --soft HEAD~1
you will remove the last commit from the current branch, but the file changes will stay in your working tree. Also the changes will stay on your index, so following with a git commit
will create a commit with the exact same changes as the commit you "removed" before.
This is the default mode and quite similar to soft. When "removing" a commit with git reset HEAD~1
you will still keep the changes in your working tree but not on the index; so if you want to "redo" the commit, you will have to add the changes (git add
) before commiting.
When using git reset --hard HEAD~1
you will lose all uncommited changes in addition to the changes introduced in the last commit. The changes won't stay in your working tree so doing a git status
command will tell you that you don't have any changes in your repository.
Tread carefully with this one. If you accidentally remove uncommited changes which were never tracked by git
(speak: committed or at least added to the index), you have no way of getting them back using git
.
git reset --keep HEAD~1
is an interesting and useful one. It only resets the files which are different between the current HEAD
and the given commit. It aborts the reset if one or more of these files has uncommited changes. It basically acts as a safer version of hard
.
You can read more about that in the git reset documentation.
Note
When doing git reset
to remove a commit the commit isn't really lost, there just is no reference pointing to it or any of it's children. You can still recover a commit which was "deleted" with git reset
by finding it's SHA-1 key, for example with a command such as git reflog
.
$(document).on('change', '.custom-file-input', function (event) {
$(this).next('.custom-file-label').html(event.target.files[0].name);
})
Best of all worlds. Works on dynamically created inputs, and uses actual file name.
You should try this for the putting 2 array in singlr foreach loop Suppose i have 2 Array 1.$item_nm 2.$item_qty
`<?php $i=1; ?>
<table><tr><td>Sr.No</td> <td>item_nm</td> <td>item_qty</td> </tr>
@foreach (array_combine($item_nm, $item_qty) as $item_nm => $item_qty)
<tr>
<td> $i++ </td>
<td> $item_nm </td>
<td> $item_qty </td>
</tr></table>
@endforeach `
You can also use dplyr
's distinct()
function! It tends to be more efficient than alternative options, especially if you have loads of observations.
distinct_data <- dplyr::distinct(yourdata)
If you happen to be using jQuery, you might want to give this a shot: http://api.jquery.com/category/deferred-object/
It allows you to defer the execution of your callback function until the ajax request (or any async operation) is completed. This can also be used to call a callback once several ajax requests have all completed.
To avoid the fact that destroy_all
instantiates all the records and destroys them one at a time, you can use it directly from the model class.
So instead of :
u = User.find_by_name('JohnBoy')
u.usage_indexes.destroy_all
You can do :
u = User.find_by_name('JohnBoy')
UsageIndex.destroy_all "user_id = #{u.id}"
The result is one query to destroy all the associated records
Feel free to browse the Lua Wiki on table serialization. It lists several ways on how to dump a table to the console.
You just have to choose which one suits you best. There are many ways to do it, but I usually end up using the one from Penlight:
> t = { a = { b = { c = "Hello world!", 1 }, 2, d = { 3 } } }
> require 'pl.pretty'.dump(t)
{
a = {
d = {
3
},
b = {
c = "Hello world!",
1
},
2
}
}
this is useful to know about hashcode in java :
http://eclipsesource.com/blogs/2012/09/04/the-3-things-you-should-know-about-hashcode/
this works fine
no | cp -rf c:\source c:\Dest\
The easiest way is through keyword arguments:
class City():
def __init__(self, city=None):
pass
someCity = City(city="Berlin")
This is pretty basic stuff. Maybe look at the Python documentation?
You can set the default value of your Id in your db to newsequentialid() or newid(). Then the identity configuration of EF should work.
You could use the .mayBeJSON(String str) available in the JSONUtils library.
#include <stdio.h>
int main() {
int c;
while((c = getchar()) != EOF) { //precedence of != is greater than =, so use braces
printf("%d\n", c);
}
printf("%d - at EOF\n", c);
}
I think this is right way to check value of EOF. And I checked the output.
For INPUT: abc and Enter I got OUTPUT: 97 98 99 10. ( the ASCII values)
For INPUT Ctrl-D I got OUTPUT: -1 - at EOF. So I think -1 is the value for EOF.
Try other inputs instead of Ctrl-D, like Ctrl-Z. I think it varies from compiler to compiler.
Just do
openssl x509 -req -days 365 -in server.cer -signkey server.key -out server.crt
I don't know how to programmatically solve this, but the first thing people do is that we sample the algorithm for certain patterns in the number of operations done, say 4n^2 + 2n + 1 we have 2 rules:
If we simplify f(x), where f(x) is the formula for number of operations done, (4n^2 + 2n + 1 explained above), we obtain the big-O value [O(n^2) in this case]. But this would have to account for Lagrange interpolation in the program, which may be hard to implement. And what if the real big-O value was O(2^n), and we might have something like O(x^n), so this algorithm probably wouldn't be programmable. But if someone proves me wrong, give me the code . . . .
A callable is anything that can be called.
The built-in callable (PyCallable_Check in objects.c) checks if the argument is either:
__call__
method orThe method named __call__
is (according to the documentation)
Called when the instance is ''called'' as a function
class Foo:
def __call__(self):
print 'called'
foo_instance = Foo()
foo_instance() #this is calling the __call__ method
This is the solution that I've came up with:
<form name = "form1" id = "form1" action = "#" method = "post">
<select name = "DropDownList1" id = "DropDownList1">
<?php
$arr = array('Yes', 'No', 'Fine' ); // create array so looping is easier
for( $i = 1; $i <= 3; $i++ ) // loop starts at first value and ends at last value
{
$selected = ''; // keep selected at nothing
if( isset( $_POST['go'] ) ) // check if form was submitted
{
if( $_POST['DropDownList1'] == $i ) // if the value of the dropdownlist is equal to the looped variable
{
$selected = 'selected = "selected"'; // if is equal, set selected = "selected"
}
}
// note: if value is not equal, selected stays defaulted to nothing as explained earlier
echo '<option value = "' . $i . '"' . $selected . '>' . $arr[$i] . '</option>'; // echo the option element to the page using the $selected variable
}
?>
</select> <!-- finish the form in html -->
<input type="text" value="" name="name">
<input type="submit" value="go" name="go">
</form>
The code I have works as long as the values are integers in some numeric order ( ascending or descending ). What it does is starts the dropdownlist in html, and adds each option element in php code. It will not work if you have random values though, i.e: 1, 4, 2, 7, 6. Each value must be unique.
Here's the GNU version of printf
... you can see it passing in stdout
to vfprintf
:
__printf (const char *format, ...)
{
va_list arg;
int done;
va_start (arg, format);
done = vfprintf (stdout, format, arg);
va_end (arg);
return done;
}
Here's a link to vfprintf
... all the formatting 'magic' happens here.
The only thing that's truly 'different' about these functions is that they use varargs to get at arguments in a variable length argument list. Other than that, they're just traditional C. (This is in contrast to Pascal's printf
equivalent, which is implemented with specific support in the compiler... at least it was back in the day.)
Cookie-Based Authentication
Cookies based Authentication works normally in these 4 steps-
Browser will submit this session Id on each subsequent requests, the session ID is verified against the database, based on this session id website will identify the session belonging to which client and then give access the request.
Once a user logs out of the app, the session is destroyed both client-side and server-side.
Since at least Spring 3, instead of using UriComponentsBuilder
to build the URL (which is a bit verbose), many of the RestTemplate
methods accept placeholders in the path for parameters (not just exchange
).
From the documentation:
Many of the
RestTemplate
methods accepts a URI template and URI template variables, either as aString
vararg, or asMap<String,String>
.For example with a
String
vararg:restTemplate.getForObject( "http://example.com/hotels/{hotel}/rooms/{room}", String.class, "42", "21");
Or with a
Map<String, String>
:Map<String, String> vars = new HashMap<>(); vars.put("hotel", "42"); vars.put("room", "21"); restTemplate.getForObject("http://example.com/hotels/{hotel}/rooms/{room}", String.class, vars);
If you look at the JavaDoc for RestTemplate
and search for "URI Template", you can see which methods you can use placeholders with.
This will get you to an answer for your simple case, but can you expand on how you'll know which columns will need to be compared (B and C in this case) and what the initial range (A1:D5
in this case) will be? Then I can try to provide a more complete answer.
Sub setCondFormat()
Range("B3").Select
With Range("B3:H63")
.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=IF($D3="""",FALSE,IF($F3>=$E3,TRUE,FALSE))"
With .FormatConditions(.FormatConditions.Count)
.SetFirstPriority
With .Interior
.PatternColorIndex = xlAutomatic
.Color = 5287936
.TintAndShade = 0
End With
End With
End With
End Sub
Note: this is tested in Excel 2010.
Edit: Updated code based on comments.
Checking out more than one repo at a time in a single workspace is possible with Jenkins + Git Plugin (maybe only in more recent versions?).
In section "Source-Code-Management", do not select "Git", but "Multiple SCMs" and add several git repositories.
Be sure that in all but one you add as an "Additional behavior" the action "Check out to a sub-directory" and specify an individual subdirectory.
do the one of these.
if(!statusCheck.equals("success"))
{
//do something
}
or
if(!"success".equals(statusCheck))
{
//do something
}
Install the following to resolve your error.
2007 Office System Driver: Data Connectivity Components
AccessDatabaseEngine.exe (25.3 MB)
This download will install a set of components that facilitate the transfer of data between existing Microsoft Office files such as Microsoft Office Access 2007 (*.mdb and .accdb) files and Microsoft Office Excel 2007 (.xls, *.xlsx, and *.xlsb) files to other data sources such as Microsoft SQL Server.
you can do it on real device by run device in Debug mode
Click Debug->Simulate Location -> add .gpx file for your location during run time
Thats because DataGridView looks for properties of containing objects. For string there is just one property - length. So, you need a wrapper for a string like this
public class StringValue
{
public StringValue(string s)
{
_value = s;
}
public string Value { get { return _value; } set { _value = value; } }
string _value;
}
Then bind List<StringValue>
object to your grid. It works
This can be an efficient way of performing different tests on a single statement
select
case colour_txt
when 'red' then 5
when 'green' then 4
when 'orange' then 3
else 0
end as Pass_Flag
this only works on equality comparisons!
Try my favorite: put in
~/.zshrc
this line:
PROMPT='%F{240}%n%F{red}@%F{green}%m:%F{141}%d$ %F{reset}'
don't forget
source ~/.zshrc
to test the changes
you can change the colors/color codes, of course :-)