What's the best way to get the current date/time in Java?
Answer
It depends on what form of date / time you want:
If you want the date / time as a single numeric value, then System.currentTimeMillis() gives you that, expressed as the number of milliseconds after the UNIX epoch (as a Java long). This value is a delta from a UTC time-point, and is independent of the local time-zone ... assuming that the system clock has been set correctly.
If you want the date / time in a form that allows you to access the components (year, month, etc) numerically, you could use one of the following:
new Date() gives you a Date object initialized with the current date / time. The problem is that the Date API methods are mostly flawed ... and deprecated.
Calendar.getInstance() gives you a Calendar object initialized with the current date / time, using the default Locale and TimeZone. Other overloads allow you to use a specific Locale and/or TimeZone. Calendar works ... but the APIs are still cumbersome.
new org.joda.time.DateTime() gives you a Joda-time object initialized with the current date / time, using the default time zone and chronology. There are lots of other Joda alternatives ... too many to describe here. (But note that some people report that Joda time has performance issues.; e.g. Jodatime's LocalDateTime is slow when used the first time.)
in Java 8, calling LocalDateTime.now() and ZonedDateTime.now() will give you representations1 for the current date / time.
Prior to Java 8, most people who know about these things recommended Joda-time as having (by far) the best Java APIs for doing things involving time point and duration calculations. With Java 8, this is no longer true. However, if you are already using Joda time in your codebase, there is no strong2 reason to migrate.
1 - Note that LocalDateTime doesn't include a time zone. As the javadoc says: "It cannot represent an instant on the time-line without additional information such as an offset or time-zone."
2 - Your code won't break if you don't, and you won't get deprecation warnings. Sure, the Joda codebase will probably stop getting updates, but it is unlikely to need them. No updates means stability and that is a good thing. Also note that it is highly likely that if that someone will fix problems caused by regressions in the Java platform.
Katie Holmes played Rachel Dawes in Batman Begins but Maggie Gyllenhall played the character in The Dark Knight.
Was there any particular reason why Katie Holmes didn't continue on in the role?
Answer
According to Julie Polkes, a spokeswoman for Ms. Holmes,
"Katie was offered but was unable to accept the role because of
scheduling conflicts. She was in the process of negotiating for another project. In addition, when she returns to work, she would like to tackle a new character."
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' DStormr', 'ddo.png', 'Online:' at line 1`
The sql is the following:
"UPDATE articulo SET '".$nombre."', '".$imagen."', '".$text."', '".$precio."', '".$popup."', ".$genero_id. " WHERE id=".$id"";
What am I missing/not seeing?
Answer
When you do an UPDATE you need to SET key = 'value'.
It is a good idea to cast the void pointer returned by malloc to the type of the destination pointer. In this case you can find an error similar to the error in your code snippet.
Here variable ptr has type char ** while the right side of the assignment statement has type char * due to the casting. So the compiler shall issue an error (more precisely a diagnostic message) because there is no implicit conversion from char *. to char **
By the way by this reason in C++ there is not allowed to assign a pointer of type void * to pointers of other types because such a code is unsafe.
The other reason to cast the void pointer returned by malloc is to make your code self-documented. Consider for example the following statement
p = malloc( sizeof( *p ) );
Here it is difficult to understand what is the type of memory is allocated. It would be much better to write for example
p = ( double * )malloc( sizeof( *p ) );
In this case the statement is more clear and you need not to scroll a big program listing that to determine what is the type of p.
Take into account that a good program is a program where each statement provides you as much information as you need that to understand what the statement is trying to do and what types of variables envolved in expressions..
There is one more reason to cast the pointer returned by malloc. If you will try to compile your code with a C++ compiler then it will issue numerous errors for each using of malloc without casting. When you will transfer your code from C to C++ you will estimate the value of such casting.
Here is the correct using of malloc for your example
I've read the documentation, but I still can't get when I should use one or the other:
According to documentation OffsetDateTime should be used when writing date to database, but I don't get why.
Answer
Q: What's the difference between java 8 ZonedDateTime and OffsetDateTime?
The javadocs say this:
"OffsetDateTime, ZonedDateTime and Instant all store an instant on the time-line to nanosecond precision. Instant is the simplest, simply representing the instant. OffsetDateTime adds to the instant the offset from UTC/Greenwich, which allows the local date-time to be obtained. ZonedDateTime adds full time-zone rules."
Thus the difference between OffsetDateTime and ZonedDateTime is that the latter includes the rules that cover daylight saving time adjustments and various other anomalies.
Q: According to documentation OffsetDateTime should be used when writing date to database, but I don't get why.
Dates with local time offsets always represent the same instants in time, and therefore have a stable ordering. By contrast, the meaning of dates with full timezone information is unstable in the face of adjustments to the rules for the respective timezones. (And these do happen; e.g. for date-time values in the future.) So if you store and then retrieve a ZonedDateTime the implementation has a problem:
It can store the computed offset ... and the retrieved object may then have an offset that is inconsistent with the current rules for the zone-id.
It can discard the computed offset ... and the retrieved object then represents a different point in the absolute / universal timeline than the one that was stored.
If you use Java object serialization, the Java 9 implementation takes the first approach. This is arguably the "more correct" way to handle this, but this doesn't appear to be documented. (JDBC drivers and ORM bindings are presumably making similar decisions, and are hopefully getting it right.)
But if you are writing an application that manually stores date/time values, or that rely on java.sql.DateTime, then dealing with the complications of a zone-id is ... probably something to be avoided. Hence the advice.
Note that dates whose meaning / ordering is unstable over time may be problematic for an application. And since changes to zone rules are an edge case, the problems are liable to emerge at unexpected times.
A (possible) second reason for the advice is that the construction of a ZonedDateTime is ambiguous at the certain points. For example in the period in time when you are "putting the clocks back", combining a local time and a zone-id can give you two different offsets. The ZonedDateTime will consistently pick one over the other ... but this isn't always the correct choice.
Now, this could be a problem for any applications that construct ZonedDateTime values that way. But from the perspective of someone building an enterprise application is a bigger problem when the (possibly incorrect) ZonedDateTime values are persistent and used later.
Okay... I want to get around the concept of computing negative numbers. I am self-learning and I am running to a lot of difficulty. How do implement negative input?
My code:
public class MainSystem {
public static void main(String[] args) { try (Scanner console = new Scanner(System.in)) { String input;
System.out.println("The console is now closed."); }
}
private static void splitEntry(String input) {
String function = "[+\\-*/]+"; //placing them in an index String[] token = input.split(function);//and this double num1 = Double.parseDouble(token[0]); double num2 = Double.parseDouble(token[1]); //double answer; String operator = input.toCharArray()[token[0].length()] + "";
if (operator.matches(function) && (token[0] + token[1] + operator).length() == input.length()) { System.out.println("Operation is " + operator + ", your first number is " + token[0] + " your second number is " + token[1]); } else { System.out.println("Your entry of " + input + " is invalid"); } if (operator.matches(function) && (token[0] + token[1] + operator).length() == input.length()) { double result = 0; if (operator.equals("+")) { // this is simplified by using formatters
result = num1 + num2; } else if (operator.equals("-")) { result = num1 - num2; } else if (operator.equals("*")) { result = num1 * num2; } else if (operator.equals("/")) { result = num1 / num2; } System.out.printf("Your first number %.2f %s by your second number %.2f = makes for %.2f%n", num1, operator, num2, result);
} } }
How do I allow my calculator to place -2 + 5 and get the answer 3?
Every time I try to do that, the program crashes? What to do to make negative numbers to be computed
I have a very strange problem - sometimes my database fails to populate with Plans and Buckets, then throws the exception shown at the end when trying to save Tasks to the db. Other times the code works perfectly. I would appreciate any insight into why this could be. Could it be a timing issue with the delete commands?
EntitiesModelContainer db = new EntitiesModelContainer();
List ignoredPlans = db.Plans.Where(p => p.Ignore).ToList();
// Delete old data completely // foreign keys will cascade delete some tables such as buckets and tasks db.Database.ExecuteSqlCommand("DELETE FROM Plans"); db.Database.ExecuteSqlCommand("DELETE FROM Assignees");
PlansResponse plans = GraphAPI.GetPlans();
foreach (PlanResponse plan in plans.Plans) { Plan planRecord = new Plan() { Id = plan.ID, Title = plan.Title, Ignore = ignoredPlans.Find(p => p.Id == plan.ID) != null }; db.Plans.Add(planRecord); bool changes = db.ChangeTracker.HasChanges();
int result = db.SaveChanges();
if (!planRecord.Ignore) { BucketsResponse buckets = GraphAPI.GetBuckets(plan); foreach (BucketResponse bucket in buckets.Buckets) { Bucket bucketRecord = new Bucket() { Id = bucket.ID,
Name = bucket.Name, PlanId = bucket.PlanID }; db.Buckets.Add(bucketRecord); db.SaveChanges(); } TasksResponse tasks = GraphAPI.GetTasks(plan); foreach (TaskResponse task in tasks.Tasks) { Task taskRecord = new Task()
SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_PlanTask". The conflict occurred in database "Dashboard-dev", table "dbo.Plans", column 'Id'. The statement has been terminated.
The strange thing is, it doesn't always throw! Any help would be appreciated.
Update: You're right - it appears the code is running twice, concurrently. Why? I didn't (intentionally) mean to do this...
public class DBController : Controller { public ActionResult Index() { DBAccess.UpdateData();
return View(); } }
The snippet posted above is the start of this method UpdateData().
Answer
Since it's complaining about the foreign key PlanId (I'm guessing), I'd say GetTasks somehow returns an incorrect PlanId.
To get to the bottom of it I'd set up a profiler session and examine the SQL statements when there's an error. Or just examine the objects in the debugger when the exception happens, I guess. The values of the properties should give a clue as to what's going on.
Edit: I just noticed your first line says 'sometimes it fails to populate with plans and tasks', missed that. I don't understand how it would continue if it couldn't save a plan, but a SQL profiler session might be able to answer that.
Edit after the fact: of course the simplest answer could be concurrency, especially if this is a web application, two requests could be coming in at the same time and overlapping.
I have a question about the primitive type short in Java. I am using JDK 1.6.
If I have the following:
short a = 2;
short b = 3; short c = a + b;
the compiler does not want to compile - it says that it "cannot convert from int to short" and suggests that I make a cast to short, so this:
short c = (short) (a + b);
really works. But my question is why do I need to cast? The values of a and b are in the range of short - the range of short values is {-32,768, 32767}.
I also need to cast when I want to perform the operations -, *, / (I haven't checked for others).
If I do the same for primitive type int, I do not need to cast aa+bb to int. The following works fine:
int aa = 2; int bb = 3; int cc = aa +bb;
I discovered this while designing a class where I needed to add two variables of type short, and the compiler wanted me to make a cast. If I do this with two variables of type int, I don't need to cast.
A small remark: the same thing also happens with the primitive type byte. So, this works:
byte a = 2; byte b = 3; byte c = (byte) (a + b);
but this not:
byte a = 2; byte b = 3; byte c = a + b;
For long, float, double, and int, there is no need to cast. Only for short and byte values.
I'm generating these images as byte arrays, and they are usually larger than the common icon they use in the examples, at 640x480.
Is there any (performance or other) problem in using the ImageIcon class to display an image that size in a JPanel?
What's the usual way of doing it?
How to add an image to a JPanel without using the ImageIcon class?
Edit: A more careful examination of the tutorials and the API shows that you cannot add an ImageIcon directly to a JPanel. Instead, they achieve the same effect by setting the image as an icon of a JLabel. This just doesn't feel right...
Answer
Here's how I do it (with a little more info on how to load an image):
public ImagePanel() { try { image = ImageIO.read(new File("image name and path")); } catch (IOException ex) { // handle exception... } }
@Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(image, 0, 0, this); // see javadoc for more info on the parameters }
I have a class. I need to do some http work inside of a timeout. The problem I am faceing is the http variable inside the timeout keeps saying it is undefined.
this.http.post( ...//http variable is defined here setTimeout(function(){ this.http.post(... //http is not defined here }
} }
Answer
The reason for this is that the callback function inside setTimeout is in a different lexical environment. This is why in ES6+ functions can be defined using =>. This is so that the code within a function shares the same scope as the function.
To fix this, you can either use ES6+ syntax, where instead of function(a,b,args) {...} you would use (a,b,args) => {...}:
I dont know much jquery therefore i tried the slider from JQUERY original website , i am able to retrieve results from DATABASE but i don't know the way t keep the slider value the same , is there a way to get the slider value from the url like same_page.php/to?=500 i want the "500" .
PLEASE DONT TELL ME I USE OBSOLETE MYSQL which will be removed from PHP 7
Answer
$("#slider1").slider({
min: 0, //minimum value max: 1100, //maximum value animate: true, value: 50, // <<<< THAT LINE!! slide: function(event, ui) { $("#value1").val(ui.value); } });
Maybe you could echo out the value you've stored there by using PHP? Or maybe store the current value in a cookie and read it out inside the slider's initiation...
Answer:
var a = window.location.href ; var matches = a.match(/\d+$/); console.log(matches);
I'm trying to build some code on Ubuntu 10.04 LTS that uses OpenSSL 1.0.0. When I run make, it invokes g++ with the "-lssl" option. The source includes:
#include
#include #include #include #include #include
I ran:
$ sudo apt-get install openssl
Reading package lists... Done Building dependency tree Reading state information... Done openssl is already the newest version. 0 upgraded, 0 newly installed, 0 to remove and 3 not upgraded.
But I guess the openssl package doesn't include the library. I get these errors on make:
foo.cpp:21:25: error: openssl/bio.h: No such file or directory
foo.cpp:22:28: error: openssl/buffer.h: No such file or directory foo.cpp:23:25: error: openssl/des.h: No such file or directory foo.cpp:24:25: error: openssl/evp.h: No such file or directory foo.cpp:25:25: error: openssl/pem.h: No such file or directory foo.cpp:26:25: error: openssl/rsa.h: No such file or directory
How do I install the OpenSSL C++ library on Ubuntu 10.04 LTS?
I did a man g++ and (under "Options for Linking") for the -l option it states: " The linker searches a standard list of directories for the library..." and "The directories searched include several standard system directories..." What are those standard system directories?
Answer
You want to install the development package, which is libssl-dev:
I have been working on a strange PHP problem the last few days where the feof() function is returning true before the end of a file. Below is a skeleton of my code:
if($dataString === false && !feof($this->fh)) { echo "Error reading file besides EOF"; } elseif($dataString === false && feof($this->fh)) { echo "We are at the end of the file.\n";
//check status of the stream $meta = stream_get_meta_data($this->fh); var_dump($meta); } else { //else all is good, process line read in } }
Through lots of testing I have found that the program works fine on everything except one file:
The file is stored on the local drive.
This file is around 8 million lines long averaging somewhere around 200-500 characters per line.
It has already been cleaned and under close examination with a hex editor, no abnormal characters have been found.
The program consistently fails on line 7172714 when it believes it has reached the end of the file (even though it has ~800K lines left).
I have tested the program on files that had fewer characters per line but were between 20-30 million lines with no problems.
I tried running the code from a comment on http://php.net/manual/en/function.fgets.php just to see if it was something in my code that was causing the issue and the 3rd party code failed on the same line. EDIT: also worth mentioning is that the 3rd party code used fread() instead of fgets().
I tried specifying several buffer sizes in the fgets function and none of them made any difference.
The output from the var_dump($meta) is as follows:
In attempting to find out what is causing feof to return true before the end of the file I have to guess that either:
A) Something is causing the fopen stream to fail and then nothing is able to be read in (causing feof to return true)
B) There is some buffer somewhere that is filling up and causing havoc
C) The PHP gods are angry
I have searched far and wide to see if anyone else was having this issue and cannot find any instances except in C++ where the file was being read in via text mode instead of binary mode and was causing the issue.
UPDATE: I had my script constantly output the number of times the read function had iterated and the unique ID of the user associated with the entry it found beside it. The script is still failing after line 7172713 out of 7175502, but the unique ID of the last user in the file is showing up on line 7172713. It seems that the problem is for some reason lines are being skipped and are not read. All line breaks are present.
Answer
fgets() is seemingly randomly reading in some lines that do have content as empty. The script actually makes it to the end of the file even though my test that showed the line numbers being read was behind due to the way I did the error checking (and the way the error checking was written in the 3rd party code). Now the real question is what is causing fgets() and fread() to think that a line is empty even though it is not. I will ask that as a separate question as that is a change in topic. Thank you all for your help!
Also, just so no one is left hanging, the reason the 3rd party code did not work is because it relied on a line at least having a line break where the current problem with fgets and fread returning an empty string does not give the script what it needs to know the line ever existed, thus it continues trying to execute past the end of the file. Below is the slightly modified 3rd party script which I still consider excellent based on it's execution speed.
//File to be opened $file = "/path/to/file.ext"; //Open file (DON'T USE a+ pointer will be wrong!) $fp = fopen($file, 'r'); //Read 16meg chunks $read = 16777216; //\n Marker $part = 0;
while(!feof($fp)) { $rbuf = fread($fp, $read); for($i=$read;$i > 0 || $n == chr(10);$i--) { $n=substr($rbuf, $i, 1); if($n == chr(10))break; //If we are at the end of the file, just grab the rest and stop loop elseif(feof($fp)) { $i = $read; $buf = substr($rbuf, 0, $i+1); echo "\n"; break; } } //This is the buffer we want to do stuff with, maybe thow to a function? $buf = substr($rbuf, 0, $i+1);
//output the chunk we just read and mark where it stopped with echo $buf . "\n\n";
//Point marker back to last \n point $part = ftell($fp)-($read-($i+1)); fseek($fp, $part); } fclose($fp);
?>
UPDATE: After hours more searching, analyzing, hair pulling, etc. it seems that the culprit was an uncaught bad character - in this case a 1/2 character hex value BD. While generating the file that I was reading from the script used stream_get_line() to read the line in from it's original source. It was then supposed to remove all bad characters (it appears that my regex was not up to par) and then use str_getcsv() to convert the content to an array, do some processing, then write to a new file (the one I was trying to read). Somewhere in this process, probably str_getcsv(), the 1/2 character caused the whole thing to just insert a blank line instead of the data. Several thousand of these were placed all throughout the file (wherever the 1/2 symbol appeared). This made the file appear to be the correct length, but for the EOF to be reached too quickly when counting input based on a known number of lines. I want to thank everyone who helped me with this problem and I am very sorry that the real cause had nothing to do with my question. However if it hadn't been for everyone's suggestions and questions I would not have looked in the right places.
Lesson learned from this experience - when EOF is reached too quickly the best place to look is for instances of double line breaks. When writing a script that reads from a formatted file a good practice is to check for these. Below is my original code modified to do just that:
if($dataString == "\n" || $dataString == "\r\n" || $dataString == "") { throw new Exception("Empty line found."); }
if($dataString === false && !feof($this->fh)) { echo "Error reading file besides EOF"; } elseif($dataString === false && feof($this->fh)) { echo "We are at the end of the file.\n";
//check status of the stream $meta = stream_get_meta_data($this->fh); var_dump($meta); } else { //else all is good, process line read in } }
For simplicity, assume all relevant fields are NOT NULL.
You can do:
SELECT table1.this, table2.that, table2.somethingelse FROM table1, table2 WHERE table1.foreignkey = table2.primarykey AND (some other conditions)
Or else:
SELECT table1.this, table2.that, table2.somethingelse FROM table1 INNER JOIN table2 ON table1.foreignkey = table2.primarykey WHERE (some other conditions)
Do these two work on the same way in MySQL?
Answer
INNER JOIN is ANSI syntax which you should use.
It is generally considered more readable, especially when you join lots of tables.
It can also be easily replaced with an OUTER JOIN whenever a need arises.
The WHERE syntax is more relational model oriented.
A result of two tables JOINed is a cartesian product of the tables to which a filter is applied which selects only those rows with joining columns matching.
It's easier to see this with the WHERE syntax.
As for your example, in MySQL (and in SQL generally) these two queries are synonyms.
Also note that MySQL also has a STRAIGHT_JOIN clause.
Using this clause, you can control the JOIN order: which table is scanned in the outer loop and which one is in the inner loop.
You cannot control this in MySQL using WHERE syntax.
This is known as heredoc. It's essentially a way of defining the value of a variable that spans multiple lines, and doesn't require escaping like traditional strings. The "CON" part is merely an identifier that represents the start and end of the value. This can be changed to a more familiar value.
$str = <<Example of string spanning multiple lines using heredoc syntax. EOD;
I see from the trailers for the new Hobbit film that Frodo Baggins is in it.
It has been a while since I read the book but I don't remember Frodo being in it.
Was his addition only for the movie adaptation or was he in the story all along?
Answer
It looks like Frodo is being shoe-horned into The Hobbit to keep audiences happy (general audiences, mind you, not LotR fans who are not pleased with this news).
What’s Frodo doing in The Hobbit? I don’t want to spoil too much, but I can say that Frodo is part of the connecting tissue between The Hobbit and Fellowship of the Ring. In fact, the next shot was an over the shoulder on Elijah Wood hammering a sign up on Bag End’s front gate: “No Admittance Except On Party Business.” You guys should have an idea where that puts this moment in the timeline
Extrapolating from this tidbit, I believe it is safe to say that 'Elderly Bilbo' (Ian Holm has already filmed his scenes in London) will be recounting his tale to Frodo before the party that we see in Fellowship of the Ring. The events of The Hobbit took place 60 years before the Lord of the Rings trilogy (and 28 years before Frodo was born) - so this explanation seems to make the most sense.
In answer to your original question - he was only added for the movie adaptation.
{ public int Id { get; set; } public string Alias { get; set; } public string Email { get; set; } public string Password { get; set; } public bool IsExternal { get; set; }
public UserModel() {
}
public UserModel(User user) { if (user == null) return; Alias = user.Alias; } }
But, I keep getting the error:
When I try to debug it, it doesn't even go into the Html.TextBox method or into my model.
Answer
Without seeing your controller action, my guess would be that your model is null.
In your controller, make sure you are passing an instance of the model to your view. For example:
Under Windows there are no UTF-8 locales, so I can't find an equivalent way to enforce correct printing. For example, with a US locale, the Hangul character doesn't display properly.
There's a related problem with Unicode characters not displaying properly when printing data frames under Windows. The advice there was to set the locale to Chinese/Japanese/Korean. This does not work here.
And the question now: what is the correct way of linking with in existing static library if it does not belong to my project and is compiled with different build system?
In the 11th doctor's 1st series there is a story arc involving cracks appearing across the universe and removing people from history.
However I don't understand, in some examples people are removed from history (the troops from the Byzantium and Rory), however in other places beings appear to be able to enter and exit the cracks at will (Prizoner Zero and the Doctor when checking for debris inside the crack).
Is there any opinion on why the cracks have different effects on different people?
Answer
The general suggestion (at least as far as The Doctor is concerned) is that as a creature of time he is able to control his contact with the effects of the crack. He has to give himself over to it willingly before it consumes him.
In the 11th season, the nature of the crack is said to not be fully understood and will be effected by the "Great Unasked Question" of season 12. It is possible that the Silence and the race that Prisoner Zero is from are involved in this greater issue and can transcend the effects of the crack.
We do see that once inside the crack, the Doctor has some general control as he steps backwards and 'unwinds' through his own history.
But now the Problem is I don have any proper validation for the exact format for example its also accepting text like " @abcd.com.gmail,.. " Is there any javascript validation for this? any idea?
Thanks in advance.
Answer
function CheckEmail(address){ address=address.replace(/(^\s*)|(\s*$)/g, ""); var reg=/([\w._-])+@([\w_-])+(\.([\w_-])+){1,2}/; var matcharr=reg.exec(address); if(matcharr!=null){ if(matcharr[0].length==address.length){ return true; } return false;
} return false; }
eg: var sVal=" t.st@gmail.com.cn "; var sVal2=" t.st@gmail.com.cn.abc "; console.log(CheckEmail("name@server.com")); //outpus true console.log(CheckEmail("@server.com")); //outpus false
From my research, System.currentTimeMillis() is not always accurate, especially on windows. I'm currently carrying out microbenchmarking on a Windows 10 machine. Would switching over to say, a linux VM give me more accurate results when using the method? Thanks.
1) Don't parse XML with regex. It just doesn't work. Use an XML parser.
2) If you do use regex for this, you don't want re.MULTILINE, which controls how ^ and $ work in a multiple-line string. You want re.DOTALL, which controls whether . matches \n or not.
3) You probably also want your pattern to return the shortest possible match, using the non-greedy +? operator.
The following code work as expected using async/await:
try { let feedbacks = await feedbackService.get(this.feedBackOdataModel); this.feedBackJsonModel.setProperty('/Avaliacoes', feedbacks.results);
} catch (error) { dialogService.showErrorDialog("Erro na obtenção das pesquisas de satisfação", error.statusText + '-' + error.statusCode); throw new Error(error); }
The execution is halted until feedbackService gets resolved.
within the server for my shinyApp, I created a dataframe based on the inputs. However, I want to add a new column that utilizes two of the columns of that dataframe.
stock_info()$return <- reactive({ rep(0, length(stock_info()$ref.date)) }) stock_info()$return <- reactive({ for (i in 2:length(stock_info()$ref.date)){ stock_info()$return[i] <- ((stock_info()$price.close[i] - stock_info()$price.close[i - 1]) / stock_info$price.close[i - 1]) } })
I have tried it like this, and it works up until I try to create stock_info()$return, where I keep getting the error that NULL left assignment. Any tips?
I seem to be running into the typical "Asynchronous Problem", with the solution eluding me.
I have a bootstrap form wizard which is just an improvised tabs/slideshow kinda thingy. All my "Steps" are forms each inside respective tabs/slides.
It has a set of next/previous buttons to navigate around the slides. And It provides a function callback on before moving to next slide. Inside which(callback) I am "client-side validating" the form in current slide and if its validated then I am submitting the form using ajax. And once I get the response from server, I am deciding whether to return true (proceed to next slide) or return false (stop the navigation to next slide).
I have looked into ..
Using callbacks but then it wont stop the plugin from proceeding to next slide, which btw is a hard coded success message, so while we are waiting for the ajax response the wizard has already moved to the next slide.
Using async:false but this hangs the browser like crazy(by design), till the request is completed, so sans the hanging this is exactly what I want.
My code is as below.
JS.
jQuery('#progressWizard').bootstrapWizard({ 'nextSelector': '.next', 'previousSelector': '.previous', onNext: function (tab, navigation, index) { if (index == 1) { // Here I am deciding which code to execute based on the current slide/tab (index) if (jQuery("#paymentstep1").data('bValidator').validate()) { var data = new FormData(jQuery('#paymentstep1')[0]); jQuery("#cgloader").fadeIn();
Fired when next button is clicked (return false to disable moving to the next step)
So simply return false from your handler. In the AJAX success callback, call next to advance to the next slide.
var requestCompleted = false; jQuery('#progressWizard').bootstrapWizard({ 'nextSelector': '.next', 'previousSelector': '.previous',
onNext: function (tab, navigation, index) { if (index == 1) { // Here I am deciding which code to execute based on the current slide/tab (index) if (jQuery("#paymentstep1").data('bValidator').validate()) { if(!requestCompleted) { var data = new FormData(jQuery('#paymentstep1')[0]); jQuery("#cgloader").fadeIn(); var success = false; jQuery.ajax({ type: "post", url: "xyz.php",
This is my first post. I have searched extensively for four days through Stackoverflow and other sources for the problem and have yet to find a solution. This one really has me racking my brain.
Using Eclipse NEON, Gradle 3.5, JavaFXPorts 1.3.5, latest Android SDK
Developing on Windows 10 x64
All expected Gradle tasks are not showing for simple, one-class "Hello World" project. (eg. android, androidRelease, androidInstall, etc. tasks all missing).
From command line, I can run gradlew android and I get an error that Android Support Repository cannot be found.
AFAIK android SDK path is set properly and the Android Support Repository is installed.
Note that that "gradlew run" does build and execute the Desktop version of the project properly.
Below are key config files and outputs. I can post anything else as requested.
C:\Users\Kent\workspace\TestJavaFXPorts3>gradlew android Starting a Gradle Daemon (subsequent builds will be faster)
FAILURE: Build failed with an exception.
* What went wrong:
You must install the Android Support Repository. Open the Android SDK Manager and choose the Android Support Repository from the Extras category at the bottom of the list of packages.
* Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
Total time: 7.627 secs
=======
Android SDK directory:
C:\androidSDK>dir Volume in drive C is Acer Volume Serial Number is C492-4415
I have debian 5.0 linux server on an IBM HS22 blade with 2 Xeon E5504 processors. I found out that oprofile could not recognize hardware performance counters on this setup, only timer interrupt is available:
# opcontrol -l Using timer interrupt. # cat /dev/oprofile/cpu_type timer
System information is:
# cat /etc/issue.net Debian GNU/Linux 5.0 # uname -a Linux xxx 2.6.26-2-686-bigmem #1 SMP Mon Jun 21 06:45:17 UTC 2010 i686 GNU/Linux
oprofile was installed from debian repository using apt.
# opcontrol --version opcontrol: oprofile 0.9.3 compiled on Feb 10 2008 12:08:26
What should I do to enable hardware performance counters? Thanks!
$result = mysql_query('SELECT * FROM Users WHERE UserName LIKE $username');
while($row = mysql_fetch_array($result)) {
echo $row['FirstName']; }
The same applies to code like
$result = mysqli_query($mysqli, 'SELECT ...'); // mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given while( $row=mysqli_fetch_array($result) ) { ...
and
$result = $mysqli->query($mysqli, 'SELECT ...'); // Call to a member function fetch_assoc() on a non-object while( $row=$result->fetch_assoc($result) ) { ...
and
$result = $pdo->query('SELECT ...', PDO::FETCH_ASSOC); // Invalid argument supplied for foreach() foreach( $result as $row ) { ...
and
$stmt = $mysqli->prepare('SELECT ...'); // Call to a member function bind_param() on a non-object $stmt->bind_param(...);
and
$stmt = $pdo->prepare('SELECT ...'); // Call to a member function bindParam() on a non-object $stmt->bindParam(...);
Answer
A query may fail for various reasons in which case both the mysql_* and the mysqli extension will return false from their respective query functions/methods. You need to test for that error condition and handle it accordingly.
Check $result before passing it to mysql_fetch_array. You'll find that it's false because the query failed. See the mysql_query documentation for possible return values and suggestions for how to deal with them.
$username = mysql_real_escape_string($_POST['username']); $password = $_POST['password']; $result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '$username'");
$username = mysqli_real_escape_string($mysqli, $_POST['username']); $result = mysqli_query($mysqli, "SELECT * FROM Users WHERE UserName LIKE '$username'");
// mysqli_query returns false if something went wrong with the query if($result === FALSE) { yourErrorHandler(mysqli_error($mysqli)); } else { // as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach foreach( $result as $row ) { ...
oo-style:
$username = $mysqli->escape_string($_POST['username']); $result = $mysqli->query("SELECT * FROM Users WHERE UserName LIKE '$username'");
// as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach foreach( $result as $row ) { ...
using a prepared statement:
$stmt = $mysqli->prepare('SELECT * FROM Users WHERE UserName LIKE ?'); if ( !$stmt ) { yourErrorHandler($mysqli->error); // or $mysqli->error_list
} else if ( !$stmt->bind_param('s', $_POST['username']) ) { yourErrorHandler($stmt->error); // or $stmt->error_list } else if ( !$stmt->execute() ) { yourErrorHandler($stmt->error); // or $stmt->error_list } else { $result = $stmt->get_result(); // as of php 5.4 mysqli_result implements Traversable, so you can use it with foreach
foreach( $result as $row ) { ...
These examples only illustrate what should be done (error handling), not how to do it. Production code shouldn't use or die when outputting HTML, else it will (at the very least) generate invalid HTML. Also, database error messages shouldn't be displayed to non-admin users, as it discloses too much information.
I need a directive that will truncate long text in element and show a popover with full text in case truncation take place.
See http://plnkr.co/edit/90WP5ISQHG7FXRpetucm?p=preview
For text truncation I've used CSS and it works well. But when I'm trying to access element content I see {{str.data}} rather then exact text from the data.
I guess that I need even't that is fired after rendering, but I can't fing any suitable.
So my question how can I run my DOM manipulation after sub view get rendered?
The only solution I've found so far is using timeout, but I think that there is better solution for it.
I'm reviewing someone else's C++ code for our project that uses MPI for high-performance computing (10^5 - 10^6 cores). The code is intended to allow for communications between (potentially) different machines on different architectures. He's written a comment that says something along the lines of:
We'd normally use new and delete, but here I'm using malloc and free. This is necessary because some compilers will pad the data differently when new is used, leading to errors in transferring data between different platforms. This doesn't happen with malloc.
This does not fit with anything I know from standard new vs malloc questions.
malloc & placement new vs. new is a fairly popular question but only talks about new using constructors where malloc doesn't, which isn't relevant to this.
how does malloc understand alignment? says that memory is guaranteed to be properly aligned with either new or malloc which is what I'd previously thought.
My guess is that he's misdiagnosed his own bug some time in the past and deduced that new and malloc give different amounts of padding, which I think probably isn't true. But I can't find the answer with Google or in any previous question.
Help me, StackOverflow, you're my only hope!
Answer
IIRC there's one picky point. malloc is guaranteed to return an address aligned for any standard type. ::operator new(n) is only guaranteed to return an address aligned for any standard type no larger than n, and if T isn't a character type then new T[n] is only required to return an address aligned for T.
But this is only relevant when you're playing implementation-specific tricks like using the bottom few bits of a pointer to store flags, or otherwise relying on the address to have more alignment than it strictly needs.
It doesn't affect padding within the object, which necessarily has exactly the same layout regardless of how you allocated the memory it occupies. So it's hard to see how the difference could result in errors transferring data.
Is there any sign what the author of that comment thinks about objects on the stack or in globals, whether in his opinion they're "padded like malloc" or "padded like new"? That might give clues to where the idea came from.
Maybe he's confused, but maybe the code he's talking about is more than a straight difference between malloc(sizeof(Foo) * n) vs new Foo[n]. Maybe it's more like:
malloc((sizeof(int) + sizeof(char)) * n);
vs.
struct Foo { int a; char b; }
new Foo[n];
That is, maybe he's saying "I use malloc", but means "I manually pack the data into unaligned locations instead of using a struct". Actually malloc is not needed in order to manually pack the struct, but failing to realize that is a lesser degree of confusion. It is necessary to define the data layout sent over the wire. Different implementations will pad the data differently when the struct is used.
I'm trying to setup AngularJS to communicate with a cross-origin resource where the asset host which delivers my template files is on a different domain and therefore the XHR request that angular performs must be cross-domain. I've added the appropriate CORS header to my server for the HTTP request to make this work, but it doesn't seem to work. The problem is that when I inspect the HTTP requests in my browser (chrome) the request sent to the asset file is an OPTIONS request (it should be a GET request).
I'm not sure whether this is a bug in AngularJS or if I need to configure something. From what I understand the XHR wrapper can't make an OPTIONS HTTP request so it looks like the browser is trying to figure out if is "allowed" to download the asset first before it performs the GET request. If this is the case, then do I need to set the CORS header (Access-Control-Allow-Origin: http://asset.host...) with the asset host as well?
Answer
OPTIONS request are by no means an AngularJS bug, this is how Cross-Origin Resource Sharing standard mandates browsers to behave. Please refer to this document: https://developer.mozilla.org/en-US/docs/HTTP_access_control, where in the "Overview" section it says:
The Cross-Origin Resource Sharing standard works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser. Additionally,
for HTTP request methods that can cause side-effects on user data (in particular; for HTTP methods other than GET, or for POST usage with certain MIME types). The specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request header, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method. Servers can also notify clients whether "credentials" (including Cookies and HTTP Authentication data) should be sent with requests.
It is very hard to provide a generic solution that would work for all the WWW servers as setup will vary depending on the server itself and HTTP verbs that you intend to support. I would encourage you to get over this excellent article (http://www.html5rocks.com/en/tutorials/cors/) that has much more details on the exact headers that needs to be sent by a server.
I have found that I can get my cursor to blink by including the following instruction in my .bashrc file:
echo -ne "\x1b[1 q"
But I also want to change the color of the blinking cursor. I know that my terminal supports color because I can set the prompt colors and print text in color, but I just can't change the cursor color. Any suggestions?
I'm adding the following comment, that I'm aware of how to change the color of text that is displayed on the terminal, but that is not the same as changing the color of the the cursor. So my question is not addressed in that other question.
But I did find a workaround in my terminal emulator software, provided below. Thanks for the feedback, especially the part about making the selection of the proper escape codes portable across terminal types.
Answer
I found afterwards that I can change the cursor color, not in bash, but in the terminal emulator program. In my case that program is MobaXTerm. I discovered the following sequence: Settings - Terminal - Cursor. At that point, selecting a cursor color causes the cursor in the bash shell to be displayed in the desired color. So now in the files that I edit using vim in the bash environment in my xterm window I see a blinking green block cursor, which is what I needed.
Attaining that was what my question was about, not about how to display colored text on the screen, which as was pointed out is already answered elsewhere. So my question is not a duplicate. Anyway, it turned out that my xterm emulation software Mobaxterm allowed me to set the cursor color whereas the escape sequence in my .bashrc file allowed me to get it to blink.
I have some jquery checking the choice made in a drop down.
function toggleFields() { if ($("#chosenmove1").val() == 4) $("#hideme").show(); else
$("#hideme").hide(); }
This works fine but I would like to change it so it checks a list of values like
if ($("#chosenmove1").val() in (3,4,5))
How can I write this to make it work (the above doesn't)
Tried a bit more
var arr = [3,4,5]; var value = $("#chosenmove1").val(); alert(value);
if ($.inArray(value, arr) > -1) $("#hideme").show(); else
$("#hideme").hide();
}
The alert box tells me var value is getting the right value from the drop down - yet the show hide wont work under this setup. IF I replace var value = $("#chosenmove1").val(); with var value = 3; then it does work?
I know I can do this by setting async to false but I would rather not.
Answer
With jQuery 1.5, you can use the brand-new $.Deferred feature, which is meant for exactly this.
// Assign handlers immediately after making the request, // and remember the jqxhr object for this request var jqxhr = $.ajax({ url: "example.php" }) .success(function() { alert("success"); })
alert("Do not alert before user has loaded"); $scope.user = user;
});
Answer
You can defer init of angular app using manual initialization, instead of auto init with ng-app attribute.
// define some service that has `$window` injected and read your data from it angular.service('myService', ['$window', ($window) =>({ getData() { return $window.myData;
var a = (function(){ var ret = {}; ret.test = "123"; function imPrivate() { /* ... */ } ret.public = function() { imPrivate(); } return ret; })();
a will contain the varible test and the function public, however you can not access imPrivate. This is the common way to handle public vs private variables;
I have a table that includes special characters such as ™.
This character can be entered and viewed using phpMyAdmin and other software, but when I use a SELECT statement in PHP to output to a browser, I get the diamond with question mark in it.
The table type is MyISAM. The encoding is UTF-8 Unicode. The collation is utf8_unicode_ci.
The first line of the html head is
I tried using the htmlentities() function on the string before outputting it. No luck.
I also tried adding this to php before any output (no difference):
header('Content-type: text/html; charset=utf-8');
Lastly I tried adding this right below the initial mysql connection (this resulted in additional odd characters being displayed):
I'm a beginner in C++. I'm compiling my code with GCC 9.2.0. Recently I've stumbled upon some weird behaviour which is segfaulting me.
I have a certain class wrapper for Hyperscan. I've made it so it basically has the same functionality as Python's re, but many times faster and multithreaded. I have a class regex which I usually allocate like
auto some_regex = regex();
Now, the what the constructor does, for those of you unfamiliar with Hyperscan is 2 (actually 3) things -> first it allocated memory for the regular expression database. This is done by calling their API, which is in C. Then, if it succeeds, you allocate scratch space. Now, because my implementation supports multithreading, my class instance holds a member which is a vector of scratch spaces. Nevertheless, I allocated a scratch space for each thread I use, also with their API. What I then have are a pointer to the compiled regex database and a vector of scratch space pointers.
When deconstructing the object, I have to free the database and scratch spaces (I also use the provided functions from the API) if they're allocated. So far so good. The problem arises when I do something like this:
auto some_regex = regex(); some_regex = regex(R"(\s+)");
Do you see a problem here? Maybe I'm too much of a noob to see it, but it looks good to me. But nope. It segfaults in the destructor while trying to free the database memory. Debugging it, I have come across these actions:
allocate memory for some_regex initialize some_regex allocated new memory for some_regex initialize new some_regex run destructor for the old some_regex run destructor for the new some_regex
Basically, the destructor for the first instance is run only after the constructor for the second one fires. What this does is essentially making it so that the first destructor frees up the data allocated and initialized by the second constructor instead of just cleaning itself.
Now, things get weirder. I looked into the addresses at hand, because I started setting the freed up pointers to nullptr - it turns out that this happens:
allocate memory for some_regex initialize some_regex allocated new memory for some_regex initialize new some_regex run destructor for the old some_regex database pointer is not 0, free it
set database pointer to nullptr run destructor for the new some_regex database pointer is not 0, free it (BUT THIS IS ALREADY FREED MEMORY???) SIGSEGV
I'm utterly confused. Even after setting the database pointer to null explicitly, the new one, after the constructor did its job, assigns it a new address.
Starting constructor... Ending constructor... Starting destructor...Address of test is 0 Ending destructor... Starting constructor... Ending constructor... Starting destructor...Address of test is 0 Ending destructor... Starting constructor... Ending constructor...
Starting destructor...Address of test is 0 Ending destructor... Starting full constructor... Ending full constructor... Starting destructor...Address of test is 0 Ending destructor... Process returned 0
Actual result:
Starting constructor... Ending constructor... Starting constructor... Ending constructor... Starting destructor...Address of test is 0 Ending destructor... Starting constructor... Ending constructor... Starting destructor...Address of test is 0
Ending destructor... Starting full constructor... Ending full constructor... Starting destructor...Address of test is 0 Ending destructor... *** Error in `/deploy/cmake-build-local-debug/CPP': double free or corruption (fasttop): 0x0000000002027c40 *** . . . Starting destructor...
Process finished with exit code 134 (interrupted by signal 6: SIGABRT)
Is this intended behaviour? If so, why??? And how can I get around it (aside from using new and deleting before reassigning)?