As stated in the question:
To align flex items along the main axis there is one property:
justify-content
To align flex items along the cross axis there are three properties:
align-content
,align-items
andalign-self
.
The question then asks:
Why are there no
justify-items
andjustify-self
properties?
One answer may be: Because they're not necessary.
The flexbox specification provides two methods for aligning flex items along the main axis:
justify-content
keyword property, andauto
marginsjustify-content
The justify-content
property aligns flex items along the main axis of the flex container.
It is applied to the flex container but only affects flex items.
There are five alignment options:
flex-start
~ Flex items are packed toward the start of the line.
flex-end
~ Flex items are packed toward the end of the line.
center
~ Flex items are packed toward the center of the line.
space-between
~ Flex items are evenly spaced, with the first item aligned to one edge of the container and the last item aligned to the opposite edge. The edges used by the first and last items depends on flex-direction
and writing mode (ltr
or rtl
).
space-around
~ Same as space-between
except with half-size spaces on both ends.
With auto
margins, flex items can be centered, spaced away or packed into sub-groups.
Unlike justify-content
, which is applied to the flex container, auto
margins go on flex items.
They work by consuming all free space in the specified direction.
Scenario from the question:
making a group of flex items align-right (
justify-content: flex-end
) but have the first item align left (justify-self: flex-start
)Consider a header section with a group of nav items and a logo. With
justify-self
the logo could be aligned left while the nav items stay far right, and the whole thing adjusts smoothly ("flexes") to different screen sizes.
Other useful scenarios:
Scenario from the question:
- placing a flex item in a corner
.box { align-self: flex-end; justify-self: flex-end; }
margin: auto
is an alternative to justify-content: center
and align-items: center
.
Instead of this code on the flex container:
.container {
justify-content: center;
align-items: center;
}
You can use this on the flex item:
.box56 {
margin: auto;
}
This alternative is useful when centering a flex item that overflows the container.
A flex container aligns flex items by distributing free space.
Hence, in order to create equal balance, so that a middle item can be centered in the container with a single item alongside, a counterbalance must be introduced.
In the examples below, invisible third flex items (boxes 61 & 68) are introduced to balance out the "real" items (box 63 & 66).
Of course, this method is nothing great in terms of semantics.
Alternatively, you can use a pseudo-element instead of an actual DOM element. Or you can use absolute positioning. All three methods are covered here: Center and bottom-align flex items
NOTE: The examples above will only work – in terms of true centering – when the outermost items are equal height/width. When flex items are different lengths, see next example.
Scenario from the question:
in a row of three flex items, affix the middle item to the center of the container (
justify-content: center
) and align the adjacent items to the container edges (justify-self: flex-start
andjustify-self: flex-end
).Note that values
space-around
andspace-between
onjustify-content
property will not keep the middle item centered in relation to the container if the adjacent items have different widths (see demo).
As noted, unless all flex items are of equal width or height (depending on flex-direction
), the middle item cannot be truly centered. This problem makes a strong case for a justify-self
property (designed to handle the task, of course).
#container {_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
background-color: lightyellow;_x000D_
}_x000D_
.box {_x000D_
height: 50px;_x000D_
width: 75px;_x000D_
background-color: springgreen;_x000D_
}_x000D_
.box1 {_x000D_
width: 100px;_x000D_
}_x000D_
.box3 {_x000D_
width: 200px;_x000D_
}_x000D_
#center {_x000D_
text-align: center;_x000D_
margin-bottom: 5px;_x000D_
}_x000D_
#center > span {_x000D_
background-color: aqua;_x000D_
padding: 2px;_x000D_
}
_x000D_
<div id="center">_x000D_
<span>TRUE CENTER</span>_x000D_
</div>_x000D_
_x000D_
<div id="container">_x000D_
<div class="box box1"></div>_x000D_
<div class="box box2"></div>_x000D_
<div class="box box3"></div>_x000D_
</div>_x000D_
_x000D_
<p>The middle box will be truly centered only if adjacent boxes are equal width.</p>
_x000D_
Here are two methods for solving this problem:
Solution #1: Absolute Positioning
The flexbox spec allows for absolute positioning of flex items. This allows for the middle item to be perfectly centered regardless of the size of its siblings.
Just keep in mind that, like all absolutely positioned elements, the items are removed from the document flow. This means they don't take up space in the container and can overlap their siblings.
In the examples below, the middle item is centered with absolute positioning and the outer items remain in-flow. But the same layout can be achieved in reverse fashion: Center the middle item with justify-content: center
and absolutely position the outer items.
Solution #2: Nested Flex Containers (no absolute positioning)
.container {_x000D_
display: flex;_x000D_
}_x000D_
.box {_x000D_
flex: 1;_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
}_x000D_
.box71 > span { margin-right: auto; }_x000D_
.box73 > span { margin-left: auto; }_x000D_
_x000D_
/* non-essential */_x000D_
.box {_x000D_
align-items: center;_x000D_
border: 1px solid #ccc;_x000D_
background-color: lightgreen;_x000D_
height: 40px;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="box box71"><span>71 short</span></div>_x000D_
<div class="box box72"><span>72 centered</span></div>_x000D_
<div class="box box73"><span>73 loooooooooooooooong</span></div>_x000D_
</div>
_x000D_
Here's how it works:
.container
) is a flex container..box
) is now a flex item..box
item is given flex: 1
in order to distribute container space equally.justify-content: center
.span
element is a centered flex item.auto
margins to shift the outer span
s left and right.You could also forgo justify-content
and use auto
margins exclusively.
But justify-content
can work here because auto
margins always have priority. From the spec:
8.1. Aligning with
auto
marginsPrior to alignment via
justify-content
andalign-self
, any positive free space is distributed to auto margins in that dimension.
justify-content: space-same (concept)
Going back to justify-content
for a minute, here's an idea for one more option.
space-same
~ A hybrid of space-between
and space-around
. Flex items are evenly spaced (like space-between
), except instead of half-size spaces on both ends (like space-around
), there are full-size spaces on both ends.This layout can be achieved with ::before
and ::after
pseudo-elements on the flex container.
(credit: @oriol for the code, and @crl for the label)
UPDATE: Browsers have begun implementing space-evenly
, which accomplishes the above. See this post for details: Equal space between flex items
PLAYGROUND (includes code for all examples above)
numpy.linspace()
gives you a one-dimensional NumPy array. For example:
>>> my_array = numpy.linspace(1, 10, 10)
>>> my_array
array([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
Therefore:
for index,point in my_array
cannot work. You would need some kind of two-dimensional array with two elements in the second dimension:
>>> two_d = numpy.array([[1, 2], [4, 5]])
>>> two_d
array([[1, 2], [4, 5]])
Now you can do this:
>>> for x, y in two_d:
print(x, y)
1 2
4 5
Here is the answer in Razor syntax
<table border="1" cellpadding="5">
<thead>
<tr>
@foreach (System.Data.DataColumn col in Model.Columns)
{
<th>@col.Caption</th>
}
</tr>
</thead>
<tbody>
@foreach(System.Data.DataRow row in Model.Rows)
{
<tr>
@foreach (var cell in row.ItemArray)
{
<td>@cell.ToString()</td>
}
</tr>
}
</tbody>
</table>
When you read()
the file, you may get a newline character '\n'
in your string. Try either
if UserInput.strip() == 'List contents':
or
if 'List contents' in UserInput:
Also note that your second file open
could also use with
:
with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile: if UserInput.strip() == 'List contents': # or if s in f: UserInputFile.write("ls") else: print "Didn't work"
I've wrote a small extension to do so.
Since you are creating the page using C# you may want to implement this:
https://github.com/felix-d-git/DesktopAppLink
Basically u are creating some registry entries to parse the links you click in your html page.
The browser will then ask to open the specified app.
C#:
DesktopAppLink.CreateLink("applink.sample", "\"<path to exe>\"", "");
HTML:
<a href="applink.sample:">Run Desktop App</a>
Result:
Your problem is that, if the user clicks cancel, operationType
is null and thus throws a NullPointerException. I would suggest that you move
if (operationType.equalsIgnoreCase("Q"))
to the beginning of the group of if statements, and then change it to
if(operationType==null||operationType.equalsIgnoreCase("Q")).
This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.
Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.
Don't create your own list - pytz
has a built-in set:
import pytz
set(pytz.all_timezones_set)
>>> {'Europe/Vienna', 'America/New_York', 'America/Argentina/Salta',..}
You can then apply a timezone:
import datetime
tz = pytz.timezone('Pacific/Johnston')
ct = datetime.datetime.now(tz=tz)
>>> ct.isoformat()
2017-01-13T11:29:22.601991-05:00
Or if you already have a datetime
object that is TZ aware (not naive):
# This timestamp is in UTC
my_ct = datetime.datetime.now(tz=pytz.UTC)
# Now convert it to another timezone
new_ct = my_ct.astimezone(tz)
>>> new_ct.isoformat()
2017-01-13T11:29:22.601991-05:00
Just write like this:
<asp:TextBox ID="TextBox1" runat="server" placeholder="hi test"></asp:TextBox>
I like to use: ArgumentException
, ArgumentNullException
, and ArgumentOutOfRangeException
.
ArgumentException
– Something is wrong with the argument.ArgumentNullException
– Argument is null.ArgumentOutOfRangeException
– I don’t use this one much, but a common use is indexing into a collection, and giving an index which is to large.There are other options, too, that do not focus so much on the argument itself, but rather judge the call as a whole:
InvalidOperationException
– The argument might be OK, but not in the current state of the object. Credit goes to STW (previously Yoooder). Vote his answer up as well.NotSupportedException
– The arguments passed in are valid, but just not supported in this implementation. Imagine an FTP client, and you pass a command in that the client doesn’t support.The trick is to throw the exception that best expresses why the method cannot be called the way it is. Ideally, the exception should be detailed about what went wrong, why it is wrong, and how to fix it.
I love when error messages point to help, documentation, or other resources. For example, Microsoft did a good first step with their KB articles, e.g. “Why do I receive an "Operation aborted" error message when I visit a Web page in Internet Explorer?”. When you encounter the error, they point you to the KB article in the error message. What they don’t do well is that they don’t tell you, why specifically it failed.
Thanks to STW (ex Yoooder) again for the comments.
In response to your followup, I would throw an ArgumentOutOfRangeException
. Look at what MSDN says about this exception:
ArgumentOutOfRangeException
is thrown when a method is invoked and at least one of the arguments passed to the method is not null reference (Nothing
in Visual Basic) and does not contain a valid value.
So, in this case, you are passing a value, but that is not a valid value, since your range is 1–12. However, the way you document it makes it clear, what your API throws. Because although I might say ArgumentOutOfRangeException
, another developer might say ArgumentException
. Make it easy and document the behavior.
If you run pub build --mode=debug
the build directory contains the application without symlinks. The Dart code should be retained when --mode=debug
is used.
Here is some discussion going on about this topic too Dart and it's place in Rails Assets Pipeline
The trick here is that the ToolTip control is an extender control, which means that it will extend the set of properties for other controls on the form. Behind the scenes this is achieved by generating code like in Svetlozar's answer. There are other controls working in the same manner (such as the HelpProvider
).
you can use from windows task scheduler for this purpose, there are many libraries like TaskScheduler that help you.
for example consider we want to scheduling a task that will executes once five seconds later:
using (var ts = new TaskService())
{
var t = ts.Execute("notepad.exe")
.Once()
.Starting(DateTime.Now.AddSeconds(5))
.AsTask("myTask");
}
notepad.exe will be executed five seconds later.
for details and more information please go to wiki
if you know which class and method in that assembly you need, you can invoke it yourself like this:
Assembly assembly = Assembly.LoadFrom("yourApp.exe");
Type[] types = assembly.GetTypes();
foreach (Type t in types)
{
if (t.Name == "YourClass")
{
MethodInfo method = t.GetMethod("YourMethod",
BindingFlags.Public | BindingFlags.Instance);
if (method != null)
{
ParameterInfo[] parameters = method.GetParameters();
object classInstance = Activator.CreateInstance(t, null);
var result = method.Invoke(classInstance, parameters.Length == 0 ? null : parameters);
break;
}
}
}
Add:
DELIMITER
at the beginning and end of the SP.validar_egreso
; at the beginning@variableName
.This works for me. (I modified some part of your script so ANYONE can run it with out having your tables).
DROP PROCEDURE IF EXISTS `validar_egreso`;
DELIMITER $$
CREATE DEFINER='root'@'localhost' PROCEDURE `validar_egreso` (
IN codigo_producto VARCHAR(100),
IN cantidad INT,
OUT valido INT(11)
)
BEGIN
DECLARE resta INT;
SET resta = 0;
SELECT (codigo_producto - cantidad) INTO resta;
IF(resta > 1) THEN
SET valido = 1;
ELSE
SET valido = -1;
END IF;
SELECT valido;
END $$
DELIMITER ;
-- execute the stored procedure
CALL validar_egreso(4, 1, @val);
-- display the result
select @val;
You are passing a target array of shape (x-dim, y-dim) while using as loss categorical_crossentropy
. categorical_crossentropy
expects targets to be binary matrices (1s and 0s) of shape (samples, classes). If your targets are integer classes, you can convert them to the expected format via:
from keras.utils import to_categorical
y_binary = to_categorical(y_int)
Alternatively, you can use the loss function sparse_categorical_crossentropy
instead, which does expect integer targets.
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
Swift 3.0
Simplest solution which will give you indexPath for visible cells..
yourCollectionView.indexPathsForVisibleItems
will return the array of indexpath.
Just take the first object from array like this.
yourCollectionView.indexPathsForVisibleItems.first
I guess it should work fine with Objective - C as well.
While former answer is absolutely correct, I prefer using the JOIN ON
syntax to be sure that I know how do I join and on what fields. It would look something like this:
SELECT bc.firstname, bc.lastname, b.title, TO_CHAR(bo.orderdate, 'MM/DD/YYYY') "Order Date", p.publishername
FROM books b
JOIN book_customer bc ON bc.costumer_id = b.book_id
LEFT JOIN book_order bo ON bo.book_id = b.book_id
(etc.)
WHERE b.publishername = 'PRINTING IS US';
This syntax seperates completely the WHERE
clause from the JOIN
clause, making the statement more readable and easier for you to debug.
I've SSL on Apache2.4.4 and executing this code at first, did the trick:
set OPENSSL_CONF=C:\wamp\bin\apache\Apache2.4.4\conf\openssl.cnf
then execute the rest codes..
I am trying to set a JPanel's background using an image, however, every example I find seems to suggest extending the panel with its own class
yes you will have to extend JPanel
and override the paintcomponent(Graphics g)
function to do so.
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bgImage, 0, 0, null);
}
I have been looking for a way to simply add the image without creating a whole new class and within the same method (trying to keep things organized and simple).
You can use other component which allows to add image as icon directly e.g. JLabel
if you want.
ImageIcon icon = new ImageIcon(imgURL);
JLabel thumb = new JLabel();
thumb.setIcon(icon);
But again in the bracket trying to keep things organized and simple !! what makes you to think that just creating a new class will lead you to a messy world ?
When I experienced this error in Visual Studio,
“A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)”
...it was during the execution of the following C# code, which was attempting to obtain my SQL Server data to display it in a grid. The break occurred exactly on the line that says connect.Open():
using (var connect = Connections.mySqlConnection)
{
const string query = "SELECT Name, Birthdate, Narrative FROM Friends";
using (var command = new SqlCommand(query, connect))
{
connect.Open();
using (var dr = command.ExecuteReader())
{
while (dr.Read())
{
// blah
}
}
}
}
It was inexplicable because the SQL query was very simple, I had the right connection string, and the database server was available. I decided to run the actual SQL query manually myself in SQL Management Studio and it ran just fine and yielded several records. But one thing stood out in the query results: there was some improperly encoded HTML text inside a varchar(max) type field within the Friends table (specifically, some encoded comment symbols of the sort <!--
lodged within the "Narrative" column's data). The suspect data row looked like this:
Name Birthdate Narrative
==== ========= ==============
Fred 21-Oct-79 <!--HTML Comment -->Once upon a time...
Notice the encoded HTML symbol "<
", which stood for a "<" character. Somehow that made its way into the database and my C# code could not pick it up! It failed everytime right at the connect.Open() line! After I manually edited that one row of data in the database table Friends and put in the decoded "<" character instead, everything worked! Here's what that row should have looked like:
Name Birthdate Narrative
==== ========= ==============
Fred 21-Oct-79 <!--HTML Comment -->Once upon a time...
I edited the one bad row I had by using this simple UPDATE statement below. But if you had several offending rows of encoded HTML, you might need a more elaborate UPDATE statement that uses the REPLACE function:
UPDATE Friends SET Narrative = '<!--HTML Comment -->Once upon a time...' WHERE Narrative LIKE '<%'
So, the moral of the story is (at least in my case), sanitize your HTML content before storing it in the database and you won't get this cryptic SQL Server error in the first place! (Uh, properly sanitizing/decoding your HTML content is the subject of another discussion worthy of a separate StackOverflow search if you need more information!)
My menu is not a navbar standard one, but i managed to auto collapse mine, using an "onclick" function and a ".click()".
<div class="main-header">
<div class="container">
<div id="menu-wrapper">
<div class="row">
<div class="logo-wrapper col-lg-4 col-md-6 col-sm-7 hidden-xs">
</div> <!-- /.logo-wrapper -->
<div class="logo-wrapper2 visible-xs col-xs-9">
</div> <!-- /.smaller logo-wrapper -->
<div class="col-lg-8 col-md-6 col-sm-5 col-xs-3 main-menu text-center">
<ul class="menu-first hidden-md hidden-sm hidden-xs">
<li class="active"><a href="#">item1</a></li> |
<li><a href="#our-team">item2</a></li> |
<li><a href="#services">item3</a></li> |
<li><a href="#elia">item4</a></li> |
<li><a href="#portfolio">item5</a></li> |
<li><a href="#contact">item6</a></li>
</ul>
<a href="#" class="toggle-menu visible-md visible-sm visible-xs"><i class="fa fa-bars"></i></a>
</div> <!-- /.main-menu -->
</div> <!-- /.row -->
</div> <!-- /#menu-wrapper -->
<div class="menu-responsive hidden-lg">
<ul>
<li class="active" onclick = $(".toggle-menu").click();><a href="#">item1</a></li>
<li><a href="#our-team" onclick = $(".toggle-menu").click();>item2</a></li>
<li><a href="#services" onclick = $(".toggle-menu").click();>item3</a></li>
<li><a href="#elia" onclick = $(".toggle-menu").click();>item4</a></li>
<li><a href="#portfolio" onclick = $(".toggle-menu").click();>item5</a></li>
<li><a href="#contact" onclick = $(".toggle-menu").click();>item6</a></li>
</ul>
</div> <!-- /.menu-responsive -->
</div> <!-- /.container -->
</div> <!-- /.main-header
You have the syntax wrong; there is no need to place a period inside a double-quoted string. Instead, it should be more like
$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$prefix%'");
You can confirm this by printing out the string to see that it turns out identical to the first case.
Of course it's not a good idea to simply inject variables into the query string like this because of the danger of SQL injection. At the very least you should manually escape the contents of the variable with mysql_real_escape_string
, which would make it look perhaps like this:
$sql = sprintf("SELECT * FROM table WHERE the_number LIKE '%s%%'",
mysql_real_escape_string($prefix));
$query = mysql_query($sql);
Note that inside the first argument of sprintf
the percent sign needs to be doubled to end up appearing once in the result.
Recently I've been in a trouble with Visual Studio 2012 with same error description: "The process cannot access the file because it is being used by another process..."
To fix this first of all you need to understand the application which still use it. I've shutdown all processes like "MSBuild" and "MSBuild host". But this is not enough. If you have installed "Code Contracts" and turned on then it sometimes takes your DLLs for checking and hanging up on this operation.
So, you need to stop all processes of "CCCheck.exe" and that's all.
Finally, to understand that process is using your DLL you always may try to just Delete "obj" folder in your File Manager and this operation will fail, you may see the "Message Window" with description of the hanging operation. Also, as a variant, you can try to use "Sys Internals Suite" application.
From django docs:
render() is the same as a call to render_to_response() with a context_instance argument that that forces the use of a RequestContext.
direct_to_template
is something different. It's a generic view that uses a data dictionary to render the html without the need of the views.py, you use it in urls.py. Docs here
>>> dict2 = dict1
# dict2 is bind to the same Dict object which binds to dict1, so if you modify dict2, you will modify the dict1
There are many ways to copy Dict object, I simply use
dict_1 = {
'a':1,
'b':2
}
dict_2 = {}
dict_2.update(dict_1)
These are the default settings I have for /etc/network/interfaces (including WiFi settings) for my Raspberry Pi 1:
auto lo
iface lo inet loopback
iface eth0 inet dhcp
allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp
A few things I've noted:
For more information (and a great usage example) refer to the LunarLander project in the SDK 's examples section.
Instead of:
input:not(disabled)not:[type="submit"]:focus {}
Use:
input:not([disabled]):not([type="submit"]):focus {}
disabled
is an attribute so it needs the brackets, and you seem to have mixed up/missing colons and parentheses on the :not()
selector.
Demo: http://jsfiddle.net/HSKPx/
One thing to note: I may be wrong, but I don't think disabled
inputs can normally receive focus, so that part may be redundant.
Alternatively, use :enabled
input:enabled:not([type="submit"]):focus { /* styles here */ }
Again, I can't think of a case where disabled input can receive focus, so it seems unnecessary.
JKALAVIS solution is good, however I would add an improvement to use shlex instead of SHELL=TRUE. below im grepping out Query times
#!/bin/python
import subprocess
import shlex
cmd = "dig @8.8.4.4 +notcp www.google.com|grep 'Query'"
ps = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
output = ps.communicate()[0]
print(output)
CoolGoose's solution is good but this is faster for large files (as it only tries to read 1 byte):
if (false === file_get_contents("http://example.com/path/to/image",0,null,0,1)) {
$image = $default_image;
}
The problem with joining subsequent sample points together with disjoint "curveTo" type functions, is that where the curves meet is not smooth. This is because the two curves share an end point but are influenced by completely disjoint control points. One solution is to "curve to" the midpoints between the next 2 subsequent sample points. Joining the curves using these new interpolated points gives a smooth transition at the end points (what is an end point for one iteration becomes a control point for the next iteration.) In other words the two disjointed curves have much more in common now.
This solution was extracted out of the book "Foundation ActionScript 3.0 Animation: Making things move". p.95 - rendering techniques: creating multiple curves.
Note: this solution does not actually draw through each of the points, which was the title of my question (rather it approximates the curve through the sample points but never goes through the sample points), but for my purposes (a drawing application), it's good enough for me and visually you can't tell the difference. There is a solution to go through all the sample points, but it is much more complicated (see http://www.cartogrammar.com/blog/actionscript-curves-update/)
Here is the the drawing code for the approximation method:
// move to the first point
ctx.moveTo(points[0].x, points[0].y);
for (i = 1; i < points.length - 2; i ++)
{
var xc = (points[i].x + points[i + 1].x) / 2;
var yc = (points[i].y + points[i + 1].y) / 2;
ctx.quadraticCurveTo(points[i].x, points[i].y, xc, yc);
}
// curve through the last two points
ctx.quadraticCurveTo(points[i].x, points[i].y, points[i+1].x,points[i+1].y);
Don't get me wrong, but you can do this way ;)
function nagitive_check($value){
if (isset($value)){
if (substr(strval($value), 0, 1) == "-"){
return 'It is negative<br>';
} else {
return 'It is not negative!<br>';
}
}
}
Output:
echo nagitive_check(-100); // It is negative
echo nagitive_check(200); // It is not negative!
echo nagitive_check(200-300); // It is negative
echo nagitive_check(200-300+1000); // It is not negative!
Starting from Java 9, you can use either of following
List.of("val1", "val2", "val3").contains(str.toLowerCase())
Set.of("val1", "val2", "val3").contains(str.toLowerCase());
That's only a convention. The Javascript language does not give any special meaning to identifiers starting with underscore characters.
That said, it's quite a useful convention for a language that doesn't support encapsulation out of the box. Although there is no way to prevent someone from abusing your classes' implementations, at least it does clarify your intent, and documents such behavior as being wrong in the first place.
My solution: a component that I'm using in my screens components (where I want a scroll to top).
import { useLayoutEffect } from 'react';
const ScrollToTop = () => {
useLayoutEffect(() => {
window.scrollTo(0, 0);
}, []);
return null;
};
export default ScrollToTop;
This preserves scroll position when going back. Using useEffect() was buggy for me, when going back the document would scroll to top and also had a blink effect when route was changed in an already scrolled document.
While @john-machin gives a good answer, it's not always the best approach. For example, it doesn't work on Python 3 unless you encode all of your inputs to the CSV writer. Also, it doesn't address the issue if the script wants to use sys.stdout as the stream.
I suggest instead setting the 'lineterminator' attribute when creating the writer:
import csv
import sys
doc = csv.writer(sys.stdout, lineterminator='\n')
doc.writerow('abc')
doc.writerow(range(3))
That example will work on Python 2 and Python 3 and won't produce the unwanted newline characters. Note, however, that it may produce undesirable newlines (omitting the LF character on Unix operating systems).
In most cases, however, I believe that behavior is preferable and more natural than treating all CSV as a binary format. I provide this answer as an alternative for your consideration.
Use AlertDialog.Builder :
AlertDialog alertDialog = new AlertDialog.Builder(this)
//set icon
.setIcon(android.R.drawable.ic_dialog_alert)
//set title
.setTitle("Are you sure to Exit")
//set message
.setMessage("Exiting will call finish() method")
//set positive button
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//set what would happen when positive button is clicked
finish();
}
})
//set negative button
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//set what should happen when negative button is clicked
Toast.makeText(getApplicationContext(),"Nothing Happened",Toast.LENGTH_LONG).show();
}
})
.show();
You will get the following output.
To view alert dialog tutorial use the link below.
I ran into this when checking on a null or empty string
if (x == NULL || x == '') {
changed it to
if (is.null(x) || x == '') {
When executable path has whitespace in system, call
#include<iostream>
using namespace std;
int main()
{
system("explorer C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe ");
system("pause");
return 0;
}
perldoc perlvar is the first place to check for any special-named Perl variable info.
Quoting:
@_
: Within a subroutine the array@_
contains the parameters passed to that subroutine.
More details can be found in perldoc perlsub (Perl subroutines) linked from the perlvar:
Any arguments passed in show up in the array
@_
.Therefore, if you called a function with two arguments, those would be stored in
$_[0]
and$_[1]
.The array
@_
is a local array, but its elements are aliases for the actual scalar parameters. In particular, if an element $_[0] is updated, the corresponding argument is updated (or an error occurs if it is not updatable).If an argument is an array or hash element which did not exist when the function was called, that element is created only when (and if) it is modified or a reference to it is taken. (Some earlier versions of Perl created the element whether or not the element was assigned to.) Assigning to the whole array @_ removes that aliasing, and does not update any arguments.
you make the use of the HTML Helper and have
@using(Html.BeginForm())
{
Username: <input type="text" name="username" /> <br />
Password: <input type="text" name="password" /> <br />
<input type="submit" value="Login">
<input type="submit" value="Create Account"/>
}
or use the Url helper
<form method="post" action="@Url.Action("MyAction", "MyController")" >
Html.BeginForm
has several (13) overrides where you can specify more information, for example, a normal use when uploading files is using:
@using(Html.BeginForm("myaction", "mycontroller", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
< ... >
}
If you don't specify any arguments, the Html.BeginForm()
will create a POST
form that points to your current controller and current action. As an example, let's say you have a controller called Posts
and an action called Delete
public ActionResult Delete(int id)
{
var model = db.GetPostById(id);
return View(model);
}
[HttpPost]
public ActionResult Delete(int id)
{
var model = db.GetPostById(id);
if(model != null)
db.DeletePost(id);
return RedirectToView("Index");
}
and your html page would be something like:
<h2>Are you sure you want to delete?</h2>
<p>The Post named <strong>@Model.Title</strong> will be deleted.</p>
@using(Html.BeginForm())
{
<input type="submit" class="btn btn-danger" value="Delete Post"/>
<text>or</text>
@Url.ActionLink("go to list", "Index")
}
<?php
$fh = fopen('filename.txt','r');
while ($line = fgets($fh)) {
// <... Do your work with the line ...>
// echo($line);
}
fclose($fh);
?>
This will give you a line by line read.. read the notes at php.net/fgets regarding the end of line issues with Macs.
You can use the following syntax:
#include <map>
std::map<char, char> my_map = {
{ 'A', '1' },
{ 'B', '2' },
{ 'C', '3' }
};
Here i am binding the gridview with dataset like this-
GVAnswer.DataSource = DS.Tables[0];
GVAnswer.DataBind();
Then after
Then we count the number of rows like this in the for loop
for (int i = 0; i < GVAnswer.Rows.Count; i++)
{
}
Then after we find the header we want make visible false
GVAnswer.HeaderRow.Cells[2].Visible = false;
then after we make the visibility false of that particular cell.
The complete code is give like this
public void FillGVAnswer(int QuestionID)
{
try
{
OBJClsQuestionAnswer = new ClsQuestionAnswer();
DS = new DataSet();
DS = OBJClsQuestionAnswer.GetAnswers(QuestionID);
GVAnswer.DataSource = DS.Tables[0];
GVAnswer.DataBind();
if (DS.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < GVAnswer.Rows.Count; i++)
{
GVAnswer.HeaderRow.Cells[2].Visible = false;
GVAnswer.HeaderRow.Cells[3].Visible = false;
GVAnswer.HeaderRow.Cells[6].Visible = false;
GVAnswer.HeaderRow.Cells[8].Visible = false;
GVAnswer.HeaderRow.Cells[10].Visible = false;
GVAnswer.HeaderRow.Cells[11].Visible = false;
//GVAnswer.Rows[i].Cells[1].Visible = false;
if (GVAnswer.Rows[i].Cells[4].Text == "T")
{
GVAnswer.Rows[i].Cells[4].Text = "Text";
}
else
{
GVAnswer.Rows[i].Cells[4].Text = "Image";
}
if (GVAnswer.Rows[i].Cells[5].Text == "View Image")
{
HtmlAnchor a = new HtmlAnchor();
a.HRef = "~/ImageHandler.aspx?ACT=AIMG&AID=" + GVAnswer.Rows[i].Cells[2].Text;
a.Attributes.Add("rel", "lightbox");
a.InnerText = GVAnswer.Rows[i].Cells[5].Text;
GVAnswer.Rows[i].Cells[5].Controls.Add(a);
}
if (GVAnswer.Rows[i].Cells[7].Text == "Yes")
{
j++;
ViewState["CheckHasMulAns"] = j;// To Chek How Many answer Of a particulaer Question Is Right
}
GVAnswer.Rows[i].Cells[8].Visible = false;
GVAnswer.Rows[i].Cells[3].Visible = false;
GVAnswer.Rows[i].Cells[10].Visible = false;
GVAnswer.Rows[i].Cells[6].Visible = false;
GVAnswer.Rows[i].Cells[11].Visible = false;
GVAnswer.Rows[i].Cells[2].Visible = false;
}
}
}
catch (Exception ex)
{
string err = ex.Message;
if (ex.InnerException != null)
{
err = err + " :: Inner Exception :- " + ex.InnerException.Message;
}
string addInfo = "Error in getting Answers :: -> ";
ClsExceptionPublisher objPub = new ClsExceptionPublisher();
objPub.Publish(err, addInfo);
}
}
This is a a recompilation of my 3 favorite answers on this board:
The results are an easy to use, and easily configurable function.
First argument can be a select object, the ID of a select object, or an array with at least 2 dimensions.
Second argument is optional. Defaults to sorting by option text, index 0. Can be passed any other index so sort on that. Can be passed 1, or the text "value", to sort by value.
sortSelect('select_object_id');
sortSelect('select_object_id', 0);
sortSelect(selectObject);
sortSelect(selectObject, 0);
sortSelect('select_object_id', 'value');
sortSelect('select_object_id', 1);
sortSelect(selectObject, 1);
var myArray = [
['ignored0', 'ignored1', 'Z-sortme2'],
['ignored0', 'ignored1', 'A-sortme2'],
['ignored0', 'ignored1', 'C-sortme2'],
];
sortSelect(myArray,2);
This last one will sort the array by index-2, the sortme's.
function sortSelect(selElem, sortVal) {
// Checks for an object or string. Uses string as ID.
switch(typeof selElem) {
case "string":
selElem = document.getElementById(selElem);
break;
case "object":
if(selElem==null) return false;
break;
default:
return false;
}
// Builds the options list.
var tmpAry = new Array();
for (var i=0;i<selElem.options.length;i++) {
tmpAry[i] = new Array();
tmpAry[i][0] = selElem.options[i].text;
tmpAry[i][1] = selElem.options[i].value;
}
// allows sortVal to be optional, defaults to text.
switch(sortVal) {
case "value": // sort by value
sortVal = 1;
break;
default: // sort by text
sortVal = 0;
}
tmpAry.sort(function(a, b) {
return a[sortVal] == b[sortVal] ? 0 : a[sortVal] < b[sortVal] ? -1 : 1;
});
// removes all options from the select.
while (selElem.options.length > 0) {
selElem.options[0] = null;
}
// recreates all options with the new order.
for (var i=0;i<tmpAry.length;i++) {
var op = new Option(tmpAry[i][0], tmpAry[i][1]);
selElem.options[i] = op;
}
return true;
}
Try this:
v=spf1 ip4:abc.de.fgh.ij ip4:klm.no.pqr.st ~all
You can also specify the TNS name in the JDBC URL as below
jdbc:oracle:thin:@(DESCRIPTION =(ADDRESS_LIST =(ADDRESS =(PROTOCOL=TCP)(HOST=blah.example.com)(PORT=1521)))(CONNECT_DATA=(SID=BLAHSID)(GLOBAL_NAME=BLAHSID.WORLD)(SERVER=DEDICATED)))
You don't need two JScrollPanes
.
Example:
JTextArea ta = new JTextArea();
JScrollPane sp = new JScrollPane(ta);
// Add the scroll pane into the content pane
JFrame f = new JFrame();
f.getContentPane().add(sp);
It seems that Go have special form of switch dedicate to this (it is called type switch):
func (e *Easy)SetOption(option Option, param interface{}) {
switch v := param.(type) {
default:
fmt.Printf("unexpected type %T", v)
case uint64:
e.code = Code(C.curl_wrapper_easy_setopt_long(e.curl, C.CURLoption(option), C.long(v)))
case string:
e.code = Code(C.curl_wrapper_easy_setopt_str(e.curl, C.CURLoption(option), C.CString(v)))
}
}
In modern browsers (IE8, Firefox, Chrome, Opera, Safari) you can use querySelector()
:
function test(el){
el.querySelector("#child").style.display = "none";
}
For older browsers (<=IE7), you would have to use some sort of library, such as Sizzle or a framework, such as jQuery, to work with selectors.
As mentioned, IDs are supposed to be unique within a document, so it's easiest to just use document.getElementById("child")
.
I suggest you to start with simple polynomial fit, scipy.optimize.curve_fit
tries to fit a function f
that you must know to a set of points.
This is a simple 3 degree polynomial fit using numpy.polyfit
and poly1d
, the first performs a least squares polynomial fit and the second calculates the new points:
import numpy as np
import matplotlib.pyplot as plt
points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
# get x and y vectors
x = points[:,0]
y = points[:,1]
# calculate polynomial
z = np.polyfit(x, y, 3)
f = np.poly1d(z)
# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)
plt.plot(x,y,'o', x_new, y_new)
plt.xlim([x[0]-1, x[-1] + 1 ])
plt.show()
int size = myHashSet.size();
int item = new Random().nextInt(size); // In real life, the Random object should be rather more shared than this
int i = 0;
for(Object obj : myhashSet)
{
if (i == item)
return obj;
i++;
}
Swift 5
Input your dictionary that you want to sort alphabetically by keys.
// Sort inputted dictionary with keys alphabetically.
func sortWithKeys(_ dict: [String: Any]) -> [String: Any] {
let sorted = dict.sorted(by: { $0.key < $1.key })
var newDict: [String: Any] = [:]
for sortedDict in sorted {
newDict[sortedDict.key] = sortedDict.value
}
return newDict
}
dict.sorted(by: { $0.key < $1.key }) by it self returns a tuple (value, value) instead of a dictionary [value: value]. Thus, the for loop parses the tuple to return as a dictionary. That way, you put in a dictionary & get a dictionary back.
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="empTable")
public class Employee implements Serializable{
private static final long serialVersionUID = 1L;
private int id;
private String empName;
List<Address> addList=new ArrayList<Address>();
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="emp_id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
@OneToMany(mappedBy="employee",cascade=CascadeType.ALL)
public List<Address> getAddList() {
return addList;
}
public void setAddList(List<Address> addList) {
this.addList = addList;
}
}
We have two entities Employee and Address with One to Many relationship.
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="address")
public class Address implements Serializable{
private static final long serialVersionUID = 1L;
private int address_id;
private String address;
Employee employee;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int getAddress_id() {
return address_id;
}
public void setAddress_id(int address_id) {
this.address_id = address_id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@ManyToOne
@JoinColumn(name="emp_id")
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
}
By this way we can implement inner join between two tables
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
public class Main {
public static void main(String[] args) {
saveEmployee();
retrieveEmployee();
}
private static void saveEmployee() {
Employee employee=new Employee();
Employee employee1=new Employee();
Employee employee2=new Employee();
Employee employee3=new Employee();
Address address=new Address();
Address address1=new Address();
Address address2=new Address();
Address address3=new Address();
address.setAddress("1485,Sector 42 b");
address1.setAddress("1485,Sector 42 c");
address2.setAddress("1485,Sector 42 d");
address3.setAddress("1485,Sector 42 a");
employee.setEmpName("Varun");
employee1.setEmpName("Krishan");
employee2.setEmpName("Aasif");
employee3.setEmpName("Dut");
address.setEmployee(employee);
address1.setEmployee(employee1);
address2.setEmployee(employee2);
address3.setEmployee(employee3);
employee.getAddList().add(address);
employee1.getAddList().add(address1);
employee2.getAddList().add(address2);
employee3.getAddList().add(address3);
Session session=HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(employee);
session.save(employee1);
session.save(employee2);
session.save(employee3);
session.getTransaction().commit();
session.close();
}
private static void retrieveEmployee() {
try{
String sqlQuery="select e from Employee e inner join e.addList";
Session session=HibernateUtil.getSessionFactory().openSession();
Query query=session.createQuery(sqlQuery);
List<Employee> list=query.list();
list.stream().forEach((p)->{System.out.println(p.getEmpName());});
session.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
I have used Java 8 for loop for priting the names. Make sure you have jdk 1.8 with tomcat 8. Also add some more records for better understanding.
public class HibernateUtil {
private static SessionFactory sessionFactory ;
static {
Configuration configuration = new Configuration();
configuration.addAnnotatedClass(Employee.class);
configuration.addAnnotatedClass(Address.class);
configuration.setProperty("connection.driver_class","com.mysql.jdbc.Driver");
configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernate");
configuration.setProperty("hibernate.connection.username", "root");
configuration.setProperty("hibernate.connection.password", "root");
configuration.setProperty("dialect", "org.hibernate.dialect.MySQLDialect");
configuration.setProperty("hibernate.hbm2ddl.auto", "update");
configuration.setProperty("hibernate.show_sql", "true");
configuration.setProperty(" hibernate.connection.pool_size", "10");
// configuration
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
I take this cost model as a reference:
http://scripts.mit.edu/~6.006/fall07/wiki/index.php?title=Python_Cost_Model
Your method of slicing the list and concatenating two sub-lists are linear-time operations. I would suggest using pop, which is a constant-time operation, e.g.:
def shift(list, n):
for i in range(n)
temp = list.pop()
list.insert(0, temp)
As far as I can tell there is no upper limit in 2008.
In SQL Server 2005 the code in your question fails on the assignment to the @GGMMsg
variable with
Attempting to grow LOB beyond maximum allowed size of 2,147,483,647 bytes.
the code below fails with
REPLICATE: The length of the result exceeds the length limit (2GB) of the target large type.
However it appears these limitations have quietly been lifted. On 2008
DECLARE @y VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),92681);
SET @y = REPLICATE(@y,92681);
SELECT LEN(@y)
Returns
8589767761
I ran this on my 32 bit desktop machine so this 8GB string is way in excess of addressable memory
Running
select internal_objects_alloc_page_count
from sys.dm_db_task_space_usage
WHERE session_id = @@spid
Returned
internal_objects_alloc_page_co
------------------------------
2144456
so I presume this all just gets stored in LOB
pages in tempdb
with no validation on length. The page count growth was all associated with the SET @y = REPLICATE(@y,92681);
statement. The initial variable assignment to @y
and the LEN
calculation did not increase this.
The reason for mentioning this is because the page count is hugely more than I was expecting. Assuming an 8KB page then this works out at 16.36 GB which is obviously more or less double what would seem to be necessary. I speculate that this is likely due to the inefficiency of the string concatenation operation needing to copy the entire huge string and append a chunk on to the end rather than being able to add to the end of the existing string. Unfortunately at the moment the .WRITE
method isn't supported for varchar(max) variables.
Addition
I've also tested the behaviour with concatenating nvarchar(max) + nvarchar(max)
and nvarchar(max) + varchar(max)
. Both of these allow the 2GB limit to be exceeded. Trying to then store the results of this in a table then fails however with the error message Attempting to grow LOB beyond maximum allowed size of 2147483647 bytes.
again. The script for that is below (may take a long time to run).
DECLARE @y1 VARCHAR(MAX) = REPLICATE(CAST('X' AS VARCHAR(MAX)),2147483647);
SET @y1 = @y1 + @y1;
SELECT LEN(@y1), DATALENGTH(@y1) /*4294967294, 4294967292*/
DECLARE @y2 NVARCHAR(MAX) = REPLICATE(CAST('X' AS NVARCHAR(MAX)),1073741823);
SET @y2 = @y2 + @y2;
SELECT LEN(@y2), DATALENGTH(@y2) /*2147483646, 4294967292*/
DECLARE @y3 NVARCHAR(MAX) = @y2 + @y1
SELECT LEN(@y3), DATALENGTH(@y3) /*6442450940, 12884901880*/
/*This attempt fails*/
SELECT @y1 y1, @y2 y2, @y3 y3
INTO Test
You could also use:
split=lambda x,n: x if not x else [x[:n]]+[split([] if not -(len(x)-n) else x[-(len(x)-n):],n)][0]
split([1,2,3,4,5,6,7,8,9],2)
[[1, 2], [3, 4], [5, 6], [7, 8], [9]]
My comment was deleted because I provided a link to a similar question I answered here. Ergo, I'll answer it more descriptively this time. Here goes.
You could do this easily by creating a CreateRoles
method in your startup
class. This helps check if the roles are created, and creates the roles if they aren't; on application startup. Like so.
private async Task CreateRoles(IServiceProvider serviceProvider)
{
//initializing custom roles
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
string[] roleNames = { "Admin", "Manager", "Member" };
IdentityResult roleResult;
foreach (var roleName in roleNames)
{
var roleExist = await RoleManager.RoleExistsAsync(roleName);
if (!roleExist)
{
//create the roles and seed them to the database: Question 1
roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
}
}
//Here you could create a super user who will maintain the web app
var poweruser = new ApplicationUser
{
UserName = Configuration["AppSettings:UserName"],
Email = Configuration["AppSettings:UserEmail"],
};
//Ensure you have these values in your appsettings.json file
string userPWD = Configuration["AppSettings:UserPassword"];
var _user = await UserManager.FindByEmailAsync(Configuration["AppSettings:AdminUserEmail"]);
if(_user == null)
{
var createPowerUser = await UserManager.CreateAsync(poweruser, userPWD);
if (createPowerUser.Succeeded)
{
//here we tie the new user to the role
await UserManager.AddToRoleAsync(poweruser, "Admin");
}
}
}
and then you could call the CreateRoles(serviceProvider).Wait();
method from the Configure
method in the Startup class.
ensure you have IServiceProvider
as a parameter in the Configure
class.
Using role-based authorization in a controller to filter user access: Question 2
You can do this easily, like so.
[Authorize(Roles="Manager")]
public class ManageController : Controller
{
//....
}
You can also use role-based authorization in the action method like so. Assign multiple roles, if you will
[Authorize(Roles="Admin, Manager")]
public IActionResult Index()
{
/*
.....
*/
}
While this works fine, for a much better practice, you might want to read about using policy based role checks. You can find it on the ASP.NET core documentation here, or this article I wrote about it here
The answer of Shyam was right. I already faced with this issue before. It's not a problem, it's a SPRING feature. "Transaction rolled back because it has been marked as rollback-only" is acceptable.
Conclusion
Let's me explain more detail:
Question: How many Transaction we have? Answer: Only one
Because you config the PROPAGATION is PROPAGATION_REQUIRED so that the @Transaction persist() is using the same transaction with the caller-processNextRegistrationMessage(). Actually, when we get an exception, the Spring will set rollBackOnly for the TransactionManager so the Spring will rollback just only one Transaction.
Question: But we have a try-catch outside (), why does it happen this exception? Answer Because of unique Transaction
Go to the catch outside
Spring will set the rollBackOnly to true -> it determine we must
rollback the caller (processNextRegistrationMessage) also.
The persist() will rollback itself first.
Question: Why we change PROPAGATION to REQUIRES_NEW, it works?
Answer: Because now the processNextRegistrationMessage() and persist() are in the different transaction so that they only rollback their transaction.
Thanks
You still haven't explained why you can't use a Float data type, so here is an example:
DECLARE @StringVal varchar(50)
SET @StringVal = '123456789.1234567'
SELECT @StringVal, CAST(@StringVal AS FLOAT)
SET @StringVal = '1.12345678'
SELECT @StringVal, CAST(@StringVal AS FLOAT)
SET @StringVal = '123456.1234'
SELECT @StringVal, CAST(@StringVal AS FLOAT)
List<string> myCollection = new List<string>()
{
"Bob", "Bob","Alex", "Abdi", "Abdi", "Bob", "Alex", "Bob","Abdi"
};
myCollection.Sort();
foreach (var name in myCollection.Distinct())
{
Console.WriteLine(name + " " + myCollection.Count(x=> x == name));
}
output: Abdi 3 Alex 2 Bob 4
Cprcrack's answer works very well for API levels 19 and under. Just a minor addition to cprcrack's onShowCustomView
will get it working on API level 21+
if (Build.VERSION.SDK_INT >= 21) {
videoViewContainer.setBackgroundColor(Color.BLACK);
((ViewGroup) webView.getParent()).addView(videoViewContainer);
webView.scrollTo(0,0); // centers full screen view
} else {
activityNonVideoView.setVisibility(View.INVISIBLE);
ViewGroup.LayoutParams vg = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
activityVideoView.addView(videoViewContainer,vg);
activityVideoView.setVisibility(View.VISIBLE);
}
You will also need to reflect the changes in onHideCustomView
An 'architect', very humble guy, you know the type, had the following:
#define retrun return
because he liked to type fast. The brain-surgeon used to like to shout at people who were smarter than him (which was pretty much everyone), and threaten to use his black-belt on them.
This may be a common problem for new users of Matplotlib to draw vertical and horizontal lines. In order to understand this problem, you should be aware that different coordinate systems exist in Matplotlib.
The method axhline and axvline are used to draw lines at the axes coordinate. In this coordinate system, coordinate for the bottom left point is (0,0), while the coordinate for the top right point is (1,1), regardless of the data range of your plot. Both the parameter xmin
and xmax
are in the range [0,1].
On the other hand, method hlines and vlines are used to draw lines at the data coordinate. The range for xmin
and xmax
are the in the range of data limit of x axis.
Let's take a concrete example,
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 100)
y = np.sin(x)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.axhline(y=0.5, xmin=0.0, xmax=1.0, color='r')
ax.hlines(y=0.6, xmin=0.0, xmax=1.0, color='b')
plt.show()
It will produce the following plot:
The value for xmin
and xmax
are the same for the axhline
and hlines
method. But the length of produced line is different.
I need to select every production with a category that doesn't contain "Business"
Although I upvoted @Arran's answer as correct, I would also add this... Strictly interpreted, the OP's specification would be implemented as
//production[category[not(contains(., 'Business'))]]
rather than
//production[not(contains(category, 'Business'))]
The latter selects every production whose first category
child doesn't contain "Business". The two XPath expressions will behave differently when a production
has no category
children, or more than one.
It doesn't make any difference in practice as long as every <production>
has exactly one <category>
child, as in your short example XML. Whether you can always count on that being true or not, depends on various factors, such as whether you have a schema that enforces that constraint. Personally, I would go for the more robust option, since it doesn't "cost" much... assuming your requirement as stated in the question is really correct (as opposed to e.g. 'select every production that doesn't have a category that contains "Business"').
In PostreSQL you can use SIMILAR TO operator (more):
-- only digits
select * from books where title similar to '^[0-9]*$';
-- start with digit
select * from books where title similar to '^[0-9]%$';
Check out the Magick++ API to ImageMagick.
Disclosure: I wrote FieldVal.
Here is a solution using FieldVal. By using FieldVal UI to build a form and then FieldVal to validate the input, you can pass the error straight back into the form.
You can even run the validation code on the backend (if you're using Node.js) and show the error in the form without wiring all of the fields up manually.
Live demo: http://codepen.io/MarcusLongmuir/pen/WbOydx
function validate_form(data) {
// This would work on the back end too (if you're using Node)
// Validate the provided data
var validator = new FieldVal(data);
validator.get("email", BasicVal.email(true));
validator.get("title", BasicVal.string(true));
validator.get("url", BasicVal.url(true));
return validator.end();
}
$(document).ready(function(){
// Create a form and add some fields
var form = new FVForm()
.add_field("email", new FVTextField("Email"))
.add_field("title", new FVTextField("Title"))
.add_field("url", new FVTextField("URL"))
.on_submit(function(value){
// Clear the existing errors
form.clear_errors();
// Use the function above to validate the input
var error = validate_form(value);
if (error) {
// Pass the error into the form
form.error(error);
} else {
// Use the data here
alert(JSON.stringify(value));
}
})
form.element.append(
$("<button/>").text("Submit")
).appendTo("body");
//Pre-populate the form
form.val({
"email": "[email protected]",
"title": "Your Title",
"url": "http://www.example.com"
})
});
Refer to RFC 6266 (Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)) http://tools.ietf.org/html/rfc6266
Why could you not just do something like this?
class Foo {
constructor(myObj){
Object.assign(this, myObj);
}
get name() { return this._name; }
set name(v) { this._name = v; }
}
let foo = new Foo({ name: "bat" });
foo.toJSON() //=> your json ...
Change HOME directory for this is wrong. Better is create symbolic link for gitconfig to HOME directory.
At least on 10.10.5, system_profiler SPUSBDataType
output is NOT
dynamically updated when a new USB device gets plugged in,
while ioreg -p IOUSB -l -w 0
does.
Use GetParent()
as shown, works nicely. Add error checking as you need.
var fn = openFileDialogSapTable.FileName;
var currentPath = Path.GetFullPath( fn );
currentPath = Directory.GetParent(currentPath).FullName;
WebSphere Application Server V7 does support Java Platform, Standard Edition (Java SE) 6 (see Specifications and API documentation in the Network Deployment (All operating systems), Version 7.0 Information Center) and it's since the release V8.5 when Java 7 has been supported.
I couldn't find the Java 6 SDK documentation, and could only consult IBM JVM Messages in Java 7 Windows documentation. Alas, I couldn't find the error message in the documentation either.
Since java.lang.UnsupportedClassVersionError is "Thrown when the Java Virtual Machine attempts to read a class file and determines that the major and minor version numbers in the file are not supported.", you ran into an issue of building the application with more recent version of Java than the one supported by the runtime environment, i.e. WebSphere Application Server 7.0.
I may be mistaken, but I think that offset=6 in the message is to let you know what position caused the incompatibility issue to occur. It's irrelevant for you, for me, and for many other people, but some might find it useful, esp. when they generate bytecode themselves.
Run the versionInfo command to find out about the Installed Features of WebSphere Application Server V7, e.g.
C:\IBM\WebSphere\AppServer>.\bin\versionInfo.bat
WVER0010I: Copyright (c) IBM Corporation 2002, 2005, 2008; All rights reserved.
WVER0012I: VersionInfo reporter version 1.15.1.47, dated 10/18/11
--------------------------------------------------------------------------------
IBM WebSphere Product Installation Status Report
--------------------------------------------------------------------------------
Report at date and time February 19, 2013 8:07:20 AM EST
Installation
--------------------------------------------------------------------------------
Product Directory C:\IBM\WebSphere\AppServer
Version Directory C:\IBM\WebSphere\AppServer\properties\version
DTD Directory C:\IBM\WebSphere\AppServer\properties\version\dtd
Log Directory C:\ProgramData\IBM\Installation Manager\logs
Product List
--------------------------------------------------------------------------------
BPMPC installed
ND installed
WBM installed
Installed Product
--------------------------------------------------------------------------------
Name IBM Business Process Manager Advanced V8.0
Version 8.0.1.0
ID BPMPC
Build Level 20121102-1733
Build Date 11/2/12
Package com.ibm.bpm.ADV.V80_8.0.1000.20121102_2136
Architecture x86-64 (64 bit)
Installed Features Non-production
Business Process Manager Advanced - Client (always installed)
Optional Languages German
Russian
Korean
Brazilian Portuguese
Italian
French
Hungarian
Simplified Chinese
Spanish
Czech
Traditional Chinese
Japanese
Polish
Romanian
Installed Product
--------------------------------------------------------------------------------
Name IBM WebSphere Application Server Network Deployment
Version 8.0.0.5
ID ND
Build Level cf051243.01
Build Date 10/22/12
Package com.ibm.websphere.ND.v80_8.0.5.20121022_1902
Architecture x86-64 (64 bit)
Installed Features IBM 64-bit SDK for Java, Version 6
EJBDeploy tool for pre-EJB 3.0 modules
Embeddable EJB container
Sample applications
Stand-alone thin clients and resource adapters
Optional Languages German
Russian
Korean
Brazilian Portuguese
Italian
French
Hungarian
Simplified Chinese
Spanish
Czech
Traditional Chinese
Japanese
Polish
Romanian
Installed Product
--------------------------------------------------------------------------------
Name IBM Business Monitor
Version 8.0.1.0
ID WBM
Build Level 20121102-1733
Build Date 11/2/12
Package com.ibm.websphere.MON.V80_8.0.1000.20121102_2222
Architecture x86-64 (64 bit)
Optional Languages German
Russian
Korean
Brazilian Portuguese
Italian
French
Hungarian
Simplified Chinese
Spanish
Czech
Traditional Chinese
Japanese
Polish
Romanian
--------------------------------------------------------------------------------
End Installation Status Report
--------------------------------------------------------------------------------
I had to do a lot of hacking of the symbolicatecrash script to get it to run properly.
As far as I can tell, symbolicatecrash right now requires the .app to be in the same directory as the .dsym. It will use the .dsym to locate the .app, but it won't use the dsym to find the symbols.
You should make a copy of your symbolicatecrash before attempting these patches which will make it look in the dsym:
Around line 212 in the getSymbolPathFor_dsymUuid function
212 my @executablePath = grep { -e && ! -d } glob("$dsymdir" . "/Contents/Resources/DWARF/" . $executable);
Around line 265 in the matchesUUID function
265 return 1;
First you need NameVirtualHost ip:443 in you config file! You probably have one with 80 at the end, but you will also need one with 443.
Second you need a *.domain certificate (wildcard) (it is possible to make one)
Third you can make only something.domain webs in one ip (because of the certificate)
This is a correlated sub-query.
(It is a "nested" query - this is very non-technical term though)
The inner query takes values from the outer-query (WHERE st.Date = ScoresTable.Date) thus it is evaluated once for each row in the outer query.
There is also a non-correlated form in which the inner query is independent as as such is only executed once.
e.g.
SELECT * FROM ScoresTable WHERE Score =
(SELECT MAX(Score) FROM Scores)
There is nothing wrong with using subqueries, except where they are not needed :)
Your statement may be rewritable as an aggregate function depending on what columns you require in your select statement.
SELECT Max(score), Date FROM ScoresTable
Group By Date
LastLogon is the last time that the user logged into whichever domain controller you happen to have been load balanced to at the moment that you ran the GET-ADUser cmdlet, and is not replicated across the domain. You really should use LastLogonTimestamp if you want the time the last user logged in to any domain controller in your domain.
I found that doing it in two relatively simple steps seemed to work quite well. The first css definition for ul sets the base indent that you want for the list as a whole. The second definition sets the indent value for each nested list item within it. In my case they are the same, but you can obviously pick whatever you want.
ul {
margin-left: 1.5em;
}
ul > ul {
margin-left: 1.5em;
}
When posting form data with an HTML form, be sure the input
tags have name
attributes, otherwise they won't be present in request.form
.
@app.route('/', methods=['GET', 'POST'])
def index():
print(request.form)
return """
<form method="post">
<input type="text">
<input type="text" id="txt2">
<input type="text" name="txt3" id="txt3">
<input type="submit">
</form>
"""
ImmutableMultiDict([('txt3', 'text 3')])
Only the txt3
input had a name
, so it's the only key present in request.form
.
InvariantCulture
is similar to en-US
, so i would use the correct CultureInfo
instead:
var dutchCulture = CultureInfo.CreateSpecificCulture("nl-NL");
var date1 = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", dutchCulture);
And what about when the culture is en-us? Will I have to code for every single language there is out there?
If you want to know how to display the date in another culture like "en-us", you can use date1.ToString(CultureInfo.CreateSpecificCulture("en-US"))
.
class Element
{
public string Company;
public string TypeOfInvestment;
public decimal Worth;
}
class Program
{
static void Main(string[] args)
{
List<Element> elements = new List<Element>()
{
new Element { Company = "JPMORGAN CHASE",TypeOfInvestment = "Stocks", Worth = 96983 },
new Element { Company = "AMER TOWER CORP",TypeOfInvestment = "Securities", Worth = 17141 },
new Element { Company = "ORACLE CORP",TypeOfInvestment = "Assets", Worth = 59372 },
new Element { Company = "PEPSICO INC",TypeOfInvestment = "Assets", Worth = 26516 },
new Element { Company = "PROCTER & GAMBL",TypeOfInvestment = "Stocks", Worth = 387050 },
new Element { Company = "QUASLCOMM INC",TypeOfInvestment = "Bonds", Worth = 196811 },
new Element { Company = "UTD TECHS CORP",TypeOfInvestment = "Bonds", Worth = 257429 },
new Element { Company = "WELLS FARGO-NEW",TypeOfInvestment = "Bank Account", Worth = 106600 },
new Element { Company = "FEDEX CORP",TypeOfInvestment = "Stocks", Worth = 103955 },
new Element { Company = "CVS CAREMARK CP",TypeOfInvestment = "Securities", Worth = 171048 },
};
//Group by on multiple column in LINQ (Query Method)
var query = from e in elements
group e by new{e.TypeOfInvestment,e.Company} into eg
select new {eg.Key.TypeOfInvestment, eg.Key.Company, Points = eg.Sum(rl => rl.Worth)};
foreach (var item in query)
{
Console.WriteLine(item.TypeOfInvestment.PadRight(20) + " " + item.Points.ToString());
}
//Group by on multiple column in LINQ (Lambda Method)
var CompanyDetails =elements.GroupBy(s => new { s.Company, s.TypeOfInvestment})
.Select(g =>
new
{
company = g.Key.Company,
TypeOfInvestment = g.Key.TypeOfInvestment,
Balance = g.Sum(x => Math.Round(Convert.ToDecimal(x.Worth), 2)),
}
);
foreach (var item in CompanyDetails)
{
Console.WriteLine(item.TypeOfInvestment.PadRight(20) + " " + item.Balance.ToString());
}
Console.ReadLine();
}
}
if you run a server instance, stop it for the time of build process. worked for me.
You are not allowed to use the concatenation operator with the case statement. One possible solution is to use a variable within the process:
process(b0,b1,b2,b3)
variable bcat : std_logic_vector(0 to 3);
begin
bcat := b0 & b1 & b2 & b3;
case bcat is
when "0000" => x <= 1;
when others => x <= 2;
end case;
end process;
No need to close the file according to the docs if you use with:
It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks:
>>> with open('workfile', 'r') as f:
... read_data = f.read()
>>> f.closed
True
More here: https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects
I had to implement a heap traversal which outputs in a BFS order. It isn't actually BFS but accomplishes the same task.
private void getNodeValue(Node node, int index, int[] array) {
array[index] = node.value;
index = (index*2)+1;
Node left = node.leftNode;
if (left!=null) getNodeValue(left,index,array);
Node right = node.rightNode;
if (right!=null) getNodeValue(right,index+1,array);
}
public int[] getHeap() {
int[] nodes = new int[size];
getNodeValue(root,0,nodes);
return nodes;
}
It has a tricky situation: If you submit a post form, then Chrome will open a new tab to send the request. It's right until now, but if it triggers an event to download file(s), this tab will close immediately so that you cannot capture this request in the Dev Tool.
Solution: Before submitting the post form, you need to cut off your network, which makes the request cannot send successfully so that the tab will not be closed. And then you can capture the request message in the Chrome Devtool(Refreshing the new tab if necessary)
You're very close:
while IFS=$'\t' read -r -a myArray
do
echo "${myArray[0]}"
echo "${myArray[1]}"
echo "${myArray[2]}"
done < myfile
(The -r
tells read
that \
isn't special in the input data; the -a myArray
tells it to split the input-line into words and store the results in myArray
; and the IFS=$'\t'
tells it to use only tabs to split words, instead of the regular Bash default of also allowing spaces to split words as well. Note that this approach will treat one or more tabs as the delimiter, so if any field is blank, later fields will be "shifted" into earlier positions in the array. Is that O.K.?)
For your example query, the only possible value greater than 2 and less than 4 is 3, so we simplify:
GROUP BY meetingID
HAVING COUNT(caseID) = 3
In your general case:
GROUP BY meetingID
HAVING COUNT(caseID) > x AND COUNT(caseID) < 7
Or (possibly easier to read?),
GROUP BY meetingID
HAVING COUNT(caseID) BETWEEN x+1 AND 6
The line-continuation will fail if you have whitespace (spaces or tab characters[1]) after the backslash and before the newline. With no such whitespace, your example works fine for me:
$ cat test.sh
if ! fab --fabfile=.deploy/fabfile.py \
--forward-agent \
--disable-known-hosts deploy:$target; then
echo failed
else
echo succeeded
fi
$ alias fab=true; . ./test.sh
succeeded
$ alias fab=false; . ./test.sh
failed
Some detail promoted from the comments: the line-continuation backslash in the shell is not really a special case; it is simply an instance of the general rule that a backslash "quotes" the immediately-following character, preventing any special treatment it would normally be subject to. In this case, the next character is a newline, and the special treatment being prevented is terminating the command. Normally, a quoted character winds up included literally in the command; a backslashed newline is instead deleted entirely. But otherwise, the mechanism is the same. Most importantly, the backslash only quotes the immediately-following character; if that character is a space or tab, you just get a literal space or tab, and any subsequent newline remains unquoted.
[1] or carriage returns, for that matter, as Czechnology points out. Bash does not get along with Windows-formatted text files, not even in WSL. Or Cygwin, but at least their Bash port has added a set -o igncr
option that you can set to make it carriage-return-tolerant.
The only way is to Base64 encode the image and place it inside the HTML code so that it doesn't need to contact the server to download the image.
This will encode an image from url so you can copy the image file code and insert it in your page like so...
body {
background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIA...);
}
You can't access Temporary Tables from within a SQL Function. You will need to use table variables so essentially:
ALTER FUNCTION FnGetCompanyIdWithCategories()
RETURNS @rtnTable TABLE
(
-- columns returned by the function
ID UNIQUEIDENTIFIER NOT NULL,
Name nvarchar(255) NOT NULL
)
AS
BEGIN
DECLARE @TempTable table (id uniqueidentifier, name nvarchar(255)....)
insert into @myTable
select from your stuff
--This select returns data
insert into @rtnTable
SELECT ID, name FROM @mytable
return
END
Based on comments to this question here is my recommendation. You want to join the results of either a procedure or table-valued function in another query. I will show you how you can do it then you pick the one you prefer. I am going to be using sample code from one of my schemas, but you should be able to adapt it. Both are viable solutions first with a stored procedure.
declare @table as table (id int, name nvarchar(50),templateid int,account nvarchar(50))
insert into @table
execute industry_getall
select *
from @table
inner join [user]
on account=[user].loginname
In this case, you have to declare a temporary table or table variable to store the results of the procedure. Now Let's look at how you would do this if you were using a UDF
select *
from fn_Industry_GetAll()
inner join [user]
on account=[user].loginname
As you can see the UDF is a lot more concise easier to read, and probably performs a little bit better since you're not using the secondary temporary table (performance is a complete guess on my part).
If you're going to be reusing your function/procedure in lots of other places, I think the UDF is your best choice. The only catch is you will have to stop using #Temp tables and use table variables. Unless you're indexing your temp table, there should be no issue, and you will be using the tempDb less since table variables are kept in memory.
Add the css
<style type="text/css">
textarea
{
border:1px solid #999999
width:99%;
margin:5px 0;
padding:1%;
}
</style>
I can't believe I haven't found this simple solution anywhere on stack overflow yet, it is by far the most useful. Changing the Document or DocumentFilter does not work for JFormattedTextField. Peter Tseng's answer comes very close.
NumberFormat longFormat = NumberFormat.getIntegerInstance();
NumberFormatter numberFormatter = new NumberFormatter(longFormat);
numberFormatter.setValueClass(Long.class); //optional, ensures you will always get a long value
numberFormatter.setAllowsInvalid(false); //this is the key!!
numberFormatter.setMinimum(0l); //Optional
JFormattedTextField field = new JFormattedTextField(numberFormatter);
I had the same problem and here is how it worked for me :
1) Open XAMPP control panel.
2)On the right top corner go to config > Service and Port setting and change the port (I did 81 from 80).
3)Open config in Apache just right(next) to Apache admin Option and click on that and select first one (httpd.conf) it will open in the notepad.
4) There you find port listen 80 and replace it with 81 in all place and save the file.
5) Now restart Apache and MYSql
6) Now type following in Browser : http://localhost:81/phpmyadmin/
I hope this works.
The cross-platform way (not only cross-platform itself, but also working, at the very least, with both *.so
and *.dll
) is using reverse-engineering framework radare2. E.g.:
$ rabin2 -s glew32.dll | head -n 5
[Symbols]
vaddr=0x62afda8d paddr=0x0005ba8d ord=000 fwd=NONE sz=0 bind=GLOBAL type=FUNC name=glew32.dll___GLEW_3DFX_multisample
vaddr=0x62afda8e paddr=0x0005ba8e ord=001 fwd=NONE sz=0 bind=GLOBAL type=FUNC name=glew32.dll___GLEW_3DFX_tbuffer
vaddr=0x62afda8f paddr=0x0005ba8f ord=002 fwd=NONE sz=0 bind=GLOBAL type=FUNC name=glew32.dll___GLEW_3DFX_texture_compression_FXT1
vaddr=0x62afdab8 paddr=0x0005bab8 ord=003 fwd=NONE sz=0 bind=GLOBAL type=FUNC name=glew32.dll___GLEW_AMD_blend_minmax_factor
As a bonus, rabin2
recognizes C++ name mangling, for example (and also with .so
file):
$ rabin2 -s /usr/lib/libabw-0.1.so.1.0.1 | head -n 5
[Symbols]
vaddr=0x00027590 paddr=0x00027590 ord=124 fwd=NONE sz=430 bind=GLOBAL type=FUNC name=libabw::AbiDocument::isFileFormatSupported
vaddr=0x0000a730 paddr=0x0000a730 ord=125 fwd=NONE sz=58 bind=UNKNOWN type=FUNC name=boost::exception::~exception
vaddr=0x00232680 paddr=0x00032680 ord=126 fwd=NONE sz=16 bind=UNKNOWN type=OBJECT name=typeinfoforboost::exception_detail::clone_base
vaddr=0x00027740 paddr=0x00027740 ord=127 fwd=NONE sz=235 bind=GLOBAL type=FUNC name=libabw::AbiDocument::parse
Works with object files too:
$ g++ test.cpp -c -o a.o
$ rabin2 -s a.o | head -n 5
Warning: Cannot initialize program headers
Warning: Cannot initialize dynamic strings
Warning: Cannot initialize dynamic section
[Symbols]
vaddr=0x08000149 paddr=0x00000149 ord=006 fwd=NONE sz=1 bind=LOCAL type=OBJECT name=std::piecewise_construct
vaddr=0x08000149 paddr=0x00000149 ord=007 fwd=NONE sz=1 bind=LOCAL type=OBJECT name=std::__ioinit
vaddr=0x080000eb paddr=0x000000eb ord=017 fwd=NONE sz=73 bind=LOCAL type=FUNC name=__static_initialization_and_destruction_0
vaddr=0x08000134 paddr=0x00000134 ord=018 fwd=NONE sz=21 bind=LOCAL type=FUNC name=_GLOBAL__sub_I__Z4funcP6Animal
The other answers here adequately explain the security caveats which are also mentioned in the subprocess
documentation. But in addition to that, the overhead of starting a shell to start the program you want to run is often unnecessary and definitely silly for situations where you don't actually use any of the shell's functionality. Moreover, the additional hidden complexity should scare you, especially if you are not very familiar with the shell or the services it provides.
Where the interactions with the shell are nontrivial, you now require the reader and maintainer of the Python script (which may or may not be your future self) to understand both Python and shell script. Remember the Python motto "explicit is better than implicit"; even when the Python code is going to be somewhat more complex than the equivalent (and often very terse) shell script, you might be better off removing the shell and replacing the functionality with native Python constructs. Minimizing the work done in an external process and keeping control within your own code as far as possible is often a good idea simply because it improves visibility and reduces the risks of -- wanted or unwanted -- side effects.
Wildcard expansion, variable interpolation, and redirection are all simple to replace with native Python constructs. A complex shell pipeline where parts or all cannot be reasonably rewritten in Python would be the one situation where perhaps you could consider using the shell. You should still make sure you understand the performance and security implications.
In the trivial case, to avoid shell=True
, simply replace
subprocess.Popen("command -with -options 'like this' and\\ an\\ argument", shell=True)
with
subprocess.Popen(['command', '-with','-options', 'like this', 'and an argument'])
Notice how the first argument is a list of strings to pass to execvp()
, and how quoting strings and backslash-escaping shell metacharacters is generally not necessary (or useful, or correct).
Maybe see also When to wrap quotes around a shell variable?
If you don't want to figure this out yourself, the shlex.split()
function can do this for you. It's part of the Python standard library, but of course, if your shell command string is static, you can just run it once, during development, and paste the result into your script.
As an aside, you very often want to avoid Popen
if one of the simpler wrappers in the subprocess
package does what you want. If you have a recent enough Python, you should probably use subprocess.run
.
check=True
it will fail if the command you ran failed.stdout=subprocess.PIPE
it will capture the command's output.text=True
(or somewhat obscurely, with the synonym universal_newlines=True
) it will decode output into a proper Unicode string (it's just bytes
in the system encoding otherwise, on Python 3).If not, for many tasks, you want check_output
to obtain the output from a command, whilst checking that it succeeded, or check_call
if there is no output to collect.
I'll close with a quote from David Korn: "It's easier to write a portable shell than a portable shell script." Even subprocess.run('echo "$HOME"', shell=True)
is not portable to Windows.
All the responses here have been way too complex. You know that the first of the current month is the current date but with 01 as the date. You can just use YEAR() and MONTH() to build the month date by inputting the NOW() method. Here's the solution:
select * from table_name
where date between CONCAT_WS('-', YEAR( NOW() ), MONTH( NOW() ), '01') and DATE( NOW() )
CONCAT_WS() joins a series of strings with a separator (a dash in this case). So if today is 2020-08-28, YEAR( NOW() ) = '2020' and MONTH( NOW() ) = '08' and then you just need to append '01' at the end.
Voila!
git diff --shortstat
gives you just the number of lines changed and added. This only works with unstaged changes. To compare against a branch:
git diff --shortstat some-branch
I've just had an email from a github.com admin stating the following: "We normally advise people to use the HTTPS URL unless they have a specific reason to be using the SSH protocol. HTTPS is secure and easier to set up, so we default to that when a new repository is created."
The password prompt does indeed accept the normal github.com login details. A tutorial on how to set up password caching can be found here. I followed the steps in the tutorial, and it worked for me.
I agree with "Is Nothing". As stated above, it's easy to negate with "IsNot Nothing".
I find this easier to read...
If printDialog IsNot Nothing Then
'blah
End If
than this...
If Not obj Is Nothing Then
'blah
End If
The radio buttons are sent on form submit when they are checked only...
use isset()
if true then its checked otherwise its not
This is working for me
$('.Count').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
Another tool is tcpmon. This is a java open-source tool to monitor a TCP connection. It's not directly a test server. It is placed in-between a client and a server but allow to see what is going through the "tube" and also to change what is going through.
.+,(.+)
Explanation:
.+,
will search for everything before the comma, including the comma.
(.+)
will search for everything after the comma, and depending on your regex environment,
\1
is the reference for the first parentheses captured group that you need, in this example, everything after the comma.
If I understand correctly the documentation of Handler.post() method:
Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.
So examples provided by @alex2k8, even though are working correctly, are not the same.
In case, where Handler.post()
is used, no new threads are created. You just post Runnable
to the thread with Handler
to be executed by EDT.
After that, EDT only executes Runnable.run()
, nothing else.
Remember:
Runnable != Thread
.
How about an extension method?
Here I have a show or hide method. Using my CSS class hidden.
public static class HtmlControlExtensions
{
public static void Hide(this HtmlControl ctrl)
{
if (!string.IsNullOrEmpty(ctrl.Attributes["class"]))
{
if (!ctrl.Attributes["class"].Contains("hidden"))
ctrl.Attributes.Add("class", ctrl.Attributes["class"] + " hidden");
}
else
{
ctrl.Attributes.Add("class", "hidden");
}
}
public static void Show(this HtmlControl ctrl)
{
if (!string.IsNullOrEmpty(ctrl.Attributes["class"]))
if (ctrl.Attributes["class"].Contains("hidden"))
ctrl.Attributes.Add("class", ctrl.Attributes["class"].Replace("hidden", ""));
}
}
Then when you want to show or hide your control:
myUserControl.Hide();
//... some other code
myUserControl.Show();
In my case, I had the Any XHR
flag set true on the XHR Breakpoints
settings, accessible over the Sources tab within Chrome's dev tools.
Uncheck it for Chrome to work normally again.
No, @media
rules and media queries cannot exist in inline style attributes as they can only contain property: value
declarations. As the spec puts it:
The value of the style attribute must match the syntax of the contents of a CSS declaration block
The only way to apply styles to an element only in certain media is with a separate rule in your stylesheet, which means you'll need to come up with a selector for it.
A dummy span
selector would look like this, but if you're targeting a very specific element you will need a more specific selector:
span { background-image: url(particular_ad.png); }
@media (max-width: 300px) {
span { background-image: url(particular_ad_small.png); }
}
This worked for me :
date -d '20121212 7 days'
date -d '12-DEC-2012 7 days'
date -d '2012-12-12 7 days'
date -d '2012-12-12 4:10:10PM 7 days'
date -d '2012-12-12 16:10:55 7 days'
then you can format output adding parameter '+%Y%m%d'
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--example', nargs='?', const=1, type=int)
args = parser.parse_args()
print(args)
% test.py
Namespace(example=None)
% test.py --example
Namespace(example=1)
% test.py --example 2
Namespace(example=2)
nargs='?'
means 0-or-1 argumentsconst=1
sets the default when there are 0 argumentstype=int
converts the argument to intIf you want test.py
to set example
to 1 even if no --example
is specified, then include default=1
. That is, with
parser.add_argument('--example', nargs='?', const=1, type=int, default=1)
then
% test.py
Namespace(example=1)
Check this one
StackTrace st = new StackTrace(ex, true);
//Get the first stack frame
StackFrame frame = st.GetFrame(0);
//Get the file name
string fileName = frame.GetFileName();
//Get the method name
string methodName = frame.GetMethod().Name;
//Get the line number from the stack frame
int line = frame.GetFileLineNumber();
//Get the column number
int col = frame.GetFileColumnNumber();
The algorithm (HS256
) used to sign the JWT means that the secret is a symmetric key that is known by both the sender and the receiver. It is negotiated and distributed out of band. Hence, if you're the intended recipient of the token, the sender should have provided you with the secret out of band.
If you're the sender, you can use an arbitrary string of bytes as the secret, it can be generated or purposely chosen. You have to make sure that you provide the secret to the intended recipient out of band.
For the record, the 3 elements in the JWT are not base64-encoded but base64url-encoded, which is a variant of base64 encoding that results in a URL-safe value.
Let say button 1 has an event called
Button1_Click(Sender, eventarg)
If you want to call it in Button2 then call this function directly.
Button1_Click(Nothing, Nothing)
If the aforementioned answers don't help then check whether the backend server is up and running or not as in my case the server crashed and this error turns out to be totally misleading.
The best option I've found was using the savetxt
from the numpy
module:
import numpy as np
np.savetxt("file_name.csv", data1, delimiter=",", fmt='%s', header=header)
In case you have multiple lists that need to be stacked
np.savetxt("file_name.csv", np.column_stack((data1, data2)), delimiter=",", fmt='%s', header=header)
In my case it was the antivirus which blocked the file.
There is a much easier solution here than adding empty event listeners.
Just set pointer-events: none
to your image. If you still need it to be clickable, add a container around it which triggers the event.
Before you extract values from $_POST
, you should check if they exist. You could use the isset
function for this (http://php.net/manual/en/function.isset.php)
You can use [[UINavigationBar appearance] setTintColor:myColor];
Since iOS 7 you need to set [[UINavigationBar appearance] setBarTintColor:myColor];
and also [[UINavigationBar appearance] setTranslucent:NO]
.
[[UINavigationBar appearance] setBarTintColor:myColor];
[[UINavigationBar appearance] setTranslucent:NO];
$(".field-group_name").each(function() {
console.log($(this).text());
});
Use LinkedList
instead. Than, you can create an array if necessary.
You can use virtualenv
# Use this to create your temporary python "install"
# (Assuming that is the correct path to the python interpreter you want to use.)
virtualenv -p /usr/bin/python2.7 --distribute temp-python
# Type this command when you want to use your temporary python.
# While you are using your temporary python you will also have access to a temporary pip,
# which will keep all packages installed with it separate from your main python install.
# A shorter version of this command would be ". temp-python/bin/activate"
source temp-python/bin/activate
# When you no longer wish to use you temporary python type
deactivate
Enjoy!
Swift version 3.0.2 , Xcode Version 8.2.1 (8C1002) (12 hr format ):
func getTodayString() -> String{
let formatter = DateFormatter()
formatter.dateFormat = "h:mm:ss a "
formatter.amSymbol = "AM"
formatter.pmSymbol = "PM"
let currentDateStr = formatter.string(from: Date())
print(currentDateStr)
return currentDateStr
}
OUTPUT : 12:41:42 AM
Feel free to comment. Thanks
use g++
instead of gcc
.
object get(int index) is used to return the object stored at the specified index within the invoking collection.
import java.util.*;
class main
{
public static void main(String [] args)
{
ArrayList<String> arr = new ArrayList<String>();
arr.add("Hello!");
arr.add("Ishe");
arr.add("Watson?");
System.out.printf("%s\n",arr.get(2));
for (String s : arr)
{
System.out.printf("%s\n",s);
}
}
}
I just encountered this problem. I tried a few things, but settled on using JSoup. The jar is about 132k, which is a bit big, but if you download the source and take out some of the methods you will not be using, then it is not as big.
=> Good thing about it is that it will handle badly formed HTML
Here's a good example from their site.
File input = new File("/tmp/input.html");
Document doc = Jsoup.parse(input, "UTF-8", "http://example.com/");
//http://jsoup.org/cookbook/input/load-document-from-url
//Document doc = Jsoup.connect("http://example.com/").get();
Element content = doc.getElementById("content");
Elements links = content.getElementsByTag("a");
for (Element link : links) {
String linkHref = link.attr("href");
String linkText = link.text();
}
While JS is probably the way to go, it could be done with HTML and CSS only.
Here you have a fake radio button which is really a label for a real hidden radio button. By doing that, you get exactly the effect you need.
<style>
#uncheck>input { display: none }
input:checked + label { display: none }
input:not(:checked) + label + label{ display: none }
</style>
<div id='uncheck'>
<input type="radio" name='food' id="box1" />
Pizza
<label for='box1'>◎</label>
<label for='box0'>◉</label>
<input type="radio" name='food' id="box2" />
Ice cream
<label for='box2'>◎</label>
<label for='box0'>◉</label>
<input type="radio" name='food' id="box0" checked />
</div>
See it here: https://jsfiddle.net/tn70yxL8/2/
Now, that assumes you need non-selectable labels.
If you were willing to include the labels, you can technically avoid repeating the "uncheck" label by changing its text in CSS, see here: https://jsfiddle.net/7tdb6quy/2/
In scikit version 0.22, you can do it like this
from sklearn.metrics import multilabel_confusion_matrix
y_true = ["cat", "ant", "cat", "cat", "ant", "bird"]
y_pred = ["ant", "ant", "cat", "cat", "ant", "cat"]
mcm = multilabel_confusion_matrix(y_true, y_pred,labels=["ant", "bird", "cat"])
tn = mcm[:, 0, 0]
tp = mcm[:, 1, 1]
fn = mcm[:, 1, 0]
fp = mcm[:, 0, 1]
#include <iostream>
#include <vector>
#include <algorithm> // std::min_element
#include <iterator> // std::begin, std::end
int main() {
std::vector<int> v = {5,14,2,4,6};
auto result = std::min_element(std::begin(v), std::end(v));
if (std::end(v)!=result)
std::cout << *result << '\n';
}
The program you show has a few problems, the primary culprit being the for
condition: i<v[n]
. You initialize the array, setting the first 5 elements to various values and the rest to zero. n
is set to the number of elements you explicitly initialized so v[n]
is the first element that was implicitly initialized to zero. Therefore the loop condition is false the first time around and the loop does not run at all; your code simply prints out the first element.
Some minor issues:
avoid raw arrays; they behave strangely and inconsistently (e.g., implicit conversion to pointer to the array's first element, can't be assigned, can't be passed to/returned from functions by value)
avoid magic numbers. int v[100]
is an invitation to a bug if you want your array to get input from somewhere and then try to handle more than 100 elements.
avoid using namespace std;
It's not a big deal in implementation files, although IMO it's better to just get used to explicit qualification, but it can cause problems if you blindly use it everywhere because you'll put it in header files and start causing unnecessary name conflicts.
as explained in above answers Also, to return only one field from the entire array you can use projection
into find. and use $
db.getCollection("sizer").find(
{ awards: { $elemMatch: { award: "National Medal", year: 1975 } } },
{ "awards.$": 1, name: 1 }
);
will be reutrn
{
_id: 1,
name: {
first: 'John',
last: 'Backus'
},
awards: [
{
award: 'National Medal',
year: 1975,
by: 'NSF'
}
]
}
Adding dependencies didn't fix the issue at my end.
The issue was happening at my end because of "additional" fields that are part of the "@Entity" class and don't exist in the database.
I removed the additional fields from the @Entity class and it worked.
You're very close. Use same type on both sides, and include ()
.
ArrayList<Class> myArray = new ArrayList<Class>();
Adding to @pranay-rana's list:
Third way is:
function passFromValue(){
var x = 15;
return x;
}
function passToValue() {
var y = passFromValue();
console.log(y);//15
}
passToValue();
You can use java.util.Arrays.binarySearch to find an element in an array or to check for its existence:
import java.util.Arrays;
...
char[] array = new char[] {'a', 'x', 'm'};
Arrays.sort(array);
if (Arrays.binarySearch(array, 'm') >= 0) {
System.out.println("Yes, m is there");
}
Be aware that for binarySearch to work correctly, the array needs to be sorted. Hence the call to Arrays.sort() in the example. If your data is already sorted, you don't need to do that. Thus, this isn't strictly a one-liner if you need to sort your array first. Unfortunately, Arrays.sort() does not return a reference to the array - thus it is not possible to combine sort and binarySearch (i.e. Arrays.binarySearch(Arrays.sort(myArray), key)) does not work).
If you can afford the extra allocation, using Arrays.asList() seems cleaner.
It depends on how you want to use it. Using a Join is one way. Another way of doing it is let the thread notify the caller of the thread by using an event. For instance when you have your graphical user interface (GUI) thread that calls a process which runs for a while and needs to update the GUI when it finishes, you can use the event to do this. This website gives you an idea about how to work with events:
http://msdn.microsoft.com/en-us/library/aa645739%28VS.71%29.aspx
Remember that it will result in cross-threading operations and in case you want to update the GUI from another thread, you will have to use the Invoke
method of the control which you want to update.
For Kotlin and bindings the code is:
binding.spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
}
}
You can also use awk
to make it a little bit prettier:
git rev-list --left-right --count origin/develop...feature-branch | awk '{print "Behind "$1" - Ahead "$2""}'
You can even make an alias that always fetches origin first and then compares the branches
commit-diff = !"git fetch &> /dev/null && git rev-list --left-right --count"
def train_val_test_split(X, y, train_size, val_size, test_size):
X_train_val, X_test, y_train_val, y_test = train_test_split(X, y, test_size = test_size)
relative_train_size = train_size / (val_size + train_size)
X_train, X_val, y_train, y_val = train_test_split(X_train_val, y_train_val,
train_size = relative_train_size, test_size = 1-relative_train_size)
return X_train, X_val, X_test, y_train, y_val, y_test
Here we split data 2 times with sklearn's train_test_split
I believe +%s
is seconds since epoch. It's timezone invariant.
If you have a rogue loop, pause the code in Google Chrome debugger (the small "||
" button while in Sources tab).
Switch back to Chrome itself, open "Task Manager" (Shift+ESC), select your tab, click the "End Process" button.
You will get the Aww Snap message and then you can reload (F5).
As others have noted, reloading the page at the point of pausing is the same as restarting the rogue loop and can cause nasty lockups if the debugger also then locks (in some cases leading to restarting chrome or even the PC). The debugger needs a "Stop" button. Nb: The accepted answer is out of date in that some aspects of it are now apparently wrong. If you vote me down, pls explain :).
An even cleaner way is to just comment out variable names:
int main(int /* argc */, char const** /* argv */) {
return 0;
}
Instance methods need to be called from an instance. Your setLoanItem
method is an instance method (it doesn't have the modifier static
), which it needs to be in order to function (because it is setting a value on the instance that it's called on (this
)).
You need to create an instance of the class before you can call the method on it:
Media media = new Media();
media.setLoanItem("Yes");
(Btw it would be better to use a boolean instead of a string containing "Yes".)
Deletion of a topic has been supported since 0.8.2.x version. You have to enable topic deletion (setting delete.topic.enable
to true) on all brokers first.
Note: Ever since 1.0.x, the functionality being stable, delete.topic.enable
is by default true
.
Follow this step by step process for manual deletion of topics
logs.dirs
and log.dir
properties) with rm -rf
commandzookeeper-shell.sh host:port
ls /brokers/topics
rmr /brokers/topics/yourtopic
kafka-topics.sh --list --zookeeper host:port
Assuming that the order of the properties in the object is not changed.
JSON.stringify() works for deep and non-deep both types of objects, not very sure of performance aspects:
var object1 = {_x000D_
key: "value"_x000D_
};_x000D_
_x000D_
var object2 = {_x000D_
key: "value"_x000D_
};_x000D_
_x000D_
var object3 = {_x000D_
key: "no value"_x000D_
};_x000D_
_x000D_
console.log('object1 and object2 are equal: ', JSON.stringify(object1) === JSON.stringify(object2));_x000D_
_x000D_
console.log('object2 and object3 are equal: ', JSON.stringify(object2) === JSON.stringify(object3));
_x000D_
use "rb" to open a binary file. Then the bytes of the file won't be encoded when you read them
The answers only cover DOM / SAX and a copy paste implementation of a JAXB example.
However, one big area of when you are using XML is missing. In many projects / programs there is a need to store / retrieve some basic data structures. Your program has already a classes for your nice and shiny business objects / data structures, you just want a comfortable way to convert this data to a XML structure so you can do more magic on it (store, load, send, manipulate with XSLT).
This is where XStream shines. You simply annotate the classes holding your data, or if you do not want to change those classes, you configure a XStream instance for marshalling (objects -> xml) or unmarshalling (xml -> objects).
Internally XStream uses reflection, the readObject and readResolve methods of standard Java object serialization.
You get a good and speedy tutorial here:
To give a short overview of how it works, I also provide some sample code which marshalls and unmarshalls a data structure.
The marshalling / unmarshalling happens all in the main
method, the rest is just code to generate some test objects and populate some data to them.
It is super simple to configure the xStream
instance and marshalling / unmarshalling is done with one line of code each.
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import com.thoughtworks.xstream.XStream;
public class XStreamIsGreat {
public static void main(String[] args) {
XStream xStream = new XStream();
xStream.alias("good", Good.class);
xStream.alias("pRoDuCeR", Producer.class);
xStream.alias("customer", Customer.class);
Producer a = new Producer("Apple");
Producer s = new Producer("Samsung");
Customer c = new Customer("Someone").add(new Good("S4", 10, new BigDecimal(600), s))
.add(new Good("S4 mini", 5, new BigDecimal(450), s)).add(new Good("I5S", 3, new BigDecimal(875), a));
String xml = xStream.toXML(c); // objects -> xml
System.out.println("Marshalled:\n" + xml);
Customer unmarshalledCustomer = (Customer)xStream.fromXML(xml); // xml -> objects
}
static class Good {
Producer producer;
String name;
int quantity;
BigDecimal price;
Good(String name, int quantity, BigDecimal price, Producer p) {
this.producer = p;
this.name = name;
this.quantity = quantity;
this.price = price;
}
}
static class Producer {
String name;
public Producer(String name) {
this.name = name;
}
}
static class Customer {
String name;
public Customer(String name) {
this.name = name;
}
List<Good> stock = new ArrayList<Good>();
Customer add(Good g) {
stock.add(g);
return this;
}
}
}
Make sure you have closed your MSAccess file before running the java program.
If you have access to the class you're going to use, you can use this approach which I used.
Create an interface that has an alternative creator:
public interface ICreatable1Param
{
void PopulateInstance(object Param);
}
Make your classes with an empty creator and implement this method:
public class MyClass : ICreatable1Param
{
public MyClass() { //do something or nothing }
public void PopulateInstance (object Param)
{
//populate the class here
}
}
Now use your generic methods:
public void MyMethod<T>(...) where T : ICreatable1Param, new()
{
//do stuff
T newT = new T();
T.PopulateInstance(Param);
}
If you don't have access, wrap the target class:
public class MyClass : ICreatable1Param
{
public WrappedClass WrappedInstance {get; private set; }
public MyClass() { //do something or nothing }
public void PopulateInstance (object Param)
{
WrappedInstance = new WrappedClass(Param);
}
}
/var/lib/tomcat5.5/webapps/spaghetti/WEB-INF/lib/jsp-api-6.0.16.jar
/var/lib/tomcat5.5/webapps/spaghetti/WEB-INF/lib/servlet-api-6.0.16.jar
You should not have any server-specific libraries in the /WEB-INF/lib
. Leave them in the appserver's own library. It would only lead to collisions in the classpath. Get rid of all appserver-specific libraries in /WEB-INF/lib
(and also in JRE/lib
and JRE/lib/ext
if you have placed any of them there).
A common cause that the appserver-specific libraries are included in the webapp's library is that starters think that it is the right way to fix compilation errors of among others the javax.servlet
classes not being resolveable. Putting them in webapp's library is the wrong solution. You should reference them in the classpath during compilation, i.e. javac -cp /path/to/server/lib/servlet.jar
and so on, or if you're using an IDE, you should integrate the server in the IDE and associate the web project with the server. The IDE will then automatically take server-specific libraries in the classpath (buildpath) of the webapp project.
Here is a solution to prevent session shearing between browser tabs for a java application. This will work for IE (JSP/Servlet)
1)first page JS
BODY onload="javascript:initPageLoad()"
function initPageLoad() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var serverResponse = xmlhttp.responseText;
top.document.title=serverResponse;
}
};
xmlhttp.open("GET", 'data.do', true);
xmlhttp.send();
}
2)common JS for all pages
window.onunload = function() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var serverResponse = xmlhttp.responseText;
}
};
xmlhttp.open("GET", 'data.do?reset=true', true);
xmlhttp.send();
}
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
init();
clearInterval(readyStateCheckInterval);
}}, 10);
function init(){
if(document.title==""){
window.onunload=function() {};
window.open('', '_self', ''); window.close();
}
}
3)web.xml - servlet mapping
<servlet-mapping>
<servlet-name>myAction</servlet-name>
<url-pattern>/data.do</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>myAction</servlet-name>
<servlet-class>xx.xxx.MyAction</servlet-class>
</servlet>
4)servlet code
public class MyAction extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
Integer sessionCount = (Integer) request.getSession().getAttribute(
"sessionCount");
PrintWriter out = response.getWriter();
Boolean reset = Boolean.valueOf(request.getParameter("reset"));
if (reset)
sessionCount = new Integer(0);
else {
if (sessionCount == null || sessionCount == 0) {
out.println("hello Title");
sessionCount = new Integer(0);
}
sessionCount++;
}
request.getSession().setAttribute("sessionCount", sessionCount);
// Set standard HTTP/1.1 no-cache headers.
response.setHeader("Cache-Control", "private, no-store, no-cache, must- revalidate");
// Set standard HTTP/1.0 no-cache header.
response.setHeader("Pragma", "no-cache");
}
}
If you do not want to define a separate class for nested json , Defining nested json object as JsonNode should work ,for example :
{"id":2,"socket":"0c317829-69bf-43d6-b598-7c0c550635bb","type":"getDashboard","data":{"workstationUuid":"ddec1caa-a97f-4922-833f-632da07ffc11"},"reply":true}
@JsonProperty("data")
private JsonNode data;
Here is an other modern approach:
const checkExtension = (id, src, callback) => {
let e = new Image()
e.src = 'chrome-extension://'+ id +'/'+ src
e.onload = () => callback(1), e.onerror = () => callback(0)
}
// "src" must be included to "web_accessible_resources" in manifest.json
checkExtension('gighmmpiobklfepjocnamgkkbiglidom', 'icons/icon24.png', (ok) => {
console.log('AdBlock: %s', ok ? 'installed' : 'not installed')
})
checkExtension('bhlhnicpbhignbdhedgjhgdocnmhomnp', 'images/checkmark-icon.png', (ok) => {
console.log('ColorZilla: %s', ok ? 'installed' : 'not installed')
})
In case anyone's interested in the Method syntax, if you have a navigation property, it's way easy:
db.Services.Where(s=>s.ServiceAssignment.LocationId == 1);
If you don't, unless there's some Join()
override I'm unaware of, I think it looks pretty gnarly (and I'm a Method syntax purist):
db.Services.Join(db.ServiceAssignments,
s => s.Id,
sa => sa.ServiceId,
(s, sa) => new {service = s, asgnmt = sa})
.Where(ssa => ssa.asgnmt.LocationId == 1)
.Select(ssa => ssa.service);
I noticed that it's quite easy to translate from integer to Roman Numeral, because there's always sort of 1, 5 and 10 for every digit (i.e. I, V and X for 1-10, X, L and C for 10-100 etc.) That's why I made an array of Roman Numerals to get the right letter from.
In my example, I go through the whole number one digit per time, using modulo operator to get the last digit each time. Then I form the Roman Numeral from current digit inside a switch-statement, adding it in the beginning of asRomanNumerals String. After the digit has been translated, it gets removed from the number and index used to look for letter in array gets increased with two (IVX -> XLC).
public static void main(String[] args) {
// number is the one to be translated into Roman Numerals
int number = 2345;
number = Math.min(3999, Math.max(1, number)); // wraps number between 1-3999
String asRomanNumerals = "";
// Array including numerals in ascending order
String[] RN = {"I", "V", "X", "L", "C", "D", "M" };
int i = 0; // Index used to keep track which digit we are translating
while (number > 0) {
switch(number % 10) {
case 1: asRomanNumerals = RN[i] + asRomanNumerals; break;
case 2: asRomanNumerals = RN[i] + RN[i] + asRomanNumerals; break;
case 3: asRomanNumerals = RN[i] + RN[i] + RN[i] + asRomanNumerals; break;
case 4: asRomanNumerals = RN[i] + RN[i + 1] + asRomanNumerals; break;
case 5: asRomanNumerals = RN[i + 1] + asRomanNumerals; break;
case 6: asRomanNumerals = RN[i + 1] + RN[i] + asRomanNumerals; break;
case 7: asRomanNumerals = RN[i + 1] + RN[i] + RN[i] + asRomanNumerals; break;
case 8: asRomanNumerals = RN[i + 1] + RN[i] + RN[i] + RN[i] +asRomanNumerals; break;
case 9: asRomanNumerals = RN[i] + RN[i + 2] + asRomanNumerals; break;
}
number = (int) number / 10;
i += 2;
}
System.out.println(asRomanNumerals);
}
This can be achieved using awk
Below Line will display unique Values
awk file_name | uniq
You can output these unique values to a new file
awk file_name | uniq > uniq_file_name
new file uniq_file_name will contain only Unique values, no duplicates
You are using g++ 4.6 version you must invoke the flag -std=c++0x to compile
g++ -std=c++0x *.cpp -o output
Instead of setting height property, use min-height.
Setting the cursor for 'body' will change the cursor for the background of the page but not for controls on it. For example, buttons will still have the regular cursor when hovering over them. The following is what I am using:
To set the 'wait' cursor, create a style element and insert in the head:
var css = "* { cursor: wait; !important}";
var style = document.createElement("style");
style.type = "text/css";
style.id = "mywaitcursorstyle";
style.appendChild(document.createTextNode(css));
document.head.appendChild(style);
Then to restore the cursor, delete the style element:
var style = document.getElementById("mywaitcursorstyle");
if (style) {
style.parentNode.removeChild(style);
}
var arr = Array.prototype.slice.call( htmlCollection )
will have the same effect using "native" code.
Edit
Since this gets a lot of views, note (per @oriol's comment) that the following more concise expression is effectively equivalent:
var arr = [].slice.call(htmlCollection);
But note per @JussiR's comment, that unlike the "verbose" form, it does create an empty, unused, and indeed unusable array instance in the process. What compilers do about this is outside the programmer's ken.
Edit
Since ECMAScript 2015 (ES 6) there is also Array.from:
var arr = Array.from(htmlCollection);
Edit
ECMAScript 2015 also provides the spread operator, which is functionally equivalent to Array.from
(although note that Array.from
supports a mapping function as the second argument).
var arr = [...htmlCollection];
I've confirmed that both of the above work on NodeList
.
A performance comparison for the mentioned methods: http://jsben.ch/h2IFA
I have also been facing this error. None of the above methods work for me. Please follow this as it worked for me.
For Installing node-sass in Ubuntu 16 via npm :-
You can install with npm 5.2.0 Version
If you are using nvm :-
nvm install 8.2.1 nvm use 8.2.1 npm install node-sass
If you are using npm separately then upgrade or downgrade npm version to 5.2.0
npm install node-sass
The If else statement needs to be wrapped in a .get or a .post to redirect. Such as
app.post('/login', function(req, res) {
});
or
app.get('/login', function(req, res) {
});
You can use boolean indexing
:
df = pd.DataFrame({'Sales':[10,20,30,40,50], 'A':[3,4,7,6,1]})
print (df)
A Sales
0 3 10
1 4 20
2 7 30
3 6 40
4 1 50
s = 30
df1 = df[df['Sales'] >= s]
print (df1)
A Sales
2 7 30
3 6 40
4 1 50
df2 = df[df['Sales'] < s]
print (df2)
A Sales
0 3 10
1 4 20
It's also possible to invert mask
by ~
:
mask = df['Sales'] >= s
df1 = df[mask]
df2 = df[~mask]
print (df1)
A Sales
2 7 30
3 6 40
4 1 50
print (df2)
A Sales
0 3 10
1 4 20
print (mask)
0 False
1 False
2 True
3 True
4 True
Name: Sales, dtype: bool
print (~mask)
0 True
1 True
2 False
3 False
4 False
Name: Sales, dtype: bool
Actually in newer Osx os's, this is stored in /Library/WebServer/Documents/
The .en file is just an html file, but it needs special permissions to change, so I just made a folder for my stuff and then accessed it by
user.local/Folder/file.html
First you are linking the file that is here:
<script src="../Script/login.js">
Which would lead the website to a file in the Folder Script
, but then in the second paragraph you are saying that the folder name is
and also i have onother folder named scripts that contains the the following login.js file
So, this won't work! Because you are not accessing the correct file. To do that please write the code as
<script src="/script/login.js"></script>
Try removing the ..
from the beginning of the code too.
This way, you'll reach the js file where the function would run!
Just to make sure:
Just to make sure that the files are attached the HTML DOM, then please open Developer Tools (F12) and in the network workspace note each request that the browser makes to the server. This way you will learn which files were loaded and which weren't, and also why they were not!
Good luck.
This is related to this answer: https://stackoverflow.com/a/2653406/931265 Creating an object solved all of my problems.
Insert > Object > Opendocument Text
This will open a document window, paste your text, format it how you want, and close it.
The result is a figure. Right click the object, and select 'add a caption'.
You can now make cross references, create a table of figures.
Use TimeSpan object which is the result of date substraction:
DateTime d1;
DateTime d2;
return (d1 - d2).TotalDays;
just check if any unnecessary Jars are added in your library or not. if yes, then simply remove that jars from your library and clean your project once. Its worked for me.
I've seen this a few times and my only solution was a re-boot.
You could try using PowerShell: Get-Process devenv | kill
But if the other methods failed, this probably will too. :-(
To get information about the table's column, you can use:
\dt+ [tablename]
To get information about the datatype in the table, you can use:
\dT+ [datatype]
I'm using this to redirect with React Router v4:
this.props.history.push('/foo');
Hope it work for you ;)
I think if you want to add content directly to the body, the best way is:
document.body.innerHTML = document.body.innerHTML + "bla bla";
To replace it, use:
document.body.innerHTML = "bla bla";
In case if anyone wants to create there own exponential function using recursion, below is for your reference.
public static double power(double value, double p) {
if (p <= 0)
return 1;
return value * power(value, p - 1);
}
Statement interface Doc
SUMMARY:
void setFetchSize(int rows)
Gives the JDBC driver a hint as to the number of rows that should be fetched from the database when more rows are needed.
Read this ebook J2EE and beyond By Art Taylor
I find jackson fasterxml
is one good choice to serializing/deserializing
bean with XML.
use this..
$('#video1').attr({'autoplay':'true'});
Wikipedia's Switch statement entry is pretty big and actually pretty good. Interesting points:
For a strange and interesting optimization using a C switch see Duff's Device.
setInterval(function () {document.getElementById("myButtonId").click();}, 1000);
Use:
Target= "_blank" property of anchor tag
Delete the hidden .git
folder (that you can locate within your project folder) and again start the process of creating a git repository using git init
command.
When you run
install.packages("whatever")
you got message that your binaries are downloaded into temporary location (e.g. The downloaded binary packages are in C:\Users\User_name\AppData\Local\Temp\RtmpC6Y8Yv\downloaded_packages ). Go there. Take binaries (zip file). Copy paste into location which you get from running the code:
.libPaths()
If libPaths shows 2 locations, then paste into second one. Load library:
library(whatever)
Fixed.
For .NET Core:
string Token = Request.Headers["Custom"];
Or
var re = Request;
var headers = re.Headers;
string token = string.Empty;
StringValues x = default(StringValues);
if (headers.ContainsKey("Custom"))
{
var m = headers.TryGetValue("Custom", out x);
}
The trick is to have an algorithm that only you know (such that it could be decoded at the other end).
There are simple things like, "Pick a prime number and add a magic number to it"
More convoluted options such as using asymmetric encryption of a set of binary data (that could include a unique identifier, version numbers, etc) and distribute the encrypted data as the key.
Might also be worth reading the responses to this question as well
For older versions of Python where the next built-in doesn't exist:
(x for x in range(10) if x > 3).next()
It's caused by n % x
where x = 0
in the first loop iteration. You can't calculate a modulus with respect to 0.
Skype likes to use port 80 and blocks IIS. That was my prob.
I tried this using Lambda expression, and it worked.
List<MyList>.Any (x => (String.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase)) && (x.Type == qbType) );
Normally, you'd get an RST if you do a close which doesn't linger (i.e. in which data can be discarded by the stack if it hasn't been sent and ACK'd) and a normal FIN if you allow the close to linger (i.e. the close waits for the data in transit to be ACK'd).
Perhaps all you need to do is set your socket to linger so that you remove the race condition between a non lingering close done on the socket and the ACKs arriving?
Your userPhotos
array is option-typed, you should retrieve the actual underlying object with !
(if you want an error in case the object isn't there) or ?
(if you want to receive nil
in url):
let userPhotos = currentUser?.photos
for var i = 0; i < userPhotos!.count ; ++i {
let url = userPhotos![i].url
}
But to preserve safe nil handling, you better use functional approach, for instance, with map
, like this:
let urls = userPhotos?.map{ $0.url }
You can use the name property for that particular element. For example to set a border of 2px around an input element with name xyz, you can use;
$(function() {
$("input[name = 'xyz']").css("border","2px solid red");
})
I also meet the same error in vbscript.
Set objFSO = CreateObject("Scripting.FileSystemObject")
Solution:
Open command line, run :
regsvr32 /i "c:\windows\system32\scrrun.dll"
and it works
vector<int> adj[n];
// where n is number of rows in 2d vector.
expanding on the answer above the 'each' function will return you the table-cell html object. wrapping that in $() will then allow you to perform jquery actions on it.
$(this).find('td').each (function( column, td) {
$(td).blah
});
Add the offset of the event to the parent element offset to get the absolute offset position of the event.
An example :
HTMLElement.addEventListener('mousedown',function(e){
var offsetX = e.offsetX;
var offsetY = e.offsetY;
if( e.target != this ){ // 'this' is our HTMLElement
offsetX = e.target.offsetLeft + e.offsetX;
offsetY = e.target.offsetTop + e.offsetY;
}
}
When the event target is not the element which the event was registered to, it adds the offset of the parent to the current event offset in order to calculate the "Absolute" offset value.
According to Mozilla Web API: "The HTMLElement.offsetLeft read-only property returns the number of pixels that the upper left corner of the current element is offset to the left within the HTMLElement.offsetParent node."
This mostly happens when you registered an event on a parent which is containing several more children, for example: a button with an inner icon or text span, an li
element with inner spans. etc...
If you do the changes in management studio and generate scripts it makes a new table and inserts the old data into that with the changed data types. Here is a small example changing two column’s data types
/*
12 August 201008:30:39
User:
Server: CLPPRGRTEL01\TELSQLEXPRESS
Database: Tracker_3
Application:
*/
/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE dbo.tblDiary
DROP CONSTRAINT FK_tblDiary_tblDiary_events
GO
ALTER TABLE dbo.tblDiary_events SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE dbo.Tmp_tblDiary
(
Diary_ID int NOT NULL IDENTITY (1, 1),
Date date NOT NULL,
Diary_event_type_ID int NOT NULL,
Notes varchar(MAX) NULL,
Expected_call_volumes real NULL,
Expected_duration real NULL,
Skill_affected smallint NULL
) ON T3_Data_2
TEXTIMAGE_ON T3_Data_2
GO
ALTER TABLE dbo.Tmp_tblDiary SET (LOCK_ESCALATION = TABLE)
GO
SET IDENTITY_INSERT dbo.Tmp_tblDiary ON
GO
IF EXISTS(SELECT * FROM dbo.tblDiary)
EXEC('INSERT INTO dbo.Tmp_tblDiary (Diary_ID, Date, Diary_event_type_ID, Notes, Expected_call_volumes, Expected_duration, Skill_affected)
SELECT Diary_ID, Date, Diary_event_type_ID, CONVERT(varchar(MAX), Notes), Expected_call_volumes, Expected_duration, CONVERT(smallint, Skill_affected) FROM dbo.tblDiary WITH (HOLDLOCK TABLOCKX)')
GO
SET IDENTITY_INSERT dbo.Tmp_tblDiary OFF
GO
DROP TABLE dbo.tblDiary
GO
EXECUTE sp_rename N'dbo.Tmp_tblDiary', N'tblDiary', 'OBJECT'
GO
ALTER TABLE dbo.tblDiary ADD CONSTRAINT
PK_tblDiary PRIMARY KEY NONCLUSTERED
(
Diary_ID
) WITH( PAD_INDEX = OFF, FILLFACTOR = 86, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON T3_Data_2
GO
CREATE UNIQUE CLUSTERED INDEX tblDiary_ID ON dbo.tblDiary
(
Diary_ID
) WITH( PAD_INDEX = OFF, FILLFACTOR = 86, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON T3_Data_2
GO
CREATE NONCLUSTERED INDEX tblDiary_date ON dbo.tblDiary
(
Date
) WITH( PAD_INDEX = OFF, FILLFACTOR = 86, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON T3_Data_2
GO
ALTER TABLE dbo.tblDiary WITH NOCHECK ADD CONSTRAINT
FK_tblDiary_tblDiary_events FOREIGN KEY
(
Diary_event_type_ID
) REFERENCES dbo.tblDiary_events
(
Diary_event_ID
) ON UPDATE CASCADE
ON DELETE CASCADE
GO
COMMIT
What about having different names for your dev and prod servers? That should avoid any confusions and you'd not have to edit the hosts file every time.
How did you configure networking when you created the guest? The easiest way is to set the network adapter to NAT, if you don't need to access the vm from another pc.
In order to have HSQLDB register itself, you need to access its jdbcDriver class. You can do this the same way as in this example.
Class.forName("org.hsqldb.jdbcDriver");
It triggers static initialization of jdbcDriver class, which is:
static {
try {
DriverManager.registerDriver(new jdbcDriver());
} catch (Exception e) {}
}
Flexible Box Layout Module - 8.1. Aligning with auto margins
Auto margins on flex items have an effect very similar to auto margins in block flow:
During calculations of flex bases and flexible lengths, auto margins are treated as 0.
Prior to alignment via
justify-content
andalign-self
, any positive free space is distributed to auto margins in that dimension.
Therefore you could use margin-top: auto
to distribute the space between the other elements and the last element.
This will position the last element at the bottom.
p:last-of-type {
margin-top: auto;
}
.container {
display: flex;
flex-direction: column;
border: 1px solid #000;
min-height: 200px;
width: 100px;
}
p {
height: 30px;
background-color: blue;
margin: 5px;
}
p:last-of-type {
margin-top: auto;
}
_x000D_
<div class="container">
<p></p>
<p></p>
<p></p>
</div>
_x000D_
Likewise, you can also use margin-left: auto
or margin-right: auto
for the same alignment horizontally.
p:last-of-type {
margin-left: auto;
}
.container {
display: flex;
width: 100%;
border: 1px solid #000;
}
p {
height: 50px;
width: 50px;
background-color: blue;
margin: 5px;
}
p:last-of-type {
margin-left: auto;
}
_x000D_
<div class="container">
<p></p>
<p></p>
<p></p>
<p></p>
</div>
_x000D_