Spark 1.6.2:
log4j = sc._jvm.org.apache.log4j
log4j.LogManager.getRootLogger().setLevel(log4j.Level.ERROR)
Spark 2.x:
spark.sparkContext.setLogLevel('WARN')
(spark being the SparkSession)
Alternatively the old methods,
Rename conf/log4j.properties.template
to conf/log4j.properties
in Spark Dir.
In the log4j.properties
, change log4j.rootCategory=INFO, console
to log4j.rootCategory=WARN, console
Different log levels available:
Given some SVG:
<div id="main">
<svg id="octocat" xmlns="http://www.w3.org/2000/svg" width="400px" height="400px" viewBox="-60 0 420 330" style="fill:#fff;stroke: #000; stroke-opacity: 0.1">
<path id="puddle" d="m296.94 295.43c0 20.533-47.56 37.176-106.22 37.176-58.67 0-106.23-16.643-106.23-37.176s47.558-37.18 106.23-37.18c58.66 0 106.22 16.65 106.22 37.18z"/>
<path class="shadow-legs" d="m161.85 331.22v-26.5c0-3.422-.619-6.284-1.653-8.701 6.853 5.322 7.316 18.695 7.316 18.695v17.004c6.166.481 12.534.773 19.053.861l-.172-16.92c-.944-23.13-20.769-25.961-20.769-25.961-7.245-1.645-7.137 1.991-6.409 4.34-7.108-12.122-26.158-10.556-26.158-10.556-6.611 2.357-.475 6.607-.475 6.607 10.387 3.775 11.33 15.105 11.33 15.105v23.622c5.72.98 11.71 1.79 17.94 2.4z"/>
<path class="shadow-legs" d="m245.4 283.48s-19.053-1.566-26.16 10.559c.728-2.35.839-5.989-6.408-4.343 0 0-19.824 2.832-20.768 25.961l-.174 16.946c6.509-.025 12.876-.254 19.054-.671v-17.219s.465-13.373 7.316-18.695c-1.034 2.417-1.653 5.278-1.653 8.701v26.775c6.214-.544 12.211-1.279 17.937-2.188v-24.113s.944-11.33 11.33-15.105c0-.01 6.13-4.26-.48-6.62z"/>
<path id="cat" d="m378.18 141.32l.28-1.389c-31.162-6.231-63.141-6.294-82.487-5.49 3.178-11.451 4.134-24.627 4.134-39.32 0-21.073-7.917-37.931-20.77-50.759 2.246-7.25 5.246-23.351-2.996-43.963 0 0-14.541-4.617-47.431 17.396-12.884-3.22-26.596-4.81-40.328-4.81-15.109 0-30.376 1.924-44.615 5.83-33.94-23.154-48.923-18.411-48.923-18.411-9.78 24.457-3.733 42.566-1.896 47.063-11.495 12.406-18.513 28.243-18.513 47.659 0 14.658 1.669 27.808 5.745 39.237-19.511-.71-50.323-.437-80.373 5.572l.276 1.389c30.231-6.046 61.237-6.256 80.629-5.522.898 2.366 1.899 4.661 3.021 6.879-19.177.618-51.922 3.062-83.303 11.915l.387 1.36c31.629-8.918 64.658-11.301 83.649-11.882 11.458 21.358 34.048 35.152 74.236 39.484-5.704 3.833-11.523 10.349-13.881 21.374-7.773 3.718-32.379 12.793-47.142-12.599 0 0-8.264-15.109-24.082-16.292 0 0-15.344-.235-1.059 9.562 0 0 10.267 4.838 17.351 23.019 0 0 9.241 31.01 53.835 21.061v32.032s-.943 11.33-11.33 15.105c0 0-6.137 4.249.475 6.606 0 0 28.792 2.361 28.792-21.238v-34.929s-1.142-13.852 5.663-18.667v57.371s-.47 13.688-7.551 18.881c0 0-4.723 8.494 5.663 6.137 0 0 19.824-2.832 20.769-25.961l.449-58.06h4.765l.453 58.06c.943 23.129 20.768 25.961 20.768 25.961 10.383 2.357 5.663-6.137 5.663-6.137-7.08-5.193-7.551-18.881-7.551-18.881v-56.876c6.801 5.296 5.663 18.171 5.663 18.171v34.929c0 23.6 28.793 21.238 28.793 21.238 6.606-2.357.474-6.606.474-6.606-10.386-3.775-11.33-15.105-11.33-15.105v-45.786c0-17.854-7.518-27.309-14.87-32.3 42.859-4.25 63.426-18.089 72.903-39.591 18.773.516 52.557 2.803 84.873 11.919l.384-1.36c-32.131-9.063-65.692-11.408-84.655-11.96.898-2.172 1.682-4.431 2.378-6.755 19.25-.80 51.38-.79 82.66 5.46z"/>
<path id="face" d="m258.19 94.132c9.231 8.363 14.631 18.462 14.631 29.343 0 50.804-37.872 52.181-84.585 52.181-46.721 0-84.589-7.035-84.589-52.181 0-10.809 5.324-20.845 14.441-29.174 15.208-13.881 40.946-6.531 70.147-6.531 29.07-.004 54.72-7.429 69.95 6.357z"/>
<path id="eyes" d="m160.1 126.06 c0 13.994-7.88 25.336-17.6 25.336-9.72 0-17.6-11.342-17.6-25.336 0-13.992 7.88-25.33 17.6-25.33 9.72.01 17.6 11.34 17.6 25.33z m94.43 0 c0 13.994-7.88 25.336-17.6 25.336-9.72 0-17.6-11.342-17.6-25.336 0-13.992 7.88-25.33 17.6-25.33 9.72.01 17.6 11.34 17.6 25.33z"/>
<path id="pupils" d="m154.46 126.38 c0 9.328-5.26 16.887-11.734 16.887s-11.733-7.559-11.733-16.887c0-9.331 5.255-16.894 11.733-16.894 6.47 0 11.73 7.56 11.73 16.89z m94.42 0 c0 9.328-5.26 16.887-11.734 16.887s-11.733-7.559-11.733-16.887c0-9.331 5.255-16.894 11.733-16.894 6.47 0 11.73 7.56 11.73 16.89z"/>
<circle id="nose" cx="188.5" cy="148.56" r="4.401"/>
<path id="mouth" d="m178.23 159.69c-.26-.738.128-1.545.861-1.805.737-.26 1.546.128 1.805.861 1.134 3.198 4.167 5.346 7.551 5.346s6.417-2.147 7.551-5.346c.26-.738 1.067-1.121 1.805-.861s1.121 1.067.862 1.805c-1.529 4.324-5.639 7.229-10.218 7.229s-8.68-2.89-10.21-7.22z"/>
<path id="octo" d="m80.641 179.82 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m8.5 4.72 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m5.193 6.14 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m4.72 7.08 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m5.188 6.61 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m7.09 5.66 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m9.91 3.78 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m9.87 0 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z m10.01 -1.64 c0 1.174-1.376 2.122-3.07 2.122-1.693 0-3.07-.948-3.07-2.122 0-1.175 1.377-2.127 3.07-2.127 1.694 0 3.07.95 3.07 2.13z"/>
<path id="drop" d="m69.369 186.12l-3.066 10.683s-.8 3.861 2.84 4.546c3.8-.074 3.486-3.627 3.223-4.781z"/>
</svg>
</div>
Using jQuery, for instance, you could do:
var _currentFill = "#f00"; // red
$svg = $("#octocat");
$("#face", $svg).attr('style', "fill:"+_currentFill); })
I provided a coloring book demo as an answer to another stackoverflow question: http://bl.ocks.org/4545199. Tested on Safari, Chrome, and Firefox.
Use parameters(seconds) i.e. youtube.com/v/VIDEO_ID?start=4&end=117
Live DEMO:
https://puvox.software/software/youtube_trimmer.php
This error comes when using the following command in Windows. You can simply run the following command by removing the dot '.'
and the slash '/'
.
Instead of writing:
D:\Gesture Recognition\Gesture Recognition\Debug>./"Gesture Recognition.exe"
Write:
D:\Gesture Recognition\Gesture Recognition\Debug>"Gesture Recognition.exe"
files directory:
Project->
-functions.php
-main.php
functions.php
function sum(a,b){
return a+b;
}
function product(a,b){
return a*b;
}
main.php
require_once "functions.php";
echo "sum of two numbers ". sum(4,2);
echo "<br>"; // create break line
echo "product of two numbers ".product(2,3);
The Output Is :
sum of two numbers 6 product of two numbers 6
Note: don't write public before function. Public, private, these modifiers can only use when you create class.
The solution you are really looking for is web sockets. However, the chromium project has developed some new technologies that are direct TCP connections TCP chromium
Suppose we have three anchor tags like ,
<a href="ID=1" class="testClick">Test1.</a>
<br />
<a href="ID=2" class="testClick">Test2.</a>
<br />
<a href="ID=3" class="testClick">Test3.</a>
now in script
$(".testClick").click(function () {
var anchorValue= $(this).attr("href");
alert(anchorValue);
});
use this keyword instead of className (testClick)
A bit late on this one but this worked perfectly for me when trying to hide the background for IE6 & 7
.myclass{
background-image: url("images/myimg.png");
background-position: right top;
background-repeat: no-repeat;
background-size: 22px auto;
padding-left: 48px;
height: 42px;
_background-image: none;
*background-image: none;
}
I got this hack via: http://briancray.com/posts/target-ie6-and-ie7-with-only-1-extra-character-in-your-css/
#myelement
{
color: #999; /* shows in all browsers */
*color: #999; /* notice the * before the property - shows in IE7 and below */
_color: #999; /* notice the _ before the property - shows in IE6 and below */
}
Even easier: just store the R.drawable
id in the view's id: use v.setId()
. Then get it back with v.getId()
.
The structure of your menu code is the issue:
cin >> choice; // new line character is left in the stream
switch ( ... ) {
// We enter the handlers, '\n' still in the stream
}
cin.ignore(); // Put this right after cin >> choice, before you go on
// getting input with getline.
set global sql_mode="NO_BACKSLASH_ESCAPES,STRICT_TRANS_TABLE,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
Try this regex:
\d+\.?\d*
\d+ digits before optional decimal
.? optional decimal(optional due to the ? quantifier)
\d* optional digits after decimal
It depends on what sender address you are talking about. The sender address visble in the recipients mailprogramm is extracted from the "From:" Header. which can probably easily be set from your program.
If you are talking about the SMTP envelope sender address, you can pass the -f argument to the sendmail binary. Depending on the server configuration you may not be allowed to do that with the apache user.
from the sendmail manpage :
-f <address>
This option sets the address of the envelope sender of a
locally-generated message (also known as the return path).
The option can normally be used only by a trusted user, but
untrusted_set_sender can be set to allow untrusted users to
use it. [...]
To run Selenium WebDriver test cases in Chrome, follow these steps:
First of all, set the property and Chrome driver path:
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
Initialize the Chrome Driver's object:
WebDriver driver = new ChromeDriver();
Pass the URL into the get
method of WebDriver:
driver.get("http://www.google.com");
Should look like this:
UPDATE DHE.dbo.tblAccounts
SET DHE.dbo.tblAccounts.ControllingSalesRep =
DHE_Import.dbo.tblSalesRepsAccountsLink.SalesRepCode
from DHE.dbo.tblAccounts
INNER JOIN DHE_Import.dbo.tblSalesRepsAccountsLink
ON DHE.dbo.tblAccounts.AccountCode =
DHE_Import.tblSalesRepsAccountsLink.AccountCode
Update table is repeated in FROM clause.
I did it by other way.
Properties prop = new Properties();
try {
File jarPath=new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
String propertiesPath=jarPath.getParentFile().getAbsolutePath();
System.out.println(" propertiesPath-"+propertiesPath);
prop.load(new FileInputStream(propertiesPath+"/importer.properties"));
} catch (IOException e1) {
e1.printStackTrace();
}
That is correct. When you do that you are casting it it into an employee
object, so that means you cannot access anything manager specific.
Downcasting is where you take a base class and then try and turn it into a more specific class. This can be accomplished with using is and an explicit cast like this:
if (employee is Manager)
{
Manager m = (Manager)employee;
//do something with it
}
or with the as
operator like this:
Manager m = (employee as Manager);
if (m != null)
{
//do something with it
}
If anything is unclear I'll be happy to correct it!
I got this from some forum. I hope it will be useful for you.
<script type="text/javascript">
function validateFileExtension(fld) {
if(!/(\.bmp|\.gif|\.jpg|\.jpeg)$/i.test(fld.value)) {
alert("Invalid image file type.");
fld.form.reset();
fld.focus();
return false;
}
return true;
} </script> </head>
<body> <form ...etc... onsubmit="return
validateFileExtension(this.fileField)"> <p> <input type="file"
name="fileField" onchange="return validateFileExtension(this)">
<input type="submit" value="Submit"> </p> </form> </body>
You can set any pointer to NULL
, though NULL
is simply defined as 0 in C++:
myObject *foo = NULL;
Also note that NULL
is defined if you include standard headers, but is not built into the language itself. If NULL
is undefined, you can use 0 instead, or include this:
#ifndef NULL
#define NULL 0
#endif
As an aside, if you really want to set an object, not a pointer, to NULL
, you can read about the Null Object Pattern.
var cubes = [["string", "string"], ["string", "string"]];
for(var i = 0; i < cubes.length; i++) {
for(var j = 0; j < cubes[i].length; j++) {
console.log(cubes[i][j]);
}
}
Now days I believe it's preferred to use a function form of typeof() so...
if(filename === undefined || typeof(filename) !== "string" || filename === "") {
console.log("no filename aborted.");
return;
}
The String Formatting Operations section of the Python documentation contains the answer you're looking for. In short:
"%0.2f" % (num,)
Some examples:
>>> "%0.2f" % 10
'10.00'
>>> "%0.2f" % 1000
'1000.00'
>>> "%0.2f" % 10.1
'10.10'
>>> "%0.2f" % 10.120
'10.12'
>>> "%0.2f" % 10.126
'10.13'
sep=''
ignore whiteSpace.
see the code to understand.Without sep=''
from itertools import permutations
s,k = input().split()
for i in list(permutations(sorted(s), int(k))):
print(*i)
output:
HACK 2
A C
A H
A K
C A
C H
C K
H A
H C
H K
K A
K C
K H
using sep=''
The code and output.
from itertools import permutations
s,k = input().split()
for i in list(permutations(sorted(s), int(k))):
print(*i,sep='')
output:
HACK 2
AC
AH
AK
CA
CH
CK
HA
HC
HK
KA
KC
KH
I would just like to add another useful advantage of using %timeit to answer by mu ? that:
PS: I know this should be a comment to answer above but I currently don't have enough reputation for that, hope what I write will be helpful to someone and help me earn enough reputation to comment next time.
So I was having this problem too and I have written this function:
/***Working function for ajax loading Start*****************/_x000D_
function fuweco_loadMoreContent(elmId/*element ID without #*/,ajaxLink/*php file path*/,postParameterObject/*post parameters list as JS object with properties (new Object())*/,tillElementEnd/*point of scroll when must be started loading from AJAX*/){_x000D_
var _x000D_
contener = $("#"+elmId),_x000D_
contenerJS = document.getElementById(elmId);_x000D_
if(contener.length !== 0){_x000D_
var _x000D_
elmFullHeight = _x000D_
contener.height()+_x000D_
parseInt(contener.css("padding-top").slice(0,-2))+_x000D_
parseInt(contener.css("padding-bottom").slice(0,-2)),_x000D_
SC_scrollTop = contenerJS.scrollTop,_x000D_
SC_max_scrollHeight = contenerJS.scrollHeight-elmFullHeight;_x000D_
if(SC_scrollTop >= SC_max_scrollHeight - tillElementEnd){_x000D_
$("#"+elmId).unbind("scroll");_x000D_
$.post(ajaxLink,postParameterObject)_x000D_
.done(function(data){_x000D_
if(data.length != 0){_x000D_
$("#"+elmId).append(data);_x000D_
$("#"+elmId).scroll(function (){_x000D_
fuweco_reloaderMore(elmId,ajaxLink,postParameterObject);_x000D_
});_x000D_
}_x000D_
});_x000D_
}_x000D_
}_x000D_
}_x000D_
/***Working function for ajax loading End*******************/_x000D_
/***Sample function Start***********************************/_x000D_
function reloaderMore(elementId) {_x000D_
var_x000D_
contener = $("#"+elementId),_x000D_
contenerJS = document.getElementById(elementId)_x000D_
;_x000D_
_x000D_
if(contener.length !== 0){_x000D_
var_x000D_
elmFullHeight = contener.height()+(parseInt(contener.css("padding-top").slice(0,-2))+parseInt(contener.css("padding-bottom").slice(0,-2))),_x000D_
SC_scrollTop = contenerJS.scrollTop,_x000D_
SC_max_scrollHeight = contenerJS.scrollHeight-elmFullHeight_x000D_
;_x000D_
if(SC_scrollTop >= SC_max_scrollHeight - 200){_x000D_
$("#"+elementId).unbind("scroll");_x000D_
$("#"+elementId).append('<div id="elm1" style="margin-bottom:15px;"><h1>Was loaded</h1><p>Some text for content. Some text for content. Some text for content. Some text for content. Some text for content. Some text for content. Some text for content. Some text for content. Some text for content. Some text for content. Some text for content. Some text for content.</p></div>');_x000D_
$("#"+elementId).delay(300).scroll(function (){reloaderMore(elementId);});_x000D_
}_x000D_
}_x000D_
}_x000D_
/***Sample function End*************************************/_x000D_
/***Sample function Use Start*******************************/_x000D_
$(document).ready(function(){_x000D_
$("#t1").scrollTop(0).scroll(function (){_x000D_
reloaderMore("t1");_x000D_
});_x000D_
});_x000D_
/***Sample function Use End*********************************/
_x000D_
.reloader {_x000D_
border: solid 1px red;_x000D_
overflow: auto;_x000D_
overflow-x: hidden;_x000D_
min-height: 400px;_x000D_
max-height: 400px;_x000D_
min-width: 400px;_x000D_
max-width: 400px;_x000D_
height: 400px;_x000D_
width: 400px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>_x000D_
<div class="reloader" id="t1">_x000D_
<div id="elm1" style="margin-bottom:15px;">_x000D_
<h1>Some text for header.</h1>_x000D_
<p>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
</p>_x000D_
</div>_x000D_
<div id="elm2" style="margin-bottom:15px;">_x000D_
<h1>Some text for header.</h1>_x000D_
<p>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
</p>_x000D_
</div>_x000D_
<div id="elm3" style="margin-bottom:15px;">_x000D_
<h1>Some text for header.</h1>_x000D_
<p>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
Some text for content.<br>_x000D_
</p>_x000D_
</div> _x000D_
</div>
_x000D_
I hope it will be helpfully for other programmers.
The reason I like Rcpp so much is that I don't always get how R Core thinks, and with Rcpp, more often than not, I don't have to.
Speaking philosophically, you're in a state of sin with regards to the functional paradigm, which tries to ensure that every value appears independent of every other value; changing one value should never cause a visible change in another value, the way you get with pointers sharing representation in C.
The problems arise when functional programming signals the small craft to move out of the way, and the small craft replies "I'm a lighthouse". Making a long series of small changes to a large object which you want to process on in the meantime puts you square into lighthouse territory.
In the C++ STL, push_back()
is a way of life. It doesn't try to be functional, but it does try to accommodate common programming idioms efficiently.
With some cleverness behind the scenes, you can sometimes arrange to have one foot in each world. Snapshot based file systems are a good example (which evolved from concepts such as union mounts, which also ply both sides).
If R Core wanted to do this, underlying vector storage could function like a union mount. One reference to the vector storage might be valid for subscripts 1:N
, while another reference to the same storage is valid for subscripts 1:(N+1)
. There could be reserved storage not yet validly referenced by anything but convenient for a quick push_back()
. You don't violate the functional concept when appending outside the range that any existing reference considers valid.
Eventually appending rows incrementally, you run out of reserved storage. You'll need to create new copies of everything, with the storage multiplied by some increment. The STL implementations I've use tend to multiply storage by 2 when extending allocation. I thought I read in R Internals that there is a memory structure where the storage increments by 20%. Either way, growth operations occur with logarithmic frequency relative to the total number of elements appended. On an amortized basis, this is usually acceptable.
As tricks behind the scenes go, I've seen worse. Every time you push_back()
a new row onto the dataframe, a top level index structure would need to be copied. The new row could append onto shared representation without impacting any old functional values. I don't even think it would complicate the garbage collector much; since I'm not proposing push_front()
all references are prefix references to the front of the allocated vector storage.
The other answers cover how to do std dev in python sufficiently, but no one explains how to do the bizarre traversal you've described.
I'm going to assume A-Z is the entire population. If not see Ome's answer on how to inference from a sample.
So to get the standard deviation/mean of the first digit of every list you would need something like this:
#standard deviation
numpy.std([A_rank[0], B_rank[0], C_rank[0], ..., Z_rank[0]])
#mean
numpy.mean([A_rank[0], B_rank[0], C_rank[0], ..., Z_rank[0]])
To shorten the code and generalize this to any nth digit use the following function I generated for you:
def getAllNthRanks(n):
return [A_rank[n], B_rank[n], C_rank[n], D_rank[n], E_rank[n], F_rank[n], G_rank[n], H_rank[n], I_rank[n], J_rank[n], K_rank[n], L_rank[n], M_rank[n], N_rank[n], O_rank[n], P_rank[n], Q_rank[n], R_rank[n], S_rank[n], T_rank[n], U_rank[n], V_rank[n], W_rank[n], X_rank[n], Y_rank[n], Z_rank[n]]
Now you can simply get the stdd and mean of all the nth places from A-Z like this:
#standard deviation
numpy.std(getAllNthRanks(n))
#mean
numpy.mean(getAllNthRanks(n))
If you are using Twig templates for Symfony, you can use the classic {{object.date_attribute.format('d/m/Y')}}
to obtain the desired formatted date.
First, create staticfiles folder. Inside that folder create css, js, and img folder.
settings.py
import os
PROJECT_DIR = os.path.dirname(__file__)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(PROJECT_DIR, 'myweblabdev.sqlite'),
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(PROJECT_DIR, 'staticfiles'),
)
main urls.py
from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from myweblab import settings
admin.autodiscover()
urlpatterns = patterns('',
.......
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
template
{% load static %}
<link rel="stylesheet" href="{% static 'css/style.css' %}">
@John, Earlz and Nathan. The way I learned it at uni is: functions return values, methods don't. In some languages the syntax is/was actually different. Example (no specific language):
Method SetY(int y) ...
Function CalculateY(int x) As Integer ...
Most languages now use the same syntax for both versions, using void as a return type to say there actually isn't a return type. I assume it's because the syntax is more consistent and easier to change from method to function, and vice versa.
You can use the inline-block value for display, however in this case you will loose the block feature of h1 i.e. the siblings will be displayed inline with h1 if they are inline elements(in which case you can use a line-break
).
display:inline-block;
select * from Table ORDER BY id LIMIT 30
Notes:
* id
should be unique.
* You can control the numbers of rows returned by replacing the 30
in the query
Swift 3.0 has replaced many "stringly-typed" APIs with struct
"wrapper types", as is the case with NotificationCenter. Notifications are now identified by a struct Notfication.Name
rather than by String
. See the Migrating to Swift 3 guide.
Previous usage:
// Define identifier
let notificationIdentifier: String = "NotificationIdentifier"
// Register to receive notification
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name: notificationIdentifier, object: nil)
// Post a notification
NSNotificationCenter.defaultCenter().postNotificationName(notificationIdentifier, object: nil)
New Swift 3.0 usage:
// Define identifier
let notificationName = Notification.Name("NotificationIdentifier")
// Register to receive notification
NotificationCenter.default.addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification), name: notificationName, object: nil)
// Post notification
NotificationCenter.default.post(name: notificationName, object: nil)
All of the system notification types are now defined as static constants on Notification.Name
; i.e. .UIDeviceBatteryLevelDidChange
, .UIApplicationDidFinishLaunching
, .UITextFieldTextDidChange
, etc.
You can extend Notification.Name
with your own custom notifications in order to stay consistent with the system notifications:
// Definition:
extension Notification.Name {
static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")
}
// Usage:
NotificationCenter.default.post(name: .yourCustomNotificationName, object: nil)
For C++ (using cURL):
#include <curl/curl.h>
//// cURL to string
size_t curl_to_str(void *contents, size_t size, size_t nmemb, void *userp) {
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
};
//// Read Instance-id
curl_global_init(CURL_GLOBAL_ALL); // Initialize cURL
CURL *curl; // cURL handler
CURLcode res_code; // Result
string response;
curl = curl_easy_init(); // Initialize handler
curl_easy_setopt(curl, CURLOPT_URL, "http://169.254.169.254/latest/meta-data/instance-id");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_to_str);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
res_code = curl_easy_perform(curl); // Perform cURL
if (res_code != CURLE_OK) { }; // Error
curl_easy_cleanup(curl); // Cleanup handler
curl_global_cleanup(); // Cleanup cURL
Solved my own problem. This line:
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
needs to be:
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
or since Java 7:
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));
It's even easier with SwiftUI:
var body: some View {
Text("Hello World")
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willResignActiveNotification)) { _ in
print("Moving to background!")
}
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willEnterForegroundNotification)) { _ in
print("Moving back to foreground!")
}
}
Edit: it seems nginx now supports error_log stderr;
as mentioned in Anon's answer.
You can send the logs to /dev/stdout
. In nginx.conf
:
daemon off;
error_log /dev/stdout info;
http {
access_log /dev/stdout;
...
}
edit: May need to run ln -sf /proc/self/fd /dev/ if using running certain docker containers, then use /dev/fd/1
or /dev/fd/2
This solution will not only display all relations but also the constraint name, which is required in some cases (e.g. drop constraint):
SELECT
CONCAT(table_name, '.', column_name) AS 'foreign key',
CONCAT(referenced_table_name, '.', referenced_column_name) AS 'references',
constraint_name AS 'constraint name'
FROM
information_schema.key_column_usage
WHERE
referenced_table_name IS NOT NULL;
If you want to check tables in a specific database, add the following:
AND table_schema = 'database_name';
[Personal Option] Avoiding using $scope, based on John Papa Angular Style Guide
so my idea is take advantage of the current model:
(function(){_x000D_
'use strict';_x000D_
_x000D_
var app = angular.module('way', [])_x000D_
app.controller('Decision', Decision);_x000D_
_x000D_
Decision.$inject = []; _x000D_
_x000D_
function Decision(){_x000D_
var vm = this;_x000D_
vm.checkItOut = _register;_x000D_
_x000D_
function _register(newOption){_x000D_
console.log('should I stay or should I go');_x000D_
console.log(newOption); _x000D_
}_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
})();
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<div ng-app="way">_x000D_
<div ng-controller="Decision as vm">_x000D_
<form name="myCheckboxTest" ng-submit="vm.checkItOut(decision)">_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="option" ng-model="decision.myWay"_x000D_
ng-value="false" ng-checked="!decision.myWay"> Should I stay?_x000D_
</label>_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="option" ng-value="true"_x000D_
ng-model="decision.myWay" > Should I go?_x000D_
</label>_x000D_
_x000D_
</form>_x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
I hope I could help ;)
prototype
is a property of a Function object. It is the prototype of objects constructed by that function.
__proto__
is internal property of an object, pointing to its prototype. Current standards provide an equivalent Object.getPrototypeOf(O)
method, though de facto standard __proto__
is quicker.
You can find instanceof
relationships by comparing a function's prototype
to an object's __proto__
chain, and you can break these relationships by changing prototype
.
function Point(x, y) {
this.x = x;
this.y = y;
}
var myPoint = new Point();
// the following are all true
myPoint.__proto__ == Point.prototype
myPoint.__proto__.__proto__ == Object.prototype
myPoint instanceof Point;
myPoint instanceof Object;
Here Point
is a constructor function, it builds an object (data structure) procedurally. myPoint
is an object constructed by Point()
so Point.prototype
gets saved to myPoint.__proto__
at that time.
You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).
For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.
Function ExtractSDI(ByVal text As String) As String
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)
If allMatches.count <> 0 Then
result = allMatches.Item(0).submatches.Item(0)
End If
ExtractSDI = result
End Function
If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:
Ex) =RegexExtract(A1, "(sdi \d+)", ", ")
Here is:
Function RegexExtract(ByVal text As String, _
ByVal extract_what As String, _
Optional seperator As String = "") As String
Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)
For i = 0 To allMatches.count - 1
For j = 0 To allMatches.Item(i).submatches.count - 1
result = result & seperator & allMatches.Item(i).submatches.Item(j)
Next
Next
If Len(result) <> 0 Then
result = Right(result, Len(result) - Len(seperator))
End If
RegexExtract = result
End Function
*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.
emulator-arm.exe error, couldn't run. Problem was that my laptop has 2 graphic cards and was selected only one (the performance one) from Nvidia 555M. By selecting the other graphic card from Nvidia mediu,(selected base Intel card) the emulator started!
To check if the property is present, irrespective of the value, use:
if (array_key_exists('userName', $_POST)) {}
To check if the property is set (property is present and value is not null
or false
), use:
if (isset($_POST['userName'])) {}
To check if the property is set and not empty (not an empty string, 0
(integer), 0.0
(float), '0'
(string), null
, false
or []
(empty array)), use:
if (!empty($_POST['userName'])) {}
If you want to access the variables some sort of dynamic you may use reflection. However Reflection works not for local variables. It is only applyable for class attributes.
A rough quick and dirty example is this:
public class T {
public Integer n1;
public Integer n2;
public Integer n3;
public void accessAttributes() throws IllegalArgumentException, SecurityException, IllegalAccessException,
NoSuchFieldException {
for (int i = 1; i < 4; i++) {
T.class.getField("n" + i).set(this, 5);
}
}
}
You need to improve this code in various ways it is only an example. This is also not considered to be good code.
I recommend another option. jQuery UI has a new position feature that allows you to position elements relative to each other. For complete documentation and demo see: http://jqueryui.com/demos/position/#option-offset.
Here's one way to position your elements using the position feature:
var options = {
"my": "top left",
"at": "top left",
"of": ".layer1"
};
$(".layer2").position(options);
The following command worked on Solaris :
find . -name "*zip" -type f | xargs ls -ltr | tail -1
Template argument deduction for class templates
[*this]{ std::cout << could << " be " << useful << '\n'; }
[[fallthrough]]
, [[nodiscard]]
, [[maybe_unused]]
attributes
using
in attributes to avoid having to repeat an attribute namespace.
Compilers are now required to ignore non-standard attributes they don't recognize.
Simple static_assert(expression);
with no string
no throw
unless throw()
, and throw()
is noexcept(true)
.
std::tie
with auto
const auto [it, inserted] = map.insert( {"foo", bar} );
it
and inserted
with deduced type from the pair
that map::insert
returns.std::array
s and relatively flat structsif (init; condition)
and switch (init; condition)
if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
if(decl)
to cases where decl
isn't convertible-to-bool sensibly.Generalizing range-based for loops
Fixed order-of-evaluation for (some) expressions with some modifications
.then
on future work.Forward progress guarantees (FPG) (also, FPGs for parallel algorithms)
u8'U', u8'T', u8'F', u8'8'
character literals (string already existed)
inherited constructors fixes to some corner cases (see P0136R0 for examples of behavior changes)
std::string
like reference-to-character-array or substringstring const&
again. Also can make parsing a bajillion times faster."hello world"sv
char_traits
std::byte
off more than they could chew.
std::invoke
std::apply
std::make_from_tuple
, std::apply
applied to object construction
is_invocable
, is_invocable_r
, invoke_result
result_of
is_invocable<Foo(Args...), R>
is "can you call Foo
with Args...
and get something compatible with R
", where R=void
is default.invoke_result<Foo, Args...>
is std::result_of_t<Foo(Args...)>
but apparently less confusing?[class.directory_iterator]
and [class.recursive_directory_iterator]
fstream
s can be opened with path
s, as well as with const path::value_type*
strings.
for_each_n
reduce
transform_reduce
exclusive_scan
inclusive_scan
transform_exclusive_scan
transform_inclusive_scan
Added for threading purposes, exposed even if you aren't using them threaded
atomic<T>
::is_always_lockfree
std::lock
pain when locking more than one mutex at a time.std
algorithms, and related machinery[func.searchers]
and [alg.search]
std::function
for allocatorsstd::sample
, sampling from a range?
try_emplace
and insert_or_assign
Splicing for map<>
, unordered_map<>
, set<>
, and unordered_set<>
non-const .data()
for string.
non-member std::size
, std::empty
, std::data
std::begin
/end
The emplace
family of functions now returns a reference to the created object.
unique_ptr<T[]>
fixes and other unique_ptr
tweaks.weak_from_this
and some fixed to shared from thisstd
datatype improvements:{}
construction of std::tuple
and other improvementsC++17 library is based on C11 instead of C99
Reserved std[0-9]+
for future standard libraries
std
implementations exposedstd::clamp()
std::clamp( a, b, c ) == std::max( b, std::min( a, c ) )
roughlygcd
and lcm
std::uncaught_exceptions
std::as_const
std::bool_constant
_v
template variablesstd::void_t<T>
std::owner_less<void>
std::less<void>
, but for smart pointers to sort based on contentsstd::chrono
polishstd::conjunction
, std::disjunction
, std::negation
exposedstd::not_fn
std
std::less
.<codecvt>
memory_order_consume
result_of
, replaced with invoke_result
shared_ptr::unique
, it isn't very threadsafeIsocpp.org has has an independent list of changes since C++14; it has been partly pillaged.
Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.
Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.
Additional entries pillaged from SD-6 feature-test list.
clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.
these slides had some features missing elsewhere.
While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:
register
, keyword reserved for future usebool b; ++b;
<functional>
stuff, random_shuffle
std::function
There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:
P0505R0 (constexpr chrono)
P0418R2 (atomic tweaks)
P0512R0 (template argument deduction tweaks)
P0490R0 (structured binding tweaks)
P0513R0 (changes to std::hash
)
P0502R0 (parallel exceptions)
P0509R1 (updating restrictions on exception handling)
P0012R1 (make exception specifications be part of the type system)
P0510R0 (restrictions on variants)
P0504R0 (tags for optional/variant/any)
P0497R0 (shared ptr tweaks)
P0508R0 (structured bindings node handles)
P0521R0 (shared pointer use count and unique changes?)
https://isocpp.org/files/papers/p0636r0.html
The problem is in the line before the one that throws the warning. When you create df_2 that's where you're creating a copy of a slice of a dataframe. Instead, when you create df_2, use .copy() and you won't get that warning later on.
df_2 = df[df['B'] == 'b.2'].copy()
to start, i used the Code posted posted in the first Comment but i changed it like this:
public class LockableScrollView extends ScrollView {
public LockableScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public LockableScrollView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public LockableScrollView(Context context)
{
super(context);
}
// true if we can scroll (not locked)
// false if we cannot scroll (locked)
private boolean mScrollable = true;
public void setScrollingEnabled(boolean enabled) {
mScrollable = enabled;
}
public boolean isScrollable() {
return mScrollable;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
// if we can scroll pass the event to the superclass
if (mScrollable) return super.onTouchEvent(ev);
// only continue to handle the touch event if scrolling enabled
return mScrollable; // mScrollable is always false at this point
default:
return super.onTouchEvent(ev);
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
// if we can scroll pass the event to the superclass
if (mScrollable) return super.onInterceptTouchEvent(ev);
// only continue to handle the touch event if scrolling enabled
return mScrollable; // mScrollable is always false at this point
default:
return super.onInterceptTouchEvent(ev);
}
}
}
then i called it in by this way
((LockableScrollView)findViewById(R.id.scrollV)).setScrollingEnabled(false);
because i tried
((LockableScrollView)findViewById(R.id.scrollV)).setIsScrollable(false);
but it said that setIsScrollable is undefined
i hope this will help you
If there is any tag with an id
(e.g., <div id="foo"
>), then you can simply append #foo
to the URL. Otherwise, you can't arbitrarily link to portions of a page.
Here's a complete example: <a href="http://example.com/page.html#foo">Jump to #foo on page.html</a>
Linking content on the same page example: <a href="#foo">Jump to #foo on same page</a>
It is called a URI fragment.
Using internal-ip:
const internalIp = require("internal-ip")
console.log(internalIp.v4.sync())
pathlib
module (python's object-oriented filesystem paths)Just for kicks, this is perhaps the latest pythonic version of the solution.
from pathlib import Path
path = Path(f'{player}.txt')
path.touch() # default exists_ok=True
with path.open('a') as highscore:
highscore.write(f'Username:{player}')
<script> var disabledDaysRange = $disabledDaysRange ???? Please Help;
$(function() {
function disableRangeOfDays(d) {
in the above assign array to javascript variable "disableDaysRange"
$disallowDates = "";
echo "[";
foreach($disabledDaysRange as $disableDates){
$disallowDates .= "'".$disableDates."',";
}
echo substr(disallowDates,0,(strlen(disallowDates)-1)); // this will escape the last comma from $disallowDates
echo "];";
so your javascript var diableDateRange shoudl be
var diableDateRange = ["2013-01-01","2013-01-02","2013-01-03"];
This work if you have an Apache server
PHP Code:
$headers = apache_request_headers();
foreach ($headers as $header => $value) {
echo "$header: $value <br />\n";
}
Result:
Accept: */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0
Host: www.example.com
Connection: Keep-Alive
For Power-Shell
./adb shell getprop | Select-String -Pattern '(model)|(version.sdk)|(manufacturer)|(platform)|(serialno)|(product.name)|(brand)'
For linux(burrowing asnwer from @0x8BADF00D)
adb shell getprop | grep "model\|version.sdk\|manufacturer\|hardware\|platform\|revision\|serialno\|product.name\|brand"
For single string find in power shell
./adb shell getprop | Select-String -Pattern 'model'
or
./adb shell getprop | Select-String -Pattern '(model)'
For multiple
./adb shell getprop | Select-String -Pattern '(a|b|c|d)'
In javascript I think that it is not possible, because modern browsers have a policy on security in javascripts.. and clearing the cache is a very violating one.
You can try to add
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
In your header, but you will have performance loss.
Sam's answer gives the reason that default arguments are preferable for constructors rather than overloading. I just want to add that C++-0x will allow delegation from one constructor to another, thereby removing the need for defaults.
One way is:
application arg0 arg1 > temp.txt
set /p VAR=<temp.txt
Another is:
for /f %%i in ('application arg0 arg1') do set VAR=%%i
Note that the first %
in %%i
is used to escape the %
after it and is needed when using the above code in a batch file rather than on the command line. Imagine, your test.bat
has something like:
for /f %%i in ('c:\cygwin64\bin\date.exe +"%%Y%%m%%d%%H%%M%%S"') do set datetime=%%i
echo %datetime%
You can try the following code:
import java.time.*;
public class Test{
public static void main(String[] args) {
DayOfWeek dow = LocalDate.of(2010,Month.FEBRUARY,23).getDayOfWeek();
String s = String.valueOf(dow);
System.out.println(String.format("%.3s",s));
}
}
EDIT: I thought that the other computer is dead so I'm fixing my answer:
You should export the certificate from the first computer with it's private key and import it in the new computer.
I prefer the iCloud way, backup to iCloud and get it in the new computer.
If you can't do it with some reason, you can revoke the certificate in Apple developers site, then let Xcode to create a new one for you, it'll also create a fresh new private key and store it in your Keychain, just be sure to back it up in your preferred way
SELECT tab.*,
row_number() OVER () as rnum
FROM tab;
Here's the relevant section in the docs.
P.S. This, in fact, fully matches the answer in the referenced question.
I know this has been posted but here is a current version for dotnet 4.5 above that I use. I recommend to use the default browser emulation respecting doctype
InternetExplorerFeatureControl.Instance.BrowserEmulation = DocumentMode.DefaultRespectDocType;
internal class InternetExplorerFeatureControl
{
private static readonly Lazy<InternetExplorerFeatureControl> LazyInstance = new Lazy<InternetExplorerFeatureControl>(() => new InternetExplorerFeatureControl());
private const string RegistryLocation = @"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl";
private readonly RegistryView _registryView = Environment.Is64BitOperatingSystem && Environment.Is64BitProcess ? RegistryView.Registry64 : RegistryView.Registry32;
private readonly string _processName;
private readonly Version _version;
#region Feature Control Strings (A)
private const string FeatureRestrictAboutProtocolIe7 = @"FEATURE_RESTRICT_ABOUT_PROTOCOL_IE7";
private const string FeatureRestrictAboutProtocol = @"FEATURE_RESTRICT_ABOUT_PROTOCOL";
#endregion
#region Feature Control Strings (B)
private const string FeatureBrowserEmulation = @"FEATURE_BROWSER_EMULATION";
#endregion
#region Feature Control Strings (G)
private const string FeatureGpuRendering = @"FEATURE_GPU_RENDERING";
#endregion
#region Feature Control Strings (L)
private const string FeatureBlockLmzScript = @"FEATURE_BLOCK_LMZ_SCRIPT";
#endregion
internal InternetExplorerFeatureControl()
{
_processName = $"{Process.GetCurrentProcess().ProcessName}.exe";
using (var webBrowser = new WebBrowser())
_version = webBrowser.Version;
}
internal static InternetExplorerFeatureControl Instance => LazyInstance.Value;
internal RegistryHive RegistryHive { get; set; } = RegistryHive.CurrentUser;
private int GetFeatureControl(string featureControl)
{
using (var currentUser = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, _registryView))
{
using (var key = currentUser.CreateSubKey($"{RegistryLocation}\\{featureControl}", false))
{
if (key.GetValue(_processName) is int value)
{
return value;
}
return -1;
}
}
}
private void SetFeatureControl(string featureControl, int value)
{
using (var currentUser = RegistryKey.OpenBaseKey(RegistryHive, _registryView))
{
using (var key = currentUser.CreateSubKey($"{RegistryLocation}\\{featureControl}", true))
{
key.SetValue(_processName, value, RegistryValueKind.DWord);
}
}
}
#region Internet Feature Controls (A)
/// <summary>
/// Windows Internet Explorer 8 and later. When enabled, feature disables the "about:" protocol. For security reasons, applications that host the WebBrowser Control are strongly encouraged to enable this feature.
/// By default, this feature is enabled for Windows Internet Explorer and disabled for applications hosting the WebBrowser Control.To enable this feature using the registry, add the name of your executable file to the following setting.
/// </summary>
internal bool AboutProtocolRestriction
{
get
{
if (_version.Major < 8)
throw new NotSupportedException($"{AboutProtocolRestriction} requires Internet Explorer 8 and Later.");
var releaseVersion = new Version(8, 0, 6001, 18702);
return Convert.ToBoolean(GetFeatureControl(_version >= releaseVersion ? FeatureRestrictAboutProtocolIe7 : FeatureRestrictAboutProtocol));
}
set
{
if (_version.Major < 8)
throw new NotSupportedException($"{AboutProtocolRestriction} requires Internet Explorer 8 and Later.");
var releaseVersion = new Version(8, 0, 6001, 18702);
SetFeatureControl(_version >= releaseVersion ? FeatureRestrictAboutProtocolIe7 : FeatureRestrictAboutProtocol, Convert.ToInt16(value));
}
}
#endregion
#region Internet Feature Controls (B)
/// <summary>
/// Windows Internet Explorer 8 and later. Defines the default emulation mode for Internet Explorer and supports the following values.
/// </summary>
internal DocumentMode BrowserEmulation
{
get
{
if (_version.Major < 8)
throw new NotSupportedException($"{nameof(BrowserEmulation)} requires Internet Explorer 8 and Later.");
var value = GetFeatureControl(FeatureBrowserEmulation);
if (Enum.IsDefined(typeof(DocumentMode), value))
{
return (DocumentMode)value;
}
return DocumentMode.NotSet;
}
set
{
if (_version.Major < 8)
throw new NotSupportedException($"{nameof(BrowserEmulation)} requires Internet Explorer 8 and Later.");
var tmp = value;
if (value == DocumentMode.DefaultRespectDocType)
tmp = DefaultRespectDocType;
else if (value == DocumentMode.DefaultOverrideDocType)
tmp = DefaultOverrideDocType;
SetFeatureControl(FeatureBrowserEmulation, (int)tmp);
}
}
#endregion
#region Internet Feature Controls (G)
/// <summary>
/// Internet Explorer 9. Enables Internet Explorer to use a graphics processing unit (GPU) to render content. This dramatically improves performance for webpages that are rich in graphics.
/// By default, this feature is enabled for Internet Explorer and disabled for applications hosting the WebBrowser Control.To enable this feature by using the registry, add the name of your executable file to the following setting.
/// Note: GPU rendering relies heavily on the quality of your video drivers. If you encounter problems running Internet Explorer with GPU rendering enabled, you should verify that your video drivers are up to date and that they support hardware accelerated graphics.
/// </summary>
internal bool GpuRendering
{
get
{
if (_version.Major < 9)
throw new NotSupportedException($"{nameof(GpuRendering)} requires Internet Explorer 9 and Later.");
return Convert.ToBoolean(GetFeatureControl(FeatureGpuRendering));
}
set
{
if (_version.Major < 9)
throw new NotSupportedException($"{nameof(GpuRendering)} requires Internet Explorer 9 and Later.");
SetFeatureControl(FeatureGpuRendering, Convert.ToInt16(value));
}
}
#endregion
#region Internet Feature Controls (L)
/// <summary>
/// Internet Explorer 7 and later. When enabled, feature allows scripts stored in the Local Machine zone to be run only in webpages loaded from the Local Machine zone or by webpages hosted by sites in the Trusted Sites list. For more information, see Security and Compatibility in Internet Explorer 7.
/// By default, this feature is enabled for Internet Explorer and disabled for applications hosting the WebBrowser Control.To enable this feature by using the registry, add the name of your executable file to the following setting.
/// </summary>
internal bool LocalScriptBlocking
{
get
{
if (_version.Major < 7)
throw new NotSupportedException($"{nameof(LocalScriptBlocking)} requires Internet Explorer 7 and Later.");
return Convert.ToBoolean(GetFeatureControl(FeatureBlockLmzScript));
}
set
{
if (_version.Major < 7)
throw new NotSupportedException($"{nameof(LocalScriptBlocking)} requires Internet Explorer 7 and Later.");
SetFeatureControl(FeatureBlockLmzScript, Convert.ToInt16(value));
}
}
#endregion
private DocumentMode DefaultRespectDocType
{
get
{
if (_version.Major >= 11)
return DocumentMode.InternetExplorer11RespectDocType;
switch (_version.Major)
{
case 10:
return DocumentMode.InternetExplorer10RespectDocType;
case 9:
return DocumentMode.InternetExplorer9RespectDocType;
case 8:
return DocumentMode.InternetExplorer8RespectDocType;
default:
throw new ArgumentOutOfRangeException();
}
}
}
private DocumentMode DefaultOverrideDocType
{
get
{
if (_version.Major >= 11)
return DocumentMode.InternetExplorer11OverrideDocType;
switch (_version.Major)
{
case 10:
return DocumentMode.InternetExplorer10OverrideDocType;
case 9:
return DocumentMode.InternetExplorer9OverrideDocType;
case 8:
return DocumentMode.InternetExplorer8OverrideDocType;
default:
throw new ArgumentOutOfRangeException();
}
}
}
}
internal enum DocumentMode
{
NotSet = -1,
[Description("Webpages containing standards-based !DOCTYPE directives are displayed in IE latest installed version mode.")]
DefaultRespectDocType,
[Description("Webpages are displayed in IE latest installed version mode, regardless of the declared !DOCTYPE directive. Failing to declare a !DOCTYPE directive could causes the page to load in Quirks.")]
DefaultOverrideDocType,
[Description(
"Internet Explorer 11. Webpages are displayed in IE11 edge mode, regardless of the declared !DOCTYPE directive. Failing to declare a !DOCTYPE directive causes the page to load in Quirks."
)] InternetExplorer11OverrideDocType = 11001,
[Description(
"IE11. Webpages containing standards-based !DOCTYPE directives are displayed in IE11 edge mode. Default value for IE11."
)] InternetExplorer11RespectDocType = 11000,
[Description(
"Internet Explorer 10. Webpages are displayed in IE10 Standards mode, regardless of the !DOCTYPE directive."
)] InternetExplorer10OverrideDocType = 10001,
[Description(
"Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode. Default value for Internet Explorer 10."
)] InternetExplorer10RespectDocType = 10000,
[Description(
"Windows Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the declared !DOCTYPE directive. Failing to declare a !DOCTYPE directive causes the page to load in Quirks."
)] InternetExplorer9OverrideDocType = 9999,
[Description(
"Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode. Default value for Internet Explorer 9.\r\n" +
"Important In Internet Explorer 10, Webpages containing standards - based !DOCTYPE directives are displayed in IE10 Standards mode."
)] InternetExplorer9RespectDocType = 9000,
[Description(
"Webpages are displayed in IE8 Standards mode, regardless of the declared !DOCTYPE directive. Failing to declare a !DOCTYPE directive causes the page to load in Quirks."
)] InternetExplorer8OverrideDocType = 8888,
[Description(
"Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode. Default value for Internet Explorer 8\r\n" +
"Important In Internet Explorer 10, Webpages containing standards - based !DOCTYPE directives are displayed in IE10 Standards mode."
)] InternetExplorer8RespectDocType = 8000,
[Description(
"Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode. Default value for applications hosting the WebBrowser Control."
)] InternetExplorer7RespectDocType = 7000
}
Ids are meant to be unique, and never use an id that starts with a number, use data-attributes instead to set the target like so :
<div id="searchbycharacter">
<a class="searchbychar" href="#" data-target="numeric">0-9 |</a>
<a class="searchbychar" href="#" data-target="A"> A |</a>
<a class="searchbychar" href="#" data-target="B"> B |</a>
<a class="searchbychar" href="#" data-target="C"> C |</a>
... Untill Z
</div>
As for the jquery :
$(document).on('click','.searchbychar', function(event) {
event.preventDefault();
var target = "#" + this.getAttribute('data-target');
$('html, body').animate({
scrollTop: $(target).offset().top
}, 2000);
});
I thought I had the solution, but I soon experienced unusual behavior with execution of batch files. Suddenly CMD is no recognizing long path statments. Normal execution of batch file from full path
C:\Documents and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat
returns
'C:\Documents' is not recognized as an internal or external command....
There's your whole problem. CMD doesn't understand spaces inside of filenames from the command line, so it thinks you're trying to pass
and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat
as parameters to the
"C:\Documents"
program.
You need to quote it to run a batch file with spaces in the path:
> "C:\Documents and Settings\Administrator\My Documents\Txt\batchtest\dataout.bat"
would have worked.
You have a couple of options. The easiest involve using the ErrorAction
settings.
-Erroraction
is a universal parameter for all cmdlets. If there are special commands you want to ignore you can use -erroraction 'silentlycontinue'
which will basically ignore all error messages generated by that command. You can also use the Ignore
value (in PowerShell 3+):
Unlike SilentlyContinue, Ignore does not add the error message to the $Error automatic variable.
If you want to ignore all errors in a script, you can use the system variable $ErrorActionPreference
and do the same thing: $ErrorActionPreference= 'silentlycontinue'
See about_CommonParameters for more info about -ErrorAction. See about_preference_variables for more info about $ErrorActionPreference.
There is a difference between
So the question is: How to reach the appropriate presentation of my datas without changing the data / data types themselves?
Here is the answer:
id
and class
attributes for further CSS styling — you may or you may not use them),use styling. Styling don't change data / data types of columns of your dataframe.
Now I show you how to reach it in the Jupyter notebook — for a presentation in the form of HTML file see the note near the end of the question.
I will suppose that your column DOB
already has the type datetime64
(you shown that you know how to reach it). I prepared a simple dataframe (with only one column) to show you some basic styling:
Not styled:
df
DOB 0 2019-07-03 1 2019-08-03 2 2019-09-03 3 2019-10-03
Styling it as mm/dd/yyyy
:
df.style.format({"DOB": lambda t: t.strftime("%m/%d/%Y")})
DOB 0 07/03/2019 1 08/03/2019 2 09/03/2019 3 10/03/2019
Styling it as dd-mm-yyyy
:
df.style.format({"DOB": lambda t: t.strftime("%d-%m-%Y")})
DOB 0 03-07-2019 1 03-08-2019 2 03-09-2019 3 03-10-2019
Be careful!
The returning object is NOT a dataframe — it is an object of the class Styler
, so don't assign it back to df
:
Don´t do this:
df = df.style.format({"DOB": lambda t: t.strftime("%m/%d/%Y")}) # Don´t do this!
(Every dataframe has its Styler object accessible by its .style
property, and we changed this df.style
object, not the dataframe itself.)
Questions and Answers:
Q: Why your Styler object (or an expression returning it) used as the last command in a Jupyter notebook cell displays your (styled) table, and not the Styler object itself?
A: Because every Styler object has a callback method ._repr_html_()
which returns an HTML code for rendering your dataframe (as a nice HTML table).
Jupyter Notebook IDE calls this method automatically to render objects which have it.
Note:
You don't need the Jupyter notebook for styling (i.e. for nice outputting a dataframe without changing its data / data types).
A Styler object has a method render()
, too, if you want to obtain a string with the HTML code (e.g. for publishing your formatted dataframe to the Web, or simply present your table in the HTML format):
df_styler = df.style.format({"DOB": lambda t: t.strftime("%m/%d/%Y")})
HTML_string = df_styler.render()
This is a supplemental answer showing the implementation of a couple of the solutions mentioned.
If you have a single widget you can use a FractionallySizedBox
widget to specify a percentage of the available space to fill. Here the green Container
is set to fill 70% of the available width and 30% of the available height.
Widget myWidget() {
return FractionallySizedBox(
widthFactor: 0.7,
heightFactor: 0.3,
child: Container(
color: Colors.green,
),
);
}
The Expanded
widget allows a widget to fill the available space, horizontally if it is in a row, or vertically if it is in a column. You can use the flex
property with multiple widgets to give them weights. Here the green Container
takes 70% of the width and the yellow Container
takes 30% of the width.
If you want to do it vertically, then just replace Row
with Column
.
Widget myWidget() {
return Row(
children: <Widget>[
Expanded(
flex: 7,
child: Container(
color: Colors.green,
),
),
Expanded(
flex: 3,
child: Container(
color: Colors.yellow,
),
),
],
);
}
Here is the main.dart
code for your reference.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("FractionallySizedBox"),
),
body: myWidget(),
),
);
}
}
// replace with example code above
Widget myWidget() {
return ...
}
Download http://download.cnet.com/Free-Desktop-Timer/3000-2350_4-75415517.html
Then add a button or something on the form and inside its event, just open this app ie:
{
Process.Start(@"C:\Program Files (x86)\Free Desktop Timer\DesktopTimer");
}
First Collection is class Interface and you can not instantiate. Collection API
List Ver APi is also an interface class.
It may be so
List list = Collections.synchronizedList(new ArrayList(...));
ver enter link description here
Collection collection= Collections.synchronizedList(new ArrayList(...));
after you create new user, please don't forget to grant
read/write/root
permission to the user. you can try the
cmd: db.grantRolesToUser('yourNewUsername',[{ role: "root", db: "admin" }])
I'm learning Algorithm right now, so i wonder how bisect module writes. Here is the code from bisect module about inserting an item into sorted list, which uses dichotomy:
def insort_right(a, x, lo=0, hi=None):
"""Insert item x in list a, and keep it sorted assuming a is sorted.
If x is already in a, insert it to the right of the rightmost x.
Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to be searched.
"""
if lo < 0:
raise ValueError('lo must be non-negative')
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
if x < a[mid]:
hi = mid
else:
lo = mid+1
a.insert(lo, x)
Another solution:
select * from traintable
where (train, time) in (select train, max(time) from traintable group by train);
Since API level 21 you can use :
android:backgroundTint="@android:color/white"
you only have to add this in your xml
Best example for this Question, SDK - Software Development Kit - Ex: Netbeans JDK - Java Development Kit.(This is Java compiler). Without JDK, we unable to run java programs in SDK.
If by "cursor speed", you mean the repeat rate when holding down a key - then have a look here: http://hints.macworld.com/article.php?story=20090823193018149
To summarize, open up a Terminal window and type the following command:
defaults write NSGlobalDomain KeyRepeat -int 0
More detail from the article:
Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:
defaults write NSGlobalDomain KeyRepeat -int 0
Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.
You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.
$com1 = new-object PSobject #Task1
$com2 = new-object PSobject #Task1
$com3 = new-object PSobject #Task1
$com1 | add-member noteproperty -name user -value jindpal #Task2
$com1 | add-member noteproperty -name code -value IT01 #Task2
$com1 | add-member scriptmethod ver {[system.Environment]::oSVersion.Version} #Task3
$com2 | add-member noteproperty -name user -value singh #Task2
$com2 | add-member noteproperty -name code -value IT02 #Task2
$com2 | add-member scriptmethod ver {[system.Environment]::oSVersion.Version} #Task3
$com3 | add-member noteproperty -name user -value dhanoa #Task2
$com3 | add-member noteproperty -name code -value IT03 #Task2
$com3 | add-member scriptmethod ver {[system.Environment]::oSVersion.Version} #Task3
$arr += $com1, $com2, $com3 #Task4
write-host "windows version of computer1 is: "$com1.ver() #Task3
write-host "user name of computer1 is: "$com1.user #Task6
write-host "code of computer1 is: "$com1,code #Task5
write-host "windows version of computer2 is: "$com2.ver() #Task3
write-host "user name of computer2 is: "$com2.user #Task6
write-host "windows version of computer3 is: "$com3.ver() #Task3
write-host "user name of computer3 is: "$com1.user #Task6
write-host "code of computer3 is: "$com3,code #Task5
read-host
Problem solved with combine solution @carlos calla and @jonathan marston.
/* Important part */
.modal-dialog{
overflow-y: initial !important
}
.modal-body{
max-height: calc(100vh - 200px);
overflow-y: auto;
}
Please use Homebrew Formulae page to see the list of installable packages. https://formulae.brew.sh/formula/
To install any package => command to use is :
brew install node
perhaps this is what you're looking for: https://github.com/android/platform_frameworks_base/blob/master/core/res/res/values/colors.xml
This is how I got it working on httpClient 4.5 (as per Olive Tree request):
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
new AuthScope(AuthScope.ANY_HOST, 443),
new UsernamePasswordCredentials(this.user, this.password));
SSLContext sslContext = SSLContexts.createDefault();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
new String[]{"TLSv1", "TLSv1.1"},
null,
new NoopHostnameVerifier());
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.setSSLSocketFactory(sslsf)
.build();
return httpclient;
You can also use the index for the sheet:
xls = pd.ExcelFile('path_to_file.xls')
sheet1 = xls.parse(0)
will give the first worksheet. for the second worksheet:
sheet2 = xls.parse(1)
Most of the time that I use AsyncTask my business logic is on a separated business class instead of being on the UI. In that case, I couldn't have a loop at doInBackground(). An example would be a synchronization process that consumes services and persist data one after another.
I end up handing on my task to the business object so it can handle cancelation. My setup is like this:
public abstract class MyActivity extends Activity {
private Task mTask;
private Business mBusiness;
public void startTask() {
if (mTask != null) {
mTask.cancel(true);
}
mTask = new mTask();
mTask.execute();
}
}
protected class Task extends AsyncTask<Void, Void, Boolean> {
@Override
protected void onCancelled() {
super.onCancelled();
mTask.cancel(true);
// ask if user wants to try again
}
@Override
protected Boolean doInBackground(Void... params) {
return mBusiness.synchronize(this);
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
mTask = null;
if (result) {
// done!
}
else {
// ask if user wants to try again
}
}
}
public class Business {
public boolean synchronize(AsyncTask<?, ?, ?> task) {
boolean response = false;
response = loadStuff(task);
if (response)
response = loadMoreStuff(task);
return response;
}
private boolean loadStuff(AsyncTask<?, ?, ?> task) {
if (task != null && task.isCancelled()) return false;
// load stuff
return true;
}
}
Thats trivial, use Intent.putExtra to pass data to activity you start. Use then Bundle.getExtra to retrieve it.
There are lots of such questions already https://stackoverflow.com/search?q=How+to+pass+a+value+from+one+Activity+to+another+in+Android be sure to use search first next time.
This means your nested SELECT returns more than one rows.
You need to add a proper WHERE clause to it.
This solution worked for me:
Go to your project folder and open .vs
folder (keep your check hidden item-box checked as this folder may be hidden sometimes)
in .vs
folder - open config
see that applicationhost
config file there? Delete that thing.(Do not worry it will regenerate automatically once you recompile the project.)
You can open an incognito window instead. Switching to an incognito window worked for me when disabling the cache in a normal chrome window still didn't reload a JavaScript file I had changed since the last cache.
https://www.quora.com/Does-incognito-mode-on-Chrome-use-the-cache-that-was-previously-stored
Here's a clean solution:
function test(str){
//Note: should be /(abc)|(def)/i if you want it case insensitive
var pattern = /(abc)|(def)/;
return !str.match(pattern);
}
It's perfectly possible to update multiple columns in the same statement, and in fact your code is doing it. So why does it seem that "INV_TOTAL is not updating, only the inv_discount"?
Because you're updating INV_TOTAL with INV_DISCOUNT, and the database is going to use the existing value of INV_DISCOUNT and not the one you change it to. So I'm afraid what you need to do is this:
UPDATE INVOICE
SET INV_DISCOUNT = DISC1 * INV_SUBTOTAL
, INV_TOTAL = INV_SUBTOTAL - (DISC1 * INV_SUBTOTAL)
WHERE INV_ID = I_INV_ID;
Perhaps that seems a bit clunky to you. It is, but the problem lies in your data model. Storing derivable values in the table, rather than deriving when needed, rarely leads to elegant SQL.
I just had a quick look at your example, but if i understood it the right way you're trying to add 404 routes to dynamic segments. I had the same issue a couple of days ago, found #458 and #1103 and ended up with a hand made check within the render function:
if (!place) return <NotFound />;
hope that helps!
I recently saw this one-liner:
def foo(name: str, opts: dict=None) -> str:
opts = {} if not opts else opts
pass
You might find it useful to lookup the classes on oracle. Eg:
http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JFrame.html
There you can see that JFrame extends JComponent and JContainer.
JComponent is a a basic object that can be drawn, JContainer extends this so that you can add components to it. JPanel and JFrame both extend JComponent as you can add things to them. JFrame provides a window, whereas JPanel is just a panel that goes inside a window. If that makes sense.
On my PC, xcopy and robocopy need also the path to them, i.e. C:\Windows\System32\xcopy.exe
That's why I use simply "copy": copy /y ....\Folder1\File.txt ....\Folder2\
Step:-1 Open the folder “application/config” and open the file “config.php“. find and replace the below code in config.php file.
//find the below code
$config['index_page'] = "index.php"
//replace with the below code
$config['index_page'] = ""
Step:-2 Go to your CodeIgniter folder and create .htaccess
Path:
Your_website_folder/
application/
assets/
system/
.htaccess <——— this file
index.php
Step:-3 Write below code in .htaccess file
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
Step:-4 In some case the default setting for uri_protocol does not work properly. To solve this problem just open the file “application/config/config.php“, then find and replace the below code
//Not needed for CodeIgniter 3 its already there.
//find the below code
$config['uri_protocol'] = "AUTO"
//replace with the below code
$config['uri_protocol'] = "REQUEST_URI"
Thats all but in wamp server it does not work because rewrite_module by default disabled so we have need to enable it. for this do the following
Use inline styles:
<div class="button" style="width:60px;height:100px;">This is a button</div>
If you want to read text of any element using javascript executor, you can do something like following code:
WebElement ele = driver.findElement(By.xpath("//div[@class='infaCompositeViewTitle']"));
String assets = (String) js.executeScript("return arguments[0].getElementsByTagName('span')[1].textContent;", ele);
In this example, I have following HTML fragment and I am reading "156".
<div class="infaCompositeViewTitle">
<span>All Assets</span>
<span>156</span>
</div>
If you don't mind getting a new data frame object returned as opposed to updating the original Pandas .assign() will avoid SettingWithCopyWarning
. Your example:
df = df.assign(B=df1['E'])
You can use JsonResponse with values. Simple example:
from django.http import JsonResponse
def some_view(request):
data = list(SomeModel.objects.values()) # wrap in list(), because QuerySet is not JSON serializable
return JsonResponse(data, safe=False) # or JsonResponse({'data': data})
Or another approach with Django's built-in serializers:
from django.core import serializers
from django.http import HttpResponse
def some_view(request):
qs = SomeModel.objects.all()
qs_json = serializers.serialize('json', qs)
return HttpResponse(qs_json, content_type='application/json')
In this case result is slightly different (without indent by default):
[
{
"model": "some_app.some_model",
"pk": 1,
"fields": {
"name": "Elon",
"age": 48,
...
}
},
...
]
I have to say, it is good practice to use something like marshmallow to serialize queryset.
...and a few notes for better performance:
objects.values()
to specify list of required fields to avoid serialization and sending to client unnecessary model's fields (you also can pass fields
to serializers.serialize
);This is how I managed to do what I was trying to do:
[Test]
public void TransferHandlesDisconnect()
{
// ... set up config here
var methodTester = new Mock<Transfer>(configInfo);
methodTester.CallBase = true;
methodTester
.Setup(m =>
m.GetFile(
It.IsAny<IFileConnection>(),
It.IsAny<string>(),
It.IsAny<string>()
))
.Throws<System.IO.IOException>();
methodTester.Object.TransferFiles("foo1", "foo2");
Assert.IsTrue(methodTester.Object.Status == TransferStatus.TransferInterrupted);
}
If there is a problem with this method, I would like to know; the other answers suggest I am doing this wrong, but this was exactly what I was trying to do.
I've experienced the same issue because of certifi
library. Installing a different version helped me as well.
Just to add to Ned's answer above: you can use this to redirect output to any object that implements a write(str) method.
This can be used to good effect to "catch" stdout output in a GUI application.
Here's a silly example in PyQt:
import sys
from PyQt4 import QtGui
class OutputWindow(QtGui.QPlainTextEdit):
def write(self, txt):
self.appendPlainText(str(txt))
app = QtGui.QApplication(sys.argv)
out = OutputWindow()
sys.stdout=out
out.show()
print "hello world !"
Disclosure:
But nice because of its simplicity:
import resource
def using(point=""):
usage=resource.getrusage(resource.RUSAGE_SELF)
return '''%s: usertime=%s systime=%s mem=%s mb
'''%(point,usage[0],usage[1],
usage[2]/1024.0 )
Just insert using("Label")
where you want to see what's going on. For example
print(using("before"))
wrk = ["wasting mem"] * 1000000
print(using("after"))
>>> before: usertime=2.117053 systime=1.703466 mem=53.97265625 mb
>>> after: usertime=2.12023 systime=1.70708 mem=60.8828125 mb
You could use HorizontalContentAlignment="Stretch"
as follows:
<ListBox HorizontalContentAlignment="Stretch"/>
The "escape hatch" operation that lets you do weird things that are not otherwise supported by streams is to ask for an Iterator
:
Iterator<T> it = users.stream().filter((user) -> user.getId() < 0).iterator();
if (!it.hasNext())
throw new NoSuchElementException();
else {
result = it.next();
if (it.hasNext())
throw new TooManyElementsException();
}
Guava has a convenience method to take an Iterator
and get the only element, throwing if there are zero or multiple elements, which could replace the bottom n-1 lines here.
This Can be Done by Style Property.
<!DOCTYPE html>
<html>
<head>
<style>
#main {
display: flex;
}
#main div {
flex-grow: 0;
flex-shrink: 0;
flex-basis: 40px;
}
</style>
</head>
<body>
<div id="main">
<div style="background-color:coral;">Red DIV</div>
<div style="background-color:lightblue;" id="myBlueDiv">Blue DIV</div>
</div>
</body>
</html>
Its Result will be :
Enjoy... Please Note: This works in Higher version of CSS (>3.0).
I had the same issue, after accepting the license launching XCode or running sudo xcodebuild -license accept
i had to restart my Mac – otherwise it did not worked.
Run the command bellow in a terminal emulator:
sudo dnf install gcc-c++
Enter password and that's it...
git tag -d your_tag_name
git push origin :refs/tags/your_tag_name
The first line deletes your_tag_name
from local repo and second line deletes your_tag_name
from remote repo.
For those who use GitHub, one more step is needed: discarding draft.
Checkboxes (radio buttons and <select>
) are OS-level components, not browser-level. You cannot reliably style them in a manner that will be consistent across browsers and operating systems.
Your best bet it to put an overlay on top and style that instead.
use css overflow:scroll;
property. you need to specify height and width then you will be able to scroll horizontally and vertically or either one of two scroll by setting overflow-x:auto;
or overflow-y:auto;
If the list to compare against is large, (ie the manilaListRange range in the example above), it is a smart move to use the match function. It avoids the use of a loop which could slow down the procedure. If you can ensure that the manilaListRange is all upper or lower case then this seems to be the best option to me. It is quick to apply 'UCase' or 'LCase' as you do your match.
If you did not have control over the ManilaListRange then you might have to resort to looping through this range in which case there are many ways to compare 'search', 'Instr', 'replace' etc.
Sorry for comment in an old post but if you want to use an else if statement this will help you
{% if title == source %}
Do This
{% elif title == value %}
Do This
{% else %}
Do This
{% endif %}
For more info see Django Documentation
The answers above are good. Adding a case that I used. Just if you don't want to use numpy and keep it as list without changing the contents.
You can run a small loop and change the dimension from 1xN to Nx1.
tmp=[]
for b in bus:
tmp.append([b])
bus=tmp
It is maybe not efficient while in case of very large numbers. But it works for a small set of numbers. Thanks
I would think , in a large file scenario using a stream would be far more efficient, because memory consumption would be very small.
But your algorithm could alternate between using a stream and loading the entire thing in memory based on the file size. I wouldn't be surprised if one is only better than the other under certain criteria.
Callback can be very helpful in Java.
Using Callback you can notify another Class of an asynchronous action that has completed with success or error.
5623125698541159
is treated as a single number (out of range of int
on most architecture). You need to write numbers in your file as
5 6 2 3 1 2 5 6 9 8 5 4 1 1 5 9
for 16 numbers.
If your file has input
5,6,2,3,1,2,5,6,9,8,5,4,1,1,5,9
then change %d
specifier in your fscanf
to %d,
.
fscanf(myFile, "%d,", &numberArray[i] );
Here is your full code after few modifications:
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *myFile;
myFile = fopen("somenumbers.txt", "r");
//read file into array
int numberArray[16];
int i;
if (myFile == NULL){
printf("Error Reading File\n");
exit (0);
}
for (i = 0; i < 16; i++){
fscanf(myFile, "%d,", &numberArray[i] );
}
for (i = 0; i < 16; i++){
printf("Number is: %d\n\n", numberArray[i]);
}
fclose(myFile);
return 0;
}
jQuery's CSS manipulation isn't queued, but you can make it executed inside the 'fx' queue by doing:
$('#div').delay(1000).queue('fx', function() { $(this).removeClass('error'); });
Quite same thing as calling setTimeout but uses jQuery's queue mecanism instead.
the command to get the effective push remote for the branch, e.g., master, is:
git config branch.master.pushRemote || git config remote.pushDefault || git config branch.master.remote
Here's why (from the "man git config" output):
branch.name.remote [...] tells git fetch and git push which remote to fetch from/push to [...] [for push] may be overridden with remote.pushDefault (for all branches) [and] for the current branch [..] further overridden by branch.name.pushRemote [...]
For some reason, "man git push" only tells about branch.name.remote (even though it has the least precedence of the three) + erroneously states that if it is not set, push defaults to origin - it does not, it's just that when you clone a repo, branch.name.remote is set to origin, but if you remove this setting, git push will fail, even though you still have the origin remote
This is a working example of making ZIPs in PHP:
$zip = new ZipArchive();
$zip_name = time().".zip"; // Zip name
$zip->open($zip_name, ZipArchive::CREATE);
foreach ($files as $file) {
echo $path = "uploadpdf/".$file;
if(file_exists($path)){
$zip->addFromString(basename($path), file_get_contents($path));
}
else{
echo"file does not exist";
}
}
$zip->close();
see my answer here:
How can I get the current date and time in UTC or GMT in Java?
I've fully tested it by changing the timezones on the emulator
I would use First()
when I know or expect the sequence to have at least one element. In other words, when it is an exceptional occurrence that the sequence is empty.
Use FirstOrDefault()
when you know that you will need to check whether there was an element or not. In other words, when it is legal for the sequence to be empty. You should not rely on exception handling for the check. (It is bad practice and might hurt performance).
Finally, the difference between First()
and Take(1)
is that First()
returns the element itself, while Take(1)
returns a sequence of elements that contains exactly one element.
This difference is due to the behavior of Promises more than fetch()
specifically.
When a .then()
callback returns an additional Promise
, the next .then()
callback in the chain is essentially bound to that Promise, receiving its resolve or reject fulfillment and value.
The 2nd snippet could also have been written as:
iterator.then(response =>
response.json().then(post => document.write(post.title))
);
In both this form and yours, the value of post
is provided by the Promise returned from response.json()
.
When you return a plain Object
, though, .then()
considers that a successful result and resolves itself immediately, similar to:
iterator.then(response =>
Promise.resolve({
data: response.json(),
status: response.status
})
.then(post => document.write(post.data))
);
post
in this case is simply the Object
you created, which holds a Promise
in its data
property. The wait for that promise to be fulfilled is still incomplete.
This class-based javascript animation works in AngularJS 1.2 (and 1.4 tested)
Edit: I ended up abandoning this code and went a completely different direction. I like my other answer much better. This answer will give you some problems in certain situations.
myApp.animation('.ng-show-toggle-slidedown', function(){
return {
beforeAddClass : function(element, className, done){
if (className == 'ng-hide'){
$(element).slideUp({duration: 400}, done);
} else {done();}
},
beforeRemoveClass : function(element, className, done){
if (className == 'ng-hide'){
$(element).css({display:'none'});
$(element).slideDown({duration: 400}, done);
} else {done();}
}
}
});
Simply add the .ng-hide-toggle-slidedown
class to the container element, and the jQuery slide down behavior will be implemented based on the ng-hide class.
You must include the $(element).css({display:'none'})
line in the beforeRemoveClass
method because jQuery will not execute a slideDown unless the element is in a state of display: none
prior to starting the jQuery animation. AngularJS uses the CSS
.ng-hide:not(.ng-hide-animate) {
display: none !important;
}
to hide the element. jQuery is not aware of this state, and jQuery will need the display:none
prior to the first slide down animation.
The AngularJS animation will add the .ng-hide-animate
and .ng-animate
classes while the animation is occuring.
Active Directory does not store the group membership on user objects. It only stores the Member list on the group. The tools show the group membership on user objects by doing queries for it.
How about:
(&(objectClass=group)(member=cn=my,ou=full,dc=domain))
(You forgot the (& ) bit in your example in the question as well).
Here's a way that I consider easier: The general idea is that you want to append a text element to a circle element then play around with its "dx" and "dy" attributes until you position the text at the point in the circle that you like. In my example, I used a negative number for the dx since I wanted to have text start towards the left of the centre.
const nodes = [ {id: ABC, group: 1, level: 1}, {id:XYZ, group: 2, level: 1}, ]
const nodeElems = svg.append('g')
.selectAll('circle')
.data(nodes)
.enter().append('circle')
.attr('r',radius)
.attr('fill', getNodeColor)
const textElems = svg.append('g')
.selectAll('text')
.data(nodes)
.enter().append('text')
.text(node => node.label)
.attr('font-size',8)//font size
.attr('dx', -10)//positions text towards the left of the center of the circle
.attr('dy',4)
If you are open to use third party tools you'd have a look at this one: https://github.com/CircleOfNice/DoctrineRestDriver
This is a completely new way to work with APIs.
First of all you define an entity which is defining the structure of incoming and outcoming data and annotate it with datasources:
/*
* @Entity
* @DataSource\Select("http://www.myApi.com/products/{id}")
* @DataSource\Insert("http://www.myApi.com/products")
* @DataSource\Select("http://www.myApi.com/products/update/{id}")
* @DataSource\Fetch("http://www.myApi.com/products")
* @DataSource\Delete("http://www.myApi.com/products/delete/{id}")
*/
class Product {
private $name;
public function setName($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
Now it's pretty easy to communicate with the REST API:
$product = new Product();
$product->setName('test');
// sends an API request POST http://www.myApi.com/products ...
$em->persist($product);
$em->flush();
$product->setName('newName');
// sends an API request UPDATE http://www.myApi.com/products/update/1 ...
$em->flush();
See my comment above, and I believe you have to use NSInvocation when there is more than one parameter
more information on NSInvocation here
http://cocoawithlove.com/2008/03/construct-nsinvocation-for-any-message.html
The documentation from Github is really explanatory.
https://help.github.com/en/articles/adding-a-new-ssh-key-to-your-github-account https://help.github.com/en/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent
I think you must do the lasts steps from the guide to proper configure your keys
$ eval "$(ssh-agent -s)"
$ ssh-add ~/.ssh/id_rsa
Note: According to JDN96, the answer below may cause a memory leak by repeatedly destroying and recreating frames. However, I have not tested to verify this myself.
One way to switch frames in tkinter
is to destroy the old frame then replace it with your new frame.
I have modified Bryan Oakley's answer to destroy the old frame before replacing it. As an added bonus, this eliminates the need for a container
object and allows you to use any generic Frame
class.
# Multi-frame tkinter application v2.3
import tkinter as tk
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self._frame = None
self.switch_frame(StartPage)
def switch_frame(self, frame_class):
"""Destroys current frame and replaces it with a new one."""
new_frame = frame_class(self)
if self._frame is not None:
self._frame.destroy()
self._frame = new_frame
self._frame.pack()
class StartPage(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="This is the start page").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Open page one",
command=lambda: master.switch_frame(PageOne)).pack()
tk.Button(self, text="Open page two",
command=lambda: master.switch_frame(PageTwo)).pack()
class PageOne(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="This is page one").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Return to start page",
command=lambda: master.switch_frame(StartPage)).pack()
class PageTwo(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
tk.Label(self, text="This is page two").pack(side="top", fill="x", pady=10)
tk.Button(self, text="Return to start page",
command=lambda: master.switch_frame(StartPage)).pack()
if __name__ == "__main__":
app = SampleApp()
app.mainloop()
switch_frame()
works by accepting any Class object that implements Frame
. The function then creates a new frame to replace the old one.
_frame
if it exists, then replaces it with the new frame..pack()
, such as menubars, will be unaffected.tkinter.Frame
.v2.3
- Pack buttons and labels as they are initialized
v2.2
- Initialize `_frame` as `None`.
- Check if `_frame` is `None` before calling `.destroy()`.
v2.1.1
- Remove type-hinting for backwards compatibility with Python 3.4.
v2.1
- Add type-hinting for `frame_class`.
v2.0
- Remove extraneous `container` frame.
- Application now works with any generic `tkinter.frame` instance.
- Remove `controller` argument from frame classes.
- Frame switching is now done with `master.switch_frame()`.
v1.6
- Check if frame attribute exists before destroying it.
- Use `switch_frame()` to set first frame.
v1.5
- Revert 'Initialize new `_frame` after old `_frame` is destroyed'.
- Initializing the frame before calling `.destroy()` results
in a smoother visual transition.
v1.4
- Pack frames in `switch_frame()`.
- Initialize new `_frame` after old `_frame` is destroyed.
- Remove `new_frame` variable.
v1.3
- Rename `parent` to `master` for consistency with base `Frame` class.
v1.2
- Remove `main()` function.
v1.1
- Rename `frame` to `_frame`.
- Naming implies variable should be private.
- Create new frame before destroying old frame.
v1.0
- Initial version.
Although this question is very old, but I see still there are no exact answer. I will try to answer the question here.
I believe the question in short here is how to set the proxy settings for the Apache commons HttpClient (org.apache.commons.httpclient.HttpClient).
Code snippet below should work :
HttpClient client = new HttpClient();
HostConfiguration hostConfiguration = client.getHostConfiguration();
hostConfiguration.setProxy("localhost", 8080);
client.setHostConfiguration(hostConfiguration);
I really like the explaination from SCJP Sun Certified Programmer for Java 5 Study Guide.
To make Java more memory efficient, the JVM sets aside a special area of memory called the "String constant pool." When the compiler encounters a String literal, it checks the pool to see if an identical String already exists. If a match is found, the reference to the new literal is directed to the existing String, and no new String literal object is created.
Efficient way (with any number of records):
SELECT id, name, MIN(price) FROM (select * from table order by price) as t group by id
You can use the CSS3 Linear Gradient property along with your background-image like this:
#landing-wrapper {
display:table;
width:100%;
background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('landingpagepic.jpg');
background-position:center top;
height:350px;
}
Here's a demo:
#landing-wrapper {_x000D_
display: table;_x000D_
width: 100%;_x000D_
background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('http://placehold.it/350x150');_x000D_
background-position: center top;_x000D_
height: 350px;_x000D_
color: white;_x000D_
}
_x000D_
<div id="landing-wrapper">Lorem ipsum dolor ismet.</div>
_x000D_
For cases where your images happen to be the same size (which is a common case for displaying image processing results), you can use numpy's concatenate to simplify your code.
To stack vertically (img1 over img2):
vis = np.concatenate((img1, img2), axis=0)
To stack horizontally (img1 to the left of img2):
vis = np.concatenate((img1, img2), axis=1)
To verify:
import cv2
import numpy as np
img1 = cv2.imread('img1.png')
img2 = cv2.imread('img2.png')
vis = np.concatenate((img1, img2), axis=1)
cv2.imwrite('out.png', vis)
The out.png image will contain img1 on the left and img2 on the right.
Regarding the issue with 'size', size is not a function on a dataframe, it is rather a property. So instead of using size(), plain size should work
Apart from that, a method like this should work
def doCalculation(df):
groupCount = df.size
groupSum = df['my_labels'].notnull().sum()
return groupCount / groupSum
dataFrame.groupby('my_labels').apply(doCalculation)
Here are the steps:
Close the file
$select = "data what we trying to store in a file";
$file = fopen("/var/www/htdocs/folder/test.txt", "w");
fwrite($file, $select->__toString());
fclose($file);
Make a truth table and use SUMPRODUCT to get the values. Copy this into cell B1 on Sheet2 and copy down as far as you need:=SUMPRODUCT(--($A1 = Sheet1!$A:$A), Sheet1!$B:$B)
the part that creates the truth table is:
--($A1 = Sheet1!$A:$A)
This returns an array of 0's and 1's. 1 when the values match and a 0 when they don't. Then the comma after that will basically do what I call "funny" matrix multiplication and will return the result. I may have misunderstood your question though, are there duplicate values in Column A of Sheet1?
Include org.json.jsonobject
in your project.
You can then do this:
JSONObject jresponse = new JSONObject(responseString);
responseString = jresponse.getString("NeededString");
Assuming, responseString
holds the response you receive.
If you need to know how to convert the received response to a String, here's how to do it:
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
String responseString = out.toString();
If you use PHP 7.4 or later you can also do it using arrow function so it looks cleaner:
Post::with(['user' => fn ($query) => $query->select('id','username')])->get();
I actually use a makefile to build any dependencies needed before invoking devenv to build a particular project as in the following:
debug: coratools_debug
devenv coralib.vcproj /build debug
coratools_debug: nothing
cd ../coratools
nmake debug
cd $(MAKEDIR)
You can also use the msbuild tool to do the same thing:
debug: coratools_debug
msbuild coralib.vcxproj /p:Configuration=debug
coratools_debug: nothing
cd ../coratools
nmake debug
cd $(MAKEDIR)
In my opinion, this is much easier than trying to figure out the overly complicated visual studio project management scheme.
Step 1: Go to the the first column of the first line you want to comment.
Step 2: Press: Ctrl+v and select the lines you want to comment:
Step 3: Shift-I
#space (Enter Insert-at-left mode, type chars to insert. The selection will disappear, but all lines within it will be modified after Step 4.)
Step 4: Esc
If you use the enumerable mixin (as Rails does) you can do something similar to the php snippet listed. Just use the each_slice method and flatten the hash.
require 'enumerator'
['a',1,'b',2].to_a.flatten.each_slice(2) {|x,y| puts "#{x} => #{y}" }
# is equivalent to...
{'a'=>1,'b'=>2}.to_a.flatten.each_slice(2) {|x,y| puts "#{x} => #{y}" }
Less monkey-patching required.
However, this does cause problems when you have a recursive array or a hash with array values. In ruby 1.9 this problem is solved with a parameter to the flatten method that specifies how deep to recurse.
# Ruby 1.8
[1,2,[1,2,3]].flatten
=> [1,2,1,2,3]
# Ruby 1.9
[1,2,[1,2,3]].flatten(0)
=> [1,2,[1,2,3]]
As for the question of whether this is a code smell, I'm not sure. Usually when I have to bend over backwards to iterate over something I step back and realize I'm attacking the problem wrong.
In order to complete BlueM's accepted answer, you can desactivate it here:
Tools > Options > Debugging > General Output Settings > Thread Exit Messages : Off
You can convert anything to a String as long as you choose what to print. The requirement was quite simple since Objet.toString()
can return a default dumb string: package.classname + @ + object number
.
If your print method should return an XML or JSON serialization, the basic result of toString() wouldn't be acceptable. Even though the method succeed.
Here is a simple example to show that Java can be dumb
public class MockTest{
String field1;
String field2;
public MockTest(String field1,String field2){
this.field1=field1;
this.field2=field2;
}
}
System.out.println(new MockTest("a","b");
will print something package.Mocktest@3254487
! Even though you only have two String members and this could be implemented to print
Mocktest@3254487{"field1":"a","field2":"b"}
(or pretty much how it appears in the debbuger)
history.pushState(null, null, document.title);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.title);
});
This script will overwrite attempts to navigate back and forth with the state of the current page.
Update:
Some users have reported better success with using document.URL
instead of document.title
:
history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
history.pushState(null, null, document.URL);
});
I am sure that you have found a solution somewhere over the past 2 years but the following is a solution that works for your requested site
package javasandbox;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
*
* @author Ryan.Oglesby
*/
public class JavaSandbox {
private static String sURL;
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws MalformedURLException, IOException {
sURL = "http://www.cumhuriyet.com.tr/?hn=298710";
System.out.println(sURL);
URL url = new URL(sURL);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
//set http request headers
httpCon.addRequestProperty("Host", "www.cumhuriyet.com.tr");
httpCon.addRequestProperty("Connection", "keep-alive");
httpCon.addRequestProperty("Cache-Control", "max-age=0");
httpCon.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
httpCon.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
httpCon.addRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
httpCon.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
//httpCon.addRequestProperty("Cookie", "JSESSIONID=EC0F373FCC023CD3B8B9C1E2E2F7606C; lang=tr; __utma=169322547.1217782332.1386173665.1386173665.1386173665.1; __utmb=169322547.1.10.1386173665; __utmc=169322547; __utmz=169322547.1386173665.1.1.utmcsr=stackoverflow.com|utmccn=(referral)|utmcmd=referral|utmcct=/questions/8616781/how-to-get-a-web-pages-source-code-from-java; __gads=ID=3ab4e50d8713e391:T=1386173664:S=ALNI_Mb8N_wW0xS_wRa68vhR0gTRl8MwFA; scrElm=body");
HttpURLConnection.setFollowRedirects(false);
httpCon.setInstanceFollowRedirects(false);
httpCon.setDoOutput(true);
httpCon.setUseCaches(true);
httpCon.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream(), "UTF-8"));
String inputLine;
StringBuilder a = new StringBuilder();
while ((inputLine = in.readLine()) != null)
a.append(inputLine);
in.close();
System.out.println(a.toString());
httpCon.disconnect();
}
}
Although your arraylist has a capacity of 10, the real list has no elements here. The add method is used to insert a element to the real list. Since it has no elements, you can't insert an element to the index of 5.
Add this to your NodeJS Server below imports:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
From the UIView reference's section about the beginAnimations:context:
method:
Use of this method is discouraged in iPhone OS 4.0 and later. You should use the block-based animation methods instead.
Eg of Block-based Animation based on Tom's Comment
[UIView transitionWithView:mysuperview
duration:0.75
options:UIViewAnimationTransitionFlipFromRight
animations:^{
[myview removeFromSuperview];
}
completion:nil];
I think the main difference I can describe relates to record oriented vs. column oriented formats. Record oriented formats are what we're all used to -- text files, delimited formats like CSV, TSV. AVRO is slightly cooler than those because it can change schema over time, e.g. adding or removing columns from a record. Other tricks of various formats (especially including compression) involve whether a format can be split -- that is, can you read a block of records from anywhere in the dataset and still know it's schema? But here's more detail on columnar formats like Parquet.
Parquet, and other columnar formats handle a common Hadoop situation very efficiently. It is common to have tables (datasets) having many more columns than you would expect in a well-designed relational database -- a hundred or two hundred columns is not unusual. This is so because we often use Hadoop as a place to denormalize data from relational formats -- yes, you get lots of repeated values and many tables all flattened into a single one. But it becomes much easier to query since all the joins are worked out. There are other advantages such as retaining state-in-time data. So anyway it's common to have a boatload of columns in a table.
Let's say there are 132 columns, and some of them are really long text fields, each different column one following the other and use up maybe 10K per record.
While querying these tables is easy with SQL standpoint, it's common that you'll want to get some range of records based on only a few of those hundred-plus columns. For example, you might want all of the records in February and March for customers with sales > $500.
To do this in a row format the query would need to scan every record of the dataset. Read the first row, parse the record into fields (columns) and get the date and sales columns, include it in your result if it satisfies the condition. Repeat. If you have 10 years (120 months) of history, you're reading every single record just to find 2 of those months. Of course this is a great opportunity to use a partition on year and month, but even so, you're reading and parsing 10K of each record/row for those two months just to find whether the customer's sales are > $500.
In a columnar format, each column (field) of a record is stored with others of its kind, spread all over many different blocks on the disk -- columns for year together, columns for month together, columns for customer employee handbook (or other long text), and all the others that make those records so huge all in their own separate place on the disk, and of course columns for sales together. Well heck, date and months are numbers, and so are sales -- they are just a few bytes. Wouldn't it be great if we only had to read a few bytes for each record to determine which records matched our query? Columnar storage to the rescue!
Even without partitions, scanning the small fields needed to satisfy our query is super-fast -- they are all in order by record, and all the same size, so the disk seeks over much less data checking for included records. No need to read through that employee handbook and other long text fields -- just ignore them. So, by grouping columns with each other, instead of rows, you can almost always scan less data. Win!
But wait, it gets better. If your query only needed to know those values and a few more (let's say 10 of the 132 columns) and didn't care about that employee handbook column, once it had picked the right records to return, it would now only have to go back to the 10 columns it needed to render the results, ignoring the other 122 of the 132 in our dataset. Again, we skip a lot of reading.
(Note: for this reason, columnar formats are a lousy choice when doing straight transformations, for example, if you're joining all of two tables into one big(ger) result set that you're saving as a new table, the sources are going to get scanned completely anyway, so there's not a lot of benefit in read performance, and because columnar formats need to remember more about the where stuff is, they use more memory than a similar row format).
One more benefit of columnar: data is spread around. To get a single record, you can have 132 workers each read (and write) data from/to 132 different places on 132 blocks of data. Yay for parallelization!
And now for the clincher: compression algorithms work much better when it can find repeating patterns. You could compress AABBBBBBCCCCCCCCCCCCCCCC
as 2A6B16C
but ABCABCBCBCBCCCCCCCCCCCCCC
wouldn't get as small (well, actually, in this case it would, but trust me :-) ). So once again, less reading. And writing too.
So we read a lot less data to answer common queries, it's potentially faster to read and write in parallel, and compression tends to work much better.
Columnar is great when your input side is large, and your output is a filtered subset: from big to little is great. Not as beneficial when the input and outputs are about the same.
But in our case, Impala took our old Hive queries that ran in 5, 10, 20 or 30 minutes, and finished most in a few seconds or a minute.
Hope this helps answer at least part of your question!
I'd rather implement TaskExecuteAsync interface function for IHttpActionResult. Something like:
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = _request.CreateResponse(HttpStatusCode.InternalServerError, _respContent);
switch ((Int32)_respContent.Code)
{
case 1:
case 6:
case 7:
response = _request.CreateResponse(HttpStatusCode.InternalServerError, _respContent);
break;
case 2:
case 3:
case 4:
response = _request.CreateResponse(HttpStatusCode.BadRequest, _respContent);
break;
}
return Task.FromResult(response);
}
, where _request is the HttpRequest and _respContent is the payload.
Like this:
#include <string>
#include <vector>
struct user
{
std::string username;
std::vector<unsigned char> userpassword;
};
int main()
{
user r; // r.username is "" and r.userpassword is empty
// ...
}
You should define a key name while storing data to local storage which should be a string and value should be a string
localStorage.setItem('dataSource', this.dataSource.length);
and to print, you should use getItem
console.log(localStorage.getItem('dataSource'));
var bd = document.getElementsByTagName('body')[0];
var time = new Date().getTime();
bd.onmousemove = goLoad;
function goLoad() {
if(new Date().getTime() - time >= 1200000) {
time = new Date().getTime();
window.location.reload(true);
}else{
time = new Date().getTime();
}
}
Each time you move the mouse it will check the last time you moved the mouse. If the time interval is greater than 20' it will reload the page, else it will renew the last-time-you-moved-the-mouse.
clientWidth and clientHeight are DOM properties that show the current in-browser size of the inner dimensions of a DOM element (excluding margin and border). So in the case of an IMG element, this will get the actual dimensions of the visible image.
var img = document.getElementById('imageid');
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
int main() {
string s1="split on whitespace";
istringstream iss(s1);
vector<string> result;
for(string s;iss>>s;)
result.push_back(s);
int n=result.size();
for(int i=0;i<n;i++)
cout<<result[i]<<endl;
return 0;
}
Output:-
split
on
whitespace
JavaScript is single-threaded, and all the time you work on a normal synchronous code-flow execution.
Good examples of the asynchronous behavior that JavaScript can have are events (user interaction, Ajax request results, etc) and timers, basically actions that might happen at any time.
I would recommend you to give a look to the following article:
That article will help you to understand the single-threaded nature of JavaScript and how timers work internally and how asynchronous JavaScript execution works.
The resolution is 480 dpi, the launcher icon is 144*144px all is scaled 3x respect to mdpi (so called "base", "baseline" or "normal") sizes.
I write code bewlow. It works well in product version. Supprot Swift 4.2 +
extension UIButton{
enum ImageTitleRelativeLocation {
case imageUpTitleDown
case imageDownTitleUp
case imageLeftTitleRight
case imageRightTitleLeft
}
func centerContentRelativeLocation(_ relativeLocation:
ImageTitleRelativeLocation,
spacing: CGFloat = 0) {
assert(contentVerticalAlignment == .center,
"only works with contentVerticalAlignment = .center !!!")
guard (title(for: .normal) != nil) || (attributedTitle(for: .normal) != nil) else {
assert(false, "TITLE IS NIL! SET TITTLE FIRST!")
return
}
guard let imageSize = self.currentImage?.size else {
assert(false, "IMGAGE IS NIL! SET IMAGE FIRST!!!")
return
}
guard let titleSize = titleLabel?
.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize) else {
assert(false, "TITLELABEL IS NIL!")
return
}
let horizontalResistent: CGFloat
// extend contenArea in case of title is shrink
if frame.width < titleSize.width + imageSize.width {
horizontalResistent = titleSize.width + imageSize.width - frame.width
print("horizontalResistent", horizontalResistent)
} else {
horizontalResistent = 0
}
var adjustImageEdgeInsets: UIEdgeInsets = .zero
var adjustTitleEdgeInsets: UIEdgeInsets = .zero
var adjustContentEdgeInsets: UIEdgeInsets = .zero
let verticalImageAbsOffset = abs((titleSize.height + spacing) / 2)
let verticalTitleAbsOffset = abs((imageSize.height + spacing) / 2)
switch relativeLocation {
case .imageUpTitleDown:
adjustImageEdgeInsets.top = -verticalImageAbsOffset
adjustImageEdgeInsets.bottom = verticalImageAbsOffset
adjustImageEdgeInsets.left = titleSize.width / 2 + horizontalResistent / 2
adjustImageEdgeInsets.right = -titleSize.width / 2 - horizontalResistent / 2
adjustTitleEdgeInsets.top = verticalTitleAbsOffset
adjustTitleEdgeInsets.bottom = -verticalTitleAbsOffset
adjustTitleEdgeInsets.left = -imageSize.width / 2 + horizontalResistent / 2
adjustTitleEdgeInsets.right = imageSize.width / 2 - horizontalResistent / 2
adjustContentEdgeInsets.top = spacing
adjustContentEdgeInsets.bottom = spacing
adjustContentEdgeInsets.left = -horizontalResistent
adjustContentEdgeInsets.right = -horizontalResistent
case .imageDownTitleUp:
adjustImageEdgeInsets.top = verticalImageAbsOffset
adjustImageEdgeInsets.bottom = -verticalImageAbsOffset
adjustImageEdgeInsets.left = titleSize.width / 2 + horizontalResistent / 2
adjustImageEdgeInsets.right = -titleSize.width / 2 - horizontalResistent / 2
adjustTitleEdgeInsets.top = -verticalTitleAbsOffset
adjustTitleEdgeInsets.bottom = verticalTitleAbsOffset
adjustTitleEdgeInsets.left = -imageSize.width / 2 + horizontalResistent / 2
adjustTitleEdgeInsets.right = imageSize.width / 2 - horizontalResistent / 2
adjustContentEdgeInsets.top = spacing
adjustContentEdgeInsets.bottom = spacing
adjustContentEdgeInsets.left = -horizontalResistent
adjustContentEdgeInsets.right = -horizontalResistent
case .imageLeftTitleRight:
adjustImageEdgeInsets.left = -spacing / 2
adjustImageEdgeInsets.right = spacing / 2
adjustTitleEdgeInsets.left = spacing / 2
adjustTitleEdgeInsets.right = -spacing / 2
adjustContentEdgeInsets.left = spacing
adjustContentEdgeInsets.right = spacing
case .imageRightTitleLeft:
adjustImageEdgeInsets.left = titleSize.width + spacing / 2
adjustImageEdgeInsets.right = -titleSize.width - spacing / 2
adjustTitleEdgeInsets.left = -imageSize.width - spacing / 2
adjustTitleEdgeInsets.right = imageSize.width + spacing / 2
adjustContentEdgeInsets.left = spacing
adjustContentEdgeInsets.right = spacing
}
imageEdgeInsets = adjustImageEdgeInsets
titleEdgeInsets = adjustTitleEdgeInsets
contentEdgeInsets = adjustContentEdgeInsets
setNeedsLayout()
}
}
Windows 7, 64 bit, no modifications to the Registry key, the location is:
C:\Users[Current User when app crashed]\AppData\Local\Microsoft\Windows\WER\ReportArchive
SELECT C.COLUMN_NAME, C.IS_NULLABLE, C.DATA_TYPE, TC.CONSTRAINT_TYPE, C.COLUMN_DEFAULT
FROM INFORMATION_SCHEMA.COLUMNS AS C
FULL JOIN INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE AS CC ON C.COLUMN_NAME = CC.COLUMN_NAME
FULL JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC ON CC.CONSTRAINT_NAME = TC.CONSTRAINT_NAME
WHERE C.TABLE_NAME = '<Table Name>';
The best and tested solution is to put the following small snippet which will collapse the accordion tab which is already open when you load. In my case the last sixth tab was open so I made it collapsed on page load.
$(document).ready(){
$('#collapseSix').collapse("hide");
}
!=
For example,
if ("apple" != "orange")
// true, the string "apple" is not equal to the string "orange"
Means not. See also the logical operators list. Also, when you see triple characters, it's a type sensitive comparison. (e.g. if (1 === '1')
[not equal])
[In no particular order.] However, if you have any other requirements, let us know. BTW: I am not just posting results of a Google query here, I have used all of these (and SDL -- wrote my first few games in SDL :) and I'd say without a set of requirements, it's very difficult to choose among the ones listed.
Checkout The Jquery Documentation
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
Your syntax is incorrect, you should either specify a hash:
hash = {abc: true, def: true, ghi: true};
Or an array:
arr = ['abc','def','ghi'];
You can effectively remove an item from a hash by simply setting it to null:
hash['def'] = null;
hash.def = null;
Or removing it entirely:
delete hash.def;
To remove an item from an array you have to iterate through each item and find the one you want (there may be duplicates). You could use array searching and splicing methods:
arr.splice(arr.indexOf("def"), 1);
This finds the first index of "def" and then removes it from the array with splice. However I would recommend .filter() because it gives you more control:
arr.filter(function(item) { return item !== 'def'; });
This will create a new array with only elements that are not 'def'.
It is important to note that arr.filter() will return a new array, while arr.splice will modify the original array and return the removed elements. These can both be useful, depending on what you want to do with the items.
You can analyze the core dump file using the "gdb" command.
gdb - The GNU Debugger
syntax:
# gdb executable-file core-file
example: # gdb out.txt core.xxx
Well try my code, atleast it gives you a string as overlay, you can very well replace it with a button or an image. You wont believe this is my first ever android app LOL. Anyways if you are more experienced with android apps than me, please try
All I had to do was add a parameter to the url state definition like so
url: '/toState?referer'
Doh!
Frequently use this:
grep
can be used in conjunction with -r
(recursive), i
(ignore case) and -o
(prints only matching part of lines). To exclude files
use --exclude
and to exclude directories use --exclude-dir
.
Putting it together you end up with something like:
grep -rio --exclude={filenames comma separated} \
--exclude-dir={directory names comma separated} <search term> <location>
Describing it makes it sound far more complicated than it actually is. Easier to illustrate with a simple example.
Example:
Suppose I am searching for current project for all places where I explicitly set the string value debugger
during a debugging session, and now wish to review / remove.
I write a script called findDebugger.sh
and use grep
to find all occurrences. However:
For file exclusions - I wish to ensure that .eslintrc
is ignored (this actually has a linting rule about debugger
so should be excluded). Likewise, I don't want my own script to be referenced in any results.
For directory exclusions - I wish to exclude node_modules
as it contains lots of libraries that do reference debugger
and I am not interested in those results. Also I just wish to omit .idea
and .git
hidden directories because I don't care about those search locations either, and wish to keep the search performant.
So here is the result - I create a script called findDebugger.sh
with:
#!/usr/bin/env bash
grep -rio --exclude={.eslintrc,findDebugger.sh} \
--exclude-dir={node_modules,.idea,.git} debugger .
I could not load fonts because I had named my font file Poppins-Medium.tff, renaming it to poppins_medium.tff worked for me. Rest of the steps remained the same:
I used all above changes but still I was getting same issue on my web application.
Then I contacted my hosting provide & asked them to check if any software or antivirus blocking our files to transfer via HTTP. or ISP/network is not allowing file to transfer.
They checked server settings & bypass the "Data Center Shared Firewall" for my server & now our application is able to download the file.
Hope this answer will help someone.This is what worked for me
Related to importing, if you are having issues importing a file with bulk inserts and you're getting MYSQL GONE AWAY, lost connection or similar error, open your my.cnf / my.ini and temporarily set your max_allowed_packet to something large like 400M
Remember to set it back again after your import!
Updated answer, from Peter in comments :
This is de "old terminology", use directally the WSDL2 "endepoint" definition (WSDL2 translated "port" to "endpoint").
Maybe you find an answer in this document : http://www.w3.org/TR/wsdl.html
A WSDL document defines services as collections of network endpoints, or ports. In WSDL, the abstract definition of endpoints and messages is separated from their concrete network deployment or data format bindings. This allows the reuse of abstract definitions: messages, which are abstract descriptions of the data being exchanged, and port types which are abstract collections of operations. The concrete protocol and data format specifications for a particular port type constitutes a reusable binding. A port is defined by associating a network address with a reusable binding, and a collection of ports define a service. Hence, a WSDL document uses the following elements in the definition of network services:
- Types– a container for data type definitions using some type system (such as XSD).
- Message– an abstract, typed definition of the data being communicated.
- Operation– an abstract description of an action supported by the service.
- Port Type–an abstract set of operations supported by one or more endpoints.
- Binding– a concrete protocol and data format specification for a particular port type.
- Port– a single endpoint defined as a combination of a binding and a network address.
- Service– a collection of related endpoints.
http://www.ehow.com/info_12212371_definition-service-endpoint.html
The endpoint is a connection point where HTML files or active server pages are exposed. Endpoints provide information needed to address a Web service endpoint. The endpoint provides a reference or specification that is used to define a group or family of message addressing properties and give end-to-end message characteristics, such as references for the source and destination of endpoints, and the identity of messages to allow for uniform addressing of "independent" messages. The endpoint can be a PC, PDA, or point-of-sale terminal.
First thing we've tried was to disable dynamic content compression for IIS , that solved the errors but the error wasn't caused server side and only one client was affected by this.
On client side we uninstalled VPN clients, reset internet settings and then reinstalled VPN clients. The error could also be caused by previous antivirus which had firewall. Then we enabled back dynamic content compression and now it works fine as before.
Error appeared in custom application which connects to a web service and also at TFS.
The answer above suggests changing the function to echo data rather than return it so that it can be captured.
For a function or program that you can't modify where the return value needs to be saved to a variable (like test
/[
, which returns a 0/1 success value), echo $?
within the command substitution:
# Test if we're remote.
isRemote="$(test -z "$REMOTE_ADDR"; echo $?)"
# Or:
isRemote="$([ -z "$REMOTE_ADDR" ]; echo $?)"
# Additionally you may want to reverse the 0 (success) / 1 (error) values
# for your own sanity, using arithmetic expansion:
remoteAddrIsEmpty="$([ -z "$REMOTE_ADDR" ]; echo $((1-$?)))"
E.g.
$ echo $REMOTE_ADDR
$ test -z "$REMOTE_ADDR"; echo $?
0
$ REMOTE_ADDR=127.0.0.1
$ test -z "$REMOTE_ADDR"; echo $?
1
$ retval="$(test -z "$REMOTE_ADDR"; echo $?)"; echo $retval
1
$ unset REMOTE_ADDR
$ retval="$(test -z "$REMOTE_ADDR"; echo $?)"; echo $retval
0
For a program which prints data but also has a return value to be saved, the return value would be captured separately from the output:
# Two different files, 1 and 2.
$ cat 1
1
$ cat 2
2
$ diffs="$(cmp 1 2)"
$ haveDiffs=$?
$ echo "Have differences? [$haveDiffs] Diffs: [$diffs]"
Have differences? [1] Diffs: [1 2 differ: char 1, line 1]
$ diffs="$(cmp 1 1)"
$ haveDiffs=$?
$ echo "Have differences? [$haveDiffs] Diffs: [$diffs]"
Have differences? [0] Diffs: []
# Or again, if you just want a success variable, reverse with arithmetic expansion:
$ cmp -s 1 2; filesAreIdentical=$((1-$?))
$ echo $filesAreIdentical
0
I have opened a pull request to Please.js that allows generating a color from a hash.
You can map the string to a color like so:
const color = Please.make_color({
from_hash: "any string goes here"
});
For example, "any string goes here"
will return as "#47291b"
and "another!"
returns as "#1f0c3d"
Position your <div>
absolutely at the bottom and don't forget to give div.A
a position: relative
- http://jsfiddle.net/TTaMx/
.A {
position: relative;
margin: 40px 0;
height: 40px;
width: 200px;
background: #eee;
}
.A:after {
content: " ";
display: block;
background: #c00;
height: 29px;
width: 100%;
position: absolute;
bottom: -29px;
}?
I did exactly what you're looking for in a very simple way. It is perfectly smooth in Google Chrome and Opera, and almost perfect in Firefox and Safari. Not tested in IE.
function newTab(url)
{
var tab=window.open("");
tab.document.write("<!DOCTYPE html><html>"+document.getElementsByTagName("html")[0].innerHTML+"</html>");
tab.document.close();
window.location.href=url;
}
Fiddle : http://jsfiddle.net/tFCnA/show/
Explanations:
Let's say there is windows A1 and B1 and websites A2 and B2.
Instead of opening B2 in B1 and then return to A1, I open B2 in A1 and re-open A2 in B1.
(Another thing that makes it work is that I don't make the user re-download A2, see line 4)
The only thing you may doesn't like is that the new tab opens before the main page.
When I did just a remove the option remained in the ddl on the view, but was gone in the html (if u inspect the page)
$("#ddlSelectList option[value='2']").remove(); //removes the option with value = 2
$('#ddlSelectList').val('').trigger('chosen:updated'); //refreshes the drop down list
Add this in your input element
<input
action="action"
onclick="window.history.go(-1); return false;"
type="submit"
value="Cancel"
/>
I have try with the SCFRench and with the Ru Hasha on octave.
And finally it works: but I have done some modification
function message = makefuns
assignin('base','fun1', @fun1); % Ru Hasha
assignin('base', 'fun2', @fun2); % Ru Hasha
message.fun1=@fun1; % SCFrench
message.fun2=@fun2; % SCFrench
end
function y=fun1(x)
y=x;
end
function z=fun2
z=1;
end
Can be called in other 'm' file:
printf("%d\n", makefuns.fun1(123));
printf("%d\n", makefuns.fun2());
update:
I added an answer because neither the +72 nor the +20 worked in octave for me. The one I wrote works perfectly (and I tested it last Friday when I later wrote the post).
The other two answers are correct. When you include spaces in your CSS selectors you're targeting child elements so:
.form-group .required {
styles
}
Is targeting an element with the class of "required" that is inside an element with the class of "form-group".
Without the space it's targeting an element that has both classes. 'required' and 'form-group'
Workbooks.open("E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm")
Or, in a more structured way...
Sub openwb()
Dim sPath As String, sFile As String
Dim wb As Workbook
sPath = "E:\sarath\PTMetrics\20131004\D8 L538-L550 16MY\"
sFile = sPath & "D8 L538-L550_16MY_Powertrain Metrics_20131002.xlsm"
Set wb = Workbooks.Open(sFile)
End Sub
You can try this:
for file in *.jpg;
do
mv $file $somestring_${file:((-7))}
done
You can see "parameter expansion" in man bash
to understand the above better.
Assuming your field is a date
type (or similar):
SELECT DATE_ADD(`your_field_name`, INTERVAL 2 DAY)
FROM `table_name`;
With the example you've provided it could look like this:
UPDATE classes
SET `date` = DATE_ADD(`date` , INTERVAL 2 DAY)
WHERE `id` = 161;
This approach works with datetime
, too.
You need the following permissions in your manifest file:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
Then you can use the following in your activity class:
WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);
Use the following to check if it's enabled or not
boolean wifiEnabled = wifiManager.isWifiEnabled()
You'll find a nice tutorial on the subject on this site.
In Bourne shell(sh), use the . command to source a file
. filename
Usually it is a simple as adding apply plugin: "eclipse"
in your build.gradle
and running
cd myProject/
gradle eclipse
and then refreshing your Eclipse project.
Occasionally you'll need to adjust build.gradle
to generate Eclipse settings in some very specific way.
There is gradle support for Eclipse if you are using STS, but I'm not sure how good it is.
The only IDE I know that has decent native support for gradle is IntelliJ IDEA. It can do full import of gradle projects from GUI. There is a free Community Edition that you can try.
You can try this:
//Your class instance
Publication publication = new Publication();
//Get class with full path(with package name)
Class<?> c = Class.forName("com.example.publication.models.Publication");
//Get method
Method method = c.getDeclaredMethod ("setTitle", String.class);
//set value
method.invoke (publication, "Value to want to set here...");
The issue is with
At the time of writing this, no environment supports ES6 modules natively. When using them in Node.js you need to use something like Babel to convert the modules to CommonJS. But how exactly does that happen?
Many people consider module.exports = ...
to be equivalent to export default ...
and exports.foo ...
to be equivalent to export const foo = ...
. That's not quite true though, or at least not how Babel does it.
ES6 default
exports are actually also named exports, except that default
is a "reserved" name and there is special syntax support for it. Lets have a look how Babel compiles named and default exports:
// input
export const foo = 42;
export default 21;
// output
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var foo = exports.foo = 42;
exports.default = 21;
Here we can see that the default export becomes a property on the exports
object, just like foo
.
We can import the module in two ways: Either using CommonJS or using ES6 import
syntax.
Your issue: I believe you are doing something like:
var bar = require('./input');
new bar();
expecting that bar
is assigned the value of the default export. But as we can see in the example above, the default export is assigned to the default
property!
So in order to access the default export we actually have to do
var bar = require('./input').default;
If we use ES6 module syntax, namely
import bar from './input';
console.log(bar);
Babel will transform it to
'use strict';
var _input = require('./input');
var _input2 = _interopRequireDefault(_input);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
console.log(_input2.default);
You can see that every access to bar
is converted to access .default
.
Your String resource
<resources>
<string name="your_string_resource_name">This is normal text<![CDATA[<b> but this is bold </b>]]> and <![CDATA[<u> but this is underline text</u>]]></string>
</resources>
your java class
yourtextView.setText(getString(R.string.your_string_resource_name));
Style your change the Submit button to an anchor tag instead and submit using javascript:
<a class="link-button" href="javascript:submit();">Submit</a>
<a class="link-button" href="some_url">Cancel</a>
function submit() {
var form = document.getElementById("form_id");
form.submit();
}
In order to completely remove pip, I believe you have to delete its files from all Python versions on your computer. For me, they are here:
cd /Library/Frameworks/Python.framework/Versions/Current/bin/
cd /Library/Frameworks/Python.framework/Versions/3.3/bin/
You may need to remove the files or the directories located at these file-paths (and more, depending on the number of versions of Python you have installed).
Edit: to find all versions of pip on your machine, use:
find / -name pip 2>/dev/null
, which starts at its highest level (hence the /
) and hides all error messages (that's what 2>/dev/null
does). This is my output:
$ find / -name pip 2>/dev/null
/Library/Frameworks/Python.framework/Versions/2.7/bin/pip
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip
/Library/Frameworks/Python.framework/Versions/3.3/bin/pip
/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/pip
/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/pip
/Library/Frameworks/Python.framework/Versions/7.1/bin/pip
/Library/Frameworks/Python.framework/Versions/7.1/lib/python2.7/site-packages/pip-1.4.1-py2.7.egg/pip
Having read the answers, I still miss one important aspect of using semicolons, possibly the only one where it really makes a difference...
When you're working in an interpreter REPL (the Python interactive shell, IDLE, ipython) the value of the last expression is printed to the screen and usually this is the intended behavior.
But in some cases you want to evaluate an expression for its side effects only, e.g., to see the results of your simulation plotted by matplotlib
.
In this cases you (probably) don't want to see the screenful of repr
s of matplotlib
objects that are sometimes returned by a call to a matplotlib
function and, in IPython at least, one of the possibilities you have is to append a semicolon to the overly verbose statement, now IPython sees the input line as composed by two expressions, the matplotlib
invocation and a null statement, so that the value of the compound expression is None
and nothing is printed to the screen by the interpreter
(the other possibility being assignment, as in _ = plot(...)
but I find that a bit more intrusive).
IMHO, the use of the semicolon to suppress not desired output in the interpreter has become more relevant following the introduction of the IPyton notebook, that permits to save the input and the output, including graphical output, of an interpreter session for documentation and eventual reuse.
Simple and clean:
$('#select_all').click(function() {_x000D_
var c = this.checked;_x000D_
$(':checkbox').prop('checked', c);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form>_x000D_
<table>_x000D_
<tr>_x000D_
<td><input type="checkbox" id="select_all" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td><input type="checkbox" name="select[]" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td><input type="checkbox" name="select[]" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td><input type="checkbox" name="select[]" /></td>_x000D_
</tr>_x000D_
</table>_x000D_
</form>
_x000D_
You can use Reflector and also use Add-In FileGenerator to extract source code into a project.