Couldn't add this as a comment, but in case anyone is interested in using the accepted answer with subplots, the divider should be formed on specific axes object (rather than on the numpy.ndarray returned from plt.subplots)
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots(ncols=2, nrows=2)
for row in ax:
for col in row:
im = col.imshow(data, cmap='bone')
divider = make_axes_locatable(col)
cax = divider.append_axes('right', size='5%', pad=0.05)
fig.colorbar(im, cax=cax, orientation='vertical')
plt.show()
I always use pseudo elements :before
and :after
for changing the appearance of checkboxes and radio buttons. it's works like a charm.
Refer this link for more info
Steps
visibility:hidden
or opacity:0
or position:absolute;left:-9999px
etc.:before
element and pass either an empty or a non-breaking space '\00a0'
;:checked
state, pass the unicode content: "\2713"
, which is a checkmark;:focus
style to make the checkbox accessible.Here is how I did it.
.box {_x000D_
background: #666666;_x000D_
color: #ffffff;_x000D_
width: 250px;_x000D_
padding: 10px;_x000D_
margin: 1em auto;_x000D_
}_x000D_
p {_x000D_
margin: 1.5em 0;_x000D_
padding: 0;_x000D_
}_x000D_
input[type="checkbox"] {_x000D_
visibility: hidden;_x000D_
}_x000D_
label {_x000D_
cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
border: 1px solid #333;_x000D_
content: "\00a0";_x000D_
display: inline-block;_x000D_
font: 16px/1em sans-serif;_x000D_
height: 16px;_x000D_
margin: 0 .25em 0 0;_x000D_
padding: 0;_x000D_
vertical-align: top;_x000D_
width: 16px;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
background: #fff;_x000D_
color: #333;_x000D_
content: "\2713";_x000D_
text-align: center;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
outline: rgb(59, 153, 252) auto 5px;_x000D_
}
_x000D_
<div class="content">_x000D_
<div class="box">_x000D_
<p>_x000D_
<input type="checkbox" id="c1" name="cb">_x000D_
<label for="c1">Option 01</label>_x000D_
</p>_x000D_
<p>_x000D_
<input type="checkbox" id="c2" name="cb">_x000D_
<label for="c2">Option 02</label>_x000D_
</p>_x000D_
<p>_x000D_
<input type="checkbox" id="c3" name="cb">_x000D_
<label for="c3">Option 03</label>_x000D_
</p>_x000D_
</div>_x000D_
</div>
_x000D_
Much more stylish using :before
and :after
body{_x000D_
font-family: sans-serif; _x000D_
}_x000D_
_x000D_
.container {_x000D_
margin-top: 50px;_x000D_
margin-left: 20px;_x000D_
margin-right: 20px;_x000D_
}_x000D_
.checkbox {_x000D_
width: 100%;_x000D_
margin: 15px auto;_x000D_
position: relative;_x000D_
display: block;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"] {_x000D_
width: auto;_x000D_
opacity: 0.00000001;_x000D_
position: absolute;_x000D_
left: 0;_x000D_
margin-left: -20px;_x000D_
}_x000D_
.checkbox label {_x000D_
position: relative;_x000D_
}_x000D_
.checkbox label:before {_x000D_
content: '';_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
margin: 4px;_x000D_
width: 22px;_x000D_
height: 22px;_x000D_
transition: transform 0.28s ease;_x000D_
border-radius: 3px;_x000D_
border: 2px solid #7bbe72;_x000D_
}_x000D_
.checkbox label:after {_x000D_
content: '';_x000D_
display: block;_x000D_
width: 10px;_x000D_
height: 5px;_x000D_
border-bottom: 2px solid #7bbe72;_x000D_
border-left: 2px solid #7bbe72;_x000D_
-webkit-transform: rotate(-45deg) scale(0);_x000D_
transform: rotate(-45deg) scale(0);_x000D_
transition: transform ease 0.25s;_x000D_
will-change: transform;_x000D_
position: absolute;_x000D_
top: 12px;_x000D_
left: 10px;_x000D_
}_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
color: #7bbe72;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
-webkit-transform: rotate(-45deg) scale(1);_x000D_
transform: rotate(-45deg) scale(1);_x000D_
}_x000D_
_x000D_
.checkbox label {_x000D_
min-height: 34px;_x000D_
display: block;_x000D_
padding-left: 40px;_x000D_
margin-bottom: 0;_x000D_
font-weight: normal;_x000D_
cursor: pointer;_x000D_
vertical-align: sub;_x000D_
}_x000D_
.checkbox label span {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
-webkit-transform: translateY(-50%);_x000D_
transform: translateY(-50%);_x000D_
}_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
outline: 0;_x000D_
}
_x000D_
<div class="container"> _x000D_
<div class="checkbox">_x000D_
<input type="checkbox" id="checkbox" name="" value="">_x000D_
<label for="checkbox"><span>Checkbox</span></label>_x000D_
</div>_x000D_
_x000D_
<div class="checkbox">_x000D_
<input type="checkbox" id="checkbox2" name="" value="">_x000D_
<label for="checkbox2"><span>Checkbox</span></label>_x000D_
</div>_x000D_
</div>
_x000D_
$ catalina.bat jpda start
On Linux/Unix
$ catalina.sh jpda start
More info ---->
https://cwiki.apache.org/confluence/display/TOMCAT/Developing
You need the "correlation id" (the "AS SS" thingy) on the sub-select to reference the fields in the "ON" condition. The id's assigned inside the sub select are not usable in the join.
SELECT
cs.CUSID
,dp.DEPID
FROM
CUSTMR cs
LEFT OUTER JOIN (
SELECT
DEPID
,DEPNAME
FROM
DEPRMNT
WHERE
dp.DEPADDRESS = 'TOKYO'
) ss
ON (
ss.DEPID = cs.CUSID
AND ss.DEPNAME = cs.CUSTNAME
)
WHERE
cs.CUSID != ''
I met the same problem in Win10 32bit OS. I resolved the problem by changing the DLL from debug to release version.
I think it is because the debug version DLL depends on other DLL, and the release version did not.
I'm 99% sure that RollingFileAppender/DailyRollingFileAppender, while it gives you the date-rolling functionality you want, doesn't have any way to specify that the current log file should use the DatePattern
as well.
You might just be able to simply subclass RollingFileAppender (or DailyRollingFileAppender, I forget which is which in log4net) and modify the naming logic.
It is working for me
MsgBox(DataGridView1.CurrentRow.Cells(0).Value.ToString)
I want to add to other answers that setters can be used to prevent putting the object in an invalid state.
For instance let's suppose that I've to set a TaxId, modelled as a String. The first version of the setter can be as follows:
private String taxId;
public void setTaxId(String taxId) {
this.taxId = taxId;
}
However we'd better prevent the use to set the object with an invalid taxId, so we can introduce a check:
private String taxId;
public void setTaxId(String taxId) throws IllegalArgumentException {
if (isTaxIdValid(taxId)) {
throw new IllegalArgumentException("Tax Id '" + taxId + "' is invalid");
}
this.taxId = taxId;
}
The next step, to improve the modularity of the program, is to make the TaxId itself as an Object, able to check itself.
private final TaxId taxId = new TaxId()
public void setTaxId(String taxIdString) throws IllegalArgumentException {
taxId.set(taxIdString); //will throw exception if not valid
}
Similarly for the getter, what if we don't have a value yet? Maybe we want to have a different path, we could say:
public String getTaxId() throws IllegalStateException {
return taxId.get(); //will throw exception if not set
}
Inside your Stack, you should wrap your background
widget in a Positioned.fill.
return new Stack(
children: <Widget>[
new Positioned.fill(
child: background,
),
foreground,
],
);
When I had this problem, I wrote adb kill-server
and adb restart-server
in terminal, but the problem appeared again the next day. Then I updated GPU debugging tools in the Android SDK manager and restarted the computer, which worked for me.
In windows you can use your Command Prompcmd cmd
, in Ubuntu you can use your terminal
by typing the following command:
mongoimport -d your_database_name -c your_collection_name /path_to_json_file/json_file_name.json
then when you open your mongo shell, you will find to check your database_name when running this command:
show databases
You can also do it this way to reference the previous branch implicitly:
git checkout mainline
git pull
git merge -
git push
From my testing using this CSS:
.expandable{
display: none;
}
.expand:hover+.expandable{
display:inline !important;
}
.expandable:hover{
display:inline !important;
}
And this HTML:
<div class="expand">expand</div>
<div class="expand">expand</div>
<div class="expandable">expandable</div>
, it resulted that it does expand using the second , but does not expand using the first one. So if there is a div between the hover target and the hidden div, then it will not work.
Your code contains dataType: json.
In this case jQuery evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner. Any malformed JSON is rejected and a parse error is thrown. An empty response is also rejected.
The server should return a response of null
or {}
instead.
You can see Silverlight/WPF sets ellipse with hexadecimal colour for using a hex value:
your_contorl.Color = DirectCast(ColorConverter.ConvertFromString("#D8E0A627"), Color)
This script searches for non-ascii characters in one column. It generates a string of all valid characters, here code point 32 to 127. Then it searches for rows that don't match the list:
declare @str varchar(128)
declare @i int
set @str = ''
set @i = 32
while @i <= 127
begin
set @str = @str + '|' + char(@i)
set @i = @i + 1
end
select col1
from YourTable
where col1 like '%[^' + @str + ']%' escape '|'
I'm using GDB7.1.1, as --help
shows:
gdb [options] --args executable-file [inferior-arguments ...]
IMHO, the order is a bit unintuitive at first.
Taken from that page, this will unset all of the cookies for your domain:
// unset cookies
if (isset($_SERVER['HTTP_COOKIE'])) {
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
foreach($cookies as $cookie) {
$parts = explode('=', $cookie);
$name = trim($parts[0]);
setcookie($name, '', time()-1000);
setcookie($name, '', time()-1000, '/');
}
}
The reason people often suggest writing
VAR=value
export VAR
instead of the shorter
export VAR=value
is that the longer form works in more different shells than the short form. If you know you're dealing with bash
, either works fine, of course.
Since no-one else has mentioned it, note that del
(unlike pop
) allows the removal of a range of indexes because of list slicing:
>>> lst = [3, 2, 2, 1]
>>> del lst[1:]
>>> lst
[3]
This also allows avoidance of an IndexError
if the index is not in the list:
>>> lst = [3, 2, 2, 1]
>>> del lst[10:]
>>> lst
[3, 2, 2, 1]
The docs give a fair indicator of what's required., however requests
allow us to skip a few steps:
You only need to install the security
package extras (thanks @admdrew for pointing it out)
$ pip install requests[security]
or, install them directly:
$ pip install pyopenssl ndg-httpsclient pyasn1
Requests will then automatically inject pyopenssl
into urllib3
If you're on ubuntu, you may run into trouble installing pyopenssl
, you'll need these dependencies:
$ apt-get install libffi-dev libssl-dev
Java does have a logical XOR operator, it is ^ (as in a ^ b
).
Apart from that, you can't define new operators in Java.
Edit: Here's an example:
public static void main(String[] args) {
boolean[] all = { false, true };
for (boolean a : all) {
for (boolean b: all) {
boolean c = a ^ b;
System.out.println(a + " ^ " + b + " = " + c);
}
}
}
Output:
false ^ false = false false ^ true = true true ^ false = true true ^ true = false
There is another solution if you want to develop in C/C++. http://www.DragonFireSDK.com will allow you to build iPhone applications in Visual Studio on Windows. It's worth a look-see for sure.
Though not POSIX, bash 4 has the &>
operator:
command &> alloutput.txt
As a complement of @stefano 's answer,
It is better to use command with -f
when generate a new SSH key for another account,
ssh-keygen -t rsa -f ~/.ssh/id_rsa_work -C "[email protected]"
Since id_rsa_work
file doesn't exist in path ~/.ssh/
, and I create this file manually, and it doesn't work :(
You can do it like this,
<input type="text" name="name" value="<?php echo $name;?>" />
But seen as you've taken it straight from user input, you want to sanitize it first so that nothing nasty is put into the output of your page.
<input type="text" name="name" value="<?php echo htmlspecialchars($name);?>" />
Additionally, you will see that float
values are rounded.
// e.g: given values 41.0473112,29.0077011 float(11,7) | decimal(11,7) --------------------------- 41.0473099 | 41.0473112 29.0077019 | 29.0077011
Those look much like Bonjour / mDNS requests to me. Those packets use multicast IP address 224.0.0.251 and port 5353.
The most likely source for this is Apple iTunes, which comes pre-installed on Mac computers (and is a popular install on Windows machines as well). Apple iTunes uses it to discover other iTunes-compatible devices in the same WiFi network.
mDNS is also used (primarily by Apple's Mac and iOS devices) to discover mDNS-compatible devices such as printers on the same network.
If this is a Linux box instead, it's probably the Avahi daemon then. Avahi is ZeroConf/Bonjour compatible and installed by default, but if you don't use DNS-SD or mDNS, it can be disabled.
A way that might be more convenient: where you want a breakpoint, write a no-op if statement and set a breakpoint in its contents.
if(tablist[i].equalsIgnoreCase("LEADDELEGATES")) {
--> int noop = 0; //don't do anything
}
(the breakpoint is represented by the arrow)
This way, the breakpoint only triggers if your condition is true. This could potentially be easier without that many pop-ups.
If anyone is searching for useState() hooks update for object
- Through Input
const [state, setState] = useState({ fName: "", lName: "" });
const handleChange = e => {
const { name, value } = e.target;
setState(prevState => ({
...prevState,
[name]: value
}));
};
<input
value={state.fName}
type="text"
onChange={handleChange}
name="fName"
/>
<input
value={state.lName}
type="text"
onChange={handleChange}
name="lName"
/>
***************************
- Through onSubmit or button click
setState(prevState => ({
...prevState,
fName: 'your updated value here'
}));
It really depends on what you're storing. If you're talking about structured data, then either XML or a very lightweight SQL RDBMS like SQLite or SQL Server Compact Edition will work well for you. The SQL solution becomes especially compelling if the data moves beyond a trivial size.
If you're storing large pieces of relatively unstructured data (binary objects like images, for example) then obviously neither a database nor XML solution are appropriate, but given your question I'm guessing it's more of the former than the latter.
Telerik's Just Decompile is the best I've used. It's free once you sign up with an email.
You have not placed the script tags for angular js
you can do so by using cdn or downloading the angularjs for your project and then referencing it
after this you have to add your own java script in your case main.js
that should do
Change branch, discarding all local modifications
git checkout -f 9-sign-in-out
Rename the current branch to master, discarding current master
git branch -M master
wget https://raw.github.com/flexiondotorg/oab-java6/master/oab-java.sh
chmod +x oab-java.sh
sudo ./oab-java.sh -7
sudo apt-get update
sudo sudo apt-get install oracle-java7-jdk oracle-java7-fonts oracle-java7-source
sudo apt-get dist-upgrade
There is an Issue 123 currently in OAB and a pull request
Here is the patched vesion:
wget https://raw.github.com/ladios/oab-java6/master/oab-java.sh
chmod +x oab-java.sh
sudo ./oab-java.sh -7
sudo apt-get update
sudo sudo apt-get install oracle-java7-jdk oracle-java7-fonts oracle-java7-source
sudo apt-get dist-upgrade
One way is to replace the double quotes in the HTML with single quotes but using double quotes has become the standard convention for attribute values in HTML.
The better option is to escape the double quotes in json and other characters that need to be escaped.
You can get some more details about escaping here: Where can I find a list of escape characters required for my JSON ajax return type?
Ok, Im assuming you want to put the .left inside the container so I suggest you edit your html. The key is the position:absolute
and right:0
#right {
background-color: red;
height: 300px;
width: 300px;
z-index: 999999;
margin-top: 0px;
position: absolute;
right:0;
}
here is the full code: http://jsfiddle.net/T9FJL/
Use setImmediate
if you want to queue the function behind whatever I/O event callbacks that are already in the event queue. Use process.nextTick
to effectively queue the function at the head of the event queue so that it executes immediately after the current function completes.
So in a case where you're trying to break up a long running, CPU-bound job using recursion, you would now want to use setImmediate
rather than process.nextTick
to queue the next iteration as otherwise any I/O event callbacks wouldn't get the chance to run between iterations.
Something like:
if(divisor == 0) {
throw new ArithmeticException("Division by zero!");
}
http://www.jsoops.net/ is quite good for oop in Js. If provide private, protected, public variable and function, and also Inheritance feature. Example Code:
var ClassA = JsOops(function (pri, pro, pub)
{// pri = private, pro = protected, pub = public
pri.className = "I am A ";
this.init = function (var1)// constructor
{
pri.className += var1;
}
pub.getData = function ()
{
return "ClassA(Top=" + pro.getClassName() + ", This=" + pri.getClassName()
+ ", ID=" + pro.getClassId() + ")";
}
pri.getClassName = function () { return pri.className; }
pro.getClassName = function () { return pri.className; }
pro.getClassId = function () { return 1; }
});
var newA = new ClassA("Class");
//***Access public function
console.log(typeof (newA.getData));
// function
console.log(newA.getData());
// ClassA(Top=I am A Class, This=I am A Class, ID=1)
//***You can not access constructor, private and protected function
console.log(typeof (newA.init)); // undefined
console.log(typeof (newA.className)); // undefined
console.log(typeof (newA.pro)); // undefined
console.log(typeof (newA.getClassName)); // undefined
I had the same problem recently and this helped me:
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="FILENAME"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize("PATH/TO/FILE"));
ob_clean();
flush();
readfile(PATH/TO/FILE);
exit();
I found this answer here
Third solution:
I would set ws
to a sheet of workbook wb
as the use of Sheet("name")
always refers to the active workbook, which might change as your code develops.
sub kl()
Dim wb As Workbook
Dim ws As Worksheet
Set wb = ActiveWorkbook
'be aware as this might produce an error, if Shet "name" does not exist
Set ws = wb.Sheets("name")
' if wb is other than the active workbook
wb.activate
ws.Select
End Sub
I had this problem, and on a hunch I removed the Qt Configs from my environment. I.e.,
rm -rf ~/.config/Qt*
Then I started qtcreator and it reconfigured itself with the existing state of the machine. It no longer remembered where my projects were, but that just meant I had to browse to them "for the first time" again.
But more importantly it built itself a coherent set of library paths, so I could rebuild and run my project executables again without the xcb or qxcb libraries going missing.
I also had this problem recently. Working with a new client, trying to get a an old web forms app running from Visual Studio, with IISExpress using Windows Authentication. For me, the web.config was correctly configured
However, the IISExpress.config settings file had:
<windowsAuthentication enabled="false">
The user account the developer was logged in was very new, so unlikely it had been edited. Simple fix it turned out, change this to enabled=true and it all ran as it should then.
If your program doesn't have a event loop already, use the sched module, which implements a general purpose event scheduler.
import sched, time
s = sched.scheduler(time.time, time.sleep)
def do_something(sc):
print("Doing stuff...")
# do your stuff
s.enter(60, 1, do_something, (sc,))
s.enter(60, 1, do_something, (s,))
s.run()
If you're already using an event loop library like asyncio
, trio
, tkinter
, PyQt5
, gobject
, kivy
, and many others - just schedule the task using your existing event loop library's methods, instead.
var objDiv = document.getElementById("divExample");
objDiv.scrollTop = objDiv.scrollHeight;
window.location is just what you need. Other thing you can do is to create anchor element and simulate click on it
$("<a href='your url'></a>").click();
in linux/ubuntu you can do, run following commands
cd ~/.config/JetBrains/PyCharm2020.1
rm eval/PyCharm201.evaluation.key
sed -i '/evlsprt/d' options/other.xml
cd ~/.java/.userPrefs/jetbrains
rm -rf pycharm*
This issue can occur if we delete the view controller or try to add new view controller inside the interface builder(main.storyboard). To fix this issue, it requires to add "Navigation Item" inside new view controller. Sometimes it happens that we create new view controller screen and it does not connect to "Navigation Item" automatically.
What I found works in the form is str_replace('<br>', PHP_EOL, $textarea);
There are a number of ways of achieving your result. If you're just wanting a solution for your case, use string multiplication as @Ant mentions. This is only going to work if each of your print
statements prints the same string. Note that it works for multiplication of any length string (e.g. 'foo' * 20
works).
>>> print 'a' * 20
aaaaaaaaaaaaaaaaaaaa
If you want to do this in general, build up a string and then print it once. This will consume a bit of memory for the string, but only make a single call to print
. Note that string concatenation using +=
is now linear in the size of the string you're concatenating so this will be fast.
>>> for i in xrange(20):
... s += 'a'
...
>>> print s
aaaaaaaaaaaaaaaaaaaa
Or you can do it more directly using sys.stdout.write(), which print
is a wrapper around. This will write only the raw string you give it, without any formatting. Note that no newline is printed even at the end of the 20 a
s.
>>> import sys
>>> for i in xrange(20):
... sys.stdout.write('a')
...
aaaaaaaaaaaaaaaaaaaa>>>
Python 3 changes the print
statement into a print() function, which allows you to set an end
parameter. You can use it in >=2.6 by importing from __future__
. I'd avoid this in any serious 2.x code though, as it will be a little confusing for those who have never used 3.x. However, it should give you a taste of some of the goodness 3.x brings.
>>> from __future__ import print_function
>>> for i in xrange(20):
... print('a', end='')
...
aaaaaaaaaaaaaaaaaaaa>>>
Taken from jQuery docs:
var arr = [ "one", "two", "three", "four", "five" ];
var obj = { one:1, two:2, three:3, four:4, five:5 };
jQuery.each(arr, function() {
$("#" + this).text("My id is " + this + ".");
return (this != "four"); // will stop running to skip "five"
});
jQuery.each(obj, function(i, val) {
$("#" + i).append(document.createTextNode(" - " + val));
});
Although almost all web sites still place Jquery and other javascript on header :D , even check stackoverflow.com .
I also suggest you to put on before end tag of body. You can check loading time after placing on either places. Script tag will pause your webpage to load further.
and after placing javascript on footer, you may get unusual looks of your webpage until it loads javascript, so place css on your header section.
Use the (excellent) JSON-Java library from json.org then
JSONObject json = new JSONObject(str);
String xml = XML.toString(json);
toString
can take a second argument to provide the name of the XML root node.
This library is also able to convert XML to JSON using XML.toJSONObject(java.lang.String string)
Check the Javadoc
Link to the the github repository
POM
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160212</version>
</dependency>
original post updated with new links
Someone with a requirement where they have to read from bits, lets say you have to read from only 3 bits but you need signed integer then use following:
data is of type: java.util.BitSet
new BigInteger(data.toByteArray).intValue() << 32 - 3 >> 32 - 3
The magic number 3
can be replaced with the number of bits (not bytes) you are using.
To make it easier I will say you can change your buttons to the following:
<input name="btnSubmit" type="submit" value="Save" />
<input name="btnProcess" type="submit" value="Process" />
Your controller:
public ActionResult Create(string btnSubmit, string btnProcess)
{
if(btnSubmit != null)
// do something for the Button btnSubmit
else
// do something for the Button btnProcess
}
If the file to read is big, and you don't want to read the whole file in memory at once:
fp = open("file")
for i, line in enumerate(fp):
if i == 25:
# 26th line
elif i == 29:
# 30th line
elif i > 29:
break
fp.close()
Note that i == n-1
for the n
th line.
In Python 2.6 or later:
with open("file") as fp:
for i, line in enumerate(fp):
if i == 25:
# 26th line
elif i == 29:
# 30th line
elif i > 29:
break
Of course, Object.keys()
is the best way to get an Object's keys. If it's not available in your environment, it can be trivially shimmed using code such as in your example (except you'd need to take into account your loop will iterate over all properties up the prototype chain, unlike Object.keys()
's behaviour).
However, your example code...
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [];
for (var key in foo) {
keys.push(key);
}
...could be modified. You can do the assignment right in the variable part.
var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
var keys = [], i = 0;
for (keys[i++] in foo) {}
Of course, this behaviour is different to what Object.keys()
actually does (jsFiddle). You could simply use the shim on the MDN documentation.
As you are referring to a combobox, I'm assuming you don't want to use 2-way databinding (if so, look at using a BindingList
)
public class Country
{
public string Name { get; set; }
public IList<City> Cities { get; set; }
public Country(string _name)
{
Cities = new List<City>();
Name = _name;
}
}
List<Country> countries = new List<Country> { new Country("UK"),
new Country("Australia"),
new Country("France") };
var bindingSource1 = new BindingSource();
bindingSource1.DataSource = countries;
comboBox1.DataSource = bindingSource1.DataSource;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Name";
To find the country selected in the bound combobox, you would do something like: Country country = (Country)comboBox1.SelectedItem;
.
If you want the ComboBox to dynamically update you'll need to make sure that the data structure that you have set as the DataSource
implements IBindingList
; one such structure is BindingList<T>
.
Tip: make sure that you are binding the DisplayMember
to a Property on the class and not a public field. If you class uses public string Name { get; set; }
it will work but if it uses public string Name;
it will not be able to access the value and instead will display the object type for each line in the combo box.
Assuming you want lower case letters:
var chr = String.fromCharCode(97 + n); // where n is 0, 1, 2 ...
97 is the ASCII code for lower case 'a'. If you want uppercase letters, replace 97 with 65 (uppercase 'A'). Note that if n > 25
, you will get out of the range of letters.
The accepted answer explains already well why the warning occurs. If you simply want to control the warnings, one could use precision_recall_fscore_support
. It offers a (semi-official) argument warn_for
that could be used to mute the warnings.
(_, _, f1, _) = metrics.precision_recall_fscore_support(y_test, y_pred,
average='weighted',
warn_for=tuple())
As mentioned already in some comments, use this with care.
java.util.Date date;
Timestamp timestamp = resultSet.getTimestamp(i);
if (timestamp != null)
date = new java.util.Date(timestamp.getTime()));
Then format it the way you like.
In your androidmanifest.xml file:
<activity android:name="MainActivity" android:configChanges="keyboardHidden|orientation">
or
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
Use the observer pattern. It works like this:
interface MyListener{
void somethingHappened();
}
public class MyForm implements MyListener{
MyClass myClass;
public MyForm(){
this.myClass = new MyClass();
myClass.addListener(this);
}
public void somethingHappened(){
System.out.println("Called me!");
}
}
public class MyClass{
private List<MyListener> listeners = new ArrayList<MyListener>();
public void addListener(MyListener listener) {
listeners.add(listener);
}
void notifySomethingHappened(){
for(MyListener listener : listeners){
listener.somethingHappened();
}
}
}
You create an interface which has one or more methods to be called when some event happens. Then, any class which needs to be notified when events occur implements this interface.
This allows more flexibility, as the producer is only aware of the listener interface, not a particular implementation of the listener interface.
In my example:
MyClass
is the producer here as its notifying a list of listeners.
MyListener
is the interface.
MyForm
is interested in when somethingHappened
, so it is implementing MyListener
and registering itself with MyClass
. Now MyClass
can inform MyForm
about events without directly referencing MyForm
. This is the strength of the observer pattern, it reduces dependency and increases reusability.
// Get current date/time in milliseconds.
#include "boost/date_time/posix_time/posix_time.hpp"
namespace pt = boost::posix_time;
int main()
{
pt::ptime current_date_microseconds = pt::microsec_clock::local_time();
long milliseconds = current_date_microseconds.time_of_day().total_milliseconds();
pt::time_duration current_time_milliseconds = pt::milliseconds(milliseconds);
pt::ptime current_date_milliseconds(current_date_microseconds.date(),
current_time_milliseconds);
std::cout << "Microseconds: " << current_date_microseconds
<< " Milliseconds: " << current_date_milliseconds << std::endl;
// Microseconds: 2013-Jul-12 13:37:51.699548 Milliseconds: 2013-Jul-12 13:37:51.699000
}
If you have Pillow
installed with scipy
and it is still giving you error then check your scipy
version because it has been removed from scipy since 1.3.0rc1
.
rather install scipy 1.1.0
by :
pip install scipy==1.1.0
check https://github.com/scipy/scipy/issues/6212
The method imread
in scipy.misc
requires the forked package of PIL
named Pillow
. If you are having problem installing the right version of PIL try using imread
in other packages:
from matplotlib.pyplot import imread
im = imread(image.png)
To read jpg
images without PIL
use:
import cv2 as cv
im = cv.imread(image.jpg)
You can try
from scipy.misc.pilutil import imread
instead of from scipy.misc import imread
Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.
I'd suggest <a href='page1.jsp'>Refresh</a>
.
As per the HTML:
<html>
<body>
<p class="content">Link1.</p>
</body>
<html>
<html>
<body>
<p class="content">Link2.</p>
</body>
<html>
Two(2) <p>
elements are having the same class content
.
So to filter the elements having the same class i.e. content
and create a list you can use either of the following Locator Strategies:
Using class_name
:
elements = driver.find_elements_by_class_name("content")
Using css_selector
:
elements = driver.find_elements_by_css_selector(".content")
Using xpath
:
elements = driver.find_elements_by_xpath("//*[@class='content']")
Ideally, to click on the element you need to induce WebDriverWait for the visibility_of_all_elements_located()
and you can use either of the following Locator Strategies:
Using CLASS_NAME
:
elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CLASS_NAME, "content")))
Using CSS_SELECTOR
:
elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, ".content")))
Using XPATH
:
elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//*[@class='content']")))
Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
You can find a couple of relevant discussions in:
Maybe you want set -e
:
www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:
This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.
As of ECMAScript 2016 you can use includes()
arr.includes(obj);
If you want to support IE or other older browsers:
function include(arr,obj) {
return (arr.indexOf(obj) != -1);
}
EDIT: This will not work on IE6, 7 or 8 though. The best workaround is to define it yourself if it's not present:
Mozilla's (ECMA-262) version:
if (!Array.prototype.indexOf)
{
Array.prototype.indexOf = function(searchElement /*, fromIndex */)
{
"use strict";
if (this === void 0 || this === null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (len === 0)
return -1;
var n = 0;
if (arguments.length > 0)
{
n = Number(arguments[1]);
if (n !== n)
n = 0;
else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
if (n >= len)
return -1;
var k = n >= 0
? n
: Math.max(len - Math.abs(n), 0);
for (; k < len; k++)
{
if (k in t && t[k] === searchElement)
return k;
}
return -1;
};
}
Daniel James's version:
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (obj, fromIndex) {
if (fromIndex == null) {
fromIndex = 0;
} else if (fromIndex < 0) {
fromIndex = Math.max(0, this.length + fromIndex);
}
for (var i = fromIndex, j = this.length; i < j; i++) {
if (this[i] === obj)
return i;
}
return -1;
};
}
roosteronacid's version:
Array.prototype.hasObject = (
!Array.indexOf ? function (o)
{
var l = this.length + 1;
while (l -= 1)
{
if (this[l - 1] === o)
{
return true;
}
}
return false;
} : function (o)
{
return (this.indexOf(o) !== -1);
}
);
Another way you can do in Jquery.
<video id="videoclip" controls="controls" poster="" title="Video title">
<source id="mp4video" src="video/bigbunny.mp4" type="video/mp4" />
</video>
<div class="list-item">
<ul>
<li class="item" data-video = "video/bigbunny.mp4"><a href="javascript:void(0)">Big Bunny.</a></li>
</ul>
</div>
$(".list-item").find(".item").on("click", function() {
let videoData = $(this).data("video");
let videoSource = $("#videoclip").find("#mp4video");
videoSource.attr("src", videoData);
let autoplayVideo = $("#videoclip").get(0);
autoplayVideo.load();
autoplayVideo.play();
});
The problem is the std namespace you are missing. cout
is in the std namespace.
Add using namespace std;
after the #include
For people do not like to modify chrome's security options, we can simply start a python
http server from directory which contains your local file:
python -m SimpleHTTPServer
and for python 3:
python3 -m http.server
Now you can reach any local file directly from your js code or externally with http://127.0.0.1:8000/some_file.txt
Easiest way my friends, is to open the server explorer tab on visual studio 2019 (in my case), and then try to create the connection to the database. After creating a succesful connection just right click on it and go to propierties. There you will find a string connection field with the correct syntax!...This worked for me because I knew my server's name before hand....just couldn't figure out the correct syntax to run my ef scaffold...
You can also use IHtmlHelper.GetEnumSelectList.
// Summary:
// Returns a select list for the given TEnum.
//
// Type parameters:
// TEnum:
// Type to generate a select list for.
//
// Returns:
// An System.Collections.Generic.IEnumerable`1 containing the select list for the
// given TEnum.
//
// Exceptions:
// T:System.ArgumentException:
// Thrown if TEnum is not an System.Enum or if it has a System.FlagsAttribute.
IEnumerable<SelectListItem> GetEnumSelectList<TEnum>() where TEnum : struct;
UPDATE your_table
SET your_field = REPLACE(your_field, 'articles/updates/', 'articles/news/')
WHERE your_field LIKE '%articles/updates/%'
Now rows that were like
http://www.example.com/articles/updates/43
will be
http://www.example.com/articles/news/43
Use Datatable.Default.Sort
property and then bind it to the datagridview.
This may be a dead thread, but I tend to use the following:
public static T? GetValueOrNull<T>(this DbDataRecord reader, string columnName)
where T : struct
{
return reader[columnName] as T?;
}
I give the answer because I need to compare 2 files in notepad++ and there is no option available.
So first enable the plugin manager as asked by question here, Then follow this step to compare 2 files which is free in this software.
1.open notepad++, go to
Plugin -> Plugin Manager -> Show Plugin Manager
2.Show the available plugin list, choose Compare and Install
3.Restart Notepad++.
http://www.technicaloverload.com/compare-two-files-using-notepad/
/*
LINES I WANT COMMENTED
LINES I WANT COMMENTED
LINES I WANT COMMENTED
*/
Declare your manifest header like this
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yourpackage"
xmlns:tools="http://schemas.android.com/tools">
Then you can add to your application tag the following attribute:
<application
tools:replace="icon, label" ../>
For example I need to replace icon and label. Good luck!
To check if a character is lower case, use the islower
method of str
. This simple imperative program prints all the lowercase letters in your string:
for c in s:
if c.islower():
print c
Note that in Python 3 you should use print(c)
instead of print c
.
Possibly ending up with assigning those letters to a different variable.
To do this I would suggest using a list comprehension, though you may not have covered this yet in your course:
>>> s = 'abCd'
>>> lowercase_letters = [c for c in s if c.islower()]
>>> print lowercase_letters
['a', 'b', 'd']
Or to get a string you can use ''.join
with a generator:
>>> lowercase_letters = ''.join(c for c in s if c.islower())
>>> print lowercase_letters
'abd'
I have faced same problem with maven dependencies, eg: unfortunetly your maven dependencies deleted from your buildpath,then you people get lot of exceptions,if you follow below process you can easily resolve this issue.
.text is correct, the following code works for me:
$('#lb'+(n+1)).text(a[i].attributes[n].name+": "+ a[i].attributes[n].value);
If you need rock solid integrity, have both tables in one database, and use an FK constraint. If your parent table is in another database, nothing prevents anyone from restoring that parent database from an old backup, and then you have orphans.
This is why FK between databases is not supported.
This is what css is for... HTML doesn't allow for unequal padding. When you say that you don't want to use style sheets, does this mean you're OK with inline css?
<table>
<tr>
<td style="padding: 5px 10px 5px 5px;">Content</td>
<td style="padding: 5px 10px 5px 5px;">Content</td>
</tr>
</table>
You could also use JS to do this if you're desperate not to use stylesheets for some reason.
Use a image style width and height 100% . This will do the trick, because the image can be resized based on the container.
Example:
<a class="navbar-brand" href="#" style="padding: 4px;margin:auto"> <img src="images/logo.png" style="height:100%;width: auto;" title="mycompanylogo"></a>
I think you are looking for:
window.location = 'http://someUrl.com';
It's not jQuery; it's pure JavaScript.
I don't know but this is the format have used...
<h1>
<span id="site-logo" title="xxx" href="#" target="_self">
<img src="http://www.xxx.com/images/xxx.png" alt="xxx" width="xxx" height="xxx" />
<a style="display:none">
<strong>xxx</strong>
</a>
</span>
</h1>
Simple and it has not done my site any harm as far as I can see. You could css it but I don't see it loading any faster.
Here's a solution using that ggplot
package (version 3.x) in addition to what you've gotten so far.
We use the position
argument of geom_bar
set to position = "fill"
. You may also use position = position_fill()
if you want to use the arguments of position_fill()
(vjust
and reverse
).
Note that your data is in a 'wide' format, whereas ggplot2
requires it to be in a 'long' format. Thus, we first need to gather
the data.
library(ggplot2)
library(dplyr)
library(tidyr)
dat <- read.table(text = " ONE TWO THREE
1 23 234 324
2 34 534 12
3 56 324 124
4 34 234 124
5 123 534 654",sep = "",header = TRUE)
# Add an id variable for the filled regions and reshape
datm <- dat %>%
mutate(ind = factor(row_number())) %>%
gather(variable, value, -ind)
ggplot(datm, aes(x = variable, y = value, fill = ind)) +
geom_bar(position = "fill",stat = "identity") +
# or:
# geom_bar(position = position_fill(), stat = "identity")
scale_y_continuous(labels = scales::percent_format())
As Bash doesn't have built in sql database connectivity... you will need to use some sort of third party tool.
You have a selector ul
on line 252
which is setting list-style: square outside none
(a square bullet). You'll have to change it to list-style: none
or just remove the line.
If you only want to remove the bullets from that specific instance, you can use the specific selector for that list and its items as follows:
ul#groups-list.items-list { list-style: none }
Multiple attributes can be connected with an and
:
GroupMember.find_or_create_by_member_id_and_group_id(4, 7)
(use find_or_initialize_by
if you don't want to save the record right away)
Edit: The above method is deprecated in Rails 4. The new way to do it will be:
GroupMember.where(:member_id => 4, :group_id => 7).first_or_create
and
GroupMember.where(:member_id => 4, :group_id => 7).first_or_initialize
Edit 2: Not all of these were factored out of rails just the attribute specific ones.
https://github.com/rails/rails/blob/4-2-stable/guides/source/active_record_querying.md
Example
GroupMember.find_or_create_by_member_id_and_group_id(4, 7)
became
GroupMember.find_or_create_by(member_id: 4, group_id: 7)
I catch the close event of the dialog box. This code then removes the <div>
(#dhx_combo_list
):
open: function(event, ui) {
//hide close button.
$(this).parent().children().children('.ui-dialog-titlebar-close').click(function(){
$("#dhx_combo_list").remove();
});
},
I faced this problem, and spent hours trying to figure out the issue. tried to follow the steps mentioned in the different answers above, the solution I found is on the same lines as Mona suggested, but slightly different. Tried to add as a comment to Mona's answer but no option was available. Issue with my eclipse was, classpath somehow got corrupted and all the jars and dependent projects were missing. after taking the latest .classpath from repository it worked fine.
You can use str_replace(), which is defined as:
str_replace($search, $replace, $subject)
So you could write the code as:
$subject = 'REGISTER 11223344 here' ;
$search = '11223344' ;
$trimmed = str_replace($search, '', $subject) ;
echo $trimmed ;
If you need better matching via regular expressions you can use preg_replace().
I have this version about datetimepicker https://tempusdominus.github.io/bootstrap-4/ and for any reason doesn`t work the change event with jquery but with JS vanilla it does
I figure out like this
document.getElementById('date').onchange = function(){ ...the jquery code...}
I hope work for you
Found this absolute hack that actually works quite well:
https://codepen.io/nikitahl/pen/vyZbwR
Not CSS only though.
The basic gist is to have a container on the dropdown, .select-container
in this case. That container has it's ::before
set up to display content
based on its data-content
attribute/dataset, along with all of the overflow:hidden; text-overflow: ellipsis;
and sizing necessary to make the ellipsis work.
When the select changes, javascript assigns the value (or you could retrieve the text of the option out of the select.options
list) to the dataset.content of the container, and voila!
Copying content of the codepen here:
var selectContainer = document.querySelector(".select-container");_x000D_
var select = selectContainer.querySelector(".select");_x000D_
select.value = "lingua latina non penis canina";_x000D_
_x000D_
selectContainer.dataset.content = select.value;_x000D_
_x000D_
function handleChange(e) {_x000D_
selectContainer.dataset.content = e.currentTarget.value;_x000D_
console.log(select.value);_x000D_
}_x000D_
_x000D_
select.addEventListener("change", handleChange);
_x000D_
span {_x000D_
margin: 0 10px 0 0;_x000D_
}_x000D_
_x000D_
.select-container {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
}_x000D_
_x000D_
.select-container::before {_x000D_
content: attr(data-content);_x000D_
position: absolute;_x000D_
top: 0;_x000D_
right: 10px;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
padding: 7px;_x000D_
font: 11px Arial, sans-serif;_x000D_
white-space: nowrap;_x000D_
text-overflow: ellipsis;_x000D_
overflow: hidden;_x000D_
text-transform: capitalize;_x000D_
pointer-events: none;_x000D_
}_x000D_
_x000D_
.select {_x000D_
width: 80px;_x000D_
padding: 5px;_x000D_
appearance: none;_x000D_
background: transparent url("https://cdn4.iconfinder.com/data/icons/ionicons/512/icon-arrow-down-b-128.png") no-repeat calc(~"100% - 5px") 7px;_x000D_
background-size: 10px 10px;_x000D_
color: transparent;_x000D_
}_x000D_
_x000D_
.regular {_x000D_
display: inline-block;_x000D_
margin: 10px 0 0;_x000D_
.select {_x000D_
color: #000;_x000D_
}_x000D_
}
_x000D_
<span>Hack:</span><div class="select-container" data-content="">_x000D_
<select class="select" id="words">_x000D_
<option value="lingua latina non penis canina">Lingua latina non penis canina</option>_x000D_
<option value="lorem">Lorem</option>_x000D_
<option value="ipsum">Ipsum</option>_x000D_
<option value="dolor">Dolor</option>_x000D_
<option value="sit">Sit</option>_x000D_
<option value="amet">Amet</option>_x000D_
<option value="lingua">Lingua</option>_x000D_
<option value="latina">Latina</option>_x000D_
<option value="non">Non</option>_x000D_
<option value="penis">Penis</option>_x000D_
<option value="canina">Canina</option>_x000D_
</select>_x000D_
</div>_x000D_
<br />_x000D_
_x000D_
<span>Regular:</span>_x000D_
<div class="regular">_x000D_
<select style="width: 80px;">_x000D_
<option value="lingua latina non penis canina">Lingua latina non penis canina</option>_x000D_
<option value="lorem">Lorem</option>_x000D_
<option value="ipsum">Ipsum</option>_x000D_
<option value="dolor">Dolor</option>_x000D_
<option value="sit">Sit</option>_x000D_
<option value="amet">Amet</option>_x000D_
<option value="lingua">Lingua</option>_x000D_
<option value="latina">Latina</option>_x000D_
<option value="non">Non</option>_x000D_
<option value="penis">Penis</option>_x000D_
<option value="canina">Canina</option>_x000D_
</select>_x000D_
</div>
_x000D_
Another nice one: Accidentally redefining modules. I copy/pasted stuff a little too eagerly earlier today and ended up having a module definition somewhere, that I overrode with my controller definitions:
// controllers.js - dependencies in one place, perfectly fine
angular.module('my.controllers', [/* dependencies */]);
Then in my definitions, I was supposed to reference it like so:
// SomeCtrl.js - grab the module, add the controller
angular.module('my.controllers')
.controller('SomeCtrl', function() { /* ... */ });
What I did instead, was:
// Do not try this at home!
// SomeCtrl.js
angular.module('my.controllers', []) // <-- redefined module, no harm done yet
.controller('SomeCtrl', function() { /* ... */ });
// SomeOtherCtrl.js
angular.module('my.controllers', []) // <-- redefined module - SomeCtrl no longer accessible
.controller('SomeOtherCtrl', function() { /* ... */ });
Note the extra bracket in the call to angular.module
.
Investigate what is your EOL, \n or \r\n. Then replace .*#region.*\r\n
with nothing in regexpr mode.
INSERT INTO tab_student (name_student, id_teacher_fk)
VALUES ('dan red',
(SELECT id_teacher FROM tab_teacher WHERE name_teacher ='jason bourne')
it is advisable to store your values in lowercase to make retrieval easier and less error prone
INSERT INTO tab_teacher (name_teacher)
VALUES ('tom stills')
INSERT INTO tab_student (name_student, id_teacher_fk)
VALUES ('rich man', LAST_INSERT_ID())
There is a lot of good information here, but I wanted to add a simple snippet that I find useful.
How does it differ from some above?
_usage(){
_echoerr "Usage: $0 <args>"
}
_echoerr(){
echo "$*" >&2
}
if [ "$#" -eq 0 ]; then # NOTE: May need to customize this conditional
_usage
exit 2
fi
main "$@"
The easiest fix is to just float
the container. (eg. float: left;
) On another note, each id
should be unique, meaning you can't use the same id
twice in the same HTML
document. You should use classes instead, where you can use the same class
for multiple elements.
.container {
position: relative;
background: rgb(255, 100, 0);
margin: 0;
width: 40%;
height: 100px;
float: left;
}
These tips on MySQL and UTF-8 may be helpful. Unfortunately, they don't constitute a full solution, just common gotchas.
Pass an empty array as the second argument to useEffect
. This effectively tells React, quoting the docs:
This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run.
Here's a snippet which you can run to show that it works:
function App() {_x000D_
const [user, setUser] = React.useState(null);_x000D_
_x000D_
React.useEffect(() => {_x000D_
fetch('https://randomuser.me/api/')_x000D_
.then(results => results.json())_x000D_
.then(data => {_x000D_
setUser(data.results[0]);_x000D_
});_x000D_
}, []); // Pass empty array to only run once on mount._x000D_
_x000D_
return <div>_x000D_
{user ? user.name.first : 'Loading...'}_x000D_
</div>;_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App/>, document.getElementById('app'));
_x000D_
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>_x000D_
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>_x000D_
_x000D_
<div id="app"></div>
_x000D_
Free for non-commercial use.
Includes plugins for jQuery, Node.js, WordPress, Drupal, Joomla, Microsoft TypeScript, etc...
Some screenshots of some of the demos:
This is a very late response, but adds some detail on the previous answers
When it comes to calling static methods in PHP from another static method on the same class, it is important to differentiate between self
and the class name.
Take for instance this code:
class static_test_class {
public static function test() {
echo "Original class\n";
}
public static function run($use_self) {
if($use_self) {
self::test();
} else {
$class = get_called_class();
$class::test();
}
}
}
class extended_static_test_class extends static_test_class {
public static function test() {
echo "Extended class\n";
}
}
extended_static_test_class::run(true);
extended_static_test_class::run(false);
The output of this code is:
Original class
Extended class
This is because self
refers to the class the code is in, rather than the class of the code it is being called from.
If you want to use a method defined on a class which inherits the original class, you need to use something like:
$class = get_called_class();
$class::function_name();
Never mind, it's req.session.destroy();
Well, Instead of doing manual lint settings we can include all the lint settings at the top of our JS file itself e.g.
Declare all the global var in that file like:
/*global require,dojo,dojoConfig,alert */
Declare all the lint settings like:
/*jslint browser:true,sloppy:true,nomen:true,unparam:true,plusplus:true,indent:4 */
Hope this will help you :)
Your concrete example could be stored in long
(or java.lang.Long
if this is necessary).
If at any point you need bigger numbers, you can try
java.math.BigInteger
(if integer), or java.math.BigDecimal
(if decimal)
Well, note that the request contains binary data, so I'm not posting the request as such - instead, I've converted every non-printable-ascii character into a dot (".").
POST /cgi-bin/qtest HTTP/1.1
Host: aram
User-Agent: Mozilla/5.0 Gecko/2009042316 Firefox/3.0.10
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://aram/~martind/banner.htm
Content-Type: multipart/form-data; boundary=2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Length: 514
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile1"; filename="r.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile2"; filename="g.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile3"; filename="b.gif"
Content-Type: image/gif
GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f--
Note that every line (including the last one) is terminated by a \r\n sequence.
You have to put a closure around your actual constructor-function, where you can define your private methods. To change data of the instances through these private methods, you have to give them "this" with them, either as an function argument or by calling this function with .apply(this) :
var Restaurant = (function(){
var private_buy_food = function(that){
that.data.soldFood = true;
}
var private_take_a_shit = function(){
this.data.isdirty = true;
}
// New Closure
function restaurant()
{
this.data = {
isdirty : false,
soldFood: false,
};
}
restaurant.prototype.buy_food = function()
{
private_buy_food(this);
}
restaurant.prototype.use_restroom = function()
{
private_take_a_shit.call(this);
}
return restaurant;
})()
// TEST:
var McDonalds = new Restaurant();
McDonalds.buy_food();
McDonalds.use_restroom();
console.log(McDonalds);
console.log(McDonalds.__proto__);
I believe this is the Debian package 'bible'.
Well, it's the Debian new maintainer's guide, so a lot of it won't be applicable, but they do cover what goes where.
Can you use date as a factor?
Yes, but you probably shouldn't.
...or should you use
as.Date
on a date column?
Yes.
Which leads us to this:
library(scales)
df$Month <- as.Date(df$Month)
ggplot(df, aes(x = Month, y = AvgVisits)) +
geom_bar(stat = "identity") +
theme_bw() +
labs(x = "Month", y = "Average Visits per User") +
scale_x_date(labels = date_format("%m-%Y"))
in which I've added stat = "identity"
to your geom_bar
call.
In addition, the message about the binwidth wasn't an error. An error will actually say "Error" in it, and similarly a warning will always say "Warning" in it. Otherwise it's just a message.
I found the similar problem and found the solution and i have blogged about how to upload the file using JSP , In that example i have used the absolute path. Note that if you want to route to some other URL based location you can put a ESB like WSO2 ESB
You should add the ngDefaultControl attribute to your input like this:
<md-input
[(ngModel)]="recipient"
name="recipient"
placeholder="Name"
class="col-sm-4"
(blur)="addRecipient(recipient)"
ngDefaultControl>
</md-input>
Taken from comments in this post:
angular2 rc.5 custom input, No value accessor for form control with unspecified name
Note: For later versions of @angular/material:
Nowadays you should instead write:
<md-input-container>
<input
mdInput
[(ngModel)]="recipient"
name="recipient"
placeholder="Name"
(blur)="addRecipient(recipient)">
</md-input-container>
A bit late but this is a solution that worked for me. Perfect if your modal is inside the overlay tag. So, the modal will close when you click anywhere outside the modal content.
HTML
<div class="modal">
<div class="overlay">
<div class="modal-content">
<p>HELLO WORLD!</p>
</div>
</div>
</div>
JS
$(document).on("click", function(event) {
if ($(event.target).has(".modal-content").length) {
$(".modal").hide();
}
});
Here is a working example
CURRENT_DATE
and CURRENT_TIMESTAMP
return the current date and time in the session time zone.
SYSDATE
and SYSTIMESTAMP
return the system date and time - that is, of the system on which the database resides.
If your client session isn't in the same timezone as the server the database is on (or says it isn't anyway, via your NLS settings), mixing the SYS*
and CURRENT_*
functions will return different values. They are all correct, they just represent different things. It looks like your server is (or thinks it is) in a +4:00 timezone, while your client session is in a +4:30 timezone.
You might also see small differences in the time if the clocks aren't synchronised, which doesn't seem to be an issue here.
You can set the default authenticator for http requests like this:
Authenticator.setDefault (new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication ("username", "password".toCharArray());
}
});
Also, if you require more flexibility, you can check out the Apache HttpClient, which will give you more authentication options (as well as session support, etc.)
To convert Hex strings to INT, I have used this in the past. It can be modified to convert any base to INT in fact (Octal, Binary, whatever)
Declare @Str varchar(200)
Set @str = 'F000BE1A'
Declare @ndx int
Set @ndx = Len(@str)
Declare @RunningTotal BigInt
Set @RunningTotal = 0
While @ndx > 0
Begin
Declare @Exponent BigInt
Set @Exponent = Len(@Str) - @ndx
Set @RunningTotal = @RunningTotal +
Power(16 * 1.0, @Exponent) *
Case Substring(@str, @ndx, 1)
When '0' then 0
When '1' then 1
When '2' then 2
When '3' then 3
When '4' then 4
When '5' then 5
When '6' then 6
When '7' then 7
When '8' then 8
When '9' then 9
When 'A' then 10
When 'B' then 11
When 'C' then 12
When 'D' then 13
When 'E' then 14
When 'F' then 15
End
Set @ndx = @ndx - 1
End
Print @RunningTotal
Use line-height:30px
for the span so that text is align with the image:
<div>
<img style="width:30px; height:30px;">
<span style="line-height:30px;">Doesn't work.</span>
</div>
= f.input_field :title, as: :hidden, value: "some value"
Is also an option. Note, however, that it skips any wrapper defined for your form builder.
document.getElementById('leaveCode').value = '10';
That should set the selection to "Annual Leave"
apache-tomcat-8.0.33
If you want to enable debug logging in tomcat for TLD scanned jars then you have to change /conf/logging.properties file in tomcat directory.
uncomment the line :
org.apache.jasper.servlet.TldScanner.level = FINE
FINE level is for debug log.
This should work for normal tomcat.
If the tomcat is running under eclipse. Then you have to set the path of tomcat logging.properties in eclipse.
Now the jar files that scanned for TLDs should show in the log.
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
public sealed class BooleanToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var flag = false;
if (value is bool)
{
flag = (bool)value;
}
else if (value is bool?)
{
var nullable = (bool?)value;
flag = nullable.GetValueOrDefault();
}
if (parameter != null)
{
if (bool.Parse((string)parameter))
{
flag = !flag;
}
}
if (flag)
{
return Visibility.Visible;
}
else
{
return Visibility.Collapsed;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var back = ((value is Visibility) && (((Visibility)value) == Visibility.Visible));
if (parameter != null)
{
if ((bool)parameter)
{
back = !back;
}
}
return back;
}
}
and then pass a true or false as the ConverterParameter
<Grid.Visibility>
<Binding Path="IsYesNoButtonSetVisible" Converter="{StaticResource booleanToVisibilityConverter}" ConverterParameter="true"/>
</Grid.Visibility>
I found that mounting a local volume over /tmp can cause permission issues when the "apt-get update" runs, which prevents the package cache from being populated. Hopefully, this isn't something most people do, but it's something else to look for if you see this issue.
In my case TLS1_2 was enabled both on client and server but the server was using MD5 while client disabled it. So, test both client and server on http://ssllabs.com or test using openssl/s_client to see what's happening. Also, check the selected cipher using Wireshark.
There is a difference between find
and find_by
in that find
will return an error if not found, whereas find_by
will return null.
Sometimes it is easier to read if you have a method like find_by email: "haha"
, as opposed to .where(email: some_params).first
.
substring(field, 1,3) will work on your examples.
select substring(field, 1,3) from table
Also, if the alphabetic part is of variable length, you can do this to extract the alphabetic part:
select substring(field, 1, PATINDEX('%[1234567890]%', field) -1)
from table
where PATINDEX('%[1234567890]%', field) > 0
<ComboBox Text="Something">
<ComboBoxItem Content="Item1"></ComboBoxItem >
<ComboBoxItem Content="Item2"></ComboBoxItem >
<ComboBoxItem Content="Item3"></ComboBoxItem >
</ComboBox>
The easiest method to install Android Studio (or any other developer tool) on Ubuntu is to use the snap package from Ubuntu Software store. No need to download Android Studio as zip, try to manually install it, add PPAs or fiddle with Java installation. The snap package bundles the latest Android Studio along with OpenJDK and all the necessary dependencies.
Search "android studio" in Ubuntu Software, select the first entry that shows up and install it:
Or if you prefer the command line way, run this in Terminal:
sudo snap install --classic android-studio
Open the newly installed Android Studio from dashboard:
Don't need to import anything if this is the first time you're installing it:
The Setup Wizard'll guide you through installation:
Select Standard install to get the latest SDK and Custom in-case you wanna change the SDK version or its install location. From here on, it's pretty straightforward, just click next-next and you'll have the SDK downloaded and installed.
This step might be useful if you want Android SDK's developer tool commands like adb, fastboot, aapt, etc available in Terminal. Might be needed by 3rd party dev platforms like React Native, Ionic, Cordova, etc and other tools too. For setting PATHs, edit your ~/.profile
file:
gedit ~/.profile
and then add the following lines to it:
# Android SDK Tools PATH
export ANDROID_HOME=${HOME}/Android/Sdk
export PATH="${ANDROID_HOME}/tools:${PATH}"
export PATH="${ANDROID_HOME}/emulator:${PATH}"
export PATH="${ANDROID_HOME}/platform-tools:${PATH}"
If you changed SDK location at the end of Step 2, don't forget to change the line export ANDROID_HOME=${HOME}/Android/Sdk
accordingly. Do a restart (or just logout and then log back in) for the PATHs to take effect.
Tested on Ubuntu 16.04LTS and above. Would work on 14.04LTS too if you install support for snap packages first.
Note: This question is similar to the AskUbuntu question "How to install Android Studio on Ubuntu?" and my answer equally applies. I'm reproducing my answer here to ensure a full complete answer exists rather than just a link.
Since nobody has added the obvious solution yet which works fine for two comparisons, I'll offer it:
if (foobar === foo || foobar === bar) {
//do something
}
And, if you have lots of values (perhaps hundreds or thousands), then I'd suggest making a Set as this makes very clean and simple comparison code and it's fast at runtime:
// pre-construct the Set
var tSet = new Set(["foo", "bar", "test1", "test2", "test3", ...]);
// test the Set at runtime
if (tSet.has(foobar)) {
// do something
}
For pre-ES6, you can get a Set polyfill of which there are many. One is described in this other answer.
Postgres hasn't implemented an equivalent to INSERT OR REPLACE
. From the ON CONFLICT
docs (emphasis mine):
It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.
Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE
applies more generally, since it lets you set new values based on preexisting data. For example:
INSERT INTO users (id, level)
VALUES (1, 0)
ON CONFLICT (id) DO UPDATE
SET level = users.level + 1;
This error usually means the file couldn't be found.
Can you see the file from the command line?
0x0d
).There's the TryParse method, which returns a bool indicating if the conversion was successful.
path is pointing to a subfolder under c:\Documents & Settings
That's right. ClickOnce applications
are installed under the profile of the user who installed them. Did you take the path that retrieving the info from the executing assembly gave you, and go check it out?
On windows Vista and Windows 7, you will find the ClickOnce cache here:
c:\users\username\AppData\Local\Apps\2.0\obfuscatedfoldername\obfuscatedfoldername
On Windows XP, you will find it here:
C:\Documents and Settings\username\LocalSettings\Apps\2.0\obfuscatedfoldername\obfuscatedfoldername
If the accepted answer isn't working right for you then you might try.
str.replace(new RegExp('\n','g'), '<br />')
It worked for me.
Check out here for dump. It seems there is a dump function in the library sqlite3.
How to fish and while using strict code. There are two prerequisite functions needed at the bottom of this post.
xml_add('before', id_('element_after'), '<span xmlns="http://www.w3.org/1999/xhtml">Some text.</span>');
xml_add('after', id_('element_before'), '<input type="text" xmlns="http://www.w3.org/1999/xhtml" />');
xml_add('inside', id_('element_parent'), '<input type="text" xmlns="http://www.w3.org/1999/xhtml" />');
Add multiple elements (namespace only needs to be on the parent element):
xml_add('inside', id_('element_parent'), '<div xmlns="http://www.w3.org/1999/xhtml"><input type="text" /><input type="button" /></div>');
Dynamic reusable code:
function id_(id) {return (document.getElementById(id)) ? document.getElementById(id) : false;}
function xml_add(pos, e, xml)
{
e = (typeof e == 'string' && id_(e)) ? id_(e) : e;
if (e.nodeName)
{
if (pos=='after') {e.parentNode.insertBefore(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true),e.nextSibling);}
else if (pos=='before') {e.parentNode.insertBefore(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true),e);}
else if (pos=='inside') {e.appendChild(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true));}
else if (pos=='replace') {e.parentNode.replaceChild(document.importNode(new DOMParser().parseFromString(xml,'application/xml').childNodes[0],true),e);}
//Add fragment and have it returned.
}
}
To create your custom log file, try this code
Mage::log('your debug message', null, 'yourlog_filename.log');
Refer this Answer
Button1.CssClass += " newClass";
This will not erase your original classes for that control. Try this, it should work.
In my case I needed to install the IIS URL rewrite module 2.0 because it is being used in the web.config and this was the first time running site on new machine.
Look at:
CMAKE_EXE_LINKER_FLAGS
CMAKE_MODULE_LINKER_FLAGS
CMAKE_SHARED_LINKER_FLAGS
CMAKE_STATIC_LINKER_FLAGS
Put your code in a method.
Try this:
public class MyClass {
public static void main(String[] args) {
UserInput input = new UserInput();
input.name();
}
}
Then "run" the class from your IDE
if you dont push your changes to git yet
git reset --soft HEAD~1
It will reset all the changes and revert to one commit back
If this is the last commit you made and you want to delete the file from local and remote repository try this :
git rm <file>
git commit --amend
or even better :
reset first
git reset --soft HEAD~1
reset the unwanted file
git reset HEAD path/to/unwanted_file
commit again
git commit -c ORIG_HEAD
Another solution from the manual:
Composer also respects a memory limit defined by the COMPOSER_MEMORY_LIMIT
environment variable:
COMPOSER_MEMORY_LIMIT=-1 composer.phar <...>
Or in my case
export COMPOSER_MEMORY_LIMIT=-1
composer <...>
I did remove integrated security ... my goal is to log onto a sql server using a connection string WITH active directory username / password. When I do that it always fails. Does not matter the format ... sam company\user ... upn [email protected] ... basic username.
For the following HTML document:
<html>
<body>
<a href="http://www.example.com">Example</a>
<a href="http://www.stackoverflow.com">SO</a>
</body>
</html>
The xpath query /html/body//a/@href
(or simply //a/@href
) will return:
http://www.example.com http://www.stackoverflow.com
To select a specific instance use /html/body//a[N]/@href
,
$ /html/body//a[2]/@href http://www.stackoverflow.com
To test for strings contained in the attribute and return the attribute itself place the check on the tag not on the attribute:
$ /html/body//a[contains(@href,'example')]/@href http://www.example.com
Mixing the two:
$ /html/body//a[contains(@href,'com')][2]/@href http://www.stackoverflow.com
While the following works well on firefox, it DOES NOT work on chrome and mobile browsers.
Content-Type: application/pdf
Content-Disposition: inline; filename="filename.pdf"
To fix the chrome & mobile browsers error, do the following:
Google PDF Viewer can be used as so:
<iframe src="http://docs.google.com/gview?url=http://example.com/path/to/my/directory/pdffile.pdf&embedded=true" frameborder="0"></iframe>
Get the system time in milliseconds at the beginning, and again at the end, and subtract.
To get the number of milliseconds since 1970 in POSIX you would write:
struct timeval tv;
gettimeofday(&tv, NULL);
return ((((unsigned long long)tv.tv_sec) * 1000) +
(((unsigned long long)tv.tv_usec) / 1000));
To get the number of milliseconds since 1601 on Windows you would write:
SYSTEMTIME systime;
FILETIME filetime;
GetSystemTime(&systime);
if (!SystemTimeToFileTime(&systime, &filetime))
return 0;
unsigned long long ns_since_1601;
ULARGE_INTEGER* ptr = (ULARGE_INTEGER*)&ns_since_1601;
// copy the result into the ULARGE_INTEGER; this is actually
// copying the result into the ns_since_1601 unsigned long long.
ptr->u.LowPart = filetime.dwLowDateTime;
ptr->u.HighPart = filetime.dwHighDateTime;
// Compute the number of milliseconds since 1601; we have to
// divide by 10,000, since the current value is the number of 100ns
// intervals since 1601, not ms.
return (ns_since_1601 / 10000);
If you cared to normalize the Windows answer so that it also returned the number of milliseconds since 1970, then you would have to adjust your answer by 11644473600000 milliseconds. But that isn't necessary if all you care about is the elapsed time.
The rules for new
are analogous to what happens when you initialize an object with automatic storage duration (although, because of vexing parse, the syntax can be slightly different).
If I say:
int my_int; // default-initialize ? indeterminate (non-class type)
Then my_int
has an indeterminate value, since it is a non-class type. Alternatively, I can value-initialize my_int
(which, for non-class types, zero-initializes) like this:
int my_int{}; // value-initialize ? zero-initialize (non-class type)
(Of course, I can't use ()
because that would be a function declaration, but int()
works the same as int{}
to construct a temporary.)
Whereas, for class types:
Thing my_thing; // default-initialize ? default ctor (class type)
Thing my_thing{}; // value-initialize ? default-initialize ? default ctor (class type)
The default constructor is called to create a Thing
, no exceptions.
So, the rules are more or less:
{}
) or default-initialized (without {}
). (There is some additional prior zeroing behavior with value-initialization, but the default constructor is always given the final say.){}
used?
These rules translate precisely to new
syntax, with the added rule that ()
can be substituted for {}
because new
is never parsed as a function declaration. So:
int* my_new_int = new int; // default-initialize ? indeterminate (non-class type)
Thing* my_new_thing = new Thing; // default-initialize ? default ctor (class type)
int* my_new_zeroed_int = new int(); // value-initialize ? zero-initialize (non-class type)
my_new_zeroed_int = new int{}; // ditto
my_new_thing = new Thing(); // value-initialize ? default-initialize ? default ctor (class type)
(This answer incorporates conceptual changes in C++11 that the top answer currently does not; notably, a new scalar or POD instance that would end up an with indeterminate value is now technically now default-initialized (which, for POD types, technically calls a trivial default constructor). While this does not cause much practical change in behavior, it does simplify the rules somewhat.)
Download and install Eclipse, and you're good to go.
http://www.eclipse.org/downloads/
Apple provides its own version of Java, so make sure it's up-to-date.
http://developer.apple.com/java/download/
Eclipse is an integrated development environment. It has many features, but the ones that are relevant for you at this stage is:
As you gain more experience, you'll start to appreciate the rest of its rich set of features.
Check this query, i created this query to check whether the check in date over lap with any reservation dates
SELECT * FROM tbl_ReservedRooms
WHERE NOT ('@checkindate' NOT BETWEEN fromdate AND todate
AND '@checkoutdate' NOT BETWEEN fromdate AND todate)
this will retrun the details which are overlaping , to get the not overlaping details then remove the 'NOT' from the query
Here's how to do it using default ACLs, at least under Linux.
First, you might need to enable ACL support on your filesystem. If you are using ext4 then it is already enabled. Other filesystems (e.g., ext3) need to be mounted with the acl
option. In that case, add the option to your /etc/fstab
. For example, if the directory is located on your root filesystem:
/dev/mapper/qz-root / ext3 errors=remount-ro,acl 0 1
Then remount it:
mount -oremount /
Now, use the following command to set the default ACL:
setfacl -dm u::rwx,g::rwx,o::r /shared/directory
All new files in /shared/directory
should now get the desired permissions. Of course, it also depends on the application creating the file. For example, most files won't be executable by anyone from the start (depending on the mode argument to the open(2) or creat(2) call), just like when using umask. Some utilities like cp
, tar
, and rsync
will try to preserve the permissions of the source file(s) which will mask out your default ACL if the source file was not group-writable.
Hope this helps!
We do all our enums like this when it comes to Rest/Json etc. It has the advantage that the error is human readable and also gives you the accepted value list. We are using a custom method MyEnum.fromString instead of MyEnum.valueOf, hope it helps.
public enum MyEnum {
A, B, C, D;
private static final Map<String, MyEnum> NAME_MAP = Stream.of(values())
.collect(Collectors.toMap(MyEnum::toString, Function.identity()));
public static MyEnum fromString(final String name) {
MyEnum myEnum = NAME_MAP.get(name);
if (null == myEnum) {
throw new IllegalArgumentException(String.format("'%s' has no corresponding value. Accepted values: %s", name, Arrays.asList(values())));
}
return myEnum;
}
}
so for example if you call
MyEnum value = MyEnum.fromString("X");
you'll get an IllegalArgumentException with the following message:
'X' has no corresponding value. Accepted values: [A, B, C, D]
you can change the IllegalArgumentException to a custom one.
As others already answered well, they both are interchangeable.
Nonetheless, it's worth mentioning that there could be a case where you may want to use the explicit statement, i.e. pointer != NULL
.
//when a Department selecting
$('#department_id').on('select2-selecting', function (e) {
console.log("Action Before Selected");
var deptid=e.choice.id;
var depttext=e.choice.text;
console.log("Department ID "+deptid);
console.log("Department Text "+depttext);
});
//when a Department removing
$('#department_id').on('select2-removing', function (e) {
console.log("Action Before Deleted");
var deptid=e.choice.id;
var depttext=e.choice.text;
console.log("Department ID "+deptid);
console.log("Department Text "+depttext);
});
Guessing that what you want to do, is call Files.lines(...) on a resource that comes from the classpath - possibly from within a jar.
Since Oracle convoluted the notion of when a Path is a Path by not making getResource return a usable path if it resides in a jar file, what you need to do is something like this:
Stream<String> stream = new BufferedReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream("/filename.txt"))).lines();
Same pdo error in sql query while trying to insert into database value from multidimential array:
$sql = "UPDATE test SET field=arr[$s][a] WHERE id = $id";
$sth = $db->prepare($sql);
$sth->execute();
Extracting array arr[$s][a]
from sql query, using instead variable containing it fixes the problem.
Using persistent homology to analyze your data set I get the following result (click to enlarge):
This is the 2D-version of the peak detection method described in this SO answer. The above figure simply shows 0-dimensional persistent homology classes sorted by persistence.
I did upscale the original dataset by a factor of 2 using scipy.misc.imresize(). However, note that I did consider the four paws as one dataset; splitting it into four would make the problem easier.
Methodology. The idea behind this quite simple: Consider the function graph of the function that assigns each pixel its level. It looks like this:
Now consider a water level at height 255 that continuously descents to lower levels. At local maxima islands pop up (birth). At saddle points two islands merge; we consider the lower island to be merged to the higher island (death). The so-called persistence diagram (of the 0-th dimensional homology classes, our islands) depicts death- over birth-values of all islands:
The persistence of an island is then the difference between the birth- and death-level; the vertical distance of a dot to the grey main diagonal. The figure labels the islands by decreasing persistence.
The very first picture shows the locations of births of the islands. This method not only gives the local maxima but also quantifies their "significance" by the above mentioned persistence. One would then filter out all islands with a too low persistence. However, in your example every island (i.e., every local maximum) is a peak you look for.
Python code can be found here.
You do not have to install something.
parseInt(req.params.year, 10);
should work properly.
console.log(typeof parseInt(req.params.year)); // returns 'number'
What is your output, if you use parseInt? is it still a string?
a = input('inter a number: ')
s = 0
if a == 1:
print a, 'is a prime'
else :
for i in range (2, a ):
if a%i == 0:
print a,' is not a prime number'
s = 'true'
break
if s == 0 : print a,' is a prime number'
it worked with me just fine :D
This Works
function saveBase64AsFile(base64, fileName) {
var link = document.createElement("a");
document.body.appendChild(link);
link.setAttribute("type", "hidden");
link.href = "data:text/plain;base64," + base64;
link.download = fileName;
link.click();
document.body.removeChild(link);
}
Based on the answer above but with some changes
Use sorted()
with a key
as follows -
>>> unsorted_list = [['a','b','c','5','d'],['e','f','g','3','h'],['i','j','k','4','m']]
>>> sorted(unsorted_list, key = lambda x: int(x[3]))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]
The lambda
returns the fourth element of each of the inner lists and the sorted
function uses that to sort those list. This assumes that int(elem)
will not fail for the list.
Or use itemgetter
(As Ashwini's comment pointed out, this method would not work if you have string representations of the numbers, since they are bound to fail somewhere for 2+ digit numbers)
>>> from operator import itemgetter
>>> sorted(unsorted_list, key = itemgetter(3))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
formatter.setLenient(false);
try {
Date date= formatter.parse("02/03/2010");
} catch (ParseException e) {
//If input date is in different format or invalid.
}
formatter.setLenient(false) will enforce strict matching.
If you are using Joda-Time -
private boolean isValidDate(String dateOfBirth) {
boolean valid = true;
try {
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy");
DateTime dob = formatter.parseDateTime(dateOfBirth);
} catch (Exception e) {
valid = false;
}
return valid;
}
Try this:
$Wsdl = 'http://xxxx.xxx.xx/webservice3.asmx?WSDL';
libxml_disable_entity_loader(false); //adding this worked for me
$Client = new SoapClient($Wsdl);
//Code...
in my case, adding -lboost_system
was not enough, it still could not find it in my custom build environment. I had to use the advice at Get rid of "gcc - /usr/bin/ld: warning lib not found" and change my ./configure
command to:
./configure CXXFLAGS="-I$HOME/include" LDFLAGS="-L$HOME/lib -Wl,-rpath-link,$HOME/lib" --with-boost-libdir=$HOME/lib --prefix=$HOME
for more details see Boost 1.51 : "error: could not link against boost_thread !"
The best way is to use this line:
var mapUrl = "http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=16900+North+Bay+Road,+Sunny+Isles+Beach,+FL+33160&aq=0&sll=37.0625,-95.677068&sspn=61.282355,146.513672&ie=UTF8&hq=&hnear=16900+North+Bay+Road,+Sunny+Isles+Beach,+FL+33160&spn=0.01628,0.025663&z=14&iwloc=A&output=embed"
Remember to replace the first and second addresses when necessary.
By simplified sequence :
mydata[-(1:3 * 2), ]
By sequence :
mydata[seq(1, nrow(mydata), by = 2) , ]
By negative sequence :
mydata[-seq(2, nrow(mydata), by = 2) , ]
Or if you want to subset by selecting odd numbers:
mydata[which(1:nrow(mydata) %% 2 == 1) , ]
Or if you want to subset by selecting odd numbers, version 2:
mydata[which(1:nrow(mydata) %% 2 != 0) , ]
Or if you want to subset by filtering even numbers out:
mydata[!which(1:nrow(mydata) %% 2 == 0) , ]
Or if you want to subset by filtering even numbers out, version 2:
mydata[!which(1:nrow(mydata) %% 2 != 1) , ]
Or create a function that creates an element including attributes from parameters
function elemCreate(elType){
var element = document.createElement(elType);
if (arguments.length>1){
var props = [].slice.call(arguments,1), key = props.shift();
while (key){
element.setAttribute(key,props.shift());
key = props.shift();
}
}
return element;
}
// usage
var img = elemCreate('img',
'width','100',
'height','100',
'src','http://example.com/something.jpeg');
FYI: height/width='100%'
would not work using attributes. For a height/width of 100% you need the elements style.height/style.width
Swift solution:
yourConstraint.constant = 50
UIView.animate(withDuration: 1.0, animations: {
yourView.layoutIfNeeded
})
Use Array.prototype.filter
instead of forEach
:
var pre = document.getElementById('out');
function log(result) {
pre.appendChild(document.createTextNode(result + '\n'));
}
var review = ['a', 'b', 'c', 'b', 'a', 'e'];
review = review.filter(item => item !== 'a');
log(review);
editText.setRawInputType(InputType.TYPE_CLASS_NUMBER);
Usually, an Alpine Linux image doesn't contain bash
, Instead you can use /bin/ash
, /bin/sh
, ash
or only sh
.
/bin/ash
docker run -it --rm alpine /bin/ash
/bin/sh
docker run -it --rm alpine /bin/sh
ash
docker run -it --rm alpine ash
sh
docker run -it --rm alpine sh
I hope this information helps you.
Apparently --max-depth
option is not in Mac OS X's version of the du
command. You can use the following instead.
du -h -d 1 | sort -n
wget http://dag.wieers.com/packages/apt/apt-0.5.15lorg3.1-4.el4.rf.i386.rpm
rpm -ivh apt-0.5.15lorg3.1-4.el4.rf.i386.rpm
wget http://dag.wieers.com/packages/rpmforge-release/rpmforge-release-0.3.4-1.el4.rf.i386.rpm
rpm -Uvh rpmforge-release-0.3.4-1.el4.rf.i386.rpm
maybe some URL is broken,please research it. Enjoy~~
WorksheetFunction Transpose()
Instead of copying, pasting via PasteSpecial, and using the Transpose
option you can simply type a formula
=TRANSPOSE(Sheet1!A1:A5)
or if you prefer VBA:
Dim v
v = WorksheetFunction.Transpose(Sheet1.Range("A1:A5"))
Sheet2.Range("A1").Resize(1, UBound(v)) = v
Note: alternatively you could use late-bound Application.Transpose
instead.
MS help reference states that having a current version of Microsoft 365, one can simply input the formula in the top-left-cell of the target range, otherwise the formula must be entered as a legacy array formula via Ctrl+Shift+Enter to confirm it.
Versions Excel vers. 2007+, Mac since 2011, Excel for Microsoft 365
You need to set a -D system property called java.library.path
that points at the directory containing the sqljdbc_auth.dll
.
If you dig into NSInteger's implementation:
#if __LP64__
typedef long NSInteger;
#else
typedef int NSInteger;
#endif
Simply, the NSInteger typedef does a step for you: if the architecture is 32-bit, it uses int
, if it is 64-bit, it uses long
. Using NSInteger, you don't need to worry about the architecture that the program is running on.
I installed miniconda and found all the installed packages in /miniconda3/pkgs
For a non-volatile solution, how about for 2007+:
for cell =INDEX($A$1:$XFC$1048576,ROW(),COLUMN())
for column =INDEX($A$1:$XFC$1048576,0,COLUMN())
for row =INDEX($A$1:$XFC$1048576,ROW(),0)
I have weird bug on Excel 2010 where it won't accept the very last row or column for these formula (row 1048576 & column XFD), so you may need to reference these one short. Not sure if that's the same for any other versions so appreciate feedback and edit.
and for 2003 (INDEX became non-volatile in '97):
for cell =INDEX($A$1:$IV$65536,ROW(),COLUMN())
for column =INDEX($A$1:$IV$65536,0,COLUMN())
for row =INDEX($A$1:$IV$65536,ROW(),0)
Yes, you can!
$ ln -sfn source_file_or_directory_name softlink_name
ISNA is the best function to use. I just did. I wanted all cells whose value was NOT in an array to conditionally format to a certain color.
=ISNA(VLOOKUP($A2,Sheet1!$A:$D,2,FALSE))
add KexAlgorithms diffie-hellman-group1-sha1,diffie-hellman-group-exchange-sha??1 to your sshd_config on the server.
This worked, but make sure you restart sshd: sudo service sshd restart
Old thread, but just only to say: to use the classic Left()
, Right()
, Mid()
right now you don't need to write the full path (Microsoft.VisualBasic.Strings
). You can use fast and easily like this:
Strings.Right(yourString, 5)
I've found variants of System.IO.Path.Combine(myPath, "..")
to be the easiest and most reliable. Even more so if what northben says is true, that GetParent requires an extra call if there is a trailing slash. That, to me, is unreliable.
Path.Combine makes sure you never go wrong with slashes.
..
behaves exactly like it does everywhere else in Windows. You can add any number of \..
to a path in cmd or explorer and it will behave exactly as I describe below.
Some basic ..
behavior:
..
will chop that off:Path.Combine(@"D:\Grandparent\Parent\Child.txt", "..")
=> D:\Grandparent\Parent\
..
will move up a level:Path.Combine(@"D:\Grandparent\Parent\", "..")
=> D:\Grandparent\
..\..
follows the same rules, twice in a row:Path.Combine(@"D:\Grandparent\Parent\Child.txt", @"..\..")
=> D:\Grandparent\
Path.Combine(@"D:\Grandparent\Parent\", @"..\..")
=> D:\
Path.Combine(@"D:\Grandparent\Parent\Child.txt", "..", "..")
=> D:\Grandparent\
Path.Combine(@"D:\Grandparent\Parent\", "..", "..")
=> D:\
I think this would be more efficient:
function toBinString (arr) {
var uarr = new Uint8Array(arr.map(function(x){return parseInt(x,2)}));
var strings = [], chunksize = 0xffff;
// There is a maximum stack size. We cannot call String.fromCharCode with as many arguments as we want
for (var i=0; i*chunksize < uarr.length; i++){
strings.push(String.fromCharCode.apply(null, uarr.subarray(i*chunksize, (i+1)*chunksize)));
}
return strings.join('');
}
To replace the old version with the new one, you need to change the link for it. Type that command to terminal.
brew link --force openssl
Check the version of openssl again. It should be changed.
I recommend you watch the video Web Application Projects & Web Deployment Projects on the ASP.NET website which explains the difference in great detail, it was quite helpful to me.
By the way, don't get confused by the title, a great part of the video explains the difference between website projects and web application projects and why Microsoft re-introduced Web application projects in Visual studio 2005 (as you probably already know, it originally shipped with only website projects then web application projects were added in SP1). A great video I highly recommend for anyone who wants to know the difference.
Magic word is: isset
Validate the entry:
if(isset($manta_option['iso_format_recent_works']) && $manta_option['iso_format_recent_works'] == 1){
$theme_img = 'recent_works_thumbnail';
} else {
$theme_img = 'recent_works_iso_thumbnail';
}
Here is exp.
$date_search_strtotime = strtotime(date("Y-m-d"));
echo 'Now strtotime date : '.$date_search_strtotime;
echo '<br>';
echo 'Now date from strtotime : '.date('Y-m-d',$date_search_strtotime);
I've tried different solutions. First was:
a_df=np.unique(df[['col1','col2']], axis=0)
and it works well for not object data Another way to do this and to avoid error (for object columns type) is to apply drop_duplicates()
a_df=df.drop_duplicates(['col1','col2'])[['col1','col2']]
You can also use SQL to do this, but it worked very slow in my case:
from pandasql import sqldf
q="""SELECT DISTINCT col1, col2 FROM df;"""
pysqldf = lambda q: sqldf(q, globals())
a_df = pysqldf(q)
I used to write my own error logging until I discovered ELMAH. I've never been able to get the emailing part down quite as perfectly as ELMAH does.
You only need to add the following line
yourWebViewName.setWebViewClient(new WebViewClient());
Check this for official documentation.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.app"
tools:ignore="GoogleAppIndexingWarning">
You can remove the warning by adding xmlns:tools="http://schemas.android.com/tools"
and tools:ignore="GoogleAppIndexingWarning"
to the <manifest>
tag.
No luck with Code lens in Community editions.
Press Shift + F12 to find all references.
Must be used convert, not cast:
SELECT
CONVERT(varchar(50), N'æøåáälcçcédnoöruýtžš')
COLLATE Cyrillic_General_CI_AI
Completely removed from java 8 +
Partially removed from java 7 (interned Strings for example)
source
DECLARE
a VARCHAR2(30);
b VARCHAR2(30);
c VARCHAR2(30);
BEGIN
a := ' Abc ';
b := ' def ';
c := a || b;
DBMS_OUTPUT.PUT_LINE(c);
END;
output:: Abc def
System.Diagnostics.ProcessStartInfo psi =
new System.Diagnostics.ProcessStartInfo(@"program_to_call.exe");
psi.RedirectStandardOutput = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi); ////
System.IO.StreamReader myOutput = proc.StandardOutput;
proc.WaitForExit(2000);
if (proc.HasExited)
{
string output = myOutput.ReadToEnd();
}