Name.objects.filter(alias__gt='',alias__isnull=False)
Just hit the same problem... For some reason, the freezepanes command just caused crosshairs to appear in the centre of the screen. It turns oout I had switched ScreenUpdating off! Solved with the following code:
Application.ScreenUpdating = True
Cells(2, 1).Select
ActiveWindow.FreezePanes = True
Now it works fine.
You can use the concept of multiple queries in the FROM keyword. Let me show you one example:
SELECT DISTINCT e.id,e.name,d.name,lap.lappy LAPTOP_MAKE,c_loc.cnty COUNTY
FROM (
SELECT c.id cnty,l.name
FROM county c, location l
WHERE c.id=l.county_id AND l.end_Date IS NOT NULL
) c_loc, emp e
INNER JOIN dept d ON e.deptno =d.id
LEFT JOIN
(
SELECT l.id lappy, c.name cmpy
FROM laptop l, company c
WHERE l.make = c.name
) lap ON e.cmpy_id=lap.cmpy
You can use as many tables as you want to. Use outer joins and union where ever it's necessary, even inside table subqueries.
That's a very easy method to involve as many as tables and fields.
There are many answers to the question, but I felt there is a need for some really simple answer clearly comparing the two. Here's the discussion I made up when a user searches for a movie name in an MVP and MVC app:
User: Click click …
View: Who’s that? [MVP|MVC]
User: I just clicked on the search button …
View: Ok, hold on a sec … . [MVP|MVC]
( View calling the Presenter|Controller … ) [MVP|MVC]
View: Hey Presenter|Controller, a User has just clicked on the search button, what shall I do? [MVP|MVC]
Presenter|Controller: Hey View, is there any search term on that page? [MVP|MVC]
View: Yes,… here it is … “piano” [MVP|MVC]
Presenter: Thanks View,… meanwhile I’m looking up the search term on the Model, please show him/her a progress bar [MVP|MVC]
( Presenter|Controller is calling the Model … ) [MVP|MVC]
Presenter|Controller: Hey Model, Do you have any match for this search term?: “piano” [MVP|MVC]
Model: Hey Presenter|Controller, let me check … [MVP|MVC]
( Model is making a query to the movie database … ) [MVP|MVC]
( After a while ... )
-------------- This is where MVP and MVC start to diverge ---------------
Model: I found a list for you, Presenter, here it is in JSON “[{"name":"Piano Teacher","year":2001},{"name":"Piano","year":1993}]” [MVP]
Model: There is some result available, Controller. I have created a field variable in my instance and filled it with the result. It's name is "searchResultsList" [MVC]
(Presenter|Controller thanks Model and gets back to the View) [MVP|MVC]
Presenter: Thanks for waiting View, I found a list of matching results for you and arranged them in a presentable format: ["Piano Teacher 2001","Piano 1993"]. Please show it to the user in a vertical list. Also please hide the progress bar now [MVP]
Controller: Thanks for waiting View, I have asked Model about your search query. It says it has found a list of matching results and stored them in a variable named "searchResultsList" inside its instance. You can get it from there. Also please hide the progress bar now [MVC]
View: Thank you very much Presenter [MVP]
View: Thank you "Controller" [MVC] (Now the View is questioning itself: How should I present the results I get from the Model to the user? Should the production year of the movie come first or last...? Should it be in a vertical or horizontal list? ...)
In case you're interested, I have been writing a series of articles dealing with app architectural patterns (MVC, MVP, MVVP, clean architecture, ...) accompanied by a Github repo here. Even though the sample is written for android, the underlying principles can be applied to any medium.
If this batch file is something you want to run as scheduled or always; you can use windows schedule tool and it doesn't opens up in a window when it starts the batch file.
To open Task Scheduler
:
'cmd'
taskschd.msc
-> enterFrom the right side, click Create Basic Task
and follow the menus.
Hope this helps.
I don't think you can do this with the standard tools. You can use ipcs -mp
to get the process ID of the last process to attach/detach but I'm not aware of how to get all attached processes with ipcs
.
With a two-process-attached segment, assuming they both stayed attached, you can possibly figure out from the creator PID cpid
and last-attached PID lpid
which are the two processes but that won't scale to more than two processes so its usefulness is limited.
The cat /proc/sysvipc/shm
method seems similarly limited but I believe there's a way to do it with other parts of the /proc
filesystem, as shown below:
When I do a grep
on the procfs
maps for all processes, I get entries containing lines for the cpid
and lpid
processes.
For example, I get the following shared memory segment from ipcs -m
:
------ Shared Memory Segments --------
key shmid owner perms bytes nattch status
0x00000000 123456 pax 600 1024 2 dest
and, from ipcs -mp
, the cpid
is 3956 and the lpid
is 9999 for that given shared memory segment (123456).
Then, with the command grep 123456 /proc/*/maps
, I see:
/proc/3956/maps: blah blah blah 123456 /SYSV000000 (deleted)
/proc/9999/maps: blah blah blah 123456 /SYSV000000 (deleted)
So there is a way to get the processes that attached to it. I'm pretty certain that the dest
status and (deleted)
indicator are because the creator has marked the segment for destruction once the final detach occurs, not that it's already been destroyed.
So, by scanning of the /proc/*/maps
"files", you should be able to discover which PIDs are currently attached to a given segment.
SELECT * FROM tableName WHERE columnName LIKE "%#%" OR columnName LIKE "%$%" OR (etc.)
The following will return NULL if the array is empty, else the last element.
var item = (arr.Length == 0) ? null : arr[arr.Length - 1]
The ng-dirty
class tells you that the form has been modified by the user, whereas the ng-pristine
class tells you that the form has not been modified by the user. So ng-dirty
and ng-pristine
are two sides of the same story.
The classes are set on any field, while the form has two properties, $dirty
and $pristine
.
You can use the $scope.form.$setPristine()
function to reset a form to pristine state (please note that this is an AngularJS 1.1.x feature).
If you want a $scope.form.$setPristine()
-ish behavior even in 1.0.x branch of AngularJS, you need to roll your own solution (some pretty good ones can be found here). Basically, this means iterating over all form fields and setting their $dirty
flag to false
.
Hope this helps.
You can make your TextBox
as customed PasswordBox
by simply adding the following value to FontFamily
property of your TextBox
control.
<TextBox
Text="{Binding Password}"
FontFamily="ms-appx:///Assets/PassDot.ttf#PassDot"
FontSize="35"/>
In my case this works perfectly. This will show dot in place of the actual text (not star(*) though).
Well, Java has "static nested classes", but they're not at all the same as C#'s static classes, if that's where you were coming from. A static nested class is just one which doesn't implicitly have a reference to an instance of the outer class.
Static nested classes can have instance methods and static methods.
There's no such thing as a top-level static class in Java.
I have a more useful version if you are interested. I lifted a bit of code from here a website where the link is no longer active. I modifyied it to allow for an array of tables into the stored procedure and it populates the drop, truncate, add statements before executing all of them. This gives you control to decide which tables need truncating.
/****** Object: UserDefinedTableType [util].[typ_objects_for_managing] Script Date: 03/04/2016 16:42:55 ******/
CREATE TYPE [util].[typ_objects_for_managing] AS TABLE(
[schema] [sysname] NOT NULL,
[object] [sysname] NOT NULL
)
GO
create procedure [util].[truncate_table_with_constraints]
@objects_for_managing util.typ_objects_for_managing readonly
--@schema sysname
--,@table sysname
as
--select
-- @table = 'TABLE',
-- @schema = 'SCHEMA'
declare @exec_table as table (ordinal int identity (1,1), statement nvarchar(4000), primary key (ordinal));
--print '/*Drop Foreign Key Statements for ['+@schema+'].['+@table+']*/'
insert into @exec_table (statement)
select
'ALTER TABLE ['+SCHEMA_NAME(o.schema_id)+'].['+ o.name+'] DROP CONSTRAINT ['+fk.name+']'
from sys.foreign_keys fk
inner join sys.objects o
on fk.parent_object_id = o.object_id
where
exists (
select * from @objects_for_managing chk
where
chk.[schema] = SCHEMA_NAME(o.schema_id)
and
chk.[object] = o.name
)
;
--o.name = @table and
--SCHEMA_NAME(o.schema_id) = @schema
insert into @exec_table (statement)
select
'TRUNCATE TABLE ' + src.[schema] + '.' + src.[object]
from @objects_for_managing src
;
--print '/*Create Foreign Key Statements for ['+@schema+'].['+@table+']*/'
insert into @exec_table (statement)
select 'ALTER TABLE ['+SCHEMA_NAME(o.schema_id)+'].['+o.name+'] ADD CONSTRAINT ['+fk.name+'] FOREIGN KEY (['+c.name+'])
REFERENCES ['+SCHEMA_NAME(refob.schema_id)+'].['+refob.name+'](['+refcol.name+'])'
from sys.foreign_key_columns fkc
inner join sys.foreign_keys fk
on fkc.constraint_object_id = fk.object_id
inner join sys.objects o
on fk.parent_object_id = o.object_id
inner join sys.columns c
on fkc.parent_column_id = c.column_id and
o.object_id = c.object_id
inner join sys.objects refob
on fkc.referenced_object_id = refob.object_id
inner join sys.columns refcol
on fkc.referenced_column_id = refcol.column_id and
fkc.referenced_object_id = refcol.object_id
where
exists (
select * from @objects_for_managing chk
where
chk.[schema] = SCHEMA_NAME(o.schema_id)
and
chk.[object] = o.name
)
;
--o.name = @table and
--SCHEMA_NAME(o.schema_id) = @schema
declare @looper int , @total_records int, @sql_exec nvarchar(4000)
select @looper = 1, @total_records = count(*) from @exec_table;
while @looper <= @total_records
begin
select @sql_exec = (select statement from @exec_table where ordinal =@looper)
exec sp_executesql @sql_exec
print @sql_exec
set @looper = @looper + 1
end
Iterables have a
__iter__
method that instantiates a new iterator every time.Iterators implement a
__next__
method that returns individual items, and a__iter__
method that returnsself
.Therefore, iterators are also iterable, but iterables are not iterators.
Luciano Ramalho, Fluent Python.
I used in similar case the answer from Günter Zöchbauer, and it was perfect to me, moving the form creation to a function and calling it from ngOnInit().
For illustration, that's how I made it, including the fields initialization:
ngOnInit() {
// initializing the form model here
this.createForm();
}
createForm() {
let EMAIL_REGEXP = /^[^@]+@([^@\.]+\.)+[^@\.]+$/i; // here just to add something more, useful too
this.userForm = new FormGroup({
name: new FormControl('', [Validators.required, Validators.minLength(3)]),
city: new FormControl(''),
email: new FormControl(null, Validators.pattern(EMAIL_REGEXP))
});
this.initializeFormValues();
}
initializeFormValues() {
const people = {
name: '',
city: 'Rio de Janeiro', // Only for demonstration
email: ''
};
(<FormGroup>this.userForm).setValue(people, { onlySelf: true });
}
resetForm() {
this.createForm();
this.submitted = false;
}
I added a button to the form for a smart reset (with the fields initialization):
In the HTML file (or inline template):
<button type="button" [disabled]="userForm.pristine" (click)="resetForm()">Reset</button>
After loading the form at first time or after clicking the reset button we have the following status:
FORM pristine: true
FORM valid: false (because I have required a field)
FORM submitted: false
Name pristine: true
City pristine: true
Email pristine: true
And all the field initializations that a simple form.reset() doesn't make for us! :-)
I solved this on 12.10 by installing libssl-dev.
sudo apt-get install libssl-dev
As the error message says, this is not supported on sql server. The only way to ensure refrerential integrity is to work with triggers.
You may try with below query :
INSERT INTO errortable (dateupdated,table1id)
VALUES (to_date(to_char(sysdate,'dd/mon/yyyy hh24:mi:ss'), 'dd/mm/yyyy hh24:mi:ss' ),1083 );
To view the result of it:
SELECT to_char(hire_dateupdated, 'dd/mm/yyyy hh24:mi:ss')
FROM errortable
WHERE table1id = 1083;
from psutil import process_iter
from termcolor import colored
names = []
ids = []
x = 0
z = 0
k = 0
for proc in process_iter():
name = proc.name()
y = len(name)
if y>x:
x = y
if y<x:
k = y
id = proc.pid
names.insert(z, name)
ids.insert(z, id)
z += 1
print(colored("Process Name", 'yellow'), (x-k-5)*" ", colored("Process Id", 'magenta'))
for b in range(len(names)-1):
z = x
print(colored(names[b], 'cyan'),(x-len(names[b]))*" ",colored(ids[b], 'white'))
path of pg_config in my case (MacOS)
/Library/PostgreSQL/13/bin
Execute the following in the terminal:
PATH="/Library/PostgreSQL/13/bin:$PATH"
Then
pip install psycopg2
There's a faster way to do that:
Arrays.hashCode(arr1) == Arrays.hashCode(arr2)
Xamarin is now owned by Microsoft So it completely free to use on Windows and mac as well.
The --cached
didn't work for me, ... where, inspired by git log
git diff origin/<branch>..<branch>
did.
You have to put your script tag after the one that references Angular. Move it out of the head
:
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="main.js"></script>
The way you've set it up now, your script runs before Angular is loaded on the page.
Use REPLACE:
SELECT REPLACE(t.column, 'est1', 'rest1')
FROM MY_TABLE t
If you want to update the values in the table, use:
UPDATE MY_TABLE t
SET column = REPLACE(t.column, 'est1', 'rest1')
Just fetch. only gets one row. So no foreach loop needed :D
$row = $STH -> fetch();
example (ty northkildonan):
$dbh = new PDO(" --- connection string --- ");
$stmt = $dbh->prepare("SELECT name FROM mytable WHERE id=4 LIMIT 1");
$stmt->execute();
$row = $stmt->fetch();
For graphics, I'd rather not prefer integers. Many systems use integers for UI painting (pixels are ints after all), but macOS for example uses float for everything. macOS only knows points and a point can translate to one pixel, but depending on monitor resolution, it might translate to something else. On retina screens half a point (0.5/0.5) is pixel. Still, I never noticed that macOS UIs are significantly slower than other UIs. After all 3D APIs (OpenGL or Direct3D) also works with floats and modern graphics libraries very often take advantage of GPU acceleration.
Now you said speed is your main concern, okay, let's go for speed. Before you run any sophisticated algorithm, first do a simple test. Create an axis aligned bounding box around your polygon. This is very easy, fast and can already safe you a lot of calculations. How does that work? Iterate over all points of the polygon and find the min/max values of X and Y.
E.g. you have the points (9/1), (4/3), (2/7), (8/2), (3/6)
. This means Xmin is 2, Xmax is 9, Ymin is 1 and Ymax is 7. A point outside of the rectangle with the two edges (2/1) and (9/7) cannot be within the polygon.
// p is your point, p.x is the x coord, p.y is the y coord
if (p.x < Xmin || p.x > Xmax || p.y < Ymin || p.y > Ymax) {
// Definitely not within the polygon!
}
This is the first test to run for any point. As you can see, this test is ultra fast but it's also very coarse. To handle points that are within the bounding rectangle, we need a more sophisticated algorithm. There are a couple of ways how this can be calculated. Which method works also depends on the fact if the polygon can have holes or will always be solid. Here are examples of solid ones (one convex, one concave):
And here's one with a hole:
The green one has a hole in the middle!
The easiest algorithm, that can handle all three cases above and is still pretty fast is named ray casting. The idea of the algorithm is pretty simple: Draw a virtual ray from anywhere outside the polygon to your point and count how often it hits a side of the polygon. If the number of hits is even, it's outside of the polygon, if it's odd, it's inside.
The winding number algorithm would be an alternative, it is more accurate for points being very close to a polygon line but it's also much slower. Ray casting may fail for points too close to a polygon side because of limited floating point precision and rounding issues, but in reality that is hardly a problem, as if a point lies that close to a side, it's often visually not even possible for a viewer to recognize if it is already inside or still outside.
You still have the bounding box of above, remember? Just pick a point outside the bounding box and use it as starting point for your ray. E.g. the point (Xmin - e/p.y)
is outside the polygon for sure.
But what is e
? Well, e
(actually epsilon) gives the bounding box some padding. As I said, ray tracing fails if we start too close to a polygon line. Since the bounding box might equal the polygon (if the polygon is an axis aligned rectangle, the bounding box is equal to the polygon itself!), we need some padding to make this safe, that's all. How big should you choose e
? Not too big. It depends on the coordinate system scale you use for drawing. If your pixel step width is 1.0, then just choose 1.0 (yet 0.1 would have worked as well)
Now that we have the ray with its start and end coordinates, the problem shifts from "is the point within the polygon" to "how often does the ray intersects a polygon side". Therefore we can't just work with the polygon points as before, now we need the actual sides. A side is always defined by two points.
side 1: (X1/Y1)-(X2/Y2)
side 2: (X2/Y2)-(X3/Y3)
side 3: (X3/Y3)-(X4/Y4)
:
You need to test the ray against all sides. Consider the ray to be a vector and every side to be a vector. The ray has to hit each side exactly once or never at all. It can't hit the same side twice. Two lines in 2D space will always intersect exactly once, unless they are parallel, in which case they never intersect. However since vectors have a limited length, two vectors might not be parallel and still never intersect because they are too short to ever meet each other.
// Test the ray against all sides
int intersections = 0;
for (side = 0; side < numberOfSides; side++) {
// Test if current side intersects with ray.
// If yes, intersections++;
}
if ((intersections & 1) == 1) {
// Inside of polygon
} else {
// Outside of polygon
}
So far so well, but how do you test if two vectors intersect? Here's some C code (not tested), that should do the trick:
#define NO 0
#define YES 1
#define COLLINEAR 2
int areIntersecting(
float v1x1, float v1y1, float v1x2, float v1y2,
float v2x1, float v2y1, float v2x2, float v2y2
) {
float d1, d2;
float a1, a2, b1, b2, c1, c2;
// Convert vector 1 to a line (line 1) of infinite length.
// We want the line in linear equation standard form: A*x + B*y + C = 0
// See: http://en.wikipedia.org/wiki/Linear_equation
a1 = v1y2 - v1y1;
b1 = v1x1 - v1x2;
c1 = (v1x2 * v1y1) - (v1x1 * v1y2);
// Every point (x,y), that solves the equation above, is on the line,
// every point that does not solve it, is not. The equation will have a
// positive result if it is on one side of the line and a negative one
// if is on the other side of it. We insert (x1,y1) and (x2,y2) of vector
// 2 into the equation above.
d1 = (a1 * v2x1) + (b1 * v2y1) + c1;
d2 = (a1 * v2x2) + (b1 * v2y2) + c1;
// If d1 and d2 both have the same sign, they are both on the same side
// of our line 1 and in that case no intersection is possible. Careful,
// 0 is a special case, that's why we don't test ">=" and "<=",
// but "<" and ">".
if (d1 > 0 && d2 > 0) return NO;
if (d1 < 0 && d2 < 0) return NO;
// The fact that vector 2 intersected the infinite line 1 above doesn't
// mean it also intersects the vector 1. Vector 1 is only a subset of that
// infinite line 1, so it may have intersected that line before the vector
// started or after it ended. To know for sure, we have to repeat the
// the same test the other way round. We start by calculating the
// infinite line 2 in linear equation standard form.
a2 = v2y2 - v2y1;
b2 = v2x1 - v2x2;
c2 = (v2x2 * v2y1) - (v2x1 * v2y2);
// Calculate d1 and d2 again, this time using points of vector 1.
d1 = (a2 * v1x1) + (b2 * v1y1) + c2;
d2 = (a2 * v1x2) + (b2 * v1y2) + c2;
// Again, if both have the same sign (and neither one is 0),
// no intersection is possible.
if (d1 > 0 && d2 > 0) return NO;
if (d1 < 0 && d2 < 0) return NO;
// If we get here, only two possibilities are left. Either the two
// vectors intersect in exactly one point or they are collinear, which
// means they intersect in any number of points from zero to infinite.
if ((a1 * b2) - (a2 * b1) == 0.0f) return COLLINEAR;
// If they are not collinear, they must intersect in exactly one point.
return YES;
}
The input values are the two endpoints of vector 1 (v1x1/v1y1
and v1x2/v1y2
) and vector 2 (v2x1/v2y1
and v2x2/v2y2
). So you have 2 vectors, 4 points, 8 coordinates. YES
and NO
are clear. YES
increases intersections, NO
does nothing.
What about COLLINEAR? It means both vectors lie on the same infinite line, depending on position and length, they don't intersect at all or they intersect in an endless number of points. I'm not absolutely sure how to handle this case, I would not count it as intersection either way. Well, this case is rather rare in practice anyway because of floating point rounding errors; better code would probably not test for == 0.0f
but instead for something like < epsilon
, where epsilon is a rather small number.
If you need to test a larger number of points, you can certainly speed up the whole thing a bit by keeping the linear equation standard forms of the polygon sides in memory, so you don't have to recalculate these every time. This will save you two floating point multiplications and three floating point subtractions on every test in exchange for storing three floating point values per polygon side in memory. It's a typical memory vs computation time trade off.
Last but not least: If you may use 3D hardware to solve the problem, there is an interesting alternative. Just let the GPU do all the work for you. Create a painting surface that is off screen. Fill it completely with the color black. Now let OpenGL or Direct3D paint your polygon (or even all of your polygons if you just want to test if the point is within any of them, but you don't care for which one) and fill the polygon(s) with a different color, e.g. white. To check if a point is within the polygon, get the color of this point from the drawing surface. This is just a O(1) memory fetch.
Of course this method is only usable if your drawing surface doesn't have to be huge. If it cannot fit into the GPU memory, this method is slower than doing it on the CPU. If it would have to be huge and your GPU supports modern shaders, you can still use the GPU by implementing the ray casting shown above as a GPU shader, which absolutely is possible. For a larger number of polygons or a large number of points to test, this will pay off, consider some GPUs will be able to test 64 to 256 points in parallel. Note however that transferring data from CPU to GPU and back is always expensive, so for just testing a couple of points against a couple of simple polygons, where either the points or the polygons are dynamic and will change frequently, a GPU approach will rarely pay off.
it is simple just use .qsize() example:
a=Queue()
a.put("abcdef")
print a.qsize() #prints 1 which is the size of queue
The above snippet applies for Queue()
class of python. Thanks @rayryeng for the update.
for deque from collections
we can use len()
as stated here by K Z.
Unless you need to be able to change the deleter at runtime, I would strongly recommend using a custom deleter type. For example, if use a function pointer for your deleter, sizeof(unique_ptr<T, fptr>) == 2 * sizeof(T*)
. In other words, half of the bytes of the unique_ptr
object are wasted.
Writing a custom deleter to wrap every function is a bother, though. Thankfully, we can write a type templated on the function:
Since C++17:
template <auto fn>
using deleter_from_fn = std::integral_constant<decltype(fn), fn>;
template <typename T, auto fn>
using my_unique_ptr = std::unique_ptr<T, deleter_from_fn<fn>>;
// usage:
my_unique_ptr<Bar, destroy> p{create()};
Prior to C++17:
template <typename D, D fn>
using deleter_from_fn = std::integral_constant<D, fn>;
template <typename T, typename D, D fn>
using my_unique_ptr = std::unique_ptr<T, deleter_from_fn<D, fn>>;
// usage:
my_unique_ptr<Bar, decltype(destroy), destroy> p{create()};
In general, if you don't know how something works, look for an example which you can learn from.
For this problem, consider this DEMO
You can see loading content with AJAX is very easily accomplished with jQuery:
$(function(){
// don't cache ajax or content won't be fresh
$.ajaxSetup ({
cache: false
});
var ajax_load = "<img src='http://automobiles.honda.com/images/current-offers/small-loading.gif' alt='loading...' />";
// load() functions
var loadUrl = "http://fiddle.jshell.net/deborah/pkmvD/show/";
$("#loadbasic").click(function(){
$("#result").html(ajax_load).load(loadUrl);
});
// end
});
Try to understand how this works and then try replicating it. Good luck.
You can find the corresponding tutorial HERE
Right now the following event starts the ajax load
function:
$("#loadbasic").click(function(){
$("#result").html(ajax_load).load(loadUrl);
});
You can also do this periodically: How to fire AJAX request Periodically?
(function worker() {
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 5000);
}
});
})();
I made a demo of this implementation for you HERE. In this demo, every 2 seconds (setTimeout(worker, 2000);
) the content is updated.
You can also just load the data immediately:
$("#result").html(ajax_load).load(loadUrl);
Which has THIS corresponding demo.
I had faced the similar issue while using Convert.ToSingle(my_value) If the OS language settings is English 2.5 (example) will be taken as 2.5 If the OS language is German, 2.5 will be treated as 2,5 which is 25 I used the invariantculture IFormat provided and it works. It always treats '.' as '.' instead of ',' irrespective of the system language.
float var = Convert.ToSingle(my_value, System.Globalization.CultureInfo.InvariantCulture);
Another alternative might be
Array.from(document.querySelectorAll("a")).map(x => x.href)
With your $$(
its even shorter
Array.from($$("a")).map(x => x.href)
I use the NERD Commenter script. It lets you easily comment, uncomment or toggle comments in your code.
As mentioned in the comments:
for anyone who is confused by the usage, default leader is "\" so 10\cc will comment ten lines and 10\cu will uncomment those ten lines
Another different answer to an old question. However, I found a implementation made specifically for bootstrap which might prove useful here. Hope this helps anybody who is looking...
Try this one
<?php
echo get_the_post_thumbnail($post_id, 'thumbnail', array('class' => 'alignleft'));
?>
I know this is old, but I just ran into the problem and didn't find a great solution. So, I decided on using some js to get the scrollBody's height, as compared to the tables height. If the scrollBody is smaller than the table, then I increase the tables width by 15px to account for the scrollbar. I set this up on resize event too, so that it works when my container changes sizes:
const tableHeight = $('#' + this.options.id).height();
const scrollBodyHeight = $('#' + this.options.id).closest('.dataTables_scrollBody').height();
if (tableHeight > scrollBodyHeight) {
$('#' + this.options.id).closest('.dataTables_scrollBody').css({
width: "calc(100% + 15px)",
})
} else {
$('#' + this.options.id).closest('.dataTables_scrollBody').css({
width: "100%",
})
}
SYMFONY 3.X
Other SF 3.X methods given here did not work for me because I could submit empty data to the form (but I have NotNull/NotBlanck constraints). In this case the error string would look like this :
string(282) "ERROR: This value should not be blank.
ERROR: This value should not be blank.
ERROR: This value should not be blank.
ERROR: This value should not be blank.
ERROR: This value should not be blank.
ERROR: This value should not be null.
name:
ERROR: This value should not be blank.
"
Which is not very usefull. So I made this:
public function buildErrorArray(FormInterface $form)
{
$errors = [];
foreach ($form->all() as $child) {
$errors = array_merge(
$errors,
$this->buildErrorArray($child)
);
}
foreach ($form->getErrors() as $error) {
$errors[$error->getCause()->getPropertyPath()] = $error->getMessage();
}
return $errors;
}
Which would return that :
array(7) {
["data.name"]=>
string(31) "This value should not be blank."
["data.street"]=>
string(31) "This value should not be blank."
["data.zipCode"]=>
string(31) "This value should not be blank."
["data.city"]=>
string(31) "This value should not be blank."
["data.state"]=>
string(31) "This value should not be blank."
["data.countryCode"]=>
string(31) "This value should not be blank."
["data.organization"]=>
string(30) "This value should not be null."
}
>>> '{:08b}'.format(1)
'00000001'
See: Format Specification Mini-Language
Note for Python 2.6 or older, you cannot omit the positional argument identifier before :
, so use
>>> '{0:08b}'.format(1)
'00000001'
The solution I've come up with is:
isinstance(y, (np.ndarray, np.generic) )
However, it's not 100% clear that all numpy types are guaranteed to be either np.ndarray
or np.generic
, and this probably isn't version robust.
Try using this code for v3:
gMap = new google.maps.Map(document.getElementById('map'));
gMap.setZoom(13); // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);
You are grouping by month only, you have to add YEAR() to the group by
if your column is varchar
use annotation length
@Column(length = 255)
or use another column type
@Column(columnDefinition="TEXT")
Alternatively, you could just return false from the click event:
$('div.toggle').hide();
$('ul.product-info li a').click(function(event){
$(this).next('div').slideToggle(200);
+ return false;
});
Which would stop the A-Href being triggered.
Note however, for usability reasons, in an ideal world that href should still go somewhere, for the people whom want to open link in new tab ;)
With Linq
var newList = GlobalStrings.Append(localStrings)
I've tried all the solutions from the answers but couldn't get mysql
command to work from the terminal, always getting the message
bash: command not found
The solution is to change the .bash_profile, and add the mysql path to .bash_profile
To do so follow these steps: 1. Open a new Terminal window or make sure you are in the home directory 2. Open .bash_profile using
nano .bash_profile
3. Add the following command to add the mysql path
PATH="/usr/local/mysql/bin:${PATH}"
export PATH
4. Press Ctrl+X, then press y and press enter.
std::array<std::string, 3> strarr = {"ram", "mohan", "sita"};
for(const std::string& str : strarr) {
listbox.items.add(str);
}
std::string strarr[] = {"ram", "mohan", "sita"};
for(int i = 0; i < 3; ++i) {
listbox.items.add(strarr[i]);
}
or
std::string strarr[] = {"ram", "mohan", "sita"};
std::vector<std::string> strvec(strarr, strarr + 3);
std::vector<std::string>::iterator itr = strvec.begin();
while(itr != strvec.end()) {
listbox.items.add(*itr);
++itr;
}
boost::array<std::string, 3> strarr = {"ram", "mohan", "sita"};
BOOST_FOREACH(std::string & str, strarr) {
listbox.items.add(str);
}
Unlike it's most popular commercial competitor, numpy pretty much from the outset is about "arbitrary-dimensional" arrays, that's why the core class is called ndarray
. You can check the dimensionality of a numpy array using the .ndim
property. The .shape
property is a tuple of length .ndim
containing the length of each dimensions. Currently, numpy can handle up to 32 dimensions:
a = np.ones(32*(1,))
a
# array([[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[ 1.]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]])
a.shape
# (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
a.ndim
# 32
If a numpy array happens to be 2d like your second example, then it's appropriate to think about it in terms of rows and columns. But a 1d array in numpy is truly 1d, no rows or columns.
If you want something like a row or column vector you can achieve this by creating a 2d array with one of its dimensions equal to 1.
a = np.array([[1,2,3]]) # a 'row vector'
b = np.array([[1],[2],[3]]) # a 'column vector'
# or if you don't want to type so many brackets:
b = np.array([[1,2,3]]).T
<h1 ng-attr-contenteditable="{{isTrue || undefined }}">{{content.title}}</h1>
will produce when isTrue=true :
<h1 contenteditable="true">{{content.title}}</h1>
and when isTrue=false :
<h1>{{content.title}}</h1>
The get_ddl procedure for a PACKAGE will return both spec AND body, so it will be better to change the query on the all_objects so the package bodies are not returned on the select.
So far I changed the query to this:
SELECT DBMS_METADATA.GET_DDL(REPLACE(object_type, ' ', '_'), object_name, owner)
FROM all_OBJECTS
WHERE (OWNER = 'OWNER1')
and object_type not like '%PARTITION'
and object_type not like '%BODY'
order by object_type, object_name;
Although other changes might be needed depending on the object types you are getting...
In Spring Boot 2.2.x
you need to configure it like this:
@Bean
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
return builder.build()
}
Kotlin:
@Bean
fun objectMapper(builder: Jackson2ObjectMapperBuilder) = builder.build()
I just wanted to share some of my results...
I have text files, which apparently came from a Linux system, so I only have a vbLF
/Chr(10)
at the end of each line and not vbCR
/Chr(13)
.
Note 1:
- This meant that the
Line Input
method would read in the entire file, instead of just one line at a time.
From my research testing small (152KB) & large (2778LB) files, both on and off the network I found the following:
Open FileName For Input: Line Input
was the slowest (See Note 1 above)
Open FileName For Binary Access Read: Input
was the fastest for reading the whole file
FSO.OpenTextFile: ReadLine
was fast, but a bit slower then Binary Input
Note 2:
If I just needed to check the file header (first 1-2 lines) to check if I had the proper file/format, then
FSO.OpenTextFile
was the fastest, followed very closely byBinary Input
.The drawback with the
Binary Input
is that you have to know how many characters you want to read.- On normal files,
Line Input
would also be a good option as well, but I couldn't test due to Note 1.
Note 3:
- Obviously, the files on the network showed the largest difference in read speed. They also showed the greatest benefit from reading the file a second time (although there are certainly memory buffers that come into play here).
By dynamically allocating a Movie object with new Movie()
, you get a pointer to the new object. You do not need a second vector for the movies, just store the pointers and you can access them. Like Brian wrote, the vector would be defined as
std::vector<Movie *> movies
But be aware that the vector will not delete your objects afterwards, which will result in a memory leak. It probably doesn't matter for your homework, but normally you should delete all pointers when you don't need them anymore.
A SQL View is a virtual table, which is based on SQL SELECT query. A view references one or more existing database tables or other views. It is the snap shot of the database whereas a stored procedure is a group of Transact-SQL statements compiled into a single execution plan.
View is simple showcasing data stored in the database tables whereas a stored procedure is a group of statements that can be executed.
A view is faster as it displays data from the tables referenced whereas a store procedure executes sql statements.
Check this article : View vs Stored Procedures . Exactly what you are looking for
You would generally test these sorts of things in an integration test, which actually connects to a service. To do a unit test, you should test the objects used by your servlet's doGet/doPost methods.
In general you don't want to have much code in your servlet methods, you would want to create a bean class to handle operations and pass your own objects to it and not servlet API objects.
Example for a public system resource:
// this will get id for android.R.drawable.ic_dialog_alert
int id = Resources.getSystem().getIdentifier("ic_dialog_alert", "drawable", "android");
Another way is to refer the documentation for android.R.drawable class.
download the library Gradle:
compile 'com.google.code.gson:gson:2.8.2'
To use the library in a method.
Gson gson = new Gson();
//transform a java object to json
System.out.println("json =" + gson.toJson(Object.class).toString());
//Transform a json to java object
String json = string_json;
List<Object> lstObject = gson.fromJson(json_ string, Object.class);
You have to tell your compiler where is the include directory. Something like this:
gcc -I/usr/lib/jvm/jdk1.7.0_07/include
But it depends on your makefile.
You can use tee
to write the result of your query to a file:
tee somepath\filename.txt
Adding the following on the div surrounding the element in question fixed this for me.
-webkit-transform-style: preserve-3d;
The jagged edges were appearing around the video window in my case.
I have never seen it done that way in JavaScript. If you want a function with optional parameters that get assigned default values if the parameters are omitted, here's a way to do it:
function(a, b) {
if (typeof a == "undefined") {
a = 10;
}
if (typeof b == "undefined") {
a = 20;
}
alert("a: " + a + " b: " + b);
}
It works with Android Studio 1.2 + OpenCV-2.4.11-android-sdk (.zip), too.
Just do the following:
1) Follow the answer that starts with "You can do this very easily in Android Studio. Follow the steps below to add OpenCV in your project as library." by TGMCians.
2) Modify in the <yourAppDir>\libraries\opencv
folder your newly created build.gradle
to (step 4 in TGMCians' answer, adapted to OpenCV2.4.11-android-sdk and using gradle 1.1.0):
apply plugin: 'android-library'
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.1.0'
}
}
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
minSdkVersion 8
targetSdkVersion 21
versionCode 2411
versionName "2.4.11"
}
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
res.srcDirs = ['res']
aidl.srcDirs = ['src']
}
}
}
3) *.so files that are located in the directories "armeabi", "armeabi-v7a", "mips", "x86"
can be found under (default OpenCV-location): ..\OpenCV-2.4.11-android-sdk\OpenCV-android-sdk\sdk\native\libs
(step 9 in TGMCians' answer).
Enjoy and if this helped, please give a positive reputation. I need 50 to answer directly to answers (19 left) :)
Hope, this would be of some help.
$('input[type=checkbox]').change(function () {
if ($(this).prop("checked")) {
//do the stuff that you would do when 'checked'
return;
}
//Here do the stuff you want to do when 'unchecked'
});
This seems to be fixed in Indigo Eclipse now, there's a video showing someone install android eclipse on youtube?
Here's an answer to a 2-year old question in case it helps anyone else with the same problem.
Based upon the information you've provided, a permissions issue on the file (or files) would be one cause of the same 500 Internal Server Error.
To check whether this is the problem (if you can't get more detailed information on the error), navigate to the directory in Terminal and run the following command:
ls -la
If you see limited permissions - e.g. -rw-------@
against your file, then that's your problem.
The solution then is to run chmod 644
on the problem file(s) or chmod 755
on the directories. See this answer - How do I set chmod for a folder and all of its subfolders and files? - for a detailed explanation of how to change permissions.
By way of background, I had precisely the same problem as you did on some files that I had copied over from another Mac via Google Drive, which transfer had stripped most of the permissions from the files.
The screenshot below illustrates. The index.php file with the -rw-------@
permissions generates a 500 Internal Server Error, while the index_finstuff.php (precisely the same content!) with -rw-r--r--@
permissions is fine. Changing the permissions on the index.php immediately resolves the problem.
In other words, your PHP code and the server may both be fine. However, the limited read permissions on the file may be forbidding the server from displaying the content, causing the 500 Internal Server Error message to be displayed instead.
That's exactly what cursor: pointer;
is supposed to do.
If you want the cursor to remain normal, you should be using cursor: default
Suppose, for example, that we have a arrays of strings:
String[] strings = {"1", "2", "3"};
With Lambda Expressions [1] [2] (since Java 8), you can do the next ?:
int[] array = Arrays.asList(strings).stream().mapToInt(Integer::parseInt).toArray();
? This is another way:
int[] array = Arrays.stream(strings).mapToInt(Integer::parseInt).toArray();
—————————
Notes
1. Lambda Expressions in The Java Tutorials.
2. Java SE 8: Lambda Quick Start
This type is defined in the C header <stdint.h>
which is part of the C++11 standard but not standard in C++03. According to the Wikipedia page on the header, it hasn't shipped with Visual Studio until VS2010.
In the meantime, you could probably fake up your own version of the header by adding typedef
s that map Microsoft's custom integer types to the types expected by C. For example:
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
/* ... etc. ... */
Hope this helps!
1) If the object is created via a pointer and that pointer is later deleted or given a new address to point to, does the object that it was pointing to call its destructor (assuming nothing else is pointing to it)?
It depends on the type of pointers. For example, smart pointers often delete their objects when they are deleted. Ordinary pointers do not. The same is true when a pointer is made to point to a different object. Some smart pointers will destroy the old object, or will destroy it if it has no more references. Ordinary pointers have no such smarts. They just hold an address and allow you to perform operations on the objects they point to by specifically doing so.
2) Following up on question 1, what defines when an object goes out of scope (not regarding to when an object leaves a given {block}). So, in other words, when is a destructor called on an object in a linked list?
That's up to the implementation of the linked list. Typical collections destroy all their contained objects when they are destroyed.
So, a linked list of pointers would typically destroy the pointers but not the objects they point to. (Which may be correct. They may be references by other pointers.) A linked list specifically designed to contain pointers, however, might delete the objects on its own destruction.
A linked list of smart pointers could automatically delete the objects when the pointers are deleted, or do so if they had no more references. It's all up to you to pick the pieces that do what you want.
3) Would you ever want to call a destructor manually?
Sure. One example would be if you want to replace an object with another object of the same type but don't want to free memory just to allocate it again. You can destroy the old object in place and construct a new one in place. (However, generally this is a bad idea.)
// pointer is destroyed because it goes out of scope,
// but not the object it pointed to. memory leak
if (1) {
Foo *myfoo = new Foo("foo");
}
// pointer is destroyed because it goes out of scope,
// object it points to is deleted. no memory leak
if(1) {
Foo *myfoo = new Foo("foo");
delete myfoo;
}
// no memory leak, object goes out of scope
if(1) {
Foo myfoo("foo");
}
You can use this QString constructor for conversion from QByteArray to QString:
QString(const QByteArray &ba)
QByteArray data;
QString DataAsString = QString(data);
If you are using Java 8, you could try something like this:
public Set<Number> difference(final Set<Number> set1, final Set<Number> set2){
final Set<Number> larger = set1.size() > set2.size() ? set1 : set2;
final Set<Number> smaller = larger.equals(set1) ? set2 : set1;
return larger.stream().filter(n -> !smaller.contains(n)).collect(Collectors.toSet());
}
The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
index.php
<html>
<body>
<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>
</body>
</html>
site2.php
<html>
<body>
Hello <?php echo $_POST["name"]; ?>!<br>
Your mail is <?php echo $_POST["mail"]; ?>.
</body>
</html>
output
Hello "name" !
Your email is "[email protected]" .
If your question is, is there some built-in thing that will do the search for you, then no, there isn't. You basically loop through the array using either String#indexOf
or a regular expression to test the strings.
For the loop, you have at least three choices:
A boring old for
loop.
On ES5-enabled environments (or with a shim), Array#filter
.
Because you're using jQuery, jQuery.map
.
Boring old for
loop example:
function search(source, name) {
var results = [];
var index;
var entry;
name = name.toUpperCase();
for (index = 0; index < source.length; ++index) {
entry = source[index];
if (entry && entry.name && entry.name.toUpperCase().indexOf(name) !== -1) {
results.push(entry);
}
}
return results;
}
Where you'd call that with obj.list
as source
and the desired name fragment as name
.
Or if there's any chance there are blank entries or entries without names, change the if
to:
if (entry && entry.name && entry.name.toUpperCase().indexOf(name) !== -1) {
Array#filter
example:
function search(source, name) {
var results;
name = name.toUpperCase();
results = source.filter(function(entry) {
return entry.name.toUpperCase().indexOf(name) !== -1;
});
return results;
}
And again, if any chance that there are blank entries (e.g., undefined
, as opposed to missing; filter
will skip missing entries), change the inner return to:
return entry && entry.name && entry.name.toUpperCase().indexOf(name) !== -1;
jQuery.map
example (here I'm assuming jQuery
= $
as is usually the case; change $
to jQuery
if you're using noConflict
):
function search(source, name) {
var results;
name = name.toUpperCase();
results = $.map(source, function(entry) {
var match = entry.name.toUpperCase().indexOf(name) !== -1;
return match ? entry : null;
});
return results;
}
(And again, add entry && entry.name &&
in there if necessary.)
if it is not necessary to modify the variable than a general workaround for this kind of problem would be to extract the part of code which use lambda and use final keyword on method-parameter.
Just to show it in a different format that I prefer to use for some reason: The first way returns your itemList as an System.Linq.IOrderedQueryable
using(var context = new ItemEntities())
{
var itemList = context.Items.Where(x => !x.Items && x.DeliverySelection)
.OrderByDescending(x => x.Delivery.SubmissionDate);
}
That approach is fine, but if you wanted it straight into a List Object:
var itemList = context.Items.Where(x => !x.Items && x.DeliverySelection)
.OrderByDescending(x => x.Delivery.SubmissionDate).ToList();
All you have to do is append a .ToList() call to the end of the Query.
Something to note, off the top of my head I can't recall if the !(not) expression is acceptable in the Where() call.
If you have a browser that doesn't support the calc
expression, it's not hard to mimic with jQuery:
$('#yourEl').css('width', '100%').css('width', '-=100px');
It's much easier to let jQuery handle the relative calculation than doing it yourself.
If we get the value as int
and we set it to String
, the error occurs. PFB my solution,
Textview = tv_property_count;
int property_id;
tv_property_count.setText(String.valueOf(property_id));
I am gonna explain with a simple example code which takes a compare
function as parameter to another sorting
function.
Lets say I have a bubble sort function that takes a custom compare function and uses it instead of a fixed if statement.
Compare Function
bool compare(int a, int b) {
return a > b;
}
Now , the Bubble sort that takes another function as its parameter to perform comparison
Bubble sort function
void bubble_sort(int arr[], int n, bool (&cmp)(int a, int b)) {
for (int i = 0;i < n - 1;i++) {
for (int j = 0;j < (n - 1 - i);j++) {
if (cmp(arr[j], arr[j + 1])) {
swap(arr[j], arr[j + 1]);
}
}
}
}
Finally , the main
which calls the Bubble sort function by passing the boolean compare function as argument.
int main()
{
int i, n = 10, key = 11;
int arr[10] = { 20, 22, 18, 8, 12, 3, 6, 12, 11, 15 };
bubble_sort(arr, n, compare);
cout<<"Sorted Order"<<endl;
for (int i = 0;i < n;i++) {
cout << arr[i] << " ";
}
}
Output:
Sorted Order
3 6 8 11 12 12 15 18 20 22
Use this to transform a moment object into a date object:
From http://momentjs.com/docs/#/displaying/as-javascript-date/
moment().toDate();
Yields:
Tue Nov 04 2014 14:04:01 GMT-0600 (CST)
Here's a simple, pure-Python implementation. It should be used when performance is not critical (included for future Googlers).
import string
allowed = set(string.ascii_lowercase + string.digits + '.')
def check(test_str):
set(test_str) <= allowed
Regarding performance, iteration will probably be the fastest method. Regexes have to iterate through a state machine, and the set equality solution has to build a temporary set. However, the difference is unlikely to matter much. If performance of this function is very important, write it as a C extension module with a switch statement (which will be compiled to a jump table).
Here's a C implementation, which uses if statements due to space constraints. If you absolutely need the tiny bit of extra speed, write out the switch-case. In my tests, it performs very well (2 seconds vs 9 seconds in benchmarks against the regex).
#define PY_SSIZE_T_CLEAN
#include <Python.h>
static PyObject *check(PyObject *self, PyObject *args)
{
const char *s;
Py_ssize_t count, ii;
char c;
if (0 == PyArg_ParseTuple (args, "s#", &s, &count)) {
return NULL;
}
for (ii = 0; ii < count; ii++) {
c = s[ii];
if ((c < '0' && c != '.') || c > 'z') {
Py_RETURN_FALSE;
}
if (c > '9' && c < 'a') {
Py_RETURN_FALSE;
}
}
Py_RETURN_TRUE;
}
PyDoc_STRVAR (DOC, "Fast stringcheck");
static PyMethodDef PROCEDURES[] = {
{"check", (PyCFunction) (check), METH_VARARGS, NULL},
{NULL, NULL}
};
PyMODINIT_FUNC
initstringcheck (void) {
Py_InitModule3 ("stringcheck", PROCEDURES, DOC);
}
Include it in your setup.py:
from distutils.core import setup, Extension
ext_modules = [
Extension ('stringcheck', ['stringcheck.c']),
],
Use as:
>>> from stringcheck import check
>>> check("abc")
True
>>> check("ABC")
False
Code bellow may help if you want to exclude boolean type from serialization either:
@JsonInclude(JsonInclude.Include.NON_ABSENT)
Simply instantiate an anonymous function:
var foo = new function () {
this.a = 5;
this.b = 6;
this.c = this.a + this.b;
};
Since different browsers are rendering border, padding, margin and etc in different way. I wrote a little function to retrieve top and left positions of specific element in every root element that you want in precise dimension:
function getTop(root, offset) {
var rootRect = root.getBoundingClientRect();
var offsetRect = offset.getBoundingClientRect();
return offsetRect.top - rootRect.top;
}
For retrieve left position you must return:
return offsetRect.left - rootRect.left;
It's may be due difference reportviewer version in your project and VS
To enable passive ftp on an EC2 server, you need to configure the ports that your ftp server should use for inbound connections, then open a list of available ports for the ftp client data connections.
I'm not that familiar with linux, but the commands you posted are the steps to install the ftp server, configure the ec2 firewall rules (through the AWS API), then configure the ftp server to use the ports you allowed on the ec2 firewall.
So this step installs the ftp client (VSFTP)
> yum install vsftpd
These steps configure the ftp client
> vi /etc/vsftpd/vsftpd.conf
-- Add following lines at the end of file --
pasv_enable=YES
pasv_min_port=1024
pasv_max_port=1048
pasv_address=<Public IP of your instance>
> /etc/init.d/vsftpd restart
but the other two steps are easier done through the amazon console under EC2 Security groups. There you need to configure the security group that is assigned to your server to allow connections on ports 20,21, and 1024-1048
Change the = to : to
fix the error.
var makeRequest = function(message) {<br>
var options = {<br>
host: 'localhost',<br>
port : 8080,<br>
path : '/',<br>
method: 'POST'<br>
}
First, you should understand the pointer is not complex. A pointer is showing the address of the variable.
Example:
int a = 10;
int *p = &a; // This means giving a pointer of variable "a" to int pointer variable "p"
And, you should understand "Pointer is an address" and "address is numerical value". So, you can get the address of variable as Integer.
int a = 10;
unsigned long address = (unsigned long)&a;
// comparison
printf("%p\n", &a);
printf("%ld\n", address);
output is below
0x7fff1216619c
7fff1216619c
Note:
If you use a 64-bit computer, you can't get pointer by the way below.
int a = 10;
unsigned int address = (unsigned int)&a;
Because pointer is 8 bytes (64 bit) on a 64-bit machine, but int is 4 bytes. So, you can't give an 8-byte memory address to 4 bytes variable.
You have to use long long
or long
to get an address of the variable.
long long
is always 8 bytes.long
is 4 bytes when code was compiled for a 32-bit machine.long
is 8 bytes when code was compiled for a 64-bit machine.Therefore, you should use long
to receive a pointer.
You can simply pass the functions as a list:
In [20]: df.groupby("dummy").agg({"returns": [np.mean, np.sum]})
Out[20]:
mean sum
dummy
1 0.036901 0.369012
or as a dictionary:
In [21]: df.groupby('dummy').agg({'returns':
{'Mean': np.mean, 'Sum': np.sum}})
Out[21]:
returns
Mean Sum
dummy
1 0.036901 0.369012
Don't go there. As a long term Mac developer, I can assure you, no solution is really working well. I tried so many solutions, but they are all not too good. I think the problem is that Apple does not really document the meta data format for the necessary data.
Here's how I'm doing it for a long time, very successfully:
Create a new DMG, writeable(!), big enough to hold the expected binary and extra files like readme (sparse might work).
Mount the DMG and give it a layout manually in Finder or with whatever tools suits you for doing that (see FileStorm link at the bottom for a good tool). The background image is usually an image we put into a hidden folder (".something") on the DMG. Put a copy of your app there (any version, even outdated one will do). Copy other files (aliases, readme, etc.) you want there, again, outdated versions will do just fine. Make sure icons have the right sizes and positions (IOW, layout the DMG the way you want it to be).
Unmount the DMG again, all settings should be stored by now.
Write a create DMG script, that works as follows:
This method may not sound optimal, but trust me, it works really well in practice. You can put the original DMG (DMG template) even under version control (e.g. SVN), so if you ever accidentally change/destroy it, you can just go back to a revision where it was still okay. You can add the DMG template to your Xcode project, together with all other files that belong onto the DMG (readme, URL file, background image), all under version control and then create a target (e.g. external target named "Create DMG") and there run the DMG script of above and add your old main target as dependent target. You can access files in the Xcode tree using ${SRCROOT} in the script (is always the source root of your product) and you can access build products by using ${BUILT_PRODUCTS_DIR} (is always the directory where Xcode creates the build results).
Result: Actually Xcode can produce the DMG at the end of the build. A DMG that is ready to release. Not only you can create a relase DMG pretty easy that way, you can actually do so in an automated process (on a headless server if you like), using xcodebuild from command line (automated nightly builds for example).
Regarding the initial layout of the template, FileStorm is a good tool for doing it. It is commercial, but very powerful and easy to use. The normal version is less than $20, so it is really affordable. Maybe one can automate FileStorm to create a DMG (e.g. via AppleScript), never tried that, but once you have found the perfect template DMG, it's really easy to update it for every release.
Linux/OS X:
Starting from the current directory, recursively find all files ending in .dll or .exe
find . -type f | grep -P "\.dll$|\.exe$"
Starting from the current directory, recursively find all files that DON'T end in .dll or .exe
find . -type f | grep -vP "\.dll$|\.exe$"
Notes:
(1) The P option in grep indicates that we are using the Perl style to write our regular expressions to be used in conjunction with the grep command. For the purpose of excecuting the grep command in conjunction with regular expressions, I find that the Perl style is the most powerful style around.
(2) The v option in grep instructs the shell to exclude any file that satisfies the regular expression
(3) The $ character at the end of say ".dll$" is a delimiter control character that tells the shell that the filename string ends with ".dll"
It worked for me after adding the following dependency in pom,
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.3.0.Final</version>
</dependency>
easy
// Creating and adding an element to the page at the same time.
$( "ul" ).append( "<li>list item</li>" );
I think you're getting confused about what can hold what in JSON.Net.
JToken
is a generic representation of a JSON value of any kind. It could be a string, object, array, property, etc.JProperty
is a single JToken
value paired with a name. It can only be added to a JObject
, and its value cannot be another JProperty
.JObject
is a collection of JProperties
. It cannot hold any other kind of JToken
directly.In your code, you are attempting to add a JObject
(the one containing the "banana" data) to a JProperty
("orange") which already has a value (a JObject
containing {"colour":"orange","size":"large"}
). As you saw, this will result in an error.
What you really want to do is add a JProperty
called "banana" to the JObject
which contains the other fruit JProperties
. Here is the revised code:
JObject foodJsonObj = JObject.Parse(jsonText);
JObject fruits = foodJsonObj["food"]["fruit"] as JObject;
fruits.Add("banana", JObject.Parse(@"{""colour"":""yellow"",""size"":""medium""}"));
A quick way to do it on your Github repo would be as followed:
In my case the reason was, I only forgot the closing
</script>
tag.
But that caused the same error message.
props.put("mail.smtp.ssl.trust", "smtp.gmail.com");
I guess this is because your nodejs cert has expired. Type this line : npm set registry http://registry.npmjs.org/
and after that try again with npm install . This actually solved my problem.
An epoch reference date is a point on the timeline from which we count time. Moments before that point are counted with a negative number, moments after are counted with a positive number.
Why is 1 January 1970 00:00:00 considered the epoch time?
No, not the epoch, an epoch. There are many epochs in use.
This choice of epoch is arbitrary.
Major computers systems and libraries use any of at least a couple dozen various epochs. One of the most popular epochs is commonly known as Unix Time, using the 1970 UTC moment you mentioned.
While popular, Unix Time’s 1970 may not be the most common. Also in the running for most common would be January 0, 1900 for countless Microsoft Excel & Lotus 1-2-3 spreadsheets, or January 1, 2001 used by Apple’s Cocoa framework in over a billion iOS/macOS machines worldwide in countless apps. Or perhaps January 6, 1980 used by GPS devices?
Different systems use different granularity in counting time.
Even the so-called “Unix Time” varies, with some systems counting whole seconds and some counting milliseconds. Many database such as Postgres use microseconds. Some, such as the modern java.time framework in Java 8 and later, use nanoseconds. Some use still other granularities.
Because there is so much variance in the use of an epoch reference and in the granularities, it is generally best to avoid communicating moments as a count-from-epoch. Between the ambiguity of epoch & granularity, plus the inability of humans to perceive meaningful values (and therefore miss buggy values), use plain text instead of numbers.
The ISO 8601 standard provides an extensive set of practical well-designed formats for expressing date-time values as text. These formats are easy to parse by machine as well as easy to read by humans across cultures.
These include:
2019-01-23
2019-01-23T12:34:56.123456Z
2019-01-23T18:04:56.123456+05:30
2019-234
I had a similar problem and found that if you remove the size definition, it works for some reason.
Remove:
<size
android:width="60dp"
android:height="40dp" />
from the shape.
Let me know if this works!
There are two setting.xml in windows.
%MAVEN_HOME%\conf\
%userprofile%\.m2\
If %userprofile%\.m2\setting.xml
takes effect, maven will not access %MAVEN_HOME%\conf\setting.xml
.
The problem is that when you initialize ks
, the value
hasn't been set.
You need to fetch the value when user submits the form. So you need to initialize the ks
inside the callback function
(function($){
$(document).ready(function(){
$('#data').submit(function(e){
//Here it will fetch the value of #keywords
var ks = $('#keywords').val().split("\n");
...
});
});
})(jQuery);
Note that the command for activating an environment has changed in Conda version 4.4. The recommended way of activating an environment is now conda activate myenv
instead of source activate myenv
. To enable the new syntax, you should modify your .bashrc
file. The line that currently reads something like
export PATH="<path_to_your_conda_install>/bin:$PATH"
Should be changed to
. <path_to_your_conda_install>/etc/profile.d/conda.sh
This only adds the conda
command to the path, but does not yet activate the base
environment (which was previously called root
). To do also that, add another line
conda activate base
after the first command. See all the details in Anaconda's blog post from December 2017. (I think that this page is currently missing a newline between the two lines, it says .../conda.shconda activate base
).
(This answer is valid for Linux, but it might be relevant for Windows and Mac as well)
This is the problem
double a[] = null;
Since a
is null
, NullPointerException
will arise every time you use it until you initialize it. So this:
a[i] = var;
will fail.
A possible solution would be initialize it when declaring it:
double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7
IMO more important than solving this exception, is the fact that you should learn to read the stacktrace and understand what it says, so you could detect the problems and solve it.
java.lang.NullPointerException
This exception means there's a variable with null
value being used. How to solve? Just make sure the variable is not null
before being used.
at twoten.TwoTenB.(TwoTenB.java:29)
This line has two parts:
<init>
method in class TwoTenB
declared in package twoten
. When you encounter an error message with SomeClassName.<init>
, means the error was thrown while creating a new instance of the class e.g. executing the constructor (in this case that seems to be the problem).a[i] = var;
.From this line, other lines will be similar to tell you where the error arose. So when reading this:
at javapractice.JavaPractice.main(JavaPractice.java:32)
It means that you were trying to instantiate a TwoTenB
object reference inside the main
method of your class JavaPractice
declared in javapractice
package.
Simple and easy :)
At java file, write:
private int intOrientation;
at onCreate
method and before setContentView
write:
intOrientation = getResources().getConfiguration().orientation;
if (intOrientation == Configuration.ORIENTATION_PORTRAIT)
setContentView(R.layout.activity_main);
else
setContentView(R.layout.layout_land); // I tested it and it works fine.
Try "perldoc -l":
$ perldoc -l Log::Dispatch /usr/local/share/perl/5.26.1/Log/Dispatch.pm
git stash show -p | git apply --reverse
Warning, that would not in every case: "git apply -R
"(man) did not handle patches that touch the same path twice correctly, which has been corrected with Git 2.30 (Q1 2021).
This is most relevant in a patch that changes a path from a regular file to a symbolic link (and vice versa).
See commit b0f266d (20 Oct 2020) by Jonathan Tan (jhowtan
).
(Merged by Junio C Hamano -- gitster
-- in commit c23cd78, 02 Nov 2020)
apply
: when-R
, also reverse list of sectionsHelped-by: Junio C Hamano
Signed-off-by: Jonathan Tan
A patch changing a symlink into a file is written with 2 sections (in the code, represented as "struct patch"): firstly, the deletion of the symlink, and secondly, the creation of the file.
When applying that patch with
-R
, the sections are reversed, so we get: (1) creation of a symlink, then (2) deletion of a file.This causes an issue when the "deletion of a file" section is checked, because Git observes that the so-called file is not a file but a symlink, resulting in a "wrong type" error message.
What we want is: (1) deletion of a file, then (2) creation of a symlink.
In the code, this is reflected in the behavior of
previous_patch()
when invoked fromcheck_preimage()
when the deletion is checked.
Creation then deletion means that when the deletion is checked,previous_patch()
returns the creation section, triggering a mode conflict resulting in the "wrong type" error message.But deletion then creation means that when the deletion is checked,
previous_patch()
returnsNULL
, so the deletion mode is checked against lstat, which is what we want.There are also other ways a patch can contain 2 sections referencing the same file, for example, in 7a07841c0b ("
git-apply
: handle a patch that touches the same path more than once better", 2008-06-27, Git v1.6.0-rc0 -- merge). "git apply -R
"(man) fails in the same way, and this commit makes this case succeed.Therefore, when building the list of sections, build them in reverse order (by adding to the front of the list instead of the back) when
-R
is passed.
In Windows, you can use /
in your path just like Linux or macOS in all places as long as you use PowerShell as your command-line interface. It comes pre-installed on Windows and it supports many Linux commands like ls
command.
If you use Windows Command Prompt (the one that appears when you type cmd
in Windows Start Menu), you need to specify paths with \
just inside it. You can use /
paths in all other places (code editor, Python interactive mode, etc.).
This can be done using Mongo's db.copyDatabase
method:
db.copyDatabase(fromdb, todb, fromhost, username, password)
Reference: http://docs.mongodb.org/manual/reference/method/db.copyDatabase/
Check that you have the latest version of the SDK installed in either C:\Program Files\Java
or C:\Program Files (x86)\Java
Then go to VS2015 and follow the path tools - options - Xamarin - Android settings and in the section JDK location select change and go to look for the version you have either x64 or x32.
It is correctly mentioned in the error: you cannot make a static reference to non-static type T. The reason is the type parameter T
can be replaced by any of the type argument e.g. Clazz<String>
or Clazz<integer>
etc. But static fields/methods are shared by all non-static objects of the class.
The following excerpt is taken from the doc:
A class's static field is a class-level variable shared by all non-static objects of the class. Hence, static fields of type parameters are not allowed. Consider the following class:
public class MobileDevice<T> { private static T os; // ... }
If static fields of type parameters were allowed, then the following code would be confused:
MobileDevice<Smartphone> phone = new MobileDevice<>(); MobileDevice<Pager> pager = new MobileDevice<>(); MobileDevice<TabletPC> pc = new MobileDevice<>();
Because the static field os is shared by phone, pager, and pc, what is the actual type of os? It cannot be Smartphone, Pager, and TabletPC at the same time. You cannot, therefore, create static fields of type parameters.
As rightly pointed out by chris in his answer you need to use type parameter with the method and not with the class in this case. You can write it like:
static <E> void doIt(E object)
The best way would be to use .each()
var num = 0;
$('.className').each(function(){
num++;
});
I wrote a pypi/github package for this question because I needed a solution as well.
https://github.com/bucknerns/logtail
Install:
pip install logtail
Usage: tails changed files
logtail <log dir> [<glob match: default=*.log>]
Usage2: Opens latest changed file in editor
editlatest <log dir> [<glob match: default=*.log>]
Update: Swift 3
class ButtonIconRight: UIButton {
override func imageRect(forContentRect contentRect:CGRect) -> CGRect {
var imageFrame = super.imageRect(forContentRect: contentRect)
imageFrame.origin.x = super.titleRect(forContentRect: contentRect).maxX - imageFrame.width
return imageFrame
}
override func titleRect(forContentRect contentRect:CGRect) -> CGRect {
var titleFrame = super.titleRect(forContentRect: contentRect)
if (self.currentImage != nil) {
titleFrame.origin.x = super.imageRect(forContentRect: contentRect).minX
}
return titleFrame
}
}
Original answer for Swift 2:
A solution that handles all horizontal alignments, with a Swift implementation example. Just translate to Objective-C if needed.
class ButtonIconRight: UIButton {
override func imageRectForContentRect(contentRect:CGRect) -> CGRect {
var imageFrame = super.imageRectForContentRect(contentRect)
imageFrame.origin.x = CGRectGetMaxX(super.titleRectForContentRect(contentRect)) - CGRectGetWidth(imageFrame)
return imageFrame
}
override func titleRectForContentRect(contentRect:CGRect) -> CGRect {
var titleFrame = super.titleRectForContentRect(contentRect)
if (self.currentImage != nil) {
titleFrame.origin.x = CGRectGetMinX(super.imageRectForContentRect(contentRect))
}
return titleFrame
}
}
Also worth noting that it handles quite well image & title insets.
Inspired from jasongregori answer ;)
Your command is wrong.
Linux
java -- version
macOS
java -version
You can't use those commands other way around.
I tried to do something similar and used a workaround solution: I thought about implicit and explicit operator on structure: The idea is to wrap the Type in a structure that can be converted into Type implicitly.
Here is such a structure:
public struct InterfaceType { private Type _type;
public InterfaceType(Type type)
{
CheckType(type);
_type = type;
}
public static explicit operator Type(InterfaceType value)
{
return value._type;
}
public static implicit operator InterfaceType(Type type)
{
return new InterfaceType(type);
}
private static void CheckType(Type type)
{
if (type == null) throw new NullReferenceException("The type cannot be null");
if (!type.IsInterface) throw new NotSupportedException(string.Format("The given type {0} is not an interface, thus is not supported", type.Name));
}
}
basic usage:
// OK
InterfaceType type1 = typeof(System.ComponentModel.INotifyPropertyChanged);
// Throws an exception
InterfaceType type2 = typeof(WeakReference);
You have to imagine your own mecanism around this, but an example could be a method taken a InterfaceType in parameter instead of a type
this.MyMethod(typeof(IMyType)) // works
this.MyMethod(typeof(MyType)) // throws exception
A method to override that should returns interface types:
public virtual IEnumerable<InterfaceType> GetInterfaces()
There are maybe things to do with generics also, but I didn't tried
Hope this can help or gives ideas :-)
You can use following regular expression construct
Punctuation: One of !"#$%&'()*+,-./:;<=>?@[]^_`{|}~
inputString.replaceAll("\\p{Punct}", "");
Often, wild cards operate with two type of jokers:
? - any character (one and only one)
* - any characters (zero or more)
so you can easily convert these rules into appropriate regular expression:
// If you want to implement both "*" and "?"
private static String WildCardToRegular(String value) {
return "^" + Regex.Escape(value).Replace("\\?", ".").Replace("\\*", ".*") + "$";
}
// If you want to implement "*" only
private static String WildCardToRegular(String value) {
return "^" + Regex.Escape(value).Replace("\\*", ".*") + "$";
}
And then you can use Regex as usual:
String test = "Some Data X";
Boolean endsWithEx = Regex.IsMatch(test, WildCardToRegular("*X"));
Boolean startsWithS = Regex.IsMatch(test, WildCardToRegular("S*"));
Boolean containsD = Regex.IsMatch(test, WildCardToRegular("*D*"));
// Starts with S, ends with X, contains "me" and "a" (in that order)
Boolean complex = Regex.IsMatch(test, WildCardToRegular("S*me*a*X"));
Convert your string to DateTime
and then use DateTime.ToString("yyyy-MM-dd");
DateTime temp = DateTime.ParseExact(sourceDate, "dd-MM-yyyy", CultureInfo.InvariantCulture);
string str = temp.ToString("yyyy-MM-dd");
java.util.Date
represents an instant in time, with no reference to a particular time zone or calendar system. It does hold both date and time though - it's basically a number of milliseconds since the Unix epoch.
Alternatively you can use java.util.Calendar
which does know about both of those things.
Personally I would strongly recommend you use Joda Time which is a much richer date/time API. It allows you to express your data much more clearly, with types for "just dates", "just local times", "local date/time", "instant", "date/time with time zone" etc. Most of the types are also immutable, which is a huge benefit in terms of code clarity.
If you don't care about formatting and you just need some quick date, you can use this:
import time
print(time.ctime())
Via Jquery:
$(location).attr('href','http://example.com/Registration/Success/');
Useful simple class are forked by me on: https://gist.github.com/kiuz/816e24aa787c2d102dd0
public class OSValidator {
private static String OS = System.getProperty("os.name").toLowerCase();
public static void main(String[] args) {
System.out.println(OS);
if (isWindows()) {
System.out.println("This is Windows");
} else if (isMac()) {
System.out.println("This is Mac");
} else if (isUnix()) {
System.out.println("This is Unix or Linux");
} else if (isSolaris()) {
System.out.println("This is Solaris");
} else {
System.out.println("Your OS is not support!!");
}
}
public static boolean isWindows() {
return OS.contains("win");
}
public static boolean isMac() {
return OS.contains("mac");
}
public static boolean isUnix() {
return (OS.contains("nix") || OS.contains("nux") || OS.contains("aix"));
}
public static boolean isSolaris() {
return OS.contains("sunos");
}
public static String getOS(){
if (isWindows()) {
return "win";
} else if (isMac()) {
return "osx";
} else if (isUnix()) {
return "uni";
} else if (isSolaris()) {
return "sol";
} else {
return "err";
}
}
}
Using IntelliJ IDEA. To generate class diagram select package and press Ctrl + Alt + U:
By default, it displays only class names and not all dependencies. To change it: right click -> Show Categories... and Show dependencies:
To genarate dependencies diagram (UML Deployment diagram) and you use maven go View -> Tool Windows -> Maven Projects and press Ctrl + Alt + U:
Also it is possible to generate more others diagrams. See documentation.
Simple, website view via intent,
Intent viewIntent = new Intent("android.intent.action.VIEW", Uri.parse("http://www.yoursite.in"));
startActivity(viewIntent);
use this simple code toview your website in android app.
Add internet permission in manifest file,
<uses-permission android:name="android.permission.INTERNET" />
yum install python-devel
will work.
If yum
doesn't work then use
apt-get install python-dev
I know this is late, but it does answer your original question.
/*Read the comments the same way that SQL runs the query
1) FROM
2) GROUP
3) SELECT
4) My final notes at the bottom
*/
SELECT
list.invoiceid
, cust.customernumber
, MAX(list.inv_amount) AS invoice_amount/* we select the max because it will be the same for each payment to that invoice (presumably invoice amounts do not vary based on payment) */
, MAX(list.inv_amount) - SUM(list.pay_amount) AS [amount_due]
FROM
Customers AS cust
INNER JOIN
Payments AS pay
ON
pay.customerid = cust.customerid
INNER JOIN ( /* generate a list of payment_ids, their amounts, and the totals of the invoices they billed to*/
SELECT
inpay.paymentid AS paymentid
, inv.invoiceid AS invoiceid
, inv.amount AS inv_amount
, pay.amount AS pay_amount
FROM
InvoicePayments AS inpay
INNER JOIN
Invoices AS inv
ON inv.invoiceid = inpay.invoiceid
INNER JOIN
Payments AS pay
ON pay.paymentid = inpay.paymentid
) AS list
ON
list.paymentid = pay.paymentid
/* so at this point my result set would look like:
-- All my customers (crossed by) every paymentid they are associated to (I'll call this A)
-- Every invoice payment and its association to: its own ammount, the total invoice ammount, its own paymentid (what I call list)
-- Filter out all records in A that do not have a paymentid matching in (list)
-- we filter the result because there may be payments that did not go towards invoices!
*/
GROUP BY
/* we want a record line for each customer and invoice ( or basically each invoice but i believe this makes more sense logically */
cust.customernumber
, list.invoiceid
/*
-- we can improve this query by only hitting the Payments table once by moving it inside of our list subquery,
-- but this is what made sense to me when I was planning.
-- Hopefully it makes it clearer how the thought process works to leave it in there
-- as several people have already pointed out, the data structure of the DB prevents us from looking at customers with invoices that have no payments towards them.
*/
You could try this:
$width:auto;
@mixin clearfix($width) {
@if $width == 'auto' {
// if width is not passed, or empty do this
} @else {
display: inline-block;
width: $width;
}
}
I'm not sure of your intended result, but setting a default value should return false.
This worked for me:
ctrl + h
(Shortcut for replace)find what
box.
[\n\r]+$
or ^[\n\r]+
Replace with
box blankSearch Mode
, select Regex
Replace All
I had to go to BUILD -> CONFIGURATION MANAGER and -- ahem -- check the box next to my project to ensure it actually gets built.
A) To control sys.getdefaultencoding()
output:
python -c 'import sys; print(sys.getdefaultencoding())'
ascii
Then
echo "import sys; sys.setdefaultencoding('utf-16-be')" > sitecustomize.py
and
PYTHONPATH=".:$PYTHONPATH" python -c 'import sys; print(sys.getdefaultencoding())'
utf-16-be
You could put your sitecustomize.py higher in your PYTHONPATH
.
Also you might like to try reload(sys).setdefaultencoding
by @EOL
B) To control stdin.encoding
and stdout.encoding
you want to set PYTHONIOENCODING
:
python -c 'import sys; print(sys.stdin.encoding, sys.stdout.encoding)'
ascii ascii
Then
PYTHONIOENCODING="utf-16-be" python -c 'import sys;
print(sys.stdin.encoding, sys.stdout.encoding)'
utf-16-be utf-16-be
Finally: you can use A) or B) or both!
While Dav is correct that the information isn't directly stored, that doesn't mean you can't ever find out. Here are a few things you can do.
git branch -a --contains <commit>
This will tell you all branches which have the given commit in their history. Obviously this is less useful if the commit's already been merged.
If you are working in the repository in which the commit was made, you can search the reflogs for the line for that commit. Reflogs older than 90 days are pruned by git-gc, so if the commit's too old, you won't find it. That said, you can do this:
git reflog show --all | grep a871742
to find commit a871742. Note that you MUST use the abbreviatd 7 first digits of the commit. The output should be something like this:
a871742 refs/heads/completion@{0}: commit (amend): mpc-completion: total rewrite
indicating that the commit was made on the branch "completion". The default output shows abbreviated commit hashes, so be sure not to search for the full hash or you won't find anything.
git reflog show
is actually just an alias for git log -g --abbrev-commit --pretty=oneline
, so if you want to fiddle with the output format to make different things available to grep for, that's your starting point!
If you're not working in the repository where the commit was made, the best you can do in this case is examine the reflogs and find when the commit was first introduced to your repository; with any luck, you fetched the branch it was committed to. This is a bit more complex, because you can't walk both the commit tree and reflogs simultaneously. You'd want to parse the reflog output, examining each hash to see if it contains the desired commit or not.
This is workflow-dependent, but with good workflows, commits are made on development branches which are then merged in. You could do this:
git log --merges <commit>..
to see merge commits that have the given commit as an ancestor. (If the commit was only merged once, the first one should be the merge you're after; otherwise you'll have to examine a few, I suppose.) The merge commit message should contain the branch name that was merged.
If you want to be able to count on doing this, you may want to use the --no-ff
option to git merge
to force merge commit creation even in the fast-forward case. (Don't get too eager, though. That could become obfuscating if overused.) VonC's answer to a related question helpfully elaborates on this topic.
Use atof()
But this is deprecated, use this instead:
const char* flt = "4.0800";
float f;
sscanf(flt, "%f", &f);
http://www.cplusplus.com/reference/clibrary/cstdlib/atof/
atof()
returns 0
for both failure and on conversion of 0.0
, best to not use it.
The quick and dirty way is using json_encode
and json_decode
which will turn the entire array (including sub elements) into an object.
$clasa = json_decode(json_encode($clasa)); //Turn it into an object
The same can be used to convert an object into an array. Simply add , true
to json_decode
to return an associated array:
$clasa = json_decode(json_encode($clasa), true); //Turn it into an array
An alternate way (without being dirty) is simply a recursive function:
function convertToObject($array) {
$object = new stdClass();
foreach ($array as $key => $value) {
if (is_array($value)) {
$value = convertToObject($value);
}
$object->$key = $value;
}
return $object;
}
or in full code:
<?php
function convertToObject($array) {
$object = new stdClass();
foreach ($array as $key => $value) {
if (is_array($value)) {
$value = convertToObject($value);
}
$object->$key = $value;
}
return $object;
}
$clasa = array(
'e1' => array('nume' => 'Nitu', 'prenume' => 'Andrei', 'sex' => 'm', 'varsta' => 23),
'e2' => array('nume' => 'Nae', 'prenume' => 'Ionel', 'sex' => 'm', 'varsta' => 27),
'e3' => array('nume' => 'Noman', 'prenume' => 'Alice', 'sex' => 'f', 'varsta' => 22),
'e4' => array('nume' => 'Geangos', 'prenume' => 'Bogdan', 'sex' => 'm', 'varsta' => 23),
'e5' => array('nume' => 'Vasile', 'prenume' => 'Mihai', 'sex' => 'm', 'varsta' => 25)
);
$obj = convertToObject($clasa);
print_r($obj);
?>
which outputs (note that there's no arrays - only stdClass
's):
stdClass Object
(
[e1] => stdClass Object
(
[nume] => Nitu
[prenume] => Andrei
[sex] => m
[varsta] => 23
)
[e2] => stdClass Object
(
[nume] => Nae
[prenume] => Ionel
[sex] => m
[varsta] => 27
)
[e3] => stdClass Object
(
[nume] => Noman
[prenume] => Alice
[sex] => f
[varsta] => 22
)
[e4] => stdClass Object
(
[nume] => Geangos
[prenume] => Bogdan
[sex] => m
[varsta] => 23
)
[e5] => stdClass Object
(
[nume] => Vasile
[prenume] => Mihai
[sex] => m
[varsta] => 25
)
)
So you'd refer to it by $obj->e5->nume
.
Just open your project urls.py, then find this if statement.
if settings.DEBUG:
urlpatterns += patterns(
'django.views.static',
(r'^media/(?P<path>.*)','serve',{'document_root': settings.MEDIA_ROOT}), )
You can change settings.DEBUG on True and it will work always. But if your project is a something serious then you should to think about other solutions mentioned above.
if True:
urlpatterns += patterns(
'django.views.static',
(r'^media/(?P<path>.*)','serve',{'document_root': settings.MEDIA_ROOT}), )
In django 1.10 you can write so:
urlpatterns += [ url(r'^media/(?P<path>.*)$', serve, { 'document_root': settings.MEDIA_ROOT, }), url(r'^static/(?P<path>.*)$', serve, { 'document_root': settings.STATIC_ROOT }), ]
Just use like this somewhere inside the form
@method('PUT')
response[0]
is not defined, check if it is defined and then check for its property title.
if(typeof response[0] !== 'undefined' && typeof response[0].title !== 'undefined'){
//Do something
}
I resolved this issue in my linux enviroment updating the IP of my machine in /etc/hosts file.
You can verify your network IP (inet end.) with:
$ifconfig
See if your IP matches with /etc/hosts file:
$cat /etc/hosts
Edit your /etc/hosts file, if nedded:
$sudo gedit /etc/hosts
Bye.
ok, here is what i understood from your question. You are writing a csv file from python but when you are opening that file into some other application like excel or open office they are showing the complete row in one cell rather than each word in individual cell. I am right??
if i am then please try this,
import csv
with open(r"C:\\test.csv", "wb") as csv_file:
writer = csv.writer(csv_file, delimiter =",",quoting=csv.QUOTE_MINIMAL)
writer.writerow(["a","b"])
you have to set the delimiter = ","
Try this:
CREATE PROCEDURE MyProc @excludedlist integer_list_tbltype READONLY AS
SELECT * FROM A WHERE ID NOT IN (@excludedlist)
And then call it like this:
DECLARE @ExcludedList integer_list_tbltype
INSERT @ExcludedList(n) VALUES(3, 4, 22)
exec MyProc @ExcludedList
just use the -d option of the date command, e.g.
date -d '20121212' +'%Y %m'
This should do the trick:
df[- grep("REVERSE", df$Name),]
Or a safer version would be:
df[!grepl("REVERSE", df$Name),]
I like Microsoft's XML Notepad 2007, but I don't know how it handles very large files, sorry.
Its gets even simpler (by pandas 0.16.0) :
df.columns.tolist()
will give you the column names in a nice list.
public class BOX
{
double height, length, breadth;
public static bool operator == (BOX b1, BOX b2)
{
if (b1 is null)
return b2 is null;
return b1.Equals(b2);
}
public static bool operator != (BOX b1, BOX b2)
{
return !(b1 == b2);
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
return obj is BOX b2? (length == b2.length &&
breadth == b2.breadth &&
height == b2.height): false;
}
public override int GetHashCode()
{
return (height,length,breadth).GetHashCode();
}
}
You can update a metadata annotation that is not relevant for your deployment. it will trigger a rolling-update
for example:
spec:
template:
metadata:
annotations:
configmap-version: 1
Don't think too much:
bool_or_string.to_s == "true"
So,
"true".to_s == "true" #true
"false".to_s == "true" #false
true.to_s == "true" #true
false.to_s == "true" #false
You could also add ".downcase," if you are worried about capital letters.
I realize this is an old thread, but for those taking @JasonMArcher's accepted answer above as fact, I'm surprised it has not been corrected many of us have known for years it is actually the PIPELINE adding the delay and NOTHING to do with whether it is Out-Null or not. In fact, if you run the tests below you will quickly see that the same "faster" casting to [void] and $void= that for years we all used thinking it was faster, are actually JUST AS SLOW and in fact VERY SLOW when you add ANY pipelining whatsoever. In other words, as soon as you pipe to anything, the whole rule of not using out-null goes into the trash.
Proof, the last 3 tests in the list below. The horrible Out-null was 32339.3792 milliseconds, but wait - how much faster was casting to [void]? 34121.9251 ms?!? WTF? These are REAL #s on my system, casting to VOID was actually SLOWER. How about =$null? 34217.685ms.....still friggin SLOWER! So, as the last three simple tests show, the Out-Null is actually FASTER in many cases when the pipeline is already in use.
So, why is this? Simple. It is and always was 100% a hallucination that piping to Out-Null was slower. It is however that PIPING TO ANYTHING is slower, and didn't we kind of already know that through basic logic? We just may not have know HOW MUCH slower, but these tests sure tell a story about the cost of using the pipeline if you can avoid it. And, we were not really 100% wrong because there is a very SMALL number of true scenarios where out-null is evil. When? When adding Out-Null is adding the ONLY pipeline activity. In other words....the reason a simple command like $(1..1000) | Out-Null as shown above showed true.
If you simply add an additional pipe to Out-String to every test above, the #s change radically (or just paste the ones below) and as you can see for yourself, the Out-Null actually becomes FASTER in many cases:
$GetProcess = Get-Process
# Batch 1 - Test 1
(Measure-Command {
for ($i = 1; $i -lt 99; $i++)
{
$GetProcess | Out-Null
}
}).TotalMilliseconds
# Batch 1 - Test 2
(Measure-Command {
for ($i = 1; $i -lt 99; $i++)
{
[void]($GetProcess)
}
}).TotalMilliseconds
# Batch 1 - Test 3
(Measure-Command {
for ($i = 1; $i -lt 99; $i++)
{
$null = $GetProcess
}
}).TotalMilliseconds
# Batch 2 - Test 1
(Measure-Command {
for ($i = 1; $i -lt 99; $i++)
{
$GetProcess | Select-Object -Property ProcessName | Out-Null
}
}).TotalMilliseconds
# Batch 2 - Test 2
(Measure-Command {
for ($i = 1; $i -lt 99; $i++)
{
[void]($GetProcess | Select-Object -Property ProcessName )
}
}).TotalMilliseconds
# Batch 2 - Test 3
(Measure-Command {
for ($i = 1; $i -lt 99; $i++)
{
$null = $GetProcess | Select-Object -Property ProcessName
}
}).TotalMilliseconds
# Batch 3 - Test 1
(Measure-Command {
for ($i = 1; $i -lt 99; $i++)
{
$GetProcess | Select-Object -Property Handles, NPM, PM, WS, VM, CPU, Id, SI, Name | Out-Null
}
}).TotalMilliseconds
# Batch 3 - Test 2
(Measure-Command {
for ($i = 1; $i -lt 99; $i++)
{
[void]($GetProcess | Select-Object -Property Handles, NPM, PM, WS, VM, CPU, Id, SI, Name )
}
}).TotalMilliseconds
# Batch 3 - Test 3
(Measure-Command {
for ($i = 1; $i -lt 99; $i++)
{
$null = $GetProcess | Select-Object -Property Handles, NPM, PM, WS, VM, CPU, Id, SI, Name
}
}).TotalMilliseconds
# Batch 4 - Test 1
(Measure-Command {
for ($i = 1; $i -lt 99; $i++)
{
$GetProcess | Out-String | Out-Null
}
}).TotalMilliseconds
# Batch 4 - Test 2
(Measure-Command {
for ($i = 1; $i -lt 99; $i++)
{
[void]($GetProcess | Out-String )
}
}).TotalMilliseconds
# Batch 4 - Test 3
(Measure-Command {
for ($i = 1; $i -lt 99; $i++)
{
$null = $GetProcess | Out-String
}
}).TotalMilliseconds
In case anyone is wondering how to use Marionette in C#.
FirefoxProfile profile = new FirefoxProfile(); // Your custom profile
var service = FirefoxDriverService.CreateDefaultService("DirectoryContainingTheDriver", "geckodriver.exe");
// Set the binary path if you want to launch the release version of Firefox.
service.FirefoxBinaryPath = @"C:\Program Files\Mozilla Firefox\firefox.exe";
var option = new FirefoxProfileOptions(profile) { IsMarionette = true };
var driver = new FirefoxDriver(
service,
option,
TimeSpan.FromSeconds(30));
Overriding FirefoxOptions to provide the function to add additional capability and set Firefox profile because selenium v53 doesn't provide that function yet.
public class FirefoxProfileOptions : FirefoxOptions
{
private DesiredCapabilities _capabilities;
public FirefoxProfileOptions()
: base()
{
_capabilities = DesiredCapabilities.Firefox();
_capabilities.SetCapability("marionette", this.IsMarionette);
}
public FirefoxProfileOptions(FirefoxProfile profile)
: this()
{
_capabilities.SetCapability(FirefoxDriver.ProfileCapabilityName, profile.ToBase64String());
}
public override void AddAdditionalCapability(string capabilityName, object capabilityValue)
{
_capabilities.SetCapability(capabilityName, capabilityValue);
}
public override ICapabilities ToCapabilities()
{
return _capabilities;
}
}
Note: Launching with profile doesn't work with FF 47, it works with FF 50 Nightly.
However, we tried to convert our test to use Marionette, and it's just not viable at the moment because the implementation of the driver is either not completed or buggy. I'd suggest people downgrade their Firefox at this moment.
I had to add packaging, so:
mvn install:install-file \
-DgroupId=javax.transaction \
-DartifactId=jta \
-Dversion=1.0.1B \
-Dfile=jta-1.0.1B.jar \
-DgeneratePom=true \
-Dpackaging=jar
You can find every content type here: http://www.iana.org/assignments/media-types/media-types.xhtml
The most common type are:
Type application
application/java-archive
application/EDI-X12
application/EDIFACT
application/javascript
application/octet-stream
application/ogg
application/pdf
application/xhtml+xml
application/x-shockwave-flash
application/json
application/ld+json
application/xml
application/zip
application/x-www-form-urlencoded
Type audio
audio/mpeg
audio/x-ms-wma
audio/vnd.rn-realaudio
audio/x-wav
Type image
image/gif
image/jpeg
image/png
image/tiff
image/vnd.microsoft.icon
image/x-icon
image/vnd.djvu
image/svg+xml
Type multipart
multipart/mixed
multipart/alternative
multipart/related (using by MHTML (HTML mail).)
multipart/form-data
Type text
text/css
text/csv
text/html
text/javascript (obsolete)
text/plain
text/xml
Type video
video/mpeg
video/mp4
video/quicktime
video/x-ms-wmv
video/x-msvideo
video/x-flv
video/webm
Type vnd :
application/vnd.android.package-archive
application/vnd.oasis.opendocument.text
application/vnd.oasis.opendocument.spreadsheet
application/vnd.oasis.opendocument.presentation
application/vnd.oasis.opendocument.graphics
application/vnd.ms-excel
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
application/vnd.ms-powerpoint
application/vnd.openxmlformats-officedocument.presentationml.presentation
application/msword
application/vnd.openxmlformats-officedocument.wordprocessingml.document
application/vnd.mozilla.xul+xml
Like Babel says in the docs, for Babel > 7.4.0 the module @babel/polyfill is deprecated, so it's recommended to use directly core-js and regenerator-runtime libraries that before were included in @babel/polyfill.
So this worked for me:
npm install --save [email protected]
npm install regenerator-runtime
then add to the very top of your initial js file:
import 'core-js/stable';
import 'regenerator-runtime/runtime';
sed -e '/^ *$/d' input > output
Deletes all lines which consist only of blanks (or is completely empty). You can change the blank to [ \t]
where the \t
is a representation for tab. Whether your shell or your sed
will do the expansion varies, but you can probably type the tab character directly. And if you're using GNU or BSD sed
, you can do the edit in-place, if that's what you want, with the -i
option.
If I execute the above command still I have blank lines in my output file. What could be the reason?
There could be several reasons. It might be that you don't have blank lines but you have lots of spaces at the end of a line so it looks like you have blank lines when you cat the file to the screen. If that's the problem, then:
sed -e 's/ *$//' -e '/^ *$/d' input > output
The new regex removes repeated blanks at the end of the line; see previous discussion for blanks or tabs.
Another possibility is that your data file came from Windows and has CRLF line endings. Unix sees the carriage return at the end of the line; it isn't a blank, so the line is not removed. There are multiple ways to deal with that. A reliable one is tr
to delete (-d
) character code octal 15, aka control-M or \r
or carriage return:
tr -d '\015' < input | sed -e 's/ *$//' -e '/^ *$/d' > output
If neither of those works, then you need to show a hex dump or octal dump (od -c
) of the first two lines of the file, so we can see what we're up against:
head -n 2 input | od -c
Judging from the comments that sed -i
does not work for you, you are not working on Linux or Mac OS X or BSD — which platform are you working on? (AIX, Solaris, HP-UX spring to mind as relatively plausible possibilities, but there are plenty of other less plausible ones too.)
You can try the POSIX named character classes such as sed -e '/^[[:space:]]*$/d'
; it will probably work, but is not guaranteed. You can try it with:
echo "Hello World" | sed 's/[[:space:]][[:space:]]*/ /'
If it works, there'll be three spaces between the 'Hello' and the 'World'. If not, you'll probably get an error from sed
. That might save you grief over getting tabs typed on the command line.
Normally, you do something like this:
def myFunction(a,b,c):
if not isinstance(a, int):
raise TypeError("Expected int, got %s" % (type(a),))
if b <= 0 or b >= 10:
raise ValueError("Value %d out of range" % (b,))
if not c:
raise ValueError("String was empty")
# Rest of function
To lock the screen:
adb shell input keyevent 82 && adb shell input keyevent 26 && adb shell input keyevent 26
To lock the screen and turn it off
adb shell input keyevent 82 && adb shell input keyevent 26
To unlock the screen without pass
adb shell input keyevent 82 && adb shell input keyevent 66
To unlock the screen that has pass 1234
adb shell input keyevent 82 && adb shell input text 1234 && adb shell input keyevent 66
I solved the issue on OS X v10.10 (Yosemite) following these instructions:
However the trick proposed by hoipolloi was a working temporary workaround, on this version too.
For whatever reason $('.panel-collapse').collapse({'toggle': true, 'parent': '#accordion'});
only seems to work the first time and it only works to expand the collapsible. (I tried to start with a expanded collapsible and it wouldn't collapse.)
It could just be something that runs once the first time you initialize collapse with those parameters.
You will have more luck using the show
and hide
methods.
Here is an example:
$(function() {
var $active = true;
$('.panel-title > a').click(function(e) {
e.preventDefault();
});
$('.collapse-init').on('click', function() {
if(!$active) {
$active = true;
$('.panel-title > a').attr('data-toggle', 'collapse');
$('.panel-collapse').collapse('hide');
$(this).html('Click to disable accordion behavior');
} else {
$active = false;
$('.panel-collapse').collapse('show');
$('.panel-title > a').attr('data-toggle','');
$(this).html('Click to enable accordion behavior');
}
});
});
Update
Granted KyleMit seems to have a way better handle on this then me. I'm impressed with his answer and understanding.
I don't understand what's going on or why the show
seemed to be toggling in some places.
But After messing around for a while.. Finally came with the following solution:
$(function() {
var transition = false;
var $active = true;
$('.panel-title > a').click(function(e) {
e.preventDefault();
});
$('#accordion').on('show.bs.collapse',function(){
if($active){
$('#accordion .in').collapse('hide');
}
});
$('#accordion').on('hidden.bs.collapse',function(){
if(transition){
transition = false;
$('.panel-collapse').collapse('show');
}
});
$('.collapse-init').on('click', function() {
$('.collapse-init').prop('disabled','true');
if(!$active) {
$active = true;
$('.panel-title > a').attr('data-toggle', 'collapse');
$('.panel-collapse').collapse('hide');
$(this).html('Click to disable accordion behavior');
} else {
$active = false;
if($('.panel-collapse.in').length){
transition = true;
$('.panel-collapse.in').collapse('hide');
}
else{
$('.panel-collapse').collapse('show');
}
$('.panel-title > a').attr('data-toggle','');
$(this).html('Click to enable accordion behavior');
}
setTimeout(function(){
$('.collapse-init').prop('disabled','');
},800);
});
});
In Google Maps v3 you can now disable scroll to zoom, which leads to a much better user experience. Other map functions will still work and you don't need extra divs. I also thought there should be some feedback for the user so they can see when scrolling is enabled, so I added a map border.
// map is the google maps object, '#map' is the jquery selector
preventAccidentalZoom(map, '#map');
// Disables and enables scroll to zoom as appropriate. Also
// gives the user a UI cue as to when scrolling is enabled.
function preventAccidentalZoom(map, mapSelector){
var mapElement = $(mapSelector);
// Disable the scroll wheel by default
map.setOptions({ scrollwheel: false })
// Enable scroll to zoom when there is a mouse down on the map.
// This allows for a click and drag to also enable the map
mapElement.on('mousedown', function () {
map.setOptions({ scrollwheel: true });
mapElement.css('border', '1px solid blue')
});
// Disable scroll to zoom when the mouse leaves the map.
mapElement.mouseleave(function () {
map.setOptions({ scrollwheel: false })
mapElement.css('border', 'none')
});
};
@scanlegentil I like this.
A little improvement would be:
$Depth = 2
$Path = "."
$Levels = "\*" * $Depth
$Folder = Get-Item $Path
$FolderFullName = $Folder.FullName
Resolve-Path $FolderFullName$Levels | Get-Item | ? {$_.PsIsContainer} | Write-Host
As mentioned, this would only scan the specified depth, so this modification is an improvement:
$StartLevel = 1 # 0 = include base folder, 1 = sub-folders only, 2 = start at 2nd level
$Depth = 2 # How many levels deep to scan
$Path = "." # starting path
For ($i=$StartLevel; $i -le $Depth; $i++) {
$Levels = "\*" * $i
(Resolve-Path $Path$Levels).ProviderPath | Get-Item | Where PsIsContainer |
Select FullName
}
As Vicky already pointed out, %DATE%
and %TIME%
return the current date and time using the short date and time formats that are fully (endlessly) customizable.
One user may configure its system to return Fri040811 08.03PM while another user may choose 08/04/2011 20:30.
It's a complete nightmare for a BAT programmer.
Changing the format to a firm format may fix the problem, provided you restore back the previous format before leaving the BAT file. But it may be subject to nasty race conditions and complicate recovery in cancelled BAT files.
Fortunately, there is an alternative.
You may use WMIC, instead. WMIC Path Win32_LocalTime Get Day,Hour,Minute,Month,Second,Year /Format:table
returns the date and time in a invariable way. Very convenient to directly parse it with a FOR /F
command.
So, putting the pieces together, try this as a starting point...
SETLOCAL enabledelayedexpansion
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
SET /A FD=%%F*1000000+%%D*100+%%A
SET /A FT=10000+%%B*100+%%C
SET FT=!FT:~-4!
ECHO Archive_!FD!_!FT!.zip
)
You can use split function.
SELECT
(select top 1 item from dbo.Split(FullName,',') where id=1 ) Column1,
(select top 1 item from dbo.Split(FullName,',') where id=2 ) Column2,
(select top 1 item from dbo.Split(FullName,',') where id=3 ) Column3,
(select top 1 item from dbo.Split(FullName,',') where id=4 ) Column4,
FROM MyTbl
Add a style with the attribute text-decoration:none;
:
There are a number of different ways of doing this.
Inline style:
<a href="xxx.html" style="text-decoration:none;">goto this link</a>
Inline stylesheet:
<html>
<head>
<style type="text/css">
a {
text-decoration:none;
}
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>
External stylesheet:
<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>
stylesheet.css:
a {
text-decoration:none;
}
Unfortunately there is no hung state for a process. Now hung can be deadlock. This is block state. The threads in the process are blocked. The other things could be live lock where the process is running but doing the same thing again and again. This process is in running state. So as you can see there is no definite hung state. As suggested you can use the top command to see if the process is using 100% CPU or lot of memory.
For those using autocmd
, it is a best practice to group those together. If a grouping is related to file-type detection, you might have something like this:
augroup filetype_c
autocmd!
:autocmd FileType c setlocal tabstop=2 shiftwidth=2 softtabstop=2 expandtab
:autocmd FileType c nnoremap <buffer> <localleader>c I/*<space><esc><s-a><space>*/<esc>
augroup end
Groupings help keep the .vimrc
organized especially once a filetype has multiple rules associated with it. In the above example, a comment shortcut specific to .c files is defined.
The initial call to autocmd!
tells vim to delete any previously defined autocommands in said grouping. This will prevent duplicate definition if .vimrc
is sourced again. See the :help augroup
for more info.
This is the ternary conditional operator, which can be used anywhere, not just the print statement. It's sometimes just called "the ternary operator", but it's not the only ternary operator, just the most common one.
Here's a good example from Wikipedia demonstrating how it works:
A traditional if-else construct in C, Java and JavaScript is written:
if (a > b) { result = x; } else { result = y; }
This can be rewritten as the following statement:
result = a > b ? x : y;
Basically it takes the form:
boolean statement ? true result : false result;
So if the boolean statement is true, you get the first part, and if it's false you get the second one.
Try these if that still doesn't make sense:
System.out.println(true ? "true!" : "false.");
System.out.println(false ? "true!" : "false.");
In eclipse click file then select switch workspace then browse and select another folder. Now repeat the same process and this time there will be no error :)
You should use the csv
module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.
import csv
with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
csvout = csv.writer(csvout)
for row in tsvin:
count = int(row[4])
if count > 0:
csvout.writerows([row[2:4] for _ in range(count)])
or, using the itertools
module to do the repeating with itertools.repeat()
:
from itertools import repeat
import csv
with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
tsvin = csv.reader(tsvin, delimiter='\t')
csvout = csv.writer(csvout)
for row in tsvin:
count = int(row[4])
if count > 0:
csvout.writerows(repeat(row[2:4], count))
If your goal is to drop the dataframe, then you need to pass all columns. For me: the best way is to pass a list comprehension to the columns kwarg. This will then work regardless of the different columns in a df.
import pandas as pd
web_stats = {'Day': [1, 2, 3, 4, 2, 6],
'Visitors': [43, 43, 34, 23, 43, 23],
'Bounce_Rate': [3, 2, 4, 3, 5, 5]}
df = pd.DataFrame(web_stats)
df.drop(columns=[i for i in check_df.columns])
You are using the wrong URL (you are using the URL for the html webpage). Try either of these instead:
https://github.com/facebook/facebook-android-sdk.git
git://github.com/facebook/facebook-android-sdk.git
Please note that MVC 3 onwards the persistence behavior of TempData has changed, now the value in TempData is persisted until it is read, and not just for the next request.
The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request. https://msdn.microsoft.com/en-in/library/dd394711%28v=vs.100%29.aspx
Were those dev-master
s added automatically? Avoid them as unnecessary version constraints, for 'any suitable version' use "*"
, or "@dev"
if you don't mind dev packages. My guess is that Entrust is the potential troublemaker.
Also, "minimum-stability": "stable"
imposes additional constraints, and
"minimum-stability": "dev",
"prefer-stable": true
is more conflict-free, consider it a rule of thumb.
I add an information that could be useful for someone. If you have any storyboard segue, to go back to the old style, you need to set the kind property to Present Modally and the Presentation property to Full Screen.
Another option
tuple([tuple(row) for row in myarray])
If you are passing NumPy arrays to C++ functions, you may also wish to look at using Cython or SWIG.
For frequent uses of this command I found it easy to add the location of C:\xampp\apache\bin
to the PATH
. Use whatever directory you have this installed in.
Then you can run from any directory in command line:
httpd -k restart
The answer above that suggests httpd -k -restart is actually a typo. You can see the commands by running httpd /?
Neither of the highly upvoted answers actually provide "just the file name without extension" and the other solutions are way too much code for such a simple job.
I think this should be a one-liner to any JavaScript programmer. It's a very simple regular expression:
function basename(prevname) {
return prevname.replace(/^(.*[/\\])?/, '').replace(/(\.[^.]*)$/, '');
}
First, strip anything up to the last slash, if present.
Then, strip anything after the last period, if present.
It's simple, it's robust, it implements exactly what's asked for. Am I missing something?
maybe there are some unmerged paths in your git repository that you have to resolve before stashing.
First of all you should fix modal HTML structure. Now it's not correct, you don't need class .hide
:
<div id="edit-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body edit-content">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Then links should point to this modal via data-target
attribute:
<a href="#myModal" data-toggle="modal" id="1" data-target="#edit-modal">Edit 1</a>
Finally Js part becomes very simple:
$('#edit-modal').on('show.bs.modal', function(e) {
var $modal = $(this),
esseyId = e.relatedTarget.id;
$.ajax({
cache: false,
type: 'POST',
url: 'backend.php',
data: 'EID=' + essayId,
success: function(data) {
$modal.find('.edit-content').html(data);
}
});
})
None of the above worked for me Swift 5 for Local Video Player
after reading apple documentation I was able to create simple example for playing video from Local resources
Here is code snip
import UIKit
import AVKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//TODO : Make Sure Add and copy "SampleVideo.mp4" file in project before play
}
@IBAction func playLocalVideo(_ sender: Any) {
guard let path = Bundle.main.path(forResource: "SampleVideo", ofType: "mp4") else {
return
}
let videoURL = NSURL(fileURLWithPath: path)
// Create an AVPlayer, passing it the local video url path
let player = AVPlayer(url: videoURL as URL)
let controller = AVPlayerViewController()
controller.player = player
present(controller, animated: true) {
player.play()
}
}
}
PS: Make sure you don't forget to add and copy video named "SampleVideo.mp4" in project
Its unbelievable after so many answers, but I did it little differently in the end. I don't like primary key to be nullable, I want to have it as first argument and also want to insert without defining it and also it should not be var.
@Entity(tableName = "employments")
data class Employment(
@PrimaryKey(autoGenerate = true) val id: Long,
@ColumnInfo(name = "code") val code: String,
@ColumnInfo(name = "title") val name: String
){
constructor(code: String, name: String) : this(0, code, name)
}
You get that error because you haven't saved your file, save it for example "holamundo.py" then run it Ctrl + B
I use #3. Same for long lists, tuples, etc. It doesn't require adding any extra spaces beyond the indentations. As always, be consistent.
mydict = {
"key1": 1,
"key2": 2,
"key3": 3,
}
mylist = [
(1, 'hello'),
(2, 'world'),
]
nested = {
a: [
(1, 'a'),
(2, 'b'),
],
b: [
(3, 'c'),
(4, 'd'),
],
}
Similarly, here's my preferred way of including large strings without introducing any whitespace (like you'd get if you used triple-quoted multi-line strings):
data = (
"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABG"
"l0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAEN"
"xBRpFYmctaKCfwrBSCrRLuL3iEW6+EEUG8XvIVjYWNgJdhFjIX"
"rz6pKtPB5e5rmq7tmxk+hqO34e1or0yXTGrj9sXGs1Ib73efh1"
"AAAABJRU5ErkJggg=="
)
Do you mean unique
:
R> x = c(1,1,2,3,4,4,4)
R> x
[1] 1 1 2 3 4 4 4
R> unique(x)
[1] 1 2 3 4
use np.random.randint()
as np.random.random_integers()
is deprecated
random_matrix = np.random.randint(min_val,max_val,(<num_rows>,<num_cols>))
The servlet API lacks this feature because it was created in a time when many believed that the query string and the message body was just two different ways of sending parameters, not realizing that the purposes of the parameters are fundamentally different.
The query string parameters ?foo=bar are a part of the URL because they are involved in identifying a resource (which could be a collection of many resources), like "all persons aged 42":
GET /persons?age=42
The message body parameters in POST or PUT are there to express a modification to the target resource(s). Fx setting a value to the attribute "hair":
PUT /persons?age=42
hair=grey
So it is definitely RESTful to use both query parameters and body parameters at the same time, separated so that you can use them for different purposes. The feature is definitely missing in the Java servlet API.
The location of the Temporary Internet Files
folder depends on your version of Windows and whether or not you are using user profiles.
If you have Windows Vista, then temporary Internet files are in these locations (note that on your PC they can be on some drive other than C):
C:\Users[username]\AppData\Local\Microsoft\Windows\Temporary Internet Files\ C:\Users[username]\AppData\Local\Microsoft\Windows\Temporary Internet Files\Low\
Note that you will have to change the settings of Windows Explorer to show all kinds of files (including the protected system files) in order to access these folders.
If you have Windows XP or Windows 2000, then temporary Internet files are in this location (note that on your PC they can be on some drive other than C):
C:\Documents and Settings[username]\Local Settings\Temporary Internet Files\
If you have only one user account, then replace [username] with Administrator to get the path of the Temporary Internet Files
folder.
If you have Windows Me, Windows 98, Windows NT or Windows 95, then index.dat
files are in these locations:
C:\Windows\Temporary Internet Files\
C:\Windows\Profiles[username]\Temporary Internet Files\
Note that on your computer, the Windows directory may not be C:\Windows
but some other directory. If you don't have a Profiles
directory in your Windows
directory, don't worry — this just means that you are not using user profiles.
If you need use it as a default configuration, just place min: 0
inside the node defaults.scale.ticks
, as follows:
defaults: {
global: {...},
scale: {
...
ticks: { min: 0 },
}
},
Reference: https://www.chartjs.org/docs/latest/axes/
Create an Arraylist of unique values
You could use Set.toArray()
method.
A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.
web2py has comet_messaging.py, which uses Tornado for websockets look at an example here: http://vimeo.com/18399381 and here vimeo . com / 18232653
long add;
mem = (void*)malloc(1024 +15);
add = (long)mem;
add = add - (add % 16);//align to 16 byte boundary
ptr = (whatever*)(add);
Works perfectly! But not a good approach because it runs in O(n^2)
boolean isAnagram(String A, String B) {
if(A.length() != B.length())
return false;
A = A.toLowerCase();
B = B.toLowerCase();
for(int i = 0; i < A.length(); i++){
boolean found = false;
for(int j = 0; j < B.length(); j++){
if(A.charAt(i) == B.charAt(j)){
found = true;
break;
}
}
if(!found){
return false;
}
}
for(int i = 0; i < B.length(); i++){
boolean found = false;
for(int j = 0; j < A.length(); j++){
if(A.charAt(j) == B.charAt(i)){
found = true;
break;
}
}
if(!found){
return false;
}
}
int sum1 = 0, sum2 = 0;
for(int i = 0; i < A.length(); i++){
sum1 += (int)A.charAt(i);
sum2 += (int)B.charAt(i);
}
if(sum1 == sum2){
return true;
}
return false;
}
Here's the correct way to do it with modern (2014) JQuery:
$(function () {
$('<script>')
.attr('type', 'text/javascript')
.text('some script here')
.appendTo('head');
})
or if you really want to replace a div you could do:
$(function () {
$('<script>')
.attr('type', 'text/javascript')
.text('some script here')
.replaceAll('#someelement');
});
What you should do is create an imap of a certain key to a series of commands, in this case the commands will drop you into normal mode, delete the current word and then put you back in insert:
:imap <C-d> <C-[>diwi
You have not one, but many mistakes. It should be:
int[] tall = new int[28123];
for (int j=0;j<28123;j++){
tall[j] = j+1;
}
Your code is putting a 0 in all the positions of the array.
Morover, it'll throw an exception, because the last index of the array is 28123-1 (arrays in Java start in 0!).
One classic root cause for this message is:
git init lis4368/assignments
),Ie, if you don't have added and committed at least once, there won't be a local master
branch to push to.
Try first to create a commit:
git add .
) then git commit -m "first commit"
git commit --allow-empty -m "Initial empty commit"
And then try git push -u origin master
again.
See "Why do I need to explicitly push a new branch?" for more.
Working for me:
var st = new StackTrace(e, true);
// Get the bottom stack frame
var frame = st.GetFrame(st.FrameCount - 1);
// Get the line number from the stack frame
var line = frame.GetFileLineNumber();
var method = frame.GetMethod().ReflectedType.FullName;
var path = frame.GetFileName();
In jQuery it would be as simple as $('#yourDivID').empty()
See the documentation.
Try this:
void drawInitialNim(int num1, int num2, int num3){
int board[3][50] = {0}; // This is a local variable. It is not possible to use it after returning from this function.
int i, j, k;
for(i=0; i<num1; i++)
board[0][i] = 'O';
for(i=0; i<num2; i++)
board[1][i] = 'O';
for(i=0; i<num3; i++)
board[2][i] = 'O';
for (j=0; j<3;j++) {
for (k=0; k<50; k++) {
if(board[j][k] != 0)
printf("%c", board[j][k]);
}
printf("\n");
}
}
So as another answer mentioned Guava has support for this by using:
Streams.stream(iterable);
I want to highlight that the implementation does something slightly different than other answers suggested. If the Iterable
is of type Collection
they cast it.
public static <T> Stream<T> stream(Iterable<T> iterable) {
return (iterable instanceof Collection)
? ((Collection<T>) iterable).stream()
: StreamSupport.stream(iterable.spliterator(), false);
}
public static <T> Stream<T> stream(Iterator<T> iterator) {
return StreamSupport.stream(
Spliterators.spliteratorUnknownSize(iterator, 0),
false
);
}
You can use the HSL color model to create your colors.
If all you want is differing hues (likely), and slight variations on lightness or saturation, you can distribute the hues like so:
// assumes hue [0, 360), saturation [0, 100), lightness [0, 100)
for(i = 0; i < 360; i += 360 / num_colors) {
HSLColor c;
c.hue = i;
c.saturation = 90 + randf() * 10;
c.lightness = 50 + randf() * 10;
addColor(c);
}