Ok found the answer. exchange()
is the best way. Oddly the HttpEntity
class doesn't have a setBody()
method (it has getBody()
), but it is still possible to set the request body, via the constructor.
// Create the request body as a MultiValueMap
MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
body.add("field", "value");
// Note the body object as first parameter!
HttpEntity<?> httpEntity = new HttpEntity<Object>(body, requestHeaders);
ResponseEntity<MyModel> response = restTemplate.exchange("/api/url", HttpMethod.POST, httpEntity, MyModel.class);
Try this.
ALTER PROCEDURE [dbo].[sp_ClientNotes_update]
@id uniqueidentifier,
@ordering smallint = NULL,
@title nvarchar(20) = NULL,
@content text = NULL
AS
BEGIN
SET NOCOUNT ON;
UPDATE tbl_ClientNotes
SET ordering=ISNULL(@ordering,ordering),
title=ISNULL(@title,title),
content=ISNULL(@content, content)
WHERE id=@id
END
It might also be worth adding an extra part to the WHERE
clause, if you use transactional replication then it will send another update to the subscriber if all are NULL, to prevent this.
WHERE id=@id AND (@ordering IS NOT NULL OR
@title IS NOT NULL OR
@content IS NOT NULL)
For completeness, echo $(__git_ps1)
, on Linux at least, should give you the name of the current branch surrounded by parentheses.
This may be useful is some scenarios as it is not a Git command (while depending on Git), notably for setting up your Bash command prompt to display the current branch.
For example:
/mnt/c/git/ConsoleApp1 (test-branch)> echo $(__git_ps1)
(test-branch)
/mnt/c/git/ConsoleApp1 (test-branch)> git checkout master
Switched to branch 'master'
/mnt/c/git/ConsoleApp1 (master)> echo $(__git_ps1)
(master)
/mnt/c/git/ConsoleApp1 (master)> cd ..
/mnt/c/git> echo $(__git_ps1)
/mnt/c/git>
If supported by your browser, you may use CSS3 :read-only
selector:
input[type="text"]:read-only {
cursor: normal;
background-color: #f8f8f8;
color: #999;
}
Am I doing that right, as far as iterating through the Arraylist goes?
No: by calling iterator
twice in each iteration, you're getting new iterators all the time.
The easiest way to write this loop is using the for-each construct:
for (String s : arrayList)
if (s.equals(value))
// ...
As for
java.lang.ArrayIndexOutOfBoundsException: -1
You just tried to get element number -1
from an array. Counting starts at zero.
If you are using VS Code editor .
Go to Explorer panel on left side -> find package.json & open it -> under dependencies find @angular/core.
This is your angular version as core is the main feature
Instant
and LocalDateTime
are two entirely different animals: One represents a moment, the other does not.
Instant
represents a moment, a specific point in the timeline.LocalDateTime
represents a date and a time-of-day. But lacking a time zone or offset-from-UTC, this class cannot represent a moment. It represents potential moments along a range of about 26 to 27 hours, the range of all time zones around the globe. A LocalDateTime
value is inherently ambiguous.
LocalDateTime
is rather date/clock representation including time-zones for humans.
Your statement is incorrect: A LocalDateTime
has no time zone. Having no time zone is the entire point of that class.
To quote that class’ doc:
This class does not store or represent a time-zone. Instead, it is a description of the date, as used for birthdays, combined with the local time as seen on a wall clock. It cannot represent an instant on the time-line without additional information such as an offset or time-zone.
So Local…
means “not zoned, no offset”.
Instant
An Instant
is a moment on the timeline in UTC, a count of nanoseconds since the epoch of the first moment of 1970 UTC (basically, see class doc for nitty-gritty details). Since most of your business logic, data storage, and data exchange should be in UTC, this is a handy class to be used often.
Instant instant = Instant.now() ; // Capture the current moment in UTC.
OffsetDateTime
The class OffsetDateTime
class represents a moment as a date and time with a context of some number of hours-minutes-seconds ahead of, or behind, UTC. The amount of offset, the number of hours-minutes-seconds, is represented by the ZoneOffset
class.
If the number of hours-minutes-seconds is zero, an OffsetDateTime
represents a moment in UTC the same as an Instant
.
ZoneOffset
The ZoneOffset
class represents an offset-from-UTC, a number of hours-minutes-seconds ahead of UTC or behind UTC.
A ZoneOffset
is merely a number of hours-minutes-seconds, nothing more. A zone is much more, having a name and a history of changes to offset. So using a zone is always preferable to using a mere offset.
ZoneId
A time zone is represented by the ZoneId
class.
A new day dawns earlier in Paris than in Montréal, for example. So we need to move the clock’s hands to better reflect noon (when the Sun is directly overhead) for a given region. The further away eastward/westward from the UTC line in west Europe/Africa the larger the offset.
A time zone is a set of rules for handling adjustments and anomalies as practiced by a local community or region. The most common anomaly is the all-too-popular lunacy known as Daylight Saving Time (DST).
A time zone has the history of past rules, present rules, and rules confirmed for the near future.
These rules change more often than you might expect. Be sure to keep your date-time library's rules, usually a copy of the 'tz' database, up to date. Keeping up-to-date is easier than ever now in Java 8 with Oracle releasing a Timezone Updater Tool.
Specify a proper time zone name in the format of Continent/Region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 2-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
Time Zone = Offset + Rules of Adjustments
ZoneId z = ZoneId.of( “Africa/Tunis” ) ;
ZonedDateTime
Think of ZonedDateTime
conceptually as an Instant
with an assigned ZoneId
.
ZonedDateTime = ( Instant + ZoneId )
To capture the current moment as seen in the wall-clock time used by the people of a particular region (a time zone):
ZonedDateTime zdt = ZonedDateTime.now( z ) ; // Pass a `ZoneId` object such as `ZoneId.of( "Europe/Paris" )`.
Nearly all of your backend, database, business logic, data persistence, data exchange should all be in UTC. But for presentation to users you need to adjust into a time zone expected by the user. This is the purpose of the ZonedDateTime
class and the formatter classes used to generate String representations of those date-time values.
ZonedDateTime zdt = instant.atZone( z ) ;
String output = zdt.toString() ; // Standard ISO 8601 format.
You can generate text in localized format using DateTimeFormatter
.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( Locale.CANADA_FRENCH ) ;
String outputFormatted = zdt.format( f ) ;
mardi 30 avril 2019 à 23 h 22 min 55 s heure de l’Inde
LocalDate
, LocalTime
, LocalDateTime
The "local" date time classes, LocalDateTime
, LocalDate
, LocalTime
, are a different kind of critter. The are not tied to any one locality or time zone. They are not tied to the timeline. They have no real meaning until you apply them to a locality to find a point on the timeline.
The word “Local” in these class names may be counter-intuitive to the uninitiated. The word means any locality, or every locality, but not a particular locality.
So for business apps, the "Local" types are not often used as they represent just the general idea of a possible date or time not a specific moment on the timeline. Business apps tend to care about the exact moment an invoice arrived, a product shipped for transport, an employee was hired, or the taxi left the garage. So business app developers use Instant
and ZonedDateTime
classes most commonly.
So when would we use LocalDateTime
? In three situations:
Notice that none of these three cases involve a single certain specific point on the timeline, none of these are a moment.
Sometimes we want to represent a certain time-of-day on a certain date, but want to apply that into multiple localities across time zones.
For example, "Christmas starts at midnight on the 25th of December 2015" is a LocalDateTime
. Midnight strikes at different moments in Paris than in Montréal, and different again in Seattle and in Auckland.
LocalDate ld = LocalDate.of( 2018 , Month.DECEMBER , 25 ) ;
LocalTime lt = LocalTime.MIN ; // 00:00:00
LocalDateTime ldt = LocalDateTime.of( ld , lt ) ; // Christmas morning anywhere.
Another example, "Acme Company has a policy that lunchtime starts at 12:30 PM at each of its factories worldwide" is a LocalTime
. To have real meaning you need to apply it to the timeline to figure the moment of 12:30 at the Stuttgart factory or 12:30 at the Rabat factory or 12:30 at the Sydney factory.
Another situation to use LocalDateTime
is for booking future events (ex: Dentist appointments). These appointments may be far enough out in the future that you risk politicians redefining the time zone. Politicians often give little forewarning, or even no warning at all. If you mean "3 PM next January 23rd" regardless of how the politicians may play with the clock, then you cannot record a moment – that would see 3 PM turn into 2 PM or 4 PM if that region adopted or dropped Daylight Saving Time, for example.
For appointments, store a LocalDateTime
and a ZoneId
, kept separately. Later, when generating a schedule, on-the-fly determine a moment by calling LocalDateTime::atZone( ZoneId )
to generate a ZonedDateTime
object.
ZonedDateTime zdt = ldt.atZone( z ) ; // Given a date, a time-of-day, and a time zone, determine a moment, a point on the timeline.
If needed, you can adjust to UTC. Extract an Instant
from the ZonedDateTime
.
Instant instant = zdt.toInstant() ; // Adjust from some zone to UTC. Same moment, same point on the timeline, different wall-clock time.
Some people might use LocalDateTime
in a situation where the time zone or offset is unknown.
I consider this case inappropriate and unwise. If a zone or offset is intended but undetermined, you have bad data. That would be like storing a price of a product without knowing the intended currency (dollars, pounds, euros, etc.). Not a good idea.
For completeness, here is a table of all the possible date-time types, both modern and legacy in Java, as well as those defined by the SQL standard. This might help to place the Instant
& LocalDateTime
classes in a larger context.
Notice the odd choices made by the Java team in designing JDBC 4.2. They chose to support all the java.time times… except for the two most commonly used classes: Instant
& ZonedDateTime
.
But not to worry. We can easily convert back and forth.
Converting Instant
.
// Storing
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;
myPreparedStatement.setObject( … , odt ) ;
// Retrieving
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
Instant instant = odt.toInstant() ;
Converting ZonedDateTime
.
// Storing
OffsetDateTime odt = zdt.toOffsetDateTime() ;
myPreparedStatement.setObject( … , odt ) ;
// Retrieving
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = odt.atZone( z ) ;
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
open with encoding UTF 16 because of lat and long.
with open(csv_name_here, 'r', encoding="utf-16") as f:
I started with this book: Relational Database Design Clearly Explained (The Morgan Kaufmann Series in Data Management Systems) (Paperback) by Jan L. Harrington and found it very clear and helpful
and as you get up to speed this one was good too Database Systems: A Practical Approach to Design, Implementation and Management (International Computer Science Series) (Paperback)
I think SQL and database design are different (but complementary) skills.
The built-in string constructor will automatically call obj.__str__
:
''.join(map(str,list))
If you are using IIS 7.5 or later you can generate the machine key from IIS and save it directly to your web.config, within the web farm you then just copy the new web.config to each server.
web.config
file of your application.web.config
file.Full Details can be seen @ Easiest way to generate MachineKey – Tips and tricks: ASP.NET, IIS and .NET development…
If you're using Emacs, you can type C-x v ~
to see a different revision of the file you're currently editing (tags, branches and hashes all work).
Based on BaileyP's answer. The main difference is that these methods return -1
if the pattern can't be matched.
Edit: Thanks to Jason Bunting's answer I got an idea. Why not modify the .lastIndex
property of the regex? Though this will only work for patterns with the global flag (/g
).
Edit: Updated to pass the test-cases.
String.prototype.regexIndexOf = function(re, startPos) {
startPos = startPos || 0;
if (!re.global) {
var flags = "g" + (re.multiline?"m":"") + (re.ignoreCase?"i":"");
re = new RegExp(re.source, flags);
}
re.lastIndex = startPos;
var match = re.exec(this);
if (match) return match.index;
else return -1;
}
String.prototype.regexLastIndexOf = function(re, startPos) {
startPos = startPos === undefined ? this.length : startPos;
if (!re.global) {
var flags = "g" + (re.multiline?"m":"") + (re.ignoreCase?"i":"");
re = new RegExp(re.source, flags);
}
var lastSuccess = -1;
for (var pos = 0; pos <= startPos; pos++) {
re.lastIndex = pos;
var match = re.exec(this);
if (!match) break;
pos = match.index;
if (pos <= startPos) lastSuccess = pos;
}
return lastSuccess;
}
You can cast a method group into a delegate.
The delegate signature selects 1 method out of the group.
This example picks the ToString()
overload which takes a string parameter:
Func<string,string> fn = 123.ToString;
Console.WriteLine(fn("00000000"));
This example picks the ToString()
overload which takes no parameters:
Func<string> fn = 123.ToString;
Console.WriteLine(fn());
You can get the same error in Asp.net MVC5 if you have a class name and a folder with a matching name Example : If you have class lands where when you want to see view/lands/index.cshtml file, if you also have a folder with name 'lands' you get the error as it first try the lands folder
From ?matrix
: "A matrix is the special case of a two-dimensional 'array'." You can simply change the dimensions of the matrix/array.
Elts_int <- as.matrix(tmp_int) # read.table returns a data.frame as Brandon noted
dim(Elts_int) <- (maxrow_int*maxcol_int,1)
Regarding [Console]::WriteLine() - you should use it if you are going to use pipelines in CMD (not in powershell). Say you want your ps1 to stream a lot of data to stdout, and some other utility to consume/transform it. If you use Write-Host in the script it will be much slower.
you will have to manually set $dirty
to true
and $pristine
to false
for the field. If you want the classes to appear on your input, then you will have to manually add ng-dirty
and remove ng-pristine
classes from the element. You can use $setDirty()
on the form level to do all of this on the form itself, but not the form inputs, form inputs do not currently have $setDirty()
as you mentioned.
This answer may change in the future as they should add $setDirty()
to inputs, seems logical.
Consider explicitly setting the header in the $http.post (I put application/json, as I am not sure which of the two versions in your example is the working one, but you can use application/x-www-form-urlencoded if it's the other one):
$http.post("/customer/data/autocomplete", {term: searchString}, {headers: {'Content-Type': 'application/json'} })
.then(function (response) {
return response;
});
I encountered the same problem. This solution allows me to keep using the generic login view:
urlpatterns += patterns('django.views.generic.simple',
(r'^accounts/profile/$', 'redirect_to', {'url': 'generic_account_url'}),
)
You cannot open a connection directly to a path on a remote host using fsockopen
. The url www.mydomain.net/1/file.php
contains a path, when the only valid value for that first parameter is the host, www.mydomain.net
.
If you are trying to access a remote URL, then file_get_contents() is your best bet. You can provide a full URL to that function, and it will fetch the content at that location using a normal HTTP request.
If you only want to send an HTTP request and ignore the response, you could use fsockopen()
and manually send the HTTP request headers, ignoring any response. It might be easier with cURL though, or just plain old fopen(), which will open the connection but not necessarily read any response. If you wanted to do it with fsockopen()
, it might look something like this:
$fp = fsockopen("www.mydomain.net", 80, $errno, $errstr, 30);
fputs($fp, "GET /1/file.php HTTP/1.1\n");
fputs($fp, "Host: www.mydomain.net\n");
fputs($fp, "Connection: close\n\n");
That leaves any error handling up to you of course, but it would mean that you wouldn't waste time reading the response.
I believe you are using Bootstrap 3. If so, please try this code, here is the bootply
<header>
<div class="navbar navbar-static-top navbar-default">
<div class="navbar-header">
<a class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="glyphicon glyphicon-th-list"></span>
</a>
</div>
<div class="container" style="background:yellow;">
<a href="/">
<img src="img/logo.png" class="logo img-responsive">
</a>
<nav class="navbar-collapse collapse pull-right" style="line-height:150px; height:150px;">
<ul class="nav navbar-nav" style="display:inline-block;">
<li><a href="">Portfolio</a></li>
<li><a href="">Blog</a></li>
<li><a href="">Contact</a></li>
</ul>
</nav>
</div>
</div>
</header>
I tried pydiction (didn't work for me) and the normal omnicompletion (too limited). I looked into Jedi as suggested but found it too complex to set up. I found python-mode, which in the end satisfied my needs. Thanks @klen.
Write a function
CREATE FUNCTION dbo.TO_SAP_DATETIME(@input datetime)
RETURNS VARCHAR(14)
AS BEGIN
DECLARE @ret VARCHAR(14)
SET @ret = COALESCE(SUBSTRING(REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(26), @input, 25),'-',''),' ',''),':',''),1,14),'00000000000000');
RETURN @ret
END
using (var cmd = new SqlCommand("SELECT EmpName FROM [Employee] WHERE EmpID = @id", con))
put []
around table name ;)
I'm encountering a similar issue and found two solutions that work as far as viewing the application directly in a browser
ngrok http 8080 -host-header="localhost:8080"
ngrok http --host-header=rewrite 8080
obviously replace 8080 with whatever port you're running on
this solution still raises an error when I use this in an embedded page, that pulls the bundle.js from the react app. I think since it rewrites the header to localhost, when this is embedded, it's looking to localhost, which the app is no longer running on
This is an answer to the comment posted by erikkallen:
You don't need a temp table. If you only have a few rows, (SELECT 1 FROM dual UNION SELECT 2 FROM dual) will do. Why would your example give ORA-0001? Wouldn't merge take the update lock on the index key and not continue until Sess1 has either committed or rolled back? – erikkallen
Well, try it yourself and tell me whether you get the same error or not:
SESS1:
create table t1 (pk int primary key, i int);
create table t11 (pk int primary key, i int);
insert into t1 values(1, 1);
insert into t11 values(2, 21);
insert into t11 values(3, 31);
commit;
SESS2: insert into t1 values(2, 2);
SESS1:
MERGE INTO t1 d
USING t11 s ON (d.pk = s.pk)
WHEN NOT MATCHED THEN INSERT (d.pk, d.i) VALUES (s.pk, s.i);
SESS2: commit;
SESS1: ORA-00001
I had the same problem and it was related to the .gitattributes
file.
However the file type that caused the problem was not specified in the .gitattributes
.
I was able to solve the issue by simply running
git rm .gitattributes
git add -A
git reset --hard
Even better, how about OnPause():
Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume().
When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A's onPause() returns, so be sure toenter code here
not do anything lengthy here.
This callback is mostly used for saving any persistent state the activity is editing and making sure nothing is lost if there are not enough resources to start the new activity without first killing this one.
This is also a good place to do things like stop animations and other things that consume a noticeable amount of CPU in order to make the switch to the next activity as fast as possible, or to close resources that are exclusive access such as the camera.
On Ubuntu and Debian
apt-get install python-six
does the trick.
Use sudo apt-get install python-six
if you get an error saying "permission denied".
Actually if you create func:
create function p1() returns INTEGER DETERMINISTIC NO SQL return @p1;
and view:
create view h_parm as
select * from sw_hardware_big where unit_id = p1() ;
Then you can call a view with a parameter:
select s.* from (select @p1:=12 p) parm , h_parm s;
I hope it helps.
I came across this one that is written in java javaANPR, I am looking for a c# library as well.
I would like a system where I can point a video camera at some sailing boats, all of which have large, identifiable numbers on them, and have it identify the boats and send a tweet when they sail past a video camera.
try picasso
nice and finishes in one statement
Picasso.with(context)
.load(ImageURL)
.resize(width,height).into(imageView);
tutorial: https://youtu.be/DxRqxsEPc2s
(note: Picasso.with()
has been renamed to Picasso.get()
in the latest release)
One solution
DetailViewController *controller = [[DetailViewController alloc] initWithNibName:nil
bundle:[NSBundle mainBundle]];
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:controller];
navController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
navController.modalPresentationStyle = UIModalPresentationCurrentContext;
[self.navigationController presentViewController:navController
animated:YES
completion:nil];
In my case my RecyclerView
have a padding top like this
<android.support.v7.widget.RecyclerView
...
android:paddingTop="100dp"
android:clipToPadding="false"
/>
Then for scroll a item to top, I need to
recyclerViewLinearLayoutManager.scrollToPositionWithOffset(position, -yourRecyclerView.getPaddingTop());
You need to open the file again using open()
, but this time passing 'w'
to indicate that you want to write to the file. I would also recommend using with
to ensure that the file will be closed when you are finished writing to it.
with open('Failed.txt', 'w') as f:
for ip in [k for k, v in ips.iteritems() if v >=5]:
f.write(ip)
Naturally you may want to include newlines or other formatting in your output, but the basics are as above.
The same issue with closing your file applies to the reading code. That should look like this:
ips = {}
with open('today','r') as myFile:
for line in myFile:
parts = line.split(' ')
if parts[1] == 'Failure':
if parts[0] in ips:
ips[pars[0]] += 1
else:
ips[parts[0]] = 0
Better:
if cells(i,1)="" then
nextEmpty=i:
exit for
Clustered Index: Primary Key constraint creates clustered Index automatically if no clustered Index already exists on the table. Actual data of clustered index can be stored at leaf level of Index.
Non Clustered Index: Actual data of non clustered index is not directly found at leaf node, instead it has to take an additional step to find because it has only values of row locators pointing towards actual data. Non clustered Index can't be sorted as clustered index. There can be multiple non clustered indexes per table, actually it depends on the sql server version we are using. Basically Sql server 2005 allows 249 Non Clustered Indexes and for above versions like 2008, 2016 it allows 999 Non Clustered Indexes per table.
See the documentation on plt.axis()
. This:
plt.axis('equal')
doesn't work because it changes the limits of the axis to make circles appear circular. What you want is:
plt.axis('square')
This creates a square plot with equal axes.
be sure, that if the declarations for the pipe are done in one module, while you are using the pipe inside another module, you should provide correct imports/declarations at the current module under which is the class where you are using the pipe. In my case that was the reason for the pipe miss
This worked for me:
ALTER USER USER() IDENTIFIED BY 'auth_string';
I found it here: http://dev.mysql.com/doc/refman/5.7/en/alter-user.html#alter-user-current
I find this problem in my MacBook, the reason is because as @Stephan said, I use easy_install
to install pip, and the mixture of both py package manage tools led to the pkg_resources.DistributionNotFound
problem.
The resolve is:
easy_install --upgrade pip
Remember: just use one of the above tools to manage your Py packages.
Check you have <meta charset="utf-8">
inside head block.
ALTER TABLE tablename
ALTER COLUMN columnname columndatatype(size)
Note: if there is a size of columns, just write the size also.
Try using this Function.It Will help You:-
public class Main {
public static void main(String args[])
{
Date today=new Date();
Date myDate=new Date(today.getYear(),today.getMonth()-1,today.getDay());
System.out.println("My Date is"+myDate);
System.out.println("Today Date is"+today);
if(today.compareTo(myDate)<0)
System.out.println("Today Date is Lesser than my Date");
else if(today.compareTo(myDate)>0)
System.out.println("Today Date is Greater than my date");
else
System.out.println("Both Dates are equal");
}
}
You can use VARRAY for a fixed-size array:
declare
type array_t is varray(3) of varchar2(10);
array array_t := array_t('Matt', 'Joanne', 'Robert');
begin
for i in 1..array.count loop
dbms_output.put_line(array(i));
end loop;
end;
Or TABLE for an unbounded array:
...
type array_t is table of varchar2(10);
...
The word "table" here has nothing to do with database tables, confusingly. Both methods create in-memory arrays.
With either of these you need to both initialise and extend the collection before adding elements:
declare
type array_t is varray(3) of varchar2(10);
array array_t := array_t(); -- Initialise it
begin
for i in 1..3 loop
array.extend(); -- Extend it
array(i) := 'x';
end loop;
end;
The first index is 1 not 0.
It's generally considered bad practice. The problem is that the constants are part of the public "interface" (for want of a better word) of the implementing class. This means that the implementing class is publishing all of these values to external classes even when they are only required internally. The constants proliferate throughout the code. An example is the SwingConstants interface in Swing, which is implemented by dozens of classes that all "re-export" all of its constants (even the ones that they don't use) as their own.
But don't just take my word for it, Josh Bloch also says it's bad:
The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.
An enum may be a better approach. Or you could simply put the constants as public static fields in a class that cannot be instantiated. This allows another class to access them without polluting its own API.
raw_input
returns a string (a sequence of characters). In Python, multiplying a string and a float makes no defined meaning (while multiplying a string and an integer has a meaning: "AB" * 3
is "ABABAB"
; how much is "L" * 3.14
? Please do not reply "LLL|"
). You need to parse the string to a numerical value.
You might want to try:
salesAmount = float(raw_input("Insert sale amount here\n"))
None of the previous answers quite got to the bottom of my own confusion, so I'd like to add my own.
What I was missing is that lea
operations treat the use of parentheses different than how mov
does.
Think of C. Let's say I have an array of long
that I call array
. Now the expression array[i]
performs a dereference, loading the value from memory at the address array + i * sizeof(long)
[1].
On the other hand, consider the expression &array[i]
. This still contains the sub-expression array[i]
, but no dereferencing is performed! The meaning of array[i]
has changed. It no longer means to perform a deference but instead acts as a kind of a specification, telling &
what memory address we're looking for. If you like, you could alternatively think of the &
as "cancelling out" the dereference.
Because the two use-cases are similar in many ways, they share the syntax array[i]
, but the existence or absence of a &
changes how that syntax is interpreted. Without &
, it's a dereference and actually reads from the array. With &
, it's not. The value array + i * sizeof(long)
is still calculated, but it is not dereferenced.
The situation is very similar with mov
and lea
. With mov
, a dereference occurs that does not happen with lea
. This is despite the use of parentheses that occurs in both. For instance, movq (%r8), %r9
and leaq (%r8), %r9
. With mov
, these parentheses mean "dereference"; with lea
, they don't. This is similar to how array[i]
only means "dereference" when there is no &
.
An example is in order.
Consider the code
movq (%rdi, %rsi, 8), %rbp
This loads the value at the memory location %rdi + %rsi * 8
into the register %rbp
. That is: get the value in the register %rdi
and the value in the register %rsi
. Multiply the latter by 8, and then add it to the former. Find the value at this location and place it into the register %rbp
.
This code corresponds to the C line x = array[i];
, where array
becomes %rdi
and i
becomes %rsi
and x
becomes %rbp
. The 8
is the length of the data type contained in the array.
Now consider similar code that uses lea
:
leaq (%rdi, %rsi, 8), %rbp
Just as the use of movq
corresponded to dereferencing, the use of leaq
here corresponds to not dereferencing. This line of assembly corresponds to the C line x = &array[i];
. Recall that &
changes the meaning of array[i]
from dereferencing to simply specifying a location. Likewise, the use of leaq
changes the meaning of (%rdi, %rsi, 8)
from dereferencing to specifying a location.
The semantics of this line of code are as follows: get the value in the register %rdi
and the value in the register %rsi
. Multiply the latter by 8, and then add it to the former. Place this value into the register %rbp
. No load from memory is involved, just arithmetic operations [2].
Note that the only difference between my descriptions of leaq
and movq
is that movq
does a dereference, and leaq
doesn't. In fact, to write the leaq
description, I basically copy+pasted the description of movq
, and then removed "Find the value at this location".
To summarize: movq
vs. leaq
is tricky because they treat the use of parentheses, as in (%rsi)
and (%rdi, %rsi, 8)
, differently. In movq
(and all other instruction except lea
), these parentheses denote a genuine dereference, whereas in leaq
they do not and are purely convenient syntax.
[1] I've said that when array
is an array of long
, the expression array[i]
loads the value from the address array + i * sizeof(long)
. This is true, but there's a subtlety that should be addressed. If I write the C code
long x = array[5];
this is not the same as typing
long x = *(array + 5 * sizeof(long));
It seems that it should be based on my previous statements, but it's not.
What's going on is that C pointer addition has a trick to it. Say I have a pointer p
pointing to values of type T
. The expression p + i
does not mean "the position at p
plus i
bytes". Instead, the expression p + i
actually means "the position at p
plus i * sizeof(T)
bytes".
The convenience of this is that to get "the next value" we just have to write p + 1
instead of p + 1 * sizeof(T)
.
This means that the C code long x = array[5];
is actually equivalent to
long x = *(array + 5)
because C will automatically multiply the 5
by sizeof(long)
.
So in the context of this StackOverflow question, how is this all relevant? It means that when I say "the address array + i * sizeof(long)
", I do not mean for "array + i * sizeof(long)
" to be interpreted as a C expression. I am doing the multiplication by sizeof(long)
myself in order to make my answer more explicit, but understand that due to that, this expression should not be read as C. Just as normal math that uses C syntax.
[2] Side note: because all lea
does is arithmetic operations, its arguments don't actually have to refer to valid addresses. For this reason, it's often used to perform pure arithmetic on values that may not be intended to be dereferenced. For instance, cc
with -O2
optimization translates
long f(long x) {
return x * 5;
}
into the following (irrelevant lines removed):
f:
leaq (%rdi, %rdi, 4), %rax # set %rax to %rdi + %rdi * 4
ret
If you use http://localhost:80/
as a prefix, you can listen to http requests with no need for Administrative privileges.
Based on Tom Gullen´s answer.
var start = new Date("02/05/2013");
var end = new Date("02/10/2013");
var loop = new Date(start);
while(loop <= end){
alert(loop);
var newDate = loop.setDate(loop.getDate() + 1);
loop = new Date(newDate);
}
The most rank answer in this post work, however its is CSV file. It is not actual Excel file. Therefore, you will get a warning when you are opening a file.
The best solution I found on the web is using CloseXML https://github.com/closedxml/closedxml You need to Open XML as well.
dt = city.GetAllCity();//your datatable
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt);
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=GridView.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
I would prefer to make a function that doesn't work with strings:
'---------------------------------------------------------------------------------------
' Procedure : RemoveTimeFromDate
' Author : berend.nieuwhof
' Date : 15-8-2013
' Purpose : removes the time part of a String and returns the date as a date
'---------------------------------------------------------------------------------------
'
Public Function RemoveTimeFromDate(DateTime As Date) As Date
Dim dblNumber As Double
RemoveTimeFromDate = CDate(Floor(CDbl(DateTime)))
End Function
Private Function Floor(ByVal x As Double, Optional ByVal Factor As Double = 1) As Double
Floor = Int(x / Factor) * Factor
End Function
You cannot style things like radio buttons, checkboxes, scrollsbars (etc.) at all. These are native to the OS and the browser and not something you can manipulate.
You can simulate this, however by hiding the radio buttons and only showing an image instead as in.
<input type="radio" style="display: none;" id="sad" /><label for="sad"><img class="sad_image" /></label>
If you are starting the python interpreter from a shell on Linux or similar systems (BSD, not sure about Mac), you should also check the default encoding for the shell.
Call locale charmap
from the shell (not the python interpreter) and you should see
[user@host dir] $ locale charmap
UTF-8
[user@host dir] $
If this is not the case, and you see something else, e.g.
[user@host dir] $ locale charmap
ANSI_X3.4-1968
[user@host dir] $
Python will (at least in some cases such as in mine) inherit the shell's encoding and will not be able to print (some? all?) unicode characters. Python's own default encoding that you see and control via sys.getdefaultencoding()
and sys.setdefaultencoding()
is in this case ignored.
If you find that you have this problem, you can fix that by
[user@host dir] $ export LC_CTYPE="en_EN.UTF-8"
[user@host dir] $ locale charmap
UTF-8
[user@host dir] $
(Or alternatively choose whichever keymap you want instead of en_EN.) You can also edit /etc/locale.conf
(or whichever file governs the locale definition in your system) to correct this.
You can use size()
, but jQuery recommends you use length to avoid the overhead of another function call:
$('div.mydivclass').length
So:
// since length is zero, it evaluates to false
if ($('div.mydivclass').length) {
UPDATE
The selected answer uses a perf test, but it's slightly flawed since it is also including element selection as part of the perf, which is not what's being tested here. Here is an updated perf test:
http://jsperf.com/check-if-div-exists/3
My first run of the test shows that property retrieval is faster than index retrieval, although IMO it's pretty negligible. I still prefer using length as to me it makes more sense as to the intent of the code instead of a more terse condition.
For compatibility with all browsers stick with .ico
.
.png is getting more and more support though as it is easier to create using multiple programs.
for .ico
<link rel="shortcut icon" href="http://example.com/myicon.ico" />
for .png, you need to specify the type
<link rel="icon" type="image/png" href="http://example.com/image.png" />
you have an extra "}" in each object, you may write the json string like this:
public class ShowActivity {
private final static String jString = "{"
+ " \"geodata\": ["
+ " {"
+ " \"id\": \"1\","
+ " \"name\": \"Julie Sherman\","
+ " \"gender\" : \"female\","
+ " \"latitude\" : \"37.33774833333334\","
+ " \"longitude\" : \"-121.88670166666667\""
+ " }"
+ " },"
+ " {"
+ " \"id\": \"2\","
+ " \"name\": \"Johnny Depp\","
+ " \"gender\" : \"male\","
+ " \"latitude\" : \"37.336453\","
+ " \"longitude\" : \"-121.884985\""
+ " }"
+ " }"
+ " ]"
+ "}";
}
What about System.IO.Packaging.ZipPackage
?
It would require .NET 3.0 or greater.
#Load some assemblys. (No line break!)
[System.Reflection.Assembly]::Load("WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")
#Create a zip file named "MyZipFile.zip". (No line break!)
$ZipPackage=[System.IO.Packaging.ZipPackage]::Open("C:\MyZipFile.zip",
[System.IO.FileMode]"OpenOrCreate", [System.IO.FileAccess]"ReadWrite")
#The files I want to add to my archive:
$files = @("/Penguins.jpg", "/Lighthouse.jpg")
#For each file you want to add, we must extract the bytes
#and add them to a part of the zip file.
ForEach ($file In $files)
{
$partName=New-Object System.Uri($file, [System.UriKind]"Relative")
#Create each part. (No line break!)
$part=$ZipPackage.CreatePart($partName, "",
[System.IO.Packaging.CompressionOption]"Maximum")
$bytes=[System.IO.File]::ReadAllBytes($file)
$stream=$part.GetStream()
$stream.Write($bytes, 0, $bytes.Length)
$stream.Close()
}
#Close the package when we're done.
$ZipPackage.Close()
via Anders Hesselbom
Do everything suggested by ziesemer.
You may also want to remove from the registry:
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\<any Ora* drivers> keys
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers<any Ora* driver> values
So they no longer appear in the "ODBC Drivers that are installed on your system" in ODBC Data Source Administrator
Note: This was written and accepted back in the Rails 2 days; nowadays grosser's answer is the way to go.
Option 1: Probably the simplest way is to include your helper module in your controller:
class MyController < ApplicationController
include MyHelper
def xxxx
@comments = []
Comment.find_each do |comment|
@comments << {:id => comment.id, :html => html_format(comment.content)}
end
end
end
Option 2: Or you can declare the helper method as a class function, and use it like so:
MyHelper.html_format(comment.content)
If you want to be able to use it as both an instance function and a class function, you can declare both versions in your helper:
module MyHelper
def self.html_format(str)
process(str)
end
def html_format(str)
MyHelper.html_format(str)
end
end
Hope this helps!
var bmp = new Bitmap(@"path\picture.bmp");
using( Graphics g = Graphics.FromImage( bmp ) )
{
g.DrawString( ... );
}
picturebox1.Image = bmp;
As explained before:
ALTER TABLE TABLEName
drop CONSTRAINT FK_CONSTRAINTNAME;
ALTER TABLE TABLENAME
ADD CONSTRAINT FK_CONSTRAINTNAME
FOREIGN KEY (FId)
REFERENCES OTHERTABLE
(Id)
ON DELETE CASCADE ON UPDATE NO ACTION;
As you can see those have to be separated commands, first dropping then adding.
var
is great when you don't want to repeat yourself. For example, I needed a data structure yesterday that was similar to this. Which representation do you prefer?
Dictionary<string, Dictionary<string, List<MyNewType>>> collection = new Dictionary<string, Dictionary<string, List<MyNewType>>>();
or
var collection = new Dictionary<string, Dictionary<string, List<MyNewType>>>();
Note that there is little ambiguity introduced by using var
in this example. However, there are times when it wouldn't be such a good idea. For example, if I used var
as in the following,
var value= 5;
when I could just write the real type and remove any ambiguity in how 5
should be represented.
double value = 5;
Let's assume you have environment variable definitions in your ~/.bash_profile
like in the following snippet:
export JAVA_HOME="$(/usr/libexec/java_home -v 1.8)"
export GOPATH="$HOME/go"
export PATH="$PATH:/usr/local/opt/go/libexec/bin:$GOPATH/bin"
export PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH"
export MANPATH="/usr/local/opt/coreutils/libexec/gnuman:$MANPATH"
We need a Launch Agent which will run on each login and anytime on demand which is going to load these variables to the user session. We'll also need a shell script to parse these definitions and build necessary commands to be executed by the agent.
Create a file with plist
suffix (e.g. named osx-env-sync.plist
) in ~/Library/LaunchAgents/
directory with the following contents:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>osx-env-sync</string>
<key>ProgramArguments</key>
<array>
<string>bash</string>
<string>-l</string>
<string>-c</string>
<string>
$HOME/.osx-env-sync.sh
</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
-l
parameter is critical here; it's necessary for executing the shell script with a login shell so that ~/.bash_profile
is sourced in the first place before this script is executed.
Now, the shell script. Create it at ~/.osx-env-sync.sh
with the following contents:
grep export $HOME/.bash_profile | while IFS=' =' read ignoreexport envvar ignorevalue; do
launchctl setenv "${envvar}" "${!envvar}"
done
Make sure the shell script is executable:
chmod +x ~/.osx-env-sync.sh
Now, load the launch agent for current session:
launchctl load ~/Library/LaunchAgents/osx-env-sync.plist
(Re)Launch a GUI application and verify that it can read the environment variables.
The setup is persistent. It will survive restarts and relogins.
After the initial setup (that you just did), if you want to reflect any changes in your ~/.bash_profile
to your whole environment again, rerunning the launchctl load ...
command won't perform what you want; instead you'll get a warning like the following:
<$HOME>/Library/LaunchAgents/osx-env-sync.plist: Operation already in progress
In order to reload your environment variables without going through the logout/login process do the following:
launchctl unload ~/Library/LaunchAgents/osx-env-sync.plist
launchctl load ~/Library/LaunchAgents/osx-env-sync.plist
Finally make sure that you relaunch your already running applications (including Terminal.app) to make them aware of the changes.
I've also pushed the code and explanations here to a GitHub project: osx-env-sync.
I hope this is going to be the ultimate solution, at least for the latest versions of OS X (Yosemite & El Capitan).
So If you present a view controller it will not show in navigation controller. It will just take complete screen. For this case you have to create another navigation controller and add your nextViewController
as root for this and present this new navigationController.
Another way is to just push the view controller.
self.presentViewController(nextViewController, animated:true, completion:nil)
For more info check Apple documentation:- https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/#//apple_ref/doc/uid/TP40006926-CH3-SW96
I have that kind of spring setup working
an abstract class with an autowired field
public abstract class AbstractJobRoute extends RouteBuilder {
@Autowired
private GlobalSettingsService settingsService;
and several children defined with @Component
annotation.
Choose which DI to inject stuff into Jersey:
Spring 4:
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring4</artifactId>
</dependency>
Spring 3:
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
</dependency>
HK2:
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
</dependency>
@Der Hochstapler thanks for the solution.
but in IONIC 4 some customization in project config.xml work for me
Add a line in Widget tag
<widget id="com.my.awesomeapp" version="1.0.0"
xmlns="http://www.w3.org/ns/widgets"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cdv="http://cordova.apache.org/ns/1.0">
after this, in the Platform tag for android customize some lines check below
add usesCleartextTraffic=true after networkSecurityConfig and resource-file tags
<platform name="android">
<edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android">
<application android:networkSecurityConfig="@xml/network_security_config" />
</edit-config>
<resource-file src="resources/android/xml/network_security_config.xml" target="app/src/main/res/xml/network_security_config.xml" />
<edit-config file="AndroidManifest.xml" mode="merge" target="/manifest/application">
<application android:usesCleartextTraffic="true" />
</edit-config>
</platform>
I am using microsoft's Android emulator with Android Studio. I have an AMD FX8350. The ARM one in android studio is terribly slow.
The only issue is that it requires Hyper-V which is not available on windows 10 Home.
Its a really quick emulator and it is free. The best emulator I have used.
One simple method is to use place
to use an image as a background image. This is the type of thing that place
is really good at doing.
For example:
background_image=tk.PhotoImage(...)
background_label = tk.Label(parent, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
You can then grid
or pack
other widgets in the parent as normal. Just make sure you create the background label first so it has a lower stacking order.
Note: if you are doing this inside a function, make sure you keep a reference to the image, otherwise the image will be destroyed by the garbage collector when the function returns. A common technique is to add a reference as an attribute of the label object:
background_label.image = background_image
It's possible that your WCF service is returning HTML. In this case, you'll want to set up a binding on the service side to return XML instead. However, this is unlikely: if it is the case, let me know and I'll make an edit with more details.
The more likely reason is that your service is throwing an error, which is returning an HTML error page. You can take a look at this blog post if you want details.
tl;dr:
There are a few possible configurations for error pages. If you're hosting on IIS, you'll want to remove the <httpErrors>
section from the WCF service's web.config
file. If not, please provide details of your service hosting scenario and I can come up with an edit to match them.
EDIT:
Having seen your edit, you can see the full error being returned. Apache can't tell which service you want to call, and is throwing an error for that reason. The service will work fine once you have the correct endpoint - you're pointed at the wrong location. I unfortunately can't tell from the information available what the right location is, but either your action (currently null
!) or the URL is incorrect.
What about something like :
angle = angle % 360;
You need to use the iconv package, specifically its iconv function.
It is possible to use setOnKeyListener
. In this method, we can customize the input edittext
!
Beginners needs practical examples. so try the following code.
public class Not_a_Number {
public static void main(String[] args) {
// TODO Auto-generated method stub
String message = "0.0/0.0 is NaN.\nsimilarly Math.sqrt(-1) is NaN.";
String dottedLine = "------------------------------------------------";
Double numerator = -2.0;
Double denominator = -2.0;
while (denominator <= 1) {
Double x = numerator/denominator;
Double y = new Double (x);
boolean z = y.isNaN();
System.out.println("y = " + y);
System.out.println("z = " + z);
if (z == true){
System.out.println(message);
}
else {
System.out.println("Hi, everyone");
}
numerator = numerator + 1;
denominator = denominator +1;
System.out.println(dottedLine);
} // end of while
} // end of main
} // end of class
Enter
git log .
from the specific directory, it also gives commits in that directory.
You can create a SUPERUSER
or promote USER
, so for your case
$ sudo -u postgres psql -c "ALTER USER myuser WITH SUPERUSER;"
or rollback
$ sudo -u postgres psql -c "ALTER USER myuser WITH NOSUPERUSER;"
To prevent a command from logging when you set password, insert a whitespace in front of it, but check that your system supports this option.
$ sudo -u postgres psql -c "CREATE USER my_user WITH PASSWORD 'my_pass';"
$ sudo -u postgres psql -c "CREATE USER my_user WITH SUPERUSER PASSWORD 'my_pass';"
The easiest way of all is as follows: Click the office button (top left) Click "Excel Options" Click "Advanced" Scroll down to "Display options for this worksheet" Untick the box "Show a zero in cells that have zero value" Click "okay"
That's all there is to it.
:)
Wget currently only supports x-www-form-urlencoded data. --post-file
is not for transmitting files as form attachments, it expects data with the form: key=value&otherkey=example
.
--post-data
and --post-file
work the same way: the only difference is that --post-data
allows you to specify the data in the command line, while --post-file
allows you to specify the path of the file that contain the data to send.
Here's the documentation:
--post-data=string
--post-file=file
Use POST as the method for all HTTP requests and send the specified data
in the request body. --post-data sends string as data, whereas
--post-file sends the contents of file. Other than that, they work in
exactly the same way. In particular, they both expect content of the
form "key1=value1&key2=value2", with percent-encoding for special
characters; the only difference is that one expects its content as a
command-line parameter and the other accepts its content from a file. In
particular, --post-file is not for transmitting files as form
attachments: those must appear as "key=value" data (with appropriate
percent-coding) just like everything else. Wget does not currently
support "multipart/form-data" for transmitting POST data; only
"application/x-www-form-urlencoded". Only one of --post-data and
--post-file should be specified.
Regarding your authentication token, it should either be provided in the header, in the path of the url, or in the data itself. This must be indicated somewhere in the documentation of the service you use. In a POST request, as in a GET request, you must specify the data using keys and values. This way the server will be able to receive multiple information with specific names. It's similar with variables.
Hence, you can't just send a magic token to the server, you also need to specify the name of the key. If the key is "token", then it should be token=YOUR_TOKEN
.
wget --post-data 'user=foo&password=bar' http://example.com/auth.php
Also, you should consider using curl if you can because it is easier to send files using it. There are many examples on the Internet for that.
Just give any name to the DataTable Like:
DataTable dt = new DataTable();
dt = SecondDataTable.Copy();
dt .TableName = "New Name";
DataSet.Tables.Add(dt );
In theory, there's nothing preventing you from sending a request body in a GET
request. The HTTP protocol allows it, but have no defined semantics, so it's up to you to document what exactly is going to happen when a client sends a GET
payload. For instance, you have to define if parameters in a JSON body are equivalent to querystring parameters or something else entirely.
However, since there are no clearly defined semantics, you have no guarantee that implementations between your application and the client will respect it. A server or proxy might reject the whole request, or ignore the body, or anything else. The REST way to deal with broken implementations is to circumvent it in a way that's decoupled from your application, so I'd say you have two options that can be considered best practices.
The simple option is to use POST
instead of GET
as recommended by other answers. Since POST
is not standardized by HTTP, you'll have to document how exactly that's supposed to work.
Another option, which I prefer, is to implement your application assuming the GET
payload is never tampered with. Then, in case something has a broken implementation, you allow clients to override the HTTP method with the X-HTTP-Method-Override
, which is a popular convention for clients to emulate HTTP methods with POST
. So, if a client has a broken implementation, it can write the GET
request as a POST
, sending the X-HTTP-Method-Override: GET
method, and you can have a middleware that's decoupled from your application implementation and rewrites the method accordingly. This is the best option if you're a purist.
Its quite simple using the "Git Parameter Plug-in".
Add Name like "SELECT_BRANCH" ## Make sure for this variable as this would be used later. Then Parameter Type : Branch
Then reach out to SCM : Select : Git and branch specifier : ${SELECT_BRANCH}
To verify, execute below in shell in jenkins:
echo ${SELECT_BRANCH}
env.enter image description here
This method doesn't require external libraries
using System.Web.Script.Serialization;
bool IsValidJson(string json)
{
try {
var serializer = new JavaScriptSerializer();
dynamic result = serializer.DeserializeObject(json);
return true;
} catch { return false; }
}
You can do both in code and XML. Only 4 basic things to be set.
e.g.
android:shadowColor="@color/text_shadow_color"
android:shadowDx="-2"
android:shadowDy="2"
android:shadowRadius="0.01"
This draws a prominent shadow on left-lower side of text. In code, you can add something like this;
TextView item = new TextView(getApplicationContext());
item.setText(R.string.text);
item.setTextColor(getResources().getColor(R.color.general_text_color));
item.setShadowLayer(0.01f, -2, 2, getResources().getColor(R.color.text_shadow_color));
According to documentation class date
is a parent for class datetime
. And isinstance()
method will give you True
in all cases. If you need to distinguish datetime
from date
you should check name of the class
import datetime
datetime.datetime.now().__class__.__name__ == 'date' #False
datetime.datetime.now().__class__.__name__ == 'datetime' #True
datetime.date.today().__class__.__name__ == 'date' #True
datetime.date.today().__class__.__name__ == 'datetime' #False
I've faced with this problem when i have different formatting rules for dates and dates with time
You can also specify context location relatively to current classpath, which may be preferable
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
@msb gives a safe solution.
I met this problem when I did import tensorflow as tf
in conda environment in CentOS 6.5
which only has glibc-2.12
.
ImportError: /lib64/libc.so.6: version `GLIBC_2.16' not found (required by /home/
I want to supply some details:
First install glibc
to your home directory:
mkdir ~/glibc-install; cd ~/glibc-install
wget http://ftp.gnu.org/gnu/glibc/glibc-2.17.tar.gz
tar -zxvf glibc-2.17.tar.gz
cd glibc-2.17
mkdir build
cd build
../configure --prefix=/home/myself/opt/glibc-2.17 # <-- where you install new glibc
make -j<number of CPU Cores> # You can find your <number of CPU Cores> by using **nproc** command
make install
Second, follow the same way to install patchelf;
Third, patch your Python:
[myself@nfkd ~]$ patchelf --set-interpreter /home/myself/opt/glibc-2.17/lib/ld-linux-x86-64.so.2 --set-rpath /home/myself/opt/glibc-2.17/lib/ /home/myself/miniconda3/envs/tensorflow/bin/python
as mentioned by @msb
Now I can use tensorflow-2.0 alpha
in CentOS 6.5
.
ref: https://serverkurma.com/linux/how-to-update-glibc-newer-version-on-centos-6-x/
$('.selectpicker').selectpicker('deselectAll');
https://developer.snapappointments.com/bootstrap-select/methods/
As everyone noticed: you can't. But you can create a obj and assign every var you declare to that obj. That way you can easily check out your vars:
var v = {}; //put everything here
var f = function(a, b){//do something
}; v.f = f; //make's easy to debug
var a = [1,2,3];
v.a = a;
var x = 'x';
v.x = x; //so on...
console.log(v); //it's all there
Here's an outline of how you could go about doing this. It should be relatively straightforward to implement it as actual code.
user.name
would become user
and name
. Look up user
in your map to get the object and use reflection to obtain the value of name
from the object. Assuming your objects have standard getters, you will look for a method getName
and invoke it.As mentioned, delete the old one on GitHub and re-push, though the commands used are a bit more verbose than necessary:
git push origin :name_of_the_old_branch_on_github
git push origin new_name_of_the_branch_that_is_local
Dissecting the commands a bit, the git push
command is essentially:
git push <remote> <local_branch>:<remote_branch>
So doing a push with no local_branch specified essentially means "take nothing from my local repository, and make it the remote branch". I've always thought this to be completely kludgy, but it's the way it's done.
As of Git 1.7 there is an alternate syntax for deleting a remote branch:
git push origin --delete name_of_the_remote_branch
As mentioned by @void.pointer in the comments
Note that you can combine the 2 push operations:
git push origin :old_branch new_branch
This will both delete the old branch and push the new one.
This can be turned into a simple alias that takes the remote, original branch and new branch name as arguments, in ~/.gitconfig
:
[alias]
branchm = "!git branch -m $2 $3 && git push $1 :$2 $3 -u #"
Usage:
git branchm origin old_branch new_branch
Note that positional arguments in shell commands were problematic in older (pre 2.8?) versions of Git, so the alias might vary according to the Git version. See this discussion for details.
The answers did help, but I think a full implementation of this will help a lot of people.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
namespace Dom
{
class Dom
{
public static string make_Sting_From_Dom(string reportname)
{
try
{
WebClient client = new WebClient();
client.Credentials = CredentialCache.DefaultCredentials;
// Retrieve resource as a stream
Stream data = client.OpenRead(new Uri(reportname.Trim()));
// Retrieve the text
StreamReader reader = new StreamReader(data);
string htmlContent = reader.ReadToEnd();
string mtch = "TILDE";
bool b = htmlContent.Contains(mtch);
if (b)
{
int index = htmlContent.IndexOf(mtch);
if (index >= 0)
Console.WriteLine("'{0} begins at character position {1}",
mtch, index + 1);
}
// Cleanup
data.Close();
reader.Close();
return htmlContent;
}
catch (Exception)
{
throw;
}
}
static void Main(string[] args)
{
make_Sting_From_Dom("https://www.w3.org/TR/PNG/iso_8859-1.txt");
}
}
}
Oh man, one of my pet peeves.
inline
is more like static
or extern
than a directive telling the compiler to inline your functions. extern
, static
, inline
are linkage directives, used almost exclusively by the linker, not the compiler.
It is said that inline
hints to the compiler that you think the function should be inlined. That may have been true in 1998, but a decade later the compiler needs no such hints. Not to mention humans are usually wrong when it comes to optimizing code, so most compilers flat out ignore the 'hint'.
static
- the variable/function name cannot be used in other translation units. Linker needs to make sure it doesn't accidentally use a statically defined variable/function from another translation unit.
extern
- use this variable/function name in this translation unit but don't complain if it isn't defined. The linker will sort it out and make sure all the code that tried to use some extern symbol has its address.
inline
- this function will be defined in multiple translation units, don't worry about it. The linker needs to make sure all translation units use a single instance of the variable/function.
Note: Generally, declaring templates inline
is pointless, as they have the linkage semantics of inline
already. However, explicit specialization and instantiation of templates require inline
to be used.
Specific answers to your questions:
When should I write the keyword 'inline' for a function/method in C++?
Only when you want the function to be defined in a header. More exactly only when the function's definition can show up in multiple translation units. It's a good idea to define small (as in one liner) functions in the header file as it gives the compiler more information to work with while optimizing your code. It also increases compilation time.
When should I not write the keyword 'inline' for a function/method in C++?
Don't add inline just because you think your code will run faster if the compiler inlines it.
When will the compiler not know when to make a function/method 'inline'?
Generally, the compiler will be able to do this better than you. However, the compiler doesn't have the option to inline code if it doesn't have the function definition. In maximally optimized code usually all private
methods are inlined whether you ask for it or not.
As an aside to prevent inlining in GCC, use __attribute__(( noinline ))
, and in Visual Studio, use __declspec(noinline)
.
Does it matter if an application is multithreaded when one writes 'inline' for a function/method?
Multithreading doesn't affect inlining in any way.
Let's say you placed all the other files and directories in a folder named 'locale'.
Just go to index.php and find these two lines:
require __DIR__.'/../bootstrap/autoload.php';
$app = require_once __DIR__.'/../bootstrap/app.php';
and change them to this:
require __DIR__.'/locale/bootstrap/autoload.php';
$app = require_once __DIR__.'/locale/bootstrap/app.php';
If you don't use parallel()
this will work
List<Long> sourceLongList = Arrays.asList(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L);
List<Long> targetLongList = new ArrayList<Long>();
sourceLongList.stream().peek(i->targetLongList.add(i)).collect(Collectors.toList());
This is due to staticmethod being a descriptor and requires a class-level attribute fetch to exercise the descriptor protocol and get the true callable.
From the source code:
It can be called either on the class (e.g.
C.f()
) or on an instance (e.g.C().f()
); the instance is ignored except for its class.
But not directly from inside the class while it is being defined.
But as one commenter mentioned, this is not really a "Pythonic" design at all. Just use a module level function instead.
For reliability I'd suggest giving class-names, or id
s to the elements to style (ideally a class
for the text-inputs, since there will presumably be several) and an id
to the submit button (though a class
would work as well):
<form action="#" method="post">
<label for="text1">Text 1</label>
<input type="text" class="textInput" id="text1" />
<label for="text2">Text 2</label>
<input type="text" class="textInput" id="text2" />
<input id="submitBtn" type="submit" />
</form>
With the CSS:
.textInput {
/* styles the text input elements with this class */
}
#submitBtn {
/* styles the submit button */
}
For more up-to-date browsers, you can select by attributes (using the same HTML):
.input {
/* styles all input elements */
}
.input[type="text"] {
/* styles all inputs with type 'text' */
}
.input[type="submit"] {
/* styles all inputs with type 'submit' */
}
You could also just use sibling combinators (since the text-inputs to style seem to always follow a label
element, and the submit follows a textarea (but this is rather fragile)):
label + input,
label + textarea {
/* styles input, and textarea, elements that follow a label */
}
input + input,
textarea + input {
/* would style the submit-button in the above HTML */
}
VT-x can normally be disabled/enabled in your BIOS.
When your PC is just starting up you should press DEL (or something) to get to the BIOS settings. There you'll find an option to enable VT-technology (or something).
Have you checked strncpy?
char * strncpy ( char * destination, const char * source, size_t num );
You must realize that begin and end actually defines a num of bytes to be copied from one place to another.
On your servlet simply override the service method of your servlet so that you can add headers for all your http methods (POST, GET, DELETE, PUT, etc...).
@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
if(("http://www.example.com").equals(req.getHeader("origin"))){
res.setHeader("Access-Control-Allow-Origin", req.getHeader("origin"));
res.setHeader("Access-Control-Allow-Headers", "Authorization");
}
super.service(req, res);
}
INADDR_ANY is a constant, that contain 0 in value . this will used only when you want connect from all active ports you don't care about ip-add . so if you want connect any particular ip you should mention like as my_sockaddress.sin_addr.s_addr = inet_addr("192.168.78.2")
If you want to discard the array at the same time as summing, you could do (say, stack
is the array):
var stack = [1,2,3],
sum = 0;
while(stack.length > 0) { sum += stack.pop() };
If we are using nodeJS, we should definitely take advantage of different libraries it provides. Inbuilt functions like each(), map(), reduce() and many more from underscoreJS reduces our efforts. Here's a sample
var _=require("underscore");
var fs=require("fs");
var jsonObject=JSON.parse(fs.readFileSync('YourJson.json', 'utf8'));
_.map( jsonObject, function(content) {
_.map(content,function(data){
if(data.Timestamp)
console.log(data.Timestamp)
})
})
Try PHP Mailer library.
Or Send mail through SMTP filter it before sending it.
Also Try to give all details like FROM
, return-path
.
In my humble opinion, idempotence means:
I send a compete resource definition, so - the resulting resource state is exactly as defined by PUT params. Each and every time I update the resource with the same PUT params - the resulting state is exactly the same.
I sent only part of the resource definition, so it might happen other users are updating this resource's OTHER parameters in a meantime. Consequently - consecutive patches with the same parameters and their values might result with different resource state. For instance:
Presume an object defined as follows:
CAR: - color: black, - type: sedan, - seats: 5
I patch it with:
{color: 'red'}
The resulting object is:
CAR: - color: red, - type: sedan, - seats: 5
Then, some other users patches this car with:
{type: 'hatchback'}
so, the resulting object is:
CAR: - color: red, - type: hatchback, - seats: 5
Now, if I patch this object again with:
{color: 'red'}
the resulting object is:
CAR: - color: red, - type: hatchback, - seats: 5
What is DIFFERENT to what I've got previously!
This is why PATCH is not idempotent while PUT is idempotent.
It is highly unlikely that adding NameVirtualHost *:443
is the right solution, because there are a limited number of situations in which it is possible to support name-based virtual hosts over SSL. Read this and this for some details (there may be better docs out there; these were just ones I found that discuss the issue in detail).
If you're running a relatively stock Apache configuration, you probably have this somewhere:
<VirtualHost _default_:443>
Your best bet is to either:
VirtualHost
container, or VirtualHost
block and create a new one. Don't forget to include all the relevant SSL options.A VERY BAD CAVEAT : Division by Zero
in a 1/x
fraction, up to x = 1e-323
it is inf
but when x = 1e-324
or little it throws ZeroDivisionError
>>> 1/1e-323
inf
>>> 1/1e-324
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: float division by zero
so be cautious!
There are probably embedded tabs (CHAR(9)
) etc. as well. You can find out what other characters you need to replace (we have no idea what your goal is) with something like this:
DECLARE @var NVARCHAR(255), @i INT;
SET @i = 1;
SELECT @var = AccountType FROM dbo.Account
WHERE AccountNumber = 200
AND AccountType LIKE '%Daily%';
CREATE TABLE #x(i INT PRIMARY KEY, c NCHAR(1), a NCHAR(1));
WHILE @i <= LEN(@var)
BEGIN
INSERT #x
SELECT SUBSTRING(@var, @i, 1), ASCII(SUBSTRING(@var, @i, 1));
SET @i = @i + 1;
END
SELECT i,c,a FROM #x ORDER BY i;
You might also consider doing better cleansing of this data before it gets into your database. Cleaning it every time you need to search or display is not the best approach.
Pandas allows to specify encoding, but does not allow to ignore errors not to automatically replace the offending bytes. So there is no one size fits all method but different ways depending on the actual use case.
You know the encoding, and there is no encoding error in the file. Great: you have just to specify the encoding:
file_encoding = 'cp1252' # set file_encoding to the file encoding (utf8, latin1, etc.)
pd.read_csv(input_file_and_path, ..., encoding=file_encoding)
You do not want to be bothered with encoding questions, and only want that damn file to load, no matter if some text fields contain garbage. Ok, you only have to use Latin1
encoding because it accept any possible byte as input (and convert it to the unicode character of same code):
pd.read_csv(input_file_and_path, ..., encoding='latin1')
You know that most of the file is written with a specific encoding, but it also contains encoding errors. A real world example is an UTF8 file that has been edited with a non utf8 editor and which contains some lines with a different encoding. Pandas has no provision for a special error processing, but Python open
function has (assuming Python3), and read_csv
accepts a file like object. Typical errors parameter to use here are 'ignore'
which just suppresses the offending bytes or (IMHO better) 'backslashreplace'
which replaces the offending bytes by their Python’s backslashed escape sequence:
file_encoding = 'utf8' # set file_encoding to the file encoding (utf8, latin1, etc.)
input_fd = open(input_file_and_path, encoding=file_encoding, errors = 'backslashreplace')
pd.read_csv(input_fd, ...)
The bottom statement is equivalent to:
.half {
flex-grow: 0;
flex-shrink: 0;
flex-basis: 50%;
}
Which, in this case, would be equivalent as the box is not allowed to flex and therefore retains the initial width set by flex-basis.
Flex-basis defines the default size of an element before the remaining space is distributed so if the element were allowed to flex (grow/shrink) it may not be 50% of the width of the page.
I've found that I regularly return to https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for help regarding flexbox :)
SELECT * FROM service s WHERE s.service_id = ?;
IF @@rowcount = 0
begin
select 'no data'
end
It worked for me:
File file = new File(getApplicationContext().getFilesDir(),"whatever.txt");
if(file.exists()){
//Do something
}
else{
//Nothing
}
String str = "Your string";
byte[] array = str.getBytes();
On Debian this was a bind problem for me so changing bind-address
from localhost
to 0.0.0.0 helped.
vim /etc/mysql/my.cnf
bind-address = 0.0.0.0
If you're using fmdb, I think you can just import FMDatabaseAdditions and use the bool function:
[yourfmdbDatabase tableExists:tableName].
USE [master]
GO
/****** this function returns Pakistan where as if you want to get ireland simply replace (SELECT SUBSTRING(@NEWSTRING,CHARINDEX('$@$@$',@NEWSTRING)+5,LEN(@NEWSTRING))) with
SELECT @NEWSTRING = (SELECT SUBSTRING(@NEWSTRING, 0,CHARINDEX('$@$@$',@NEWSTRING)))******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[FN_RETURN_AFTER_SPLITER]
(
@SPLITER varchar(max))
RETURNS VARCHAR(max)
AS
BEGIN
--declare @testString varchar(100),
DECLARE @NEWSTRING VARCHAR(max)
-- set @teststring = '@ram?eez(ali)'
SET @NEWSTRING = @SPLITER ;
SELECT @NEWSTRING = (SELECT SUBSTRING(@NEWSTRING,CHARINDEX('$@$@$',@NEWSTRING)+5,LEN(@NEWSTRING)))
return @NEWSTRING
END
--select [dbo].[FN_RETURN_AFTER_SPLITER] ('Ireland$@$@$Pakistan')
changing the <useSecurity>true</useSecurity>
to <useSecurity>false</useSecurity>
will not be enough, you should remove <authorizationStrategy>
and <securityRealm>
elements too and restart your jenkins server by doing sudo service jenkins restart
.
remember this, set <usesecurity>
to false
only may cause a problem for you, since these instructions are mentioned in thier official documentation here.
Regardless of the version, for your example, the <update>
is:
{ $set: { lastLookedAt: Date.now() / 1000 } }
However, depending on your version of MongoDB, the query will look different. Regardless of version, the key is that the empty condition {}
will match any document. In the Mongo shell, or with any MongoDB client:
db.foo.updateMany( {}, <update> )
{}
is the condition (the empty condition matches any document)db.foo.update( {}, <update>, { multi: true } )
{}
is the condition (the empty condition matches any document){multi: true}
is the "update multiple documents" optiondb.foo.update( {}, <update>, false, true )
{}
is the condition (the empty condition matches any document)false
is for the "upsert" parametertrue
is for the "multi" parameter (update multiple records)None of the current answers helped me here. We were getting something like:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:
#.#.#:compile (default-compile) on project Streaming_Test: Compilation failure
[ERROR] Unable to locate the Javac Compiler in:
[ERROR] /opt/java/J7.0/../lib/tools.jar
This happens because the Java installation has determined that it is a JRE installation. It's expecting there to be JDK stuff above the JRE subdirectory, hence the ../lib
in the path. Our tools.jar
is in $JAVA_HOME/lib/tools.jar
not in $JAVA_HOME/../lib/tools.jar
.
Unfortunately, we do not have an option to install a JDK on our OS (don't ask) so that wasn't an option. I fixed the problem by adding the following to the maven pom.xml
:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<fork>true</fork> <!-- not sure if this is also needed -->
<executable>${JAVA_HOME}/bin/javac</executable>
<!-- ^^^^^^^^^^^^^^^^^^^^^^ -->
</configuration>
</plugin>
By pointing the executable to the right place this at least got past our compilation failures.
You need to take extra precautions when using user supplied data in HTML attributes. Because attributes has many more attack vectors than output inside HTML tags.
The only way to avoid XSS attacks is to encode everything except alphanumeric characters. Escape all characters with ASCII values less than 256 with the &#xHH; format. Which unfortunately may cause problems in your scenario, if you are using CSS classes and javascript to fetch those elements.
OWASP has a good description of how to mitigate HTML attribute XSS:
.extends()
create a class which is a child of another class.Child.prototype.__proto__
sets its value to Parent.prototype
.prototype
inherit features from one to another..__proto__
is a getter/setter for Prototype.Lot's of regex here, despite the fact i really like them this way might be more stable to me:
$resultCurl=curl_exec($curl); //get curl result
//Optional line if you want to store the http status code
$headerHttpCode=curl_getinfo($curl,CURLINFO_HTTP_CODE);
//let's use dom and xpath
$dom = new \DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($resultCurl, LIBXML_HTML_NODEFDTD);
libxml_use_internal_errors(false);
$xpath = new \DOMXPath($dom);
$head=$xpath->query("/html/body/p/a/@href");
$newUrl=$head[0]->nodeValue;
The location part is a link in the HTML sent by apache. So Xpath is perfect to recover it.
This works fine for me. It marks both simple nav elements and dropdown nav elements as active.
$(document).ready(function () {
var url = window.location;
$('ul.nav a[href="' + this.location.pathname + '"]').parent().addClass('active');
$('ul.nav a').filter(function() {
return this.href == url;
}).parent().parent().parent().addClass('active');
});
Passing this.location.pathname
to $('ul.nav a[href="'...'"]')
marks also simple nav elements. Passing url
did'nt work for me.
Another way is to do :
md5sum filename |cut -f 1 -d " "
Cut will split line to each space and return only first field.
Use 0 for true and 1 for false.
Sample:
#!/bin/bash
isdirectory() {
if [ -d "$1" ]
then
# 0 = true
return 0
else
# 1 = false
return 1
fi
}
if isdirectory $1; then echo "is directory"; else echo "nopes"; fi
Edit
From @amichair's comment, these are also possible
isdirectory() {
if [ -d "$1" ]
then
true
else
false
fi
}
isdirectory() {
[ -d "$1" ]
}
Here's a clean solution:
function test(str){
//Note: should be /(abc)|(def)/i if you want it case insensitive
var pattern = /(abc)|(def)/;
return !str.match(pattern);
}
When explicitly dealing with a ByteArrayInputStream
then contrary to some of the comments on this page you can use the .available()
function to get the size. Just have to do it before you start reading from it.
From the JavaDocs:
Returns the number of remaining bytes that can be read (or skipped over) from this input stream. The value returned is count - pos, which is the number of bytes remaining to be read from the input buffer.
https://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayInputStream.html#available()
You have to dot source
them:
. .\build_funtions.ps1
. .\build_builddefs.ps1
Note the extra .
This heyscriptingguy
article should be of help - How to Reuse Windows PowerShell Functions in Scripts
This should do it:
declare
v_count integer;
begin
for r in (select table_name, owner from all_tables
where owner = 'SCHEMA_NAME')
loop
execute immediate 'select count(*) from ' || r.table_name
into v_count;
INSERT INTO STATS_TABLE(TABLE_NAME,SCHEMA_NAME,RECORD_COUNT,CREATED)
VALUES (r.table_name,r.owner,v_count,SYSDATE);
end loop;
end;
I removed various bugs from your code.
Note: For the benefit of other readers, Oracle does not provide a table called STATS_TABLE
, you would need to create it.
Using table
:
library(magrittr)
myvec %>% unique %>% '['(1) %>% table %>% as.data.frame %>%
setNames(c("name","number_of_distinct_orders"))
# name number_of_distinct_orders
# 1 Amy 2
# 2 Dave 1
# 3 Jack 3
# 4 Larry 1
# 5 Tom 2
There is an option “unlimited scrollback buffer” which you can find under Preferences > Profiles > Terminal
or you can just pump up number of lines that you want to have in history in the same place.
First you have to ensure that there is a SMTP server listening on port 25.
To look whether you have the service, you can try using TELNET client, such as:
C:\> telnet localhost 25
(telnet client by default is disabled on most recent versions of Windows, you have to add/enable the Windows component from Control Panel. In Linux/UNIX usually telnet client is there by default.
$ telnet localhost 25
If it waits for long then time out, that means you don't have the required SMTP service. If successfully connected you enter something and able to type something, the service is there.
If you don't have the service, you can use these:
If you are sure that you already have the service, may be the SMTP requires additional security credentials. If you can tell me what SMTP server listening on port 25 I may be able to tell you more.
Had exactly the same problem as UseR (original question), I'm also using windows 7. I tried all proposed solutions and they didn't work.
I resolved the problem doing as follows:
Using RStudio instead of R console.
Actualising the version of R (from 3.1.0 to 3.1.1) so that the library RCurl runs OK on it. (I'm using now R3.1.1 32bit although my system is 64bit).
I typed the URL address as https (secure connection) and with /
instead of backslashes \\
.
Setting method = "auto"
.
It works for me now. You should see the message:
Content type 'text/csv; charset=utf-8' length 9294 bytes
opened URL
downloaded 9294 by
String hql="from DrawUnusedBalance where unusedBalanceDate= :today";
DrawUnusedBalance drawUnusedBalance = em.unwrap(Session.class)
.createQuery(hql, DrawUnusedBalance.class)
.setParameter("today",new LocalDate())
.uniqueResultOptional()
.orElseThrow(NotFoundException::new);
Either remove one } from end of responseText;}}
or from the end of the line
Difference between each annotation are :
+-------------------------------------------------------------------------------------------------------+
¦ Feature ¦ Junit 4 ¦ Junit 5 ¦
¦--------------------------------------------------------------------------+--------------+-------------¦
¦ Execute before all test methods of the class are executed. ¦ @BeforeClass ¦ @BeforeAll ¦
¦ Used with static method. ¦ ¦ ¦
¦ For example, This method could contain some initialization code ¦ ¦ ¦
¦-------------------------------------------------------------------------------------------------------¦
¦ Execute after all test methods in the current class. ¦ @AfterClass ¦ @AfterAll ¦
¦ Used with static method. ¦ ¦ ¦
¦ For example, This method could contain some cleanup code. ¦ ¦ ¦
¦-------------------------------------------------------------------------------------------------------¦
¦ Execute before each test method. ¦ @Before ¦ @BeforeEach ¦
¦ Used with non-static method. ¦ ¦ ¦
¦ For example, to reinitialize some class attributes used by the methods. ¦ ¦ ¦
¦-------------------------------------------------------------------------------------------------------¦
¦ Execute after each test method. ¦ @After ¦ @AfterEach ¦
¦ Used with non-static method. ¦ ¦ ¦
¦ For example, to roll back database modifications. ¦ ¦ ¦
+-------------------------------------------------------------------------------------------------------+
Most of annotations in both versions are same, but few differs.
Order of Execution.
Dashed box -> optional annotation.
List<Card> list = new ArrayList<Card>(Arrays.asList(hand));
The percent sign is escaped using a percent sign:
System.out.printf("%s\t%s\t%1.2f%%\t%1.2f%%\n",ID,pattern,support,confidence);
The complete syntax can be accessed in java docs. This particular information is in the section Conversions
of the first link.
The reason the compiler is generating an error is that only a limited amount of characters may follow a backslash. %
is not a valid character.
this is an old thread but i got interested and wanted to share my solution.
def find_all(a_string, sub):
result = []
k = 0
while k < len(a_string):
k = a_string.find(sub, k)
if k == -1:
return result
else:
result.append(k)
k += 1 #change to k += len(sub) to not search overlapping results
return result
It should return a list of positions where the substring was found. Please comment if you see an error or room for improvment.
An example,
d <- data.frame(x1=rnorm(10),
x2=rnorm(10),
x3=rnorm(10))
cor(d) # get correlations (returns matrix)
As a follow on, you could select "all nodes with a particular attribute" like this:
//*[@id='4']
If you want to drop column(s) from the target data frame, but the column(s) are required for the join, you can do the following:
df1 = df1.merge(df2[['a', 'b', 'key1']], how = 'left',
left_on = 'key2', right_on = 'key1').drop('key1')
The .drop('key1')
part will prevent 'key1' from being kept in the resulting data frame, despite it being required to join in the first place.
It seems that CharEscapers from Google GData-java-client has what you want. It has uriPathEscaper method, uriQueryStringEscaper, and generic uriEscaper. (All return Escaper object which does actual escaping). Apache License.
First of all, the fact that the value in the database is a float does not mean that it also fits in a Java float
. Float is short for floating point, and floating point types of various precisions exist. Java types float
and double
are both floating point types of different precision. In a database both are called FLOAT
. Since double
has a higher precision than float
, it probably is a better idea not to cast your value to a float
, because you might lose precision.
You might also use BigDecimal
, which represent an arbitrary-precision number.
Surprising to see nobody mentioned document.hasFocus
if (document.hasFocus()) console.log('Tab is active')
Example
public class myThread extends Thread{
@override
public void run(){
while(true){
threadCondWait();// Circle waiting...
//bla bla bla bla
}
}
public synchronized void threadCondWait(){
while(myCondition){
wait();//Comminucate with notify()
}
}
}
public class myAnotherThread extends Thread{
@override
public void run(){
//Bla Bla bla
notify();//Trigger wait() Next Step
}
}
Download source code from here (Open pdf in webview android)
activity_main.xml
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<WebView
android:layout_width="match_parent"
android:background="#ffffff"
android:layout_height="match_parent"
android:id="@+id/webview"></WebView>
</RelativeLayout>
MainActivity.java
package com.pdfwebview;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
WebView webview;
ProgressDialog pDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
listener();
}
private void init() {
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setTitle("PDF");
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
webview.loadUrl("https://drive.google.com/file/d/0B534aayZ5j7Yc3RhcnRlcl9maWxl/view");
}
private void listener() {
webview.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
pDialog.show();
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
pDialog.dismiss();
}
});
}
}
Old question ... nonetheless, just add a checkbox somewhere in the sheet. Checking or unchecking it will refresh the cell formulae.
This code works on ROOTED phones if the app is moved to /system/aps
, and they have the following permissions in the manifest:
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS"/>
Code
private void turnGpsOn (Context context) {
beforeEnable = Settings.Secure.getString (context.getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
String newSet = String.format ("%s,%s",
beforeEnable,
LocationManager.GPS_PROVIDER);
try {
Settings.Secure.putString (context.getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
newSet);
} catch(Exception e) {}
}
private void turnGpsOff (Context context) {
if (null == beforeEnable) {
String str = Settings.Secure.getString (context.getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (null == str) {
str = "";
} else {
String[] list = str.split (",");
str = "";
int j = 0;
for (int i = 0; i < list.length; i++) {
if (!list[i].equals (LocationManager.GPS_PROVIDER)) {
if (j > 0) {
str += ",";
}
str += list[i];
j++;
}
}
beforeEnable = str;
}
}
try {
Settings.Secure.putString (context.getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
beforeEnable);
} catch(Exception e) {}
}
You can do the same thing which i did for dictionary.
Create a list and empty dictionary:
dictionary_items = {}
fields = [['Name', 'Himanshu Kanojiya'], ['email id', '[email protected]']]
l = fields[0][0]
m = fields[0][1]
n = fields[1][0]
q = fields[1][1]
dictionary_items[l] = m
dictionary_items[n] = q
print dictionary_items
CSS3 offers a way to do it with the @font-face rule.
http://www.w3.org/TR/css3-webfonts/#the-font-face-rule
http://www.css3.info/preview/web-fonts-with-font-face/
Here is a number of different ways which will work in browsers that don't support the @font-face rule.
I think it would be better to actually bind your listBoxes to a datasource, since it looks like you are adding the same elements to each listbox. A simple example would be something like this:
private List<String> _weight = new List<string>() { "kilogram", "pound" };
private List<String> _height = new List<string>() { "foot", "inch", "meter" };
public Window1()
{
InitializeComponent();
}
private void Weight_Click(object sender, RoutedEventArgs e)
{
listBox1.ItemsSource = _weight;
listBox2.ItemsSource = _weight;
}
private void Height_Click(object sender, RoutedEventArgs e)
{
listBox1.ItemsSource = _height;
listBox2.ItemsSource = _height;
}
Building on dotancohen's answer I'm using an alias:
alias sudo="cygstart --action=runas"
Works as a charm:
sudo chown User:Group <file>
And if you have SysInternals installed you can even start a command shell as the system user very easily
sudo psexec -i -s -d cmd
conn = sqlite3.connect('/path/to/your/sqlite_file.db')
c = conn.cursor()
for item in my_list:
c.execute('insert into tablename values (?,?,?)', item)
Depending on what you need, you can use either element.innerText
or element.textContent
. They differ in many ways. innerText
tries to approximate what would happen if you would select what you see (rendered html) and copy it to the clipboard, while textContent
sort of just strips the html tags and gives you what's left.
innerText
is not just used for IE anymore, and it is supported in all major browsers. Of course, unlike textContent
, it has compatability with old IE browsers (since they came up with it).
Complete example (from Gabi's answer):
var element = document.getElementById('txt');
var text = element.innerText || element.textContent; // or element.textContent || element.innerText
element.innerHTML = text;
The CBO builds a decision tree, estimating the costs of each possible execution path available per query. The costs are set by the CPU_cost or I/O_cost parameter set on the instance. And the CBO estimates the costs, as best it can with the existing statistics of the tables and indexes that the query will use. You should not tune your query based on cost alone. Cost allows you to understand WHY the optimizer is doing what it does. Without cost you could figure out why the optimizer chose the plan it did. Lower cost does not mean a faster query. There are cases where this is true and there will be cases where this is wrong. Cost is based on your table stats and if they are wrong the cost is going to be wrong.
When tuning your query, you should take a look at the cardinality and the number of rows of each step. Do they make sense? Is the cardinality the optimizer is assuming correct? Is the rows being return reasonable. If the information present is wrong then its very likely the optimizer doesn't have the proper information it needs to make the right decision. This could be due to stale or missing statistics on the table and index as well as cpu-stats. Its best to have stats updated when tuning a query to get the most out of the optimizer. Knowing your schema is also of great help when tuning. Knowing when the optimizer chose a really bad decision and pointing it in the correct path with a small hint can save a load of time.
You can do a simple return of the .length
here:
function areAnyChecked(formID) {
return !!$('#'+formID+' input[type=checkbox]:checked').length;
}
This look for checkboxes in the given form, sees if any are :checked
and returns true
if they are (since the length would be 0 otherwise). To make it a bit clearer, here's the non boolean converted version:
function howManyAreChecked(formID) {
return $('#'+formID+' input[type=checkbox]:checked').length;
}
This would return a count of how many were checked.
getActivity().getSupportFragmentManager().beginTransaction().replace(GeneralInfo.this.getId(), new GeneralInfo()).commit();
GeneralInfo
it's my Fragment class GeneralInfo.java
I put it as a method in the fragment class:
public void Reload(){
getActivity().getSupportFragmentManager().beginTransaction().replace(LogActivity.this.getId(), new LogActivity()).commit();
}
I use the following alternative to get default/optional params and "kind-of-overloaded" constructors with variable number of params:
private x?: number;
private y?: number;
constructor({x = 10, y}: {x?: number, y?: number}) {
this.x = x;
this.y = y;
}
I know it's not the prettiest code ever, but one gets used to it. No need for the additional Interface and it allows private members, which is not possible when using the Interface.
Thread is a light weight process while, the process is a self contained execution environment.
What is meant by "self contained execution process"? Private set of basic runtime resources.
What is meant by "private set of basic runtime resources"? The space allocated from memory to run the the process.(Simply a memory space.)
You're better off using typed np.arrays, and then pass the data and column names as a dictionary.
import numpy as np
import pandas as pd
# Feature: np arrays are 1: efficient, 2: can be pre-sized
x = np.array(['a', 'b'], dtype=object)
y = np.array([ 1 , 2 ], dtype=np.int32)
df = pd.DataFrame({
'x' : x, # Feature: column name is near data array
'y' : y,
}
)
It's possible that the Windows internal resolver is adding '.local' to the domain name because there's no dots in it. nslookup
wouldn't do that.
To verify this possiblity, install 'Wireshark' (previously aka Ethereal) on your client machine and observe any DNS request packets leaving it when you run the ping
command.
OK, further investigation on my own XP machine at home reveals that for single label names (i.e. "foo", or "foo.") the system doesn't use DNS at all, and instead uses NBNS (NetBios Name Service).
Using a hint found at http://www.chicagotech.net/netforums/viewtopic.php?t=1476, I found that I was able to force DNS lookups for single label domains by putting a single entry reading "." in the "Append these DNS suffixes (in order)" in the "Advanced TCP/IP settings" dialog
CREATE TABLE fractest( c1 TIME(3), c2 DATETIME(3), c3 TIMESTAMP(3) );
INSERT INTO fractest VALUES
('17:51:04.777', '2018-09-08 17:51:04.777', '2018-09-08 17:51:04.777');
The .encode
method gets applied to a Unicode string to make a byte-string; but you're calling it on a byte-string instead... the wrong way 'round! Look at the codecs
module in the standard library and codecs.open
in particular for better general solutions for reading UTF-8 encoded text files. However, for the csv
module in particular, you need to pass in utf-8 data, and that's what you're already getting, so your code can be much simpler:
import csv
def unicode_csv_reader(utf8_data, dialect=csv.excel, **kwargs):
csv_reader = csv.reader(utf8_data, dialect=dialect, **kwargs)
for row in csv_reader:
yield [unicode(cell, 'utf-8') for cell in row]
filename = 'da.csv'
reader = unicode_csv_reader(open(filename))
for field1, field2, field3 in reader:
print field1, field2, field3
PS: if it turns out that your input data is NOT in utf-8, but e.g. in ISO-8859-1, then you do need a "transcoding" (if you're keen on using utf-8 at the csv
module level), of the form line.decode('whateverweirdcodec').encode('utf-8')
-- but probably you can just use the name of your existing encoding in the yield
line in my code above, instead of 'utf-8'
, as csv
is actually going to be just fine with ISO-8859-* encoded bytestrings.
If you're trying to do something like splitting command line arguments in a .NET Console app, you're going to have issues because .NET is either broken or is trying to be clever (which means it's as good as broken). I needed to be able to split arguments by the space character, preserving any literals that were quoted so they didn't get split in the middle. This is the code I wrote to do the job:
private static List<String> Tokenise(string value, char seperator)
{
List<string> result = new List<string>();
value = value.Replace(" ", " ").Replace(" ", " ").Trim();
StringBuilder sb = new StringBuilder();
bool insideQuote = false;
foreach(char c in value.ToCharArray())
{
if(c == '"')
{
insideQuote = !insideQuote;
}
if((c == seperator) && !insideQuote)
{
if (sb.ToString().Trim().Length > 0)
{
result.Add(sb.ToString().Trim());
sb.Clear();
}
}
else
{
sb.Append(c);
}
}
if (sb.ToString().Trim().Length > 0)
{
result.Add(sb.ToString().Trim());
}
return result;
}
A submodule is its own repo/work-area, with its own .git
directory.
So, first commit/push
your submodule's changes:
$ cd path/to/submodule
$ git add <stuff>
$ git commit -m "comment"
$ git push
Then, update your main project to track the updated version of the submodule:
$ cd /main/project
$ git add path/to/submodule
$ git commit -m "updated my submodule"
$ git push
Sometimes you want to delete a file whatever the case(whatever the exception occurs ,please do delete the file). For such situations.
public static void DeleteFile(string path)
{
if (!File.Exists(path))
{
return;
}
bool isDeleted = false;
while (!isDeleted)
{
try
{
File.Delete(path);
isDeleted = true;
}
catch (Exception e)
{
}
Thread.Sleep(50);
}
}
Note:An exception is not thrown if the specified file does not exist.
int rgb = ((r&0x0ff)<<16)|((g&0x0ff)<<8)|(b&0x0ff);
If you know that your r, g, and b values are never > 255 or < 0 you don't need the &0x0ff
Additionaly
int red = (rgb>>16)&0x0ff;
int green=(rgb>>8) &0x0ff;
int blue= (rgb) &0x0ff;
No need for multipling.
Is it possible to set a number to NaN or infinity?
Yes, in fact there are several ways. A few work without any imports, while others require import
, however for this answer I'll limit the libraries in the overview to standard-library and NumPy (which isn't standard-library but a very common third-party library).
The following table summarizes the ways how one can create a not-a-number or a positive or negative infinity float
:
+-------------------------------------------------------------------+
¦ result ¦ NaN ¦ Infinity ¦ -Infinity ¦
¦ module ¦ ¦ ¦ ¦
¦----------+--------------+--------------------+--------------------¦
¦ built-in ¦ float("nan") ¦ float("inf") ¦ -float("inf") ¦
¦ ¦ ¦ float("infinity") ¦ -float("infinity") ¦
¦ ¦ ¦ float("+inf") ¦ float("-inf") ¦
¦ ¦ ¦ float("+infinity") ¦ float("-infinity") ¦
+----------+--------------+--------------------+--------------------¦
¦ math ¦ math.nan ¦ math.inf ¦ -math.inf ¦
+----------+--------------+--------------------+--------------------¦
¦ cmath ¦ cmath.nan ¦ cmath.inf ¦ -cmath.inf ¦
+----------+--------------+--------------------+--------------------¦
¦ numpy ¦ numpy.nan ¦ numpy.PINF ¦ numpy.NINF ¦
¦ ¦ numpy.NaN ¦ numpy.inf ¦ -numpy.inf ¦
¦ ¦ numpy.NAN ¦ numpy.infty ¦ -numpy.infty ¦
¦ ¦ ¦ numpy.Inf ¦ -numpy.Inf ¦
¦ ¦ ¦ numpy.Infinity ¦ -numpy.Infinity ¦
+-------------------------------------------------------------------+
A couple remarks to the table:
float
constructor is actually case-insensitive, so you can also use float("NaN")
or float("InFiNiTy")
. cmath
and numpy
constants return plain Python float
objects.numpy.NINF
is actually the only constant I know of that doesn't require the -
.It is possible to create complex NaN and Infinity with complex
and cmath
:
+------------------------------------------------------------------------------------------+
¦ result ¦ NaN+0j ¦ 0+NaNj ¦ Inf+0j ¦ 0+Infj ¦
¦ module ¦ ¦ ¦ ¦ ¦
¦----------+----------------+-----------------+---------------------+----------------------¦
¦ built-in ¦ complex("nan") ¦ complex("nanj") ¦ complex("inf") ¦ complex("infj") ¦
¦ ¦ ¦ ¦ complex("infinity") ¦ complex("infinityj") ¦
+----------+----------------+-----------------+---------------------+----------------------¦
¦ cmath ¦ cmath.nan ¹ ¦ cmath.nanj ¦ cmath.inf ¹ ¦ cmath.infj ¦
+------------------------------------------------------------------------------------------+
The options with ¹ return a plain float
, not a complex
.
is there any function to check whether a number is infinity or not?
Yes there is - in fact there are several functions for NaN, Infinity, and neither Nan nor Inf. However these predefined functions are not built-in, they always require an import
:
+--------------------------------------------------------------+
¦ for ¦ NaN ¦ Infinity or ¦ not NaN and ¦
¦ ¦ ¦ -Infinity ¦ not Infinity and ¦
¦ module ¦ ¦ ¦ not -Infinity ¦
¦----------+-------------+----------------+--------------------¦
¦ math ¦ math.isnan ¦ math.isinf ¦ math.isfinite ¦
+----------+-------------+----------------+--------------------¦
¦ cmath ¦ cmath.isnan ¦ cmath.isinf ¦ cmath.isfinite ¦
+----------+-------------+----------------+--------------------¦
¦ numpy ¦ numpy.isnan ¦ numpy.isinf ¦ numpy.isfinite ¦
+--------------------------------------------------------------+
Again a couple of remarks:
cmath
and numpy
functions also work for complex objects, they will check if either real or imaginary part is NaN or Infinity.numpy
functions also work for numpy
arrays and everything that can be converted to one (like lists, tuple, etc.)numpy.isposinf
and numpy.isneginf
.NaN
: pandas.isna
and pandas.isnull
(but not only NaN, it matches also None
and NaT
)Even though there are no built-in functions, it would be easy to create them yourself (I neglected type checking and documentation here):
def isnan(value):
return value != value # NaN is not equal to anything, not even itself
infinity = float("infinity")
def isinf(value):
return abs(value) == infinity
def isfinite(value):
return not (isnan(value) or isinf(value))
To summarize the expected results for these functions (assuming the input is a float):
+----------------------------------------------------------------------+
¦ input ¦ NaN ¦ Infinity ¦ -Infinity ¦ something else ¦
¦ function ¦ ¦ ¦ ¦ ¦
¦----------------+-------+------------+-------------+------------------¦
¦ isnan ¦ True ¦ False ¦ False ¦ False ¦
+----------------+-------+------------+-------------+------------------¦
¦ isinf ¦ False ¦ True ¦ True ¦ False ¦
+----------------+-------+------------+-------------+------------------¦
¦ isfinite ¦ False ¦ False ¦ False ¦ True ¦
+----------------------------------------------------------------------+
Is it possible to set an element of an array to NaN in Python?
In a list it's no problem, you can always include NaN (or Infinity) there:
>>> [math.nan, math.inf, -math.inf, 1] # python list
[nan, inf, -inf, 1]
However if you want to include it in an array
(for example array.array
or numpy.array
) then the type of the array must be float
or complex
because otherwise it will try to downcast it to the arrays type!
>>> import numpy as np
>>> float_numpy_array = np.array([0., 0., 0.], dtype=float)
>>> float_numpy_array[0] = float("nan")
>>> float_numpy_array
array([nan, 0., 0.])
>>> import array
>>> float_array = array.array('d', [0, 0, 0])
>>> float_array[0] = float("nan")
>>> float_array
array('d', [nan, 0.0, 0.0])
>>> integer_numpy_array = np.array([0, 0, 0], dtype=int)
>>> integer_numpy_array[0] = float("nan")
ValueError: cannot convert float NaN to integer
my_var = (int)my_var;
As simple as that. Basically you don't need it if the variable is int.
If you include Guava, then you can use:
String fileContent = Files.asCharSource(new File(filename), Charset.forName("UTF-8")).read();
(Other solutions mentioned other method for Guava but they are deprecated)
My JSON file name: terrifcalculatordata.json
[
{
"id": 1,
"name": "Vigo",
"picture": "./static/images/vigo.png",
"charges": "PKR 100 per excess km"
},
{
"id": 2,
"name": "Mercedes",
"picture": "./static/images/Marcedes.jpg",
"charges": "PKR 200 per excess km"
},
{
"id": 3,
"name": "Lexus",
"picture": "./static/images/Lexus.jpg",
"charges": "PKR 150 per excess km"
}
]
First , import on top:
import calculatorData from "../static/data/terrifcalculatordata.json";
then after return:
<div>
{
calculatorData.map((calculatedata, index) => {
return (
<div key={index}>
<img
src={calculatedata.picture}
class="d-block"
height="170"
/>
<p>
{calculatedata.charges}
</p>
</div>
try this
HTML:
<div class="icon-2x-circle"><i class="fa fa-check fa-2x"></i></div>
CSS:
i {
width: 30px;
height: 30px;
}
.icon-2x-circle {
text-align: center;
padding: 3px;
display: inline-block;
-moz-border-radius: 100px;
-webkit-border-radius: 100px;
border-radius: 100px;
-moz-box-shadow: 0px 0px 2px #888;
-webkit-box-shadow: 0px 0px 2px #888;
box-shadow: 0px 0px 2px #888;
}
r = R * sqrt(random())
theta = random() * 2 * PI
(Assuming random()
gives a value between 0 and 1 uniformly)
If you want to convert this to Cartesian coordinates, you can do
x = centerX + r * cos(theta)
y = centerY + r * sin(theta)
sqrt(random())
?Let's look at the math that leads up to sqrt(random())
. Assume for simplicity that we're working with the unit circle, i.e. R = 1.
The average distance between points should be the same regardless of how far from the center we look. This means for example, that looking on the perimeter of a circle with circumference 2 we should find twice as many points as the number of points on the perimeter of a circle with circumference 1.
Since the circumference of a circle (2πr) grows linearly with r, it follows that the number of random points should grow linearly with r. In other words, the desired probability density function (PDF) grows linearly. Since a PDF should have an area equal to 1 and the maximum radius is 1, we have
So we know how the desired density of our random values should look like. Now: How do we generate such a random value when all we have is a uniform random value between 0 and 1?
We use a trick called inverse transform sampling
Sounds complicated? Let me insert a blockquote with a little side track that conveys the intuition:
Suppose we want to generate a random point with the following distribution:
That is
- 1/5 of the points uniformly between 1 and 2, and
- 4/5 of the points uniformly between 2 and 3.
The CDF is, as the name suggests, the cumulative version of the PDF. Intuitively: While PDF(x) describes the number of random values at x, CDF(x) describes the number of random values less than x.
In this case the CDF would look like:
To see how this is useful, imagine that we shoot bullets from left to right at uniformly distributed heights. As the bullets hit the line, they drop down to the ground:
See how the density of the bullets on the ground correspond to our desired distribution! We're almost there!
The problem is that for this function, the y axis is the output and the x axis is the input. We can only "shoot bullets from the ground straight up"! We need the inverse function!
This is why we mirror the whole thing; x becomes y and y becomes x:
We call this CDF-1. To get values according to the desired distribution, we use CDF-1(random()).
…so, back to generating random radius values where our PDF equals 2x.
Step 1: Create the CDF:
Since we're working with reals, the CDF is expressed as the integral of the PDF.
CDF(x) = ? 2x = x2
Step 2: Mirror the CDF along y = x:
Mathematically this boils down to swapping x and y and solving for y:
CDF: y = x2
Swap: x = y2
Solve: y = √x
CDF-1: y = √x
Step 3: Apply the resulting function to a uniform value between 0 and 1
CDF-1(random()) = √random()
Which is what we set out to derive :-)
You are mixing the 2 different CASE
syntaxes inappropriately.
Use this style (Searched)
CASE
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Or this style (Simple)
CASE u.nnmu
WHEN '0' THEN mu.naziv_mesta
WHEN '1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Not This (Simple but with boolean search predicates)
CASE u.nnmu
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
In MySQL this will end up testing whether u.nnmu
is equal to the value of the boolean expression u.nnmu ='0'
itself. Regardless of whether u.nnmu
is 1
or 0
the result of the case expression itself will be 1
For example if nmu = '0'
then (nnmu ='0'
) evaluates as true
(1) and (nnmu ='1'
) evaluates as false
(0). Substituting these into the case expression gives
SELECT CASE '0'
WHEN 1 THEN '0'
WHEN 0 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
if nmu = '1'
then (nnmu ='0'
) evaluates as false
(0) and (nnmu ='1'
) evaluates as true
(1). Substituting these into the case expression gives
SELECT CASE '1'
WHEN 0 THEN '0'
WHEN 1 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
For MS IE 10 you'll probably find you need to do the following:
-ms-overflow-style: none
See the following:
https://msdn.microsoft.com/en-us/library/hh771902(v=vs.85).aspx
As the other answers note, you can add a background-color
to a <span>
around your text to get this to work.
In the case where you have line-height
though, you will see gaps. To fix this you can add a box-shadow
with a little bit of grow to your span. You will also want box-decoration-break: clone;
for FireFox to render it properly.
EDIT: If you're getting issues in IE11 with the box-shadow, try adding an outline: 1px solid [color];
as well for IE only.
Here's what it looks like in action:
.container {_x000D_
margin: 0 auto;_x000D_
width: 400px;_x000D_
padding: 10px;_x000D_
border: 1px solid black;_x000D_
}_x000D_
_x000D_
h2 {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
font-family: Verdana, sans-serif;_x000D_
text-transform: uppercase;_x000D_
line-height: 1.5;_x000D_
text-align: center;_x000D_
font-size: 40px;_x000D_
}_x000D_
_x000D_
h2 > span {_x000D_
background-color: #D32;_x000D_
color: #FFF;_x000D_
box-shadow: -10px 0px 0 7px #D32,_x000D_
10px 0px 0 7px #D32,_x000D_
0 0 0 7px #D32;_x000D_
box-decoration-break: clone;_x000D_
}
_x000D_
<div class="container">_x000D_
<h2><span>A HEADLINE WITH BACKGROUND-COLOR PLUS BOX-SHADOW :3</span></h2>_x000D_
</div>
_x000D_
Like the other answers say, you can't remove an item from a collection you're iterating over. You can get around this by explicitly using an Iterator
and removing the item there.
Iterator<Item> iter = list.iterator();
while(iter.hasNext()) {
Item blah = iter.next();
if(...) {
iter.remove(); // Removes the 'current' item
}
}
If you want to do this in code you can do
View.bringToFront();
see docs
vec1[i] = vec2[i]
will set the value of vec1[i]
to the value of vec2[i]
. Nothing is inserted. Your second approach is almost correct. Instead of +i+1
you need just +i
v1.insert(v1.begin()+i, v2[i])
as in javascript:
mydata.match(/'([^']+)'/)[1]
the actual regexp is: /'([^']+)'/
if you use the non greedy modifier (as per another post) it's like this:
mydata.match(/'(.*?)'/)[1]
it is cleaner.
You can now use the npm package sequelize-auto-migrations to automatically generate a migrations file. https://www.npmjs.com/package/sequelize-auto-migrations
Using sequelize-cli, initialize your project with
sequelize init
Create your models and put them in your models folder.
Install sequelize-auto-migrations:
npm install sequelize-auto-migrations
Create an initial migration file with
node ./node_modules/sequelize-auto-migrations/bin/makemigration --name <initial_migration_name>
Run your migration:
node ./node_modules/sequelize-auto-migrations/bin/runmigration
You can also automatically generate your models from an existing database, but that is beyond the scope of the question.
ES6/ES2015 version:
import customData from './customData.json';
They changed the packaging for psycopg2. Installing the binary version fixed this issue for me. The above answers still hold up if you want to compile the binary yourself.
See http://initd.org/psycopg/docs/news.html#what-s-new-in-psycopg-2-8.
Binary packages no longer installed by default. The ‘psycopg2-binary’ package must be used explicitly.
And http://initd.org/psycopg/docs/install.html#binary-install-from-pypi
So if you don't need to compile your own binary, use:
pip install psycopg2-binary
HttpWebRequest request =(HttpWebRequest)WebRequest.Create("some url");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 7.1; Trident/5.0)";
request.Accept = "/";
request.UseDefaultCredentials = true;
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
doc.Save(request.GetRequestStream());
HttpWebResponse resp = request.GetResponse() as HttpWebResponse;
Hope it helps
If your command is available in cmd.exe (something like python ./script.py
, but not PowerShell command like ii .
(this means to open the current directory by Windows Explorer)), you can run cmd.exe within PowerShell. The syntax is like this:
cmd /c "command1 && command2"
Here, &&
is provided by cmd syntax described in this question.
You can insert new rows with modified values and then delete old rows. Following example change ID to be same as foreign key PersonId
SET IDENTITY_INSERT [PersonApiLogin] ON
INSERT INTO [PersonApiLogin](
[Id]
,[PersonId]
,[ApiId]
,[Hash]
,[Password]
,[SoftwareKey]
,[LoggedIn]
,[LastAccess])
SELECT [PersonId]
,[PersonId]
,[ApiId]
,[Hash]
,[Password]
,[SoftwareKey]
,[LoggedIn]
,[LastAccess]
FROM [db304].[dbo].[PersonApiLogin]
GO
DELETE FROM [PersonApiLogin]
WHERE [PersonId] <> ID
GO
SET IDENTITY_INSERT [PersonApiLogin] OFF
GO
In case you recently updated to Xcode 11 beta 3 and try to run an older SwiftUI project, you have to make some changes in the SceneDelegate where the views are loaded, otherwise the screens will remain black on devices running iOS 13 beta 3 which of course includes all simulators.
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Use a UIHostingController as window root view controller
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: ContentView())
self.window = window
window.makeKeyAndVisible()
}
}
The behavior not strictly limited to the simulators, but since most people will run beta software exclusively on simulators it will only occur in this context. It baffled me for quite a while, so hope it helps.
like say a class .c1 has height:40px; how do I get rid of this height property?
Sadly, you can't. CSS doesn't have a "default" placeholder.
In that case, you would reset the property using
height: auto;
as @Ben correctly points out, in some cases, inherit
is the correct way to go, for example when resetting the text colour of an a
element (that property is inherited from the parent element):
a { color: inherit }
I know this may be obvious for most people who use RegEx frequently, but in case any readers are new to RegEx, I thought I should point out an observation I made that was helpful for one of my projects.
In a previous answer from @kennytm:
^\d{5}(?:[-\s]\d{4})?$
…? = The pattern before it is optional (for condition 1)
If you want to allow both standard 5 digit and +4 zip codes, this is a great example.
To match only zip codes in the US 'Zip + 4' format as I needed to do (conditions 2 and 3 only), simply remove the last ?
so it will always match the last 5 character group.
A useful tool I recommend for tinkering with RegEx is linked below:
I use this tool frequently when I find RegEx that does something similar to what I need, but could be tailored a bit better. It also has a nifty RegEx reference menu and informative interface that keeps you aware of how your changes impact the matches for the sample text you entered.
If I got anything wrong or missed an important piece of information, please correct me.
I generally just put a log4j.xml file into src/test/resources and let log4j find it by itself: no code required, the default log4j initialisation will pick it up. (I typically want to set my own loggers to 'DEBUG' anyway)
You may find Noah Gift's presentation Creating Agile Commandline Tools With Python. In it he combines subprocess, Queue and threading to develop solution that is capable of pinging hosts concurrently and speeding up the process. Below is a basic version before he adds command line parsing and some other features. The code to this version and others can be found here
#!/usr/bin/env python2.5
from threading import Thread
import subprocess
from Queue import Queue
num_threads = 4
queue = Queue()
ips = ["10.0.1.1", "10.0.1.3", "10.0.1.11", "10.0.1.51"]
#wraps system ping command
def pinger(i, q):
"""Pings subnet"""
while True:
ip = q.get()
print "Thread %s: Pinging %s" % (i, ip)
ret = subprocess.call("ping -c 1 %s" % ip,
shell=True,
stdout=open('/dev/null', 'w'),
stderr=subprocess.STDOUT)
if ret == 0:
print "%s: is alive" % ip
else:
print "%s: did not respond" % ip
q.task_done()
#Spawn thread pool
for i in range(num_threads):
worker = Thread(target=pinger, args=(i, queue))
worker.setDaemon(True)
worker.start()
#Place work in queue
for ip in ips:
queue.put(ip)
#Wait until worker threads are done to exit
queue.join()
He is also author of: Python for Unix and Linux System Administration
http://ecx.images-amazon.com/images/I/515qmR%2B4sjL._SL500_AA240_.jpg