Tuesday, April 30, 2019

Round number up in JavaScript

I have the following number




0.135


I'd like to round it to 2 decimal places, I'm using...



(newCostDiff/2).toFixed(2)


only this returns




0.13


Can anyvody advise me on how to do this?

timestamp - Python copy file but keep original





Python query.



I want to take a copy of a file, called randomfile.dat, and add a timestamp to the end of the copied file.



However, I want to keep the original file too. So in my current directory (no moving files) I would end up with:
randomfile.dat
randomfile.dat.201711241923 (or whatever the timestamp format is..)



Can someone advise? Anything I have tried causes me to lose the original file.


Answer




How about this?



$ ls

$ touch randomfile.dat

$ ls
randomfile.dat

$ python

[...]
>>> import time
>>> src_filename = 'randomfile.dat'
>>> dst_filename = src_filename + time.strftime('.%Y%m%d%H%M')

>>> import shutil
>>> shutil.copy(src_filename, dst_filename)
'randomfile.dat.201711241929'
>>> [Ctrl+D]


$ ls
randomfile.dat
randomfile.dat.201711241929

javascript - How can I parse records on demand with Node.js?

Is there a Node module that can parse a specific number of records from a CSV file? The use case is to parse a large log file and deliver records to a paging client as requested.



node-csv can't yet do this, and the closest I've found is to read lines one by one, which requires reinventing the CSV parsing wheel, and will break on multi-line records.




But let's lower the bar: how can I parse single-line CSV records one by one with Node.js? Pretty trivial task in most other languages.

javascript - jQuery evaluate if checkbox is checked and contains the class true





I'm creating a multiple choice assessment using jQuery. Currently the DOM structure is as follows:





  • Answer 1


  • Answer 1

  • Answer 1

  • Answer 1




I need to write a function that when the button is clicked to see if the checkbox is ticked and that the class name of the li contains 'True'.



So far this is my jQuery:




      $('.multiplechoice_answer .Paragraph').prepend('');
$('.multiplechoice_wrap').prepend('');


$('.multiplesubmit').click(function() {
multipleChoiceCheck();

});

var multipleChoiceCheck = function() {

if($('input:checkbox[name=checkme]').is(':checked') && $('.multiplechoice_answer').hasClass('True')) {
alert('correct!');
}

};

Answer



$('.multiplesubmit').click(function () {
var correctAnswers = $(this).next('ul').children('li').filter(function () {
return $(this).hasClass('True') && $(this).find('input[type="checkbox"]:checked').length>0;

});
if(correctAnswers.length>0) {
alert('found')
}
});


JSFiddle



Update




As per comments



$('.multiplesubmit').click(function () {
var correctAnswers = $(this).next('ul').children('li').filter(function () {
return $(this).hasClass('True') && $(this).find('input[type="checkbox"]:checked').length>0;
});
var wrongAnswers = $(this).next('ul').children('li').filter(function () {
return $(this).hasClass('False') && $(this).find('input[type="checkbox"]:checked').length>0;
});

if (correctAnswers.length>0 && wrongAnswers.length<1) {
alert('found')
}
});


JSFiddle


How do I convert a String to an int in Java?



How can I convert a String to an int in Java?



My String contains only numbers, and I want to return the number it represents.



For example, given the string "1234" the result should be the number 1234.


Answer



String myString = "1234";

int foo = Integer.parseInt(myString);


If you look at the Java Documentation you'll notice the "catch" is that this function can throw a NumberFormatException, which of course you have to handle:



int foo;
try {
foo = Integer.parseInt(myString);
}
catch (NumberFormatException e)

{
foo = 0;
}


(This treatment defaults a malformed number to 0, but you can do something else if you like.)



Alternatively, you can use an Ints method from the Guava library, which in combination with Java 8's Optional, makes for a powerful and concise way to convert a string into an int:



import com.google.common.primitives.Ints;


int foo = Optional.ofNullable(myString)
.map(Ints::tryParse)
.orElse(0)

c++ - use of: while (cin >> x) and eof



I am not so sure how the works I suppose is my root problem here. I've read a few previous posts on while(cin>>x) but nothing seems to answer my question really.
I am using this loop to read in some text data:



while (cin >> x){
searchText.push_back(x);
}



but then later in the code I am trying to read in a single word using:



cout << "Please enter your target word: ";
string targetWord;
cin >> targetWord;


but the above while loop/ eof seems to scupper the 2nd code snippet (if I move the 2nd code snippet up above it all works fine, but obviously that is not what im trying to do)




EDIT
Here is the full code for clarity:



int main()
{
// ask for the target word
// cout << "Please enter your target word: ";
// string targetWord;
// cin >> targetWord;


// ask for and read the search text
cout << "Enter the complete search text, "
"followed by end-of-file: ";
vector searchText;
string x;
while (cin >> x){
searchText.push_back(x);
}

// check that some text was entered

typedef vector::size_type vec_sz;
vec_sz size = searchText.size();
if (size == 0){
cout << endl << "You must enter some text. "
"Please try again." << endl;
return 1;
}

// ask for the target word
cin.clear();

cout << "";
cout << "Please enter your target word: ";
string targetWord;
cin >> targetWord;


int count = 0;
for (int i=0; i if (targetWord == searchText[i]){
count++;

}
}

cout << "The target word [" << targetWord << "] was "
"in the search text " << count << " times." << endl;

return 0;
}



I am just trying to take in some text from the user... then a search word and see how many times the word appears in the entered text (pretty simple!)



I know I could do it differently but the question here is more about how can I use the cout/ cin stream again after it has had an EOF in it previously


Answer



When cin (or any other std::stream) hits an end of file, it sets a status to indicate that this has happened.



To reset this status, you need to call cin.clear();, which will clear any "bad" state, and make sure the stream is "ok" to use again. This also applies if you are reading from a file, and want to restart from the beginning.



Edit: I just took the code posted above, and ran it on my machine, adding at the top




#include 
#include

using namespace std;


This following is the compile and run:



$ g++ -Wall words.cpp 
words.cpp: In function ‘int main()’:

words.cpp:40:20: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
$ ./a.out
Enter the complete search text, followed by end-of-file: aa bb cc [CTRL-D]
Please enter your target word: aa
The target word [aa] was in the search text 1 times.


which is what I expected to see...



Edit2: For completeness: The "success rate" of using cin.clear() will depend on the implementation. A more reliable solution is to use a different way to mark the end of the stream of words in the first phase of the program. One could use a single "." or "!" or some other thing that isn't supposed to be in a "word" - or something longer, such as "&&@&&", but that makes it hard to type and remember when one is 15 pages into the input.



Undefined index in PHP

It's where you test to see that is isn't there. It should be !isset($_POST['SUBMIT']). This is because the index, SUBMIT, won't be set, thus won't have a value such as true to pass the if(...). isset() checks to see if the index/variable is actually set.


Try this:


    if (!isset($_POST['SUBMIT'])){   //ERROR: Undefined index
?>

Add Employee












SSN
 


}
else {
//code here
}
?>

Javascript- is there a way to destroy all elements of an array by one command?

my script creates an empty array and then fill it. But if new arguments come then script is expected to destroy old one and create new one.




var Passengers = new Array();

function FillPassengers(count){
for(var i=0;i Passengers[i] = i;
}


I wanna destroy the old one because new count may be less than old one and last elements of array still will store old array? is that right and if it is how can I destroy it?

brew install mysql on macOS




I'm trying to setup up MySQL on mac os 10.6 using Homebrew by brew install mysql 5.1.52.



Everything goes well and I am also successful with the mysql_install_db.
However when I try to connect to the server using:



/usr/local/Cellar/mysql/5.1.52/bin/mysqladmin -u root password 'mypass'


I get:





/usr/local/Cellar/mysql/5.1.52/bin/mysqladmin: connect to server at 'localhost'
failed error: 'Access denied for user 'root'@'localhost' (using password: NO)'


I've tried to access mysqladmin or mysql using -u root -proot as well,
but it doesn't work with or without password.



This is a brand new installation on a brand new machine and as far as I know the new installation must be accessible without a root password. I also tried:



/usr/local/Cellar/mysql/5.1.52/bin/mysql_secure_installation



but I also get




ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Answer



I think one can end up in this position with older versions of mysql already installed. I had the same problem and none of the above solutions worked for me. I fixed it thus:



Used brew's remove & cleanup commands, unloaded the launchctl script, then deleted the mysql directory in /usr/local/var, deleted my existing /etc/my.cnf (leave that one up to you, should it apply) and launchctl plist




Updated the string for the plist. Note also your alternate security script directory will be based on which version of MySQL you are installing.



Step-by-step:



brew remove mysql

brew cleanup

launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist


rm ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist

sudo rm -rf /usr/local/var/mysql


I then started from scratch:




  1. installed mysql with brew install mysql

  2. ran the commands brew suggested: (see note: below)




    unset TMPDIR

    mysql_install_db --verbose --user=`whoami` --basedir="$(brew --prefix mysql)" --datadir=/usr/local/var/mysql --tmpdir=/tmp

  3. Start mysql with mysql.server start command, to be able to log on it


  4. Used the alternate security script:



    /usr/local/Cellar/mysql/5.5.10/bin/mysql_secure_installation


  5. Followed the launchctl section from the brew package script output such as,



    #start
    launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist

    #stop
    launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist

  6. Boom.





Hope that helps someone!



Note: the --force bit on brew cleanup will also cleanup outdated kegs, think it's a new-ish homebrew feature.



Note the second: a commenter says step 2 is not required. I don't want to test it, so YMMV!


Can't save new record into table using C# and Entity Framework because of NullReference error

Here is my problem:




My button click event handler:



protected void add_btn_Click(object sender, EventArgs e)
{
motorok m = new motorok();
m.marka = t1.Text;
m.tipus = t2.Text;

if (t3.Text.Length > 0)
{

m.evjarat = Convert.ToInt32(t3.Text);
}

if (t4.HasFile)
{
m.kep = t4.FileName;
}

sqlchannel.SaveNewMotor(m);
}



My method to save the data in the database:



public static void SaveNewMotor(motorok m)
{
MOTORAB_MODEL.motorok.Add(m);
MOTORAB_MODEL.SaveChanges();
}



My table:



CREATE TABLE [dbo].[motorok] 
(
[id] INT IDENTITY (1, 1) NOT NULL,
[marka] VARCHAR (50) NOT NULL,
[tipus] VARCHAR (100) NOT NULL,
[evjarat] INT NULL,
[kep] VARCHAR (100) NULL,


PRIMARY KEY CLUSTERED ([id] ASC)
);


Error: the MOTORAB_MODEL.SaveChanges() call throws a System.NullReferenceException



I think the problem has to be with the IDENTITY somehow but I can't figure out why. The method gets the object correctly with every value I want. In the DB, in my 'motorok' table the id column is set to IDENTITY and it is an integer. A select works perfectly so the database connection is fine.



Can you please help me? I've been googling for days now.




Edit:



Screenshot of the error



Edit 2:



MOTORAB_MODEL (motorab.mdf is my database file):



private static MOTORAB MOTORAB_MODEL;

static sqlchannel()
{
MOTORAB_MODEL = new MOTORAB();
}


I haven't override SaveChanges().

floating point - What is the best way to compare floats for almost-equality in Python?



It's well known that comparing floats for equality is a little fiddly due to rounding and precision issues.



For example:
https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/



What is the recommended way to deal with this in Python?




Surely there is a standard library function for this somewhere?


Answer



Python 3.5 adds the math.isclose and cmath.isclose functions as described in PEP 485.



If you're using an earlier version of Python, the equivalent function is given in the documentation.



def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)



rel_tol is a relative tolerance, it is multiplied by the greater of the magnitudes of the two arguments; as the values get larger, so does the allowed difference between them while still considering them equal.



abs_tol is an absolute tolerance that is applied as-is in all cases. If the difference is less than either of those tolerances, the values are considered equal.


Memory Leak LibGDX ANdroid

I am making a live wallpaper app with libgdx in which I change the assets depending on the time. For. e.g from 6am to 6pm I have the "morning graphics" after that I have "evening graphics" from 6pm to 6am.



The way I have structured the Assets is as follows



I have 12 static arrays of type AtlasRegion 1 static Texture Region variable and 1 static texture variable.




I have two static functions loadMorning() and loadEvening() for loading the assets.



In the funcions I load as follows



For all arrays if they are not null do array.clear()
then load the regions. Dispose the TextureRegion variable and set texture variable to null before resetting their values.



The thing that is happening is that after every change of assets the memory seems to increasing
As a user's perepective I am using this app to see the memory




https://play.google.com/store/apps/details?id=mem.usage&hl=en



When I start my app for the first time .. it is showing as 68MB in the app ,



Day1 Morning Stats



Day 1



ID      Heap Size       Allocated       Free            %Used    #Objects

1 10.812 MB 3.186 MB 7.626 MB 29.47% 45,405



Pss Private Private Swapped Heap Heap Heap
Total Dirty Clean Dirty Size Alloc Free
------ ------ ------ ------ ------ ------ ------
Native Heap 0 0 0 0 16620 4285 38
Dalvik Heap 8692 8604 0 0 11072 3293 7779
Dalvik Other 1374 1216 0 0

Stack 96 96 0 0
Other dev 33016 4908 4 0
.so mmap 1266 692 136 0
.apk mmap 160 0 116 0
.dex mmap 287 20 8 0
Other mmap 5 4 0 0
Unknown 1431 1412 0 0
TOTAL 46327 16952 264 0 27692 7578 7817

Objects

Views: 1 ViewRootImpl: 0
AppContexts: 3 Activities: 0
Assets: 2 AssetManagers: 2
Local Binders: 11 Proxy Binders: 19
Death Recipients: 0
OpenSSL Sockets: 0

SQL
MEMORY_USED: 0
PAGECACHE_OVERFLOW: 0 MALLOC_SIZE: 0



Day 1 Evening Stats



adb log after evening assets are loaded



D/dalvikvm(2451): GC_FOR_ALLOC freed 1619K, 71% free 3281K/11072K, paused 14ms, total 15ms



D/dalvikvm(2451): GC_FOR_ALLOC freed 1517K, 71% free 3281K/11072K, paused 11ms, total 11ms




I/dalvikvm-heap(2451): Grow heap (frag case) to 6.548MB for 1331595-byte allocation



D/dalvikvm(2451): GC_CONCURRENT freed 1862K, 67% free 4127K/12376K, paused 2ms+2ms, total 13ms



D/dalvikvm(2451): GC_EXPLICIT freed 2384K, 74% free 3268K/12376K, paused 2ms+3ms, total 27ms



ID      Heap Size       Allocated       Free            %Used    #Objects
1 10.816 MB 3.191 MB 7.625 MB 29.50% 45,525



This adb log right after change


Pss Private Private Swapped Heap Heap Heap
Total Dirty Clean Dirty Size Alloc Free
------ ------ ------ ------ ------ ------ ------
Native Heap 0 0 0 0 16728 4346 29
Dalvik Heap 1654 1576 0 0 11076 3348 7728
Dalvik Other 1435 1296 0 0
Stack 100 100 0 0

Other dev 63332 32644 4 0
.so mmap 1110 692 116 0
.apk mmap 7 0 4 0
.dex mmap 586 20 368 0
Other mmap 5 4 0 0
Unknown 1504 1488 0 0
TOTAL 69733 37820 492 0 27804 7694 7757

Objects
Views: 1 ViewRootImpl: 0

AppContexts: 3 Activities: 0
Assets: 2 AssetManagers: 2
Local Binders: 10 Proxy Binders: 17
Death Recipients: 0
OpenSSL Sockets: 0

SQL
MEMORY_USED: 0
PAGECACHE_OVERFLOW: 0 MALLOC_SIZE: 0



The memory showing in the app is now 117MB
This keeps increasing , next morning the size shown in app is about 150 MB.



I need some pointers where to look to understand this better.

php - SMTP Mail Error on both server and localhost



I have an email account with zoho.com that is configured and running. On GoDaddy, I am hosting my site and have configured my mail such that any mail sent via the website is received at zoho mail. This setup worked fine till last week. Now I am getting errors and I have no idea what triggers them.




I get the following error on GoDaddy server when I try to send a mail to any account:




SMTP -> ERROR: Failed to connect to server: Connection refused (111)
SMTP Error: Could not connect to SMTP host.




AND the following error on localhost for the same script:





SMTP -> ERROR: Failed to connect to server: A connection attempt
failed because the connected party did not properly respond after a
period of time, or established connection failed because connected
host has failed to respond. (10060)




I have tried the following to correct the errors (on both localhost and GoDaddy) by:




  • Changed port number to 25,465 and 587



  • Changed smtp server from smtp.zoho.com to relay-hosting.secureserver.net


  • Changed ssl to tls and vice versa


  • Removed the SMTPSecure Parameter altogether


  • Increased timeout variable to 1000


  • Verified that the mail accounts exist and are up and running


  • Verified that mail accounts have valid passwords and usernames.




A working demo can be found here.I have echoed the errors out as well as the message to be sent just for the purpose of this question.




Edit 1 I commented out "$mail->Host="smtp.zoho.com" and got the following error:




SMTP -> FROM SERVER: SMTP -> FROM SERVER: SMTP -> ERROR: EHLO not
accepted from server: SMTP -> FROM SERVER: SMTP -> ERROR: HELO not
accepted from server: SMTP -> ERROR: AUTH not accepted from server:
SMTP -> NOTICE: EOF caught while checking if connectedSMTP Error:
Could not authenticate.





Does this mean that GoDaddy is not authenticating the credentials?



Edit 2: My settings on zoho mail are:




Incoming server: poppro.zoho.com, Port: 995, SSL (POP)
Incoming server: imappro.zoho.com, Port: 993, SSL (IMAP) Outgoing
server: smtp.zoho.com, Port: 465, SSL (POP and IMAP)



Answer



Try Using Following Code:




require_once('class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded

$mail = new PHPMailer(true); // the true param means it will throw exceptions on errors, which we need to catch

$mail->IsSMTP(); // telling the class to use SMTP

try {

//SMTP needs accurate times, and the PHP time zone MUST be set
//This should be done in your php.ini, but this is how to do it if you don't have access to that
#require '../PHPMailerAutoload.php';

//Create a new PHPMailer instance
$mail = new PHPMailer;

//Tell PHPMailer to use SMTP
$mail->isSMTP();
//Enable SMTP debugging

// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->SMTPDebug = 3;

//Ask for HTML-friendly debug output
$mail->Debugoutput = 'html';

//Set the hostname of the mail server
$mail->Host = 'smtp.zoho.com';


// use
// $mail->Host = gethostbyname('smtp.zoho.com');
// if your network does not support SMTP over IPv6

//Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
$mail->Port = 465;

//Set the encryption system to use - ssl (deprecated) or tls
//$mail->SMTPSecure = 'tls';


//Whether to use SMTP authentication
$mail->SMTPAuth = true;

//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = "care@subillion.com";

//Password to use for SMTP authentication
$mail->Password = "care@subillion";


//Set who the message is to be sent from
$mail->setFrom('care@subillion.com', 'care@subillion.com');

//Set an alternative reply-to address
#$mail->addReplyTo('replyto@example.com', 'First Last');

//Set who the message is to be sent to
$mail->AddAddress($touser, $username);

$mail->Subject = $subject;

$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
$mail->MsgHTML($msg);
echo $msg;
//$mail->AddAttachment('img/logo-dark.png');
$mail->Send();

// echo "Message Sent OK

\n";
} catch (Exception $e) {
// echo $e->getMessage(); //Boring error messages from anything else!
}

?>


EDIT: if still not working then you must have proper configuration settings as below(as example):



Non-SSL Settings
(NOT Recommended)
Username: jon@domain.com
Password: Use the email account’s password.
Incoming Server: mail.domain.com

IMAP Port: 143
POP3 Port: 110
Outgoing Server: mail.domian.com
SMTP Port: 25
Authentication is required for IMAP, POP3, and SMTP.

character - In Prometheus, is Meredith Vickers a human or android?

While I was watching Prometheus this weekend, I initially thought that Meredith Vickers was an android, like David. They never made it perfectly clear that she was or wasn't human. They did hint at both though.



  1. Peter Weyland, the old trillionaire, did say that she was his daughter. He could have meant this figuratively though.


  2. Janek, the captain of the Prometheus, asked Vickers for sex like he was asking an android for a glass of water. After she agreed without emotion, he sang "if you can't be with the one you love, love the one you're with" before he had sex with her (although they didn't show it). This suggested to me that he wasn't going to be with a human, but was going to love the android he was with.


  3. The surgery pod wasn't designed for use by a woman. Why would a trillionaire who could afford to build a surgery pod not build one for use by his own daughter?


  4. Vickers has a different last name than Weyland, which at least suggest that they are not natural father-daughter.



Answer


In my mind, it's likely that Vickers is an android.



  • The first clue while watching the film was her quick recovery from cryosleep.

  • Later she's called Weyland's daughter, but David was given the name Weyland "had initially reserved for his own human son".

  • Vickers has the physical strength to easily push David around. In Alien, androids are depicted as being much stronger than humans, so this suggests Vickers is as strong as David, an android.

  • David and Vickers were the only ones who knew that Weyland was on board, so Weyland trusted them both completely. We know why he trusted David, it doesn't seem outlandish that he trusted Vickers for the exact same reason.

  • The med pod is in Vickers quarters but would be unable to properly perform surgery on her, given that it's set to male. If she were a human, it's possible that Weyland didn't care enough for Vickers to provide her with the medical capabilities that the med pod provided.


My own theory is that Vickers is a later model of android than David. David's (a male, mind you) a logical breakthrough who can imitate human emotions. Then for a later model, a female android is created who has actual emotions. This provides a sort of symbolical balance in Weyland's ultimate creation, artificial men and women. This also makes a nice biblical reference.


debugging - index out of bounds exception java

So the error message is this:



Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at FcfsScheduler.sortArrival(FcfsScheduler.java:77)
at FcfsScheduler.computeSchedule(FcfsScheduler.java:30)
at ScheduleDisks.main(ScheduleDisks.java:33)



with my code as



public void sortArrival(List r)
{
int pointer = 0;
int sProof = 0;
while(true)
{
if(r.get(pointer).getArrivalTime() {

Request r1 = r.get(pointer);
Request r2 = r.get(pointer+1);
r.set(pointer, r2);
r.set(pointer+1, r1);
}
else
{
sProof++;
}
++pointer;

if(pointer>r.size()-2)
{
pointer=0;
sProof=0;
}
if(sProof>=r.size()-2)
{
break;
}
}

}


The error is at



if(r.get(pointer).getArrivalTime()


but I think the array index is checked ok with the code after the increment of pointer. Is it an array out of bounds exception or something else? Normally, the error is ArrayIndexOutOfBoundsException when it is the array. What seems to be the problem here?

c++ - In GCC, Clang and MSVC is there any way to conform against C++98 and not C++03?



The meta question proposes that the and tags should be made synonyms. The question asker followed it up with Is value initialization part of the C++98 standard? If not, why was it added in the C++03 standard?, an excellent question which sheds light on the addition of value initialization to C++03. Consider this question to be a follow-up to the latter.



The OP asserts that modern compilers do not bother distinguishing between C++98 and C++03. This was surprising to me, as it turns out to be the case for three modern compilers. Although this question could boil down to "RTFM", my searches have not found anything conclusive.



GCC



Their standards page:





The original ISO C++ standard was published as the ISO standard
(ISO/IEC 14882:1998) and amended by a Technical Corrigenda published
in 2003 (ISO/IEC 14882:2003). These standards are referred to as C++98
and C++03, respectively. GCC implements the majority of C++98 (export
is a notable exception) and most of the changes in C++03. To select
this standard in GCC, use one of the options -ansi, -std=c++98, or
-std=c++03; ...





Furthermore, their dialect options page says:




In C++ mode, [ansi] is equivalent to -std=c++98.




And group "c++98" and "c++03" together:






The 1998 ISO C++ standard plus the 2003 technical corrigendum and some
additional defect reports. Same as -ansi for C++ code.





This seems to imply there is no way to turn on only C++98 mode.



Clang




The only thing I found find for Clang was on their manual, it says under C++ Language Features:




clang fully implements all of standard C++98 except for exported
templates (which were removed in C++11), ...




With no mention of C++03. It also states:





clang supports the -std option, which changes what language mode clang
uses. The supported modes for C are c89, gnu89, c94, c99, gnu99, c11,
gnu11, and various aliases for those modes. If no -std option is
specified, clang defaults to gnu11 mode. Many C99 and C11 features are
supported in earlier modes as a conforming extension, with a warning.




This is of course for their C compiler, I was not able to find any documentation on the C++ compiler, such as which options are valid to pass to -std. I simply assume that Clang mirrors GCC's dialect options (for example, C++03 is valid on Clang), although without proof I cannot state so conclusively.



MSVC




As far as I know, MSVC doesn't allow you to change language standards like the two above do. A search for "C++98" on MSDN doesn't turn up anything. It appears that they implement C++98/C++11, for example as stated by Herb Sutter.



Questions



Although these questions sound obvious, the meta question has made me realize that it is not so obvious.




  • Is there a way to make GCC only conform to C++98? Enforcing the C++98 standard in gcc simply links to the same documentation I did, without any further consideration on whether it really is conforming against C++98.


  • Does Clang conform to C++98 or do they actually conform to C++03? Where can I find the relevant documentation for this?



  • Same for MSVC. Is there a way to change language standards in MSVC to conform only against C++98?



Answer




Is there a way to make GCC only conform to C++98?




No. You already thoroughly covered the available flags in your question, and none of them can do this.








Does Clang conform to C++98 or do they actually conform to C++03? Where can I find the relevant documentation for this?




Clang implements C++03 minus export, just like GCC:




Clang implements all of the ISO C++ 1998 standard (including the defects addressed in the ISO C++ 2003 standard) except for export (which was removed in C++11).











Same for MSVC. Is there a way to change language standards in MSVC to conform only against C++98?




No. As you say, you cannot specify the C++ version in MSVC. There is a list of compiler flags and that is not the function of any of them.









The whole point of C++03 was to make corrections to C++98 and thus to effectively replace it outright, rather than to follow it as a new unit. It does not make sense to want to "revert" those fixes. That would be like asking Windows 7 SP2 to boot into Windows 7 SP1 mode. It just isn't a model that anyone would want to support.



Fictional.


angularjs - Angular js timeout inside link function after dom manipulation

I have a directive, through which I am dynamically adding span before a label in html. The span tag is created using template property. Now I have one case where label is displayed none so no need for span to add.



Can we use timeout inside link function after DOM manipulation is completed in link function? Since i am able to get instance of all label elements after DOM has completed loading. Below is the directive code working as expected.



myModule.directive('lockIcon', ['$compile', '$filter', '$timeout', function($compile, $filter, $timeout) {
return {
restrict: 'A',
scope: {
visible: '=visible'
},

link: function (scope, element) {
var template = '';
var newElement = angular.element(template);
element.wrap( '
' ).parent().append(newElement);
$compile(newElement)(scope);
$timeout(function() {
var lockLabelElm = angular.element('.lock-icon-wrapper label');
if(lockLabelElm) {
angular.forEach(lockLabelElm, function(elmlock) {
var labelDisplayState = angular.element(elmlock).css('display');

if(labelDisplayState === 'none') {
angular.element(elmlock).next().css('display','none');
}
});
}
});
}
};
}]);

javascript - Insert Object data in HTML




How can I list the structured contents of a Javascript Object in HTML?



My object looks like this:



var lists = {
"Cars":{"Ford":false,"Ferarri":false},
"Names":{"John":true,"Harry":false},
"Homework":{"Maths":true,"Science":false,"History":true,"English":true}
}


What would the loop look like to print the keys as headers, and the property + values as an ordered list underneath?



Example:



Cars




  1. Ford = False

  2. Ferrari = False



Names




  1. John = True

  2. Harry = False



Homework




  1. Maths = True

  2. Science = False

  3. History = True

  4. English = True



I understand that I can append the object by name to HTML, but if the object is dynamic, and the key isn't known, how can I make a loop to do so?


Answer



Just got to loop, create the HTML string, and append! Say you have a container:






And your JS



var htmlString = "";
for (var key in lists) {
htmlString += "" + key + "";
htmlString += "
    ";
    for (var item in lists[key]) {
    htmlString += "
  • " + item + " = " + lists[key][item] + "
  • ";
    }
    htmlString += "
";
}

document.getElementById("container").innerHTML = htmlString;


Working demo: http://jsfiddle.net/owqt5obp/


html - PHP Mail not working properly

I have a very long form and the content of the form is sent via mail (HTML email).



My PHP mail function is working perfectly for the rest of the content. But when I add the following content to the message body, the mail is not working.



OCCUPATION:



Please provide a specific and identifiable business activity and
your current position . Vague references such as"Businessman" or
"Manager" will not be accepted and will delay the incorporation
process. In the case of no employment please describe the normal
day to day activities such as "House Wife" In case of retirement
please provide details of previous occupation and your last
position.






I went through each and every line but cannot find whats wrong with these particular lines.



My PHP mail sends HTML email.




if(mail($to, $subject, $message, $headers)){
$mail_status_message = "

Form Submitted Successfully.

";
}else{
$mail_status_message = "

Something went wrong. Please try again later.

";
}

?>


Basically I am getting the Something went wrong. Please try again later when I add the above code to the message body.



The mail headers are



    $headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Additional headers
$headers .= 'To: '.$to_name.'<'.$to_email.'>' . "\r\n";
$headers .= 'From: Business Name ' . "\r\n";

Monday, April 29, 2019

excel vba - How can make Sheet to activate in VBA from a variable? (A cell particularly)

I am actually quite new to VBA but I am doing some coding to streamline my office work. I understand this would be some amateur level questions to most of you but I tried to google for quite a while and I do not find satisfactory answer.



I have an excel write up that based on the inputted parameters, It should ultimately refer to the correct sheet -> copy the selected cells -> Generate an e-Mail with the body pasting the copied cells along with an attachment




I can do most of the parts, just that I cannot reference the "Correct Sheet" as a variable in my codes. Please shed some lights on for me. Thank you.



Here are most of the codes, the rest are irrelevant and too clumsy to paste all I guess.



Sub GenerateEmail()

Dim olApp As Object
Dim olMailItm As Object
Dim iCounter As Integer

Dim Dest As Variant
Dim SDest As String
Dim StrAtt1 As String
Dim rng As Range



Set rng = Nothing
On Error Resume Next
Set rng = Sheets("test").Range("A1:Q500").SpecialCells(xlCellTypeVisible)

On Error GoTo 0

If rng Is Nothing Then
MsgBox "The selection is not a range or the sheet is protected" & _
vbNewLine & "please correct and try again.", vbOKOnly
Exit Sub
End If

With Application
.EnableEvents = False

.ScreenUpdating = False
End With

Set olApp = CreateObject("Outlook.Application")
Set olMailItm = olApp.CreateItem(0)

On Error Resume Next
With olMailItm
SDest = ""
StrAtt1 = ThisWorkbook.Path & "\PDF\" & Sheets("Email_Generator").Range("B16")


.To = Worksheets("Email_Generator").Range("B14")
.CC = "Myself"
.BCC = ""
.Subject = Worksheets("Email_Generator").Range("B18")
.HTMLBody = RangetoHTML(rng)
.attachments.Add StrAtt1
.Display
End With


Set olMailItm = Nothing
Set olApp = Nothing
End Sub


Specifically, I would like this code "Sheets("test") as a Cell in Sheet "Test" that is a variable based on the paramters I have inputted in my excel so that this code will reference to the correct worksheet



   Set rng = Sheets("test").Range("A1:Q500").SpecialCells(xlCellTypeVisible)



But when I identify the sheet as a named sheet e.g. Sheets("Email1"), it perfectly works, just that it cannot become a variable.



I hope this post is not too long to read because I tried to be as specific as possible. Thank you to all who reads this and tries to help. I really appreciate it.

c++ - Segmentation Fault before main() when using glut, and std::string?




On 64-bit Ubuntu 14.04 LTS, I am trying to compile a simple OpenGL program that uses glut. I am getting a Segmentation Fault (SIGSEV) before any line of code is executed in main; even on a very stripped down test program. What could cause this?



My command line:



g++ -Wall -g main.cpp -lglut -lGL -lGLU -o main



My simple test case:



#include                                                                                                                                          
#include

#include

#include
#include

int main(int argc, char** argv){
printf("Started\n");
std::string dummy = "hello";
glutInit(&argc, argv);
return 0;

}


When I run the program, the printf at the beginning of main doesn't get to execute before the segfault.
Under GDB, I get this back trace after the segfault is



#0  0x0000000000000000 in ?? ()
#1 0x00007ffff3488291 in init () at dlerror.c:177
#2 0x00007ffff34886d7 in _dlerror_run (operate=operate@entry=0x7ffff3488130 , args=args@entry=0x7fffffffddf0) at dlerror.c:129
#3 0x00007ffff3488198 in __dlsym (handle=, name=) at dlsym.c:70

#4 0x00007ffff702628e in ?? () from /usr/lib/nvidia-352/libGL.so.1
#5 0x00007ffff6fd1aa7 in ?? () from /usr/lib/nvidia-352/libGL.so.1
#6 0x00007ffff7dea0fd in call_init (l=0x7ffff7fd39c8, argc=argc@entry=1, argv=argv@entry=0x7fffffffdf48, env=env@entry=0x7fffffffdf58) at dl-init.c:64
#7 0x00007ffff7dea223 in call_init (env=, argv=, argc=, l=) at dl-init.c:36
#8 _dl_init (main_map=0x7ffff7ffe1c8, argc=1, argv=0x7fffffffdf48, env=0x7fffffffdf58) at dl-init.c:126
#9 0x00007ffff7ddb30a in _dl_start_user () from /lib64/ld-linux-x86-64.so.2
#10 0x0000000000000001 in ?? ()
#11 0x00007fffffffe2ba in ?? ()
#12 0x0000000000000000 in ?? ()



And here's the kicker. If I comment out either the gluInit line or the std::string dummy line, the program compiles and runs just fine. Up until I noticed this I assumed there was something wrong with my GLUT (though I've tried the original program I'm debugging on (that I stripped down to this example)) several systems with no success. I am at a bit of a loss here.



Edit: I have tried gmbeard's suggestions. Turining off optimizations (-O0) didn't change anything about the callstack produced by gdb.



Running ldd on the program gives me:



linux-vdso.so.1 =>  (0x00007ffe3b7f1000)
libglut.so.3 => /usr/lib/x86_64-linux-gnu/libglut.so.3 (0x00007f04978fa000)
libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f04975f6000)

libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f04973e0000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f049701b000)
libGL.so.1 => /usr/lib/nvidia-352/libGL.so.1 (0x00007f0496cec000)
libX11.so.6 => /usr/lib/x86_64-linux-gnu/libX11.so.6 (0x00007f04969b7000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f04966b1000)
libXi.so.6 => /usr/lib/x86_64-linux-gnu/libXi.so.6 (0x00007f04964a1000)
libXxf86vm.so.1 => /usr/lib/x86_64-linux-gnu/libXxf86vm.so.1 (0x00007f049629b000)
/lib64/ld-linux-x86-64.so.2 (0x00007f0497b44000)
libnvidia-tls.so.352.21 => /usr/lib/nvidia-352/tls/libnvidia-tls.so.352.21 (0x00007f0496098000)
libnvidia-glcore.so.352.21 => /usr/lib/nvidia-352/libnvidia-glcore.so.352.21 (0x00007f0493607000)

libXext.so.6 => /usr/lib/x86_64-linux-gnu/libXext.so.6 (0x00007f04933f5000)
libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f04931f1000)
libxcb.so.1 => /usr/lib/x86_64-linux-gnu/libxcb.so.1 (0x00007f0492fd2000)
libXau.so.6 => /usr/lib/x86_64-linux-gnu/libXau.so.6 (0x00007f0492dce000)
libXdmcp.so.6 => /usr/lib/x86_64-linux-gnu/libXdmcp.so.6 (0x00007f0492bc8000)


And then, having identified which libGL I am using, I ran ldd on it



linux-vdso.so.1 =>  (0x00007ffc55df8000)

libnvidia-tls.so.352.21 => /usr/lib/nvidia-352/tls/libnvidia-tls.so.352.21 (0x00007faa60d83000)
libnvidia-glcore.so.352.21 => /usr/lib/nvidia-352/libnvidia-glcore.so.352.21 (0x00007faa5e2f2000)
libX11.so.6 => /usr/lib/x86_64-linux-gnu/libX11.so.6 (0x00007faa5dfbd000)
libXext.so.6 => /usr/lib/x86_64-linux-gnu/libXext.so.6 (0x00007faa5ddab000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007faa5d9e6000)
libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007faa5d7e2000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007faa5d4dc000)
libxcb.so.1 => /usr/lib/x86_64-linux-gnu/libxcb.so.1 (0x00007faa5d2bd000)
/lib64/ld-linux-x86-64.so.2 (0x00007faa612b5000)
libXau.so.6 => /usr/lib/x86_64-linux-gnu/libXau.so.6 (0x00007faa5d0b9000)

libXdmcp.so.6 => /usr/lib/x86_64-linux-gnu/libXdmcp.so.6 (0x00007faa5ceb3000)


But a quick glance doesn't reveal anything amiss.


Answer



So you see in the LD_DEBUG output:




The last thing it prints out is: " 20863: symbol=__pthread_key_create;
lookup in file=/usr/lib/x86_64-linux-gnu/libXdmcp.so.6 [0]





It means that ld.so id looking for __pthread_key_create since it is needed by one of your librarie [and you'd better find what library is needed this symbol, it possibly will answer what library need libpthread.so].



So __pthread_key_create must be in libpthread.so but you have no libpthread.so in your ldd output. As you can see below your program crashes possibly in using __pthread_key_create in init(). By the way you can try also



LD_PRELOAD=/lib64/libpthread.so.0 ./main


in order to make sure that pthread_key_create is loaded before other symbols.




So lgut is unlikely to be a problem. It just calls dlsym in initialization and it is absolutely correct behaviour. But the program crashes:



#0  0x0000000000000000 in ?? ()
#1 0x00007ffff3488291 in init () at dlerror.c:177
#2 0x00007ffff34886d7 in _dlerror_run (operate=operate@entry=0x7ffff3488130 , args=args@entry=0x7fffffffddf0) at dlerror.c:129


This backtrace shows that a function with 0x00000000 address (my guess it is yet unresolved address of __pthread_key_create) was called and that is an error. What function was called? Look at sources:




This is dlerror.c:129 (frame #2):



int
internal_function
_dlerror_run (void (*operate) (void *), void *args)
{
struct dl_action_result *result;

/* If we have not yet initialized the buffer do it now. */
__libc_once (once, init);



(frame #1):



/* Initialize buffers for results.  */
static void
init (void)
{
if (__libc_key_create (&key, free_key_mem))
/* Creating the key failed. This means something really went

wrong. In any case use a static buffer which is better than
nothing. */
static_buf = &last_result;
}


It must be __libc_key_create that is a macro and it has in glibc different definitions. If you build for POSIX it is defined



/* Create thread-specific key.  */
#define __libc_key_create(KEY, DESTRUCTOR) \

__libc_ptf_call (__pthread_key_create, (KEY, DESTRUCTOR), 1)


I asked you to build with:



g++ -pthread -Wall -g main.cpp -lpthread -lglut -lGL -lGLU -o main


In order to make sure that __libc_key_create in fact calls __pthread_key_create and lpthread is initialized before -lglut. But if you do not want use -pthread then possibly you need to analyze frame #1




#1  0x00007ffff3488291 in init () at dlerror.c:177


For example you can add disasemble for frame #1 to your question


c# - Enum String Name from Value



I have an enum construct like this:



public enum EnumDisplayStatus
{
None = 1,

Visible = 2,
Hidden = 3,
MarkedForDeletion = 4
}


In my database, the enumerations are referenced by value. My question is, how can I turn the number representation of the enum back to the string name.



For example, given 2 the result should be Visible.


Answer




You can convert the int back to an enumeration member with a simple cast, and then call ToString():



int value = GetValueFromDb();
var enumDisplayStatus = (EnumDisplayStatus)value;
string stringValue = enumDisplayStatus.ToString();

email - Using ReceivedTime in Outlook VBA to count yesterday's mail



I want to flash up a message box with the amount of mail received yesterday.



The code I have at the moment is:




Public Sub YesterdayCount()

Set ns = Application.GetNamespace("MAPI")
Set outApp = CreateObject("Outlook.Application")
Set outNS = outApp.GetNamespace("MAPI")

Dim Items As Outlook.Items
Dim MailItem As Object


Dim yestcount As Integer
yestcount = 0

Set Folder = outNS.Folders("Correspondence Debt Advisor Queries").Folders("Inbox")
Set Items = Folder.Items

For Each Item In Items
If MailItem.ReceivedTime = (Date - 1) Then
yestcount = yestcount + 1
End If

Next

MsgBox yestcount

End Sub


The problem is with the line:



If MailItem.ReceivedTime = (Date - 1) Then



The error says that an object variable is not set, but I can't fathom this after researching.


Answer



You almost got it. You basically never set the MailItem nor qualified it to the Item, and since ReceivedTime is Date / Time format, it will never equal a straight Date.



See the code below. I added some features to sort by ReceivedTime, then Exit the loop once it passes yesterday's date. I also cleaned up some of the variable naming so it will not be confused with inherent Outlook Object naming conventions.



Public Sub YesterdayCount()


Dim outNS As Outlook.NameSpace
Set outNS = Application.GetNamespace("MAPI")

Dim olFolder As Outlook.Folder
Set olFolder = outNS.Folders("Correspondence Debt Advisor Queries").Folders("Inbox")

Dim olItems As Outlook.Items
Set olItems = olFolder.Items

olItems.Sort "[ReceivedTime]", True


Dim yestcount As Integer
yestcount = 0

Dim item As Object

For Each item In olItems

'commented code works for MailItems
'Dim olMail As Outlook.MailItem

'Set olMail = item

Dim dRT As Date
'dRT = olMail.ReceivedTime
dRT = item.ReceivedTime

If dRT < Date And dRT > Date - 2 Then
If dRT < Date - 1 Then Exit For
yestcount = yestcount + 1
End If



Next

MsgBox yestcount

End Sub

javascript - How to declare initialize and use 2 dimensional arrays in Java Script Using a text from html page





How to declare , initialize and use 2 dimensional arrays in javascript,
If I write



var arr=new array(2,2)


is it correct to declare a array with 2 rows and two columns



and is it fine if i declare an array variable globally and allocate space in some function.
or is the following is correct?




var arr;
//Some operations
function(){
arr[0][1]=8;
};


I dont know how can you mark it as duplicate please read the description of the question not the title i want to declare the array without initializing it are you getting my point if not please ........ you are pointing it to the static declaration of an array and that i know and i learnt from the basics of programming 10 years ago so if you dont know know English kindly go to some language school and come back


Answer




There is no "matrix" structure natively in the language. But you can create them without major problem as far as you "book" the required memory.



Let's say you would like to create a 3x3 matrix, first you have to create an Array which will store references to each row/column (depending of your point of view, of course).



function createMatrix(N, M) {
var matrix = new Array(N); // Array with initial size of N, not fixed!

for (var i = 0; i < N; ++i) {
matrix[i] = new Array(M);
}


return matrix;
}

excel - Select multiple ranges with VBA



I need to select multiple ranges in a worksheet to run various VBA code on them. The ranges will always begin on row 84 but the end depends on how far down the data goes. I've been selecting these ranges separately using code like this:




Sub SelectRange()
Dim LastRow As Integer
LastRow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
Range("A84:B" & LastRow).Select
End Sub


That works fine, but I can't figure out how to select multiple ranges at once. I've tried everything I can think of:





  • Range("A84:B", "D84:E", "H84:J" & LastRow).Select

  • Range("A84:B,D84:E,H84:J" & LastRow).Select

  • Range("A84:B & LastRow,D84:E & LastRow,H84:J & LastRow").Select



Nothing works. I get a run-time error when running any of those.


Answer



Use UNION:




Dim rng as Range
With ActiveSheet
set rng = Union(.Range("A84:B" & LastRow),.Range("D84:E" & LastRow),.Range("H84:J" & LastRow))
End With
rng.select


But if you intend on doing something with that range then skip the .Select and just do what is wanted, ie rng.copy


java - Unsupported major.minor version 52.0

Pictures:



Command Prompt showing versions
Command Prompt showing versions




Picture of error
Picture of error



Hello.java



import java.applet.Applet;
import java.awt.*;

public class Hello extends Applet {


// Java applet to draw "Hello World"
public void paint (Graphics page) {
page.drawString ("Hello World!", 50, 50);
}
}


Hello.html






HelloWorld Applet










Error



Hello : Unsupported major.minor version 52.0


What may the problem be?

PHP Sessions: Explanation please?




I have been learning PHP for a little bit now, and it has been going really easy for the most part. The only thing I'm hung up on is getting sessions to work. Google has been unforgiving in this endeavor.



It could be one of two reasons; syntax or my software. I'm currently building a local website using EasyPHP 5.3.5.0 on a machine that isn't connected to the internet. Connecting it to the internet is not an option.



What I currently know of sessions is that a lot of syntax related to it has be deprecated, replaced by the superglobal $_SESSION array, which is a lot easier to use. start_session(); must be before any syntax relating to sessions. However, my login script isn't establishing a session, as a quick !isset ($_SESSION['username']) always returns true.



My script is set up like this:



PHP include to login.php, which is a form. check_login.php is what validates it, and if a query returns one row, it'll redirect to login_success.php which establishes the session, gives a welcome message then redirects (Using JavaScript) to the homepage.




Any ideas?



EDIT to include more information:



Here is a synopsis of my code:



index.php:



include 'main_login.php';



main_login.php:



if(!isset ($_SESSION['username'])){
...
Login form, action="cehcklogin.php" method="post"
...
}else{
var_dump ($_SESSION): // Just to see if it works
}



checklogin.php:



Connect to SQL
$username = $_POST['username'];
$password = $_POST['password'];

$username / $password stripslashes / mysql_real_escape_string

Query to find the username & password


$count = mysql_num_rows($result);

if($count = 1){
$_SESSION["username"] = $username;
$_SESSION["password"] = $password;
header("location:login_success.php");
}else{
echo "Wrong Username or Password."
}



login_success.php:



The login process goes to all of the way here, redirects home and that's where the problem is.



session_start();
var_dump($_SESSION); //This works
if(!isset ($_SESSION['username'])){
header("location:index.php");
}


Javascript redirect, and a welcome message appears.


It all works until you get to the homepage, which $_SESSION['username'] should be set, and it should not display the form, but it does.


Answer



It looks like you're not using session_start() in your main_login.php like etranger alluded to. You need to call that function at the start of each new request to begin using sessions.



Otherwise, if you are calling session_start() and you just neglected to show it in the code sample, then maybe the session ID is being lost during the redirect. Are you using cookie-based sessions or passing session ID as a URL parameter? Try printing session_id() or SID at the top of each page. This will let you know when the session is lost (the session ID will change or be "").



If you're using cookie-based sessions, then maybe the cookie is getting lost for some reason. If you're using URL parameter to pass session ID, then maybe transparent session ID support isn't working right.


javascript - How to remove elements from Array?










How to remove all items from jQuery array?




I have array var myArray = [];, I want to clear all items in this array on every post back.


Answer



Simplest thing to do is just



myArray = [];


again.



edit — as pointed out in the comments, and in answers to other questions, another "simplest thing" is




myArray.length = 0;


and that has the advantage of retaining the same array object.


javascript - Why is document.GetElementById returning null

I've been using document.GetElementById succesfully but from some time on I can't make it work again.
Old pages in which I used it still work but things as simple as this:





no title









Are giving me "document.getElementById("parsedOutput") is null" all the time now.
It doesnt matter if I use Firefox or Chrome or which extensions i have enabled or what headers I use for the html, it's always null and I can't find what could be wrong.



Thanks for your input =)

c++ - Does C++11 guarantee memory ordering between a release fence and a consume operation?

Consider the following code:



struct payload

{
std::atomic< int > value;
};

std::atomic< payload* > pointer( nullptr );

void thread_a()
{
payload* p = new payload();
p->value.store( 10, std::memory_order_relaxed );

std::atomic_thread_fence( std::memory_order_release );
pointer.store( p, std::memory_order_relaxed );
}

void thread_b()
{
payload* p = pointer.load( std::memory_order_consume );
if ( p )
{
printf( "%d\n", p->value.load( std::memory_order_relaxed ) );

}
}


Does C++ make any guarantees about the interaction of the fence in thread a with the consume operation in thread b?



I know that in this example case I can replace the fence + atomic store with a store-release and have it work. But my question is about this particular case using the fence.



Reading the standard text I can find clauses about the interaction of a release fence with an acquire fence, and of a release fence with an acquire operation, but nothing about the interaction of a release fence and a consume operation.




Replacing the consume with an acquire would make the code standards-compliant, I think. But as far as I understand the memory ordering constraints implemented by processors, I should only really require the weaker 'consume' ordering in thread b, as the memory barrier forces all stores in thread a to be visible before the store to the pointer, and reading the payload is dependent on the read from the pointer.



Does the standard agree?

Did Neil Marshall deliberately reference The Matrix in Dog Soldiers?

In the film Dog Soldiers by Neil Marshall, the following dialogue occurs between two characters:



Where is Spoon?


There is no Spoon



The Spoon referenced in the dialogue was one of the characters in the film who was eaten by werewolves.


Was this a deliberate reference to The Matrix?


Answer


According to the Wikipedia page for the movie, the director, cast and crew commentary on the DVD confirms that:



The film contains homages to H.G. Wells, the films The Evil Dead,
Zulu, Aliens, The Matrix and Star Trek: The Wrath of Khan.



That means that the dialogue mention by you is directly referring to The Matrix.


actionscript 3 - How to get a time as a variable in Flash CS6

I am trying to get a time that is in a text document to become a variable in a Flash CS6 AS3 project. I can't seem to find where the problem is and the error messages aren't really helping. The highlighted parts are the changed lines.




Here is the newest code:




this.onEnterFrame = function()



{



var StartTime:URLLoader = new URLLoader();




StartTime.dataFormat=URLLoaderDataFormat.VARIABLES;



StartTime.addEventListener(Event.COMPLETE, onLoaded);



function onLoaded(e:Event):void {



}



StartTime.load(new URLRequest("ResponseTime.txt"));




var today:Date = new Date();



var currentTime = today.getTime();



var targetDate:Date = new Date();



var timeLeft = e.data - currentTime;



var sec = Math.floor(timeLeft/1000);




var min = Math.floor(sec/60);



sec = String(sec % 60);



if(sec.length < 2){



sec = "0" + sec;



}




min = String(min % 60);



if(min.length < 2){



min = "0" + min;



}



if(timeLeft > 0 ){




var counter:String = min + ":" + sec;



time_txt.text = counter;



}else{



    var newTime:String = "00:00";

time_txt.text = newTime;


delete (this.onEnterFrame);


}



}




Newest Error:





1120: Access of undefined property e. (Line 17).


linux - "while read line" giving garbage data while reading a C file

I want to write a small script of parsing all the comments of the C file using shell script but I am not even getting the read o/p correct,I am getting the file o/p mixed with other garbage data.



>/.1432804547.3007 /.1432804567.3007 /.1432804587.3007 /.1432804608.4021 /.1432804628.4021 /.1432804648.4021 /.1432804668.4021 /.1432804688.4021 /bin >/boot /dev /etc /home /lib /lib64 /lost+found /media /misc /mnt /net /opt /proc >/root /sbin /selinux /srv /sys /tmp /usr /var
>parsed_comments.tmp parse_func.sh file_update_time - update mtime and ctime time

>parsed_comments.tmp parse_func.sh @file: file accessed
>parsed_comments.tmp parse_func.sh
>parsed_comments.tmp parse_func.sh Update the mtime and ctime members of an inode and mark the inode
>parsed_comments.tmp parse_func.sh for writeback. Note that this function is meant exclusively for
>parsed_comments.tmp parse_func.sh usage in the file write path of filesystems, and filesystems may
>parsed_comments.tmp parse_func.sh choose to explicitly ignore update via this function with the
>parsed_comments.tmp parse_func.sh S_NOCMTIME inode flag, e.g. for network filesystem where these
>parsed_comments.tmp parse_func.sh timestamps are handled by the server.
>*/
>void file_update_time(struct file *file)



Here is what I am doing..



   parse_comments() {
local filename="$1"
while read line; do
echo $line | grep "*"
done < "$filename"
parse_comments "/root/rpmbuild/linux-2.6.32-431.17.1.el6.x86_64/fs/inode.c"



I have tried all the solutions(like- while read -r, while read -u 3 and other too) told on SO for while read problem none of the solution worked for me.
I don't know whats wrong with read with while loop please help...
If I use 'awk' for the same work it works fine. But 'awk' doesn't serve my purpose.

php - Warning: mysql_select_db() Access denied for user ''@'localhost' (using password: NO)



I am fairly new to web dev and I am in need of help trying to find out what the problem is. I had an install of MySQL 5.6.10 and I was given a task to update the src of a website that is currently live for past 5 years. None of the code has changed and it works for the other devs local machine. The server is running 5.0.51b and I just downgraded to 5.5.30 trying to get a syntax error to go away. The error was the SET OPTION SQL_BIG_SELECTS=1 was deprecated to SET SQL_BIG_SELECTS in a certain version. I am unable to change the syntax due to the version the server runs. So I chose to down version to 5.5.30.




My problem after the down grade is:



Warning: mysql_select_db() [function.mysql-select-db]: Access denied for user
''@'localhost' (using password: NO) in C:\Program Files (x86)\Apache Software
Foundation\Apache2.2\htdocs\****\src\www\include\func\func.db.php on line 47


I use MySQL Workbench for my connections none of the connections or users have passwords associated with them. I have another project that is not live that works fine from the localhost. My vhost and host files all have the proper syntax for this to work (verified with the other project). This all worked properly and was able to bring up the pages through vhost just fine yesterday. I never had any issues with how it was all setup to pull the index page. The only problem was the MySQL version issues. What can I do to fix this problem? I have tried recreating connections in the workbench and even deleting all the instances and recreating them. I am stumped. Any help would be greatly appreciated.


Answer




Looking closely at your error you can see that it's telling you what is wrong (typically what error reports are for):



Access denied for user
''@'localhost' (using password: NO)


Looking specifically at:



''@'localhost'
^^



You see that no user was specified. You need to specify the user you wish to connect as.



mysql_connect("HOST","USER","PASSWORD")


Which comes before a mysql_select_db call.



MySQL Connect

& MySQL Select DB



NOTICE: Don't upgrade to PHP 5.5 for MySQL_* functions have been deprecated. I say this since you do not wish to change any code.


java - Check if a specific string contains any lower/uppercase

Solution :



String name1="test";


System.out.println(name1.toLowerCase().equals(name1)); //true
System.out.println(name1.toUpperCase().equals(name1)); //false


The logic is
if the first statement is true it means the string has only lower case letters.
if the second statement is true it means the string has only upper case letters.
if both are false it means that it has a mixture of both.

php - $_SESSION wont load first attempt

I got some script. And when I input username and pass it opens some fields to fill and to udapte mysql_query..



Here is the problem:




When I fill out the fields, it redirects me on process.php page. And process.php can't recognize the session username, but when I get back and fill it agian and press Submit, it works..



It happends every time (one time) when I open browser..



index.php



session_start();
$name= $_POST['name'];
$_SESSION['name']= $name;



process.php



session_start();
$name= $_SESSION['name'];

Sunday, April 28, 2019

c++ - How can I initialize an std::vector of std::map items?



I have the following:



#include 
#include
#include

int main() {

std::vector> data = {{"close", 14.4}, {"close", 15.6}};

return 0;
}


And when I try to compile, I get the following error:




g++ -std=c++11 -Wall -pedantic ./test.cpp




./test.cpp:6:49: error: no matching constructor for initialization of 'std::vector >' (aka
'vector, allocator >, double> >')
std::vector> data = {{"close", 14.4}, {"close", 15.6}};



Answer



You need an extra pair of braces for each element/pair:



std::vector> data = {{{"close", 14.4}}, {{"close", 15.6}}};
^ ^ ^ ^



The extra pair of braces is needed because std::map elements are of type std::pair in your case std::pair. Thus, you need an extra pair of braces to signify to the compiler the initialization of the std::pair elements.


Service vs Controller vs Provider naming conventions

As i grow in my professional career i consider naming conventions very important. I noticed that people throw around controller, LibraryController, service, LibraryService, and provider, LibraryProvider and use them somewhat interchangeable. Is there any specific reasoning to use one vs the other?



If there are websites that have more concrete definitions that would be great.

plot explanation - Why does the werewolf exhale a green mist?

I have only watched a few episodes of Being Human (the original BBC series) so I may have missed something. (Just got hold of the dvds so trying to catch up.) In episode 3, George transforms into a werewolf after/during fighting Tully in the shed. He exhales a green mist just after the transformation has finished. I didn't notice this in any other episode, did it have something to do with fighting Tully? Eg, proximity of another werewolf?


Any other explanation - maybe just werewolves have very bad breath?


Answer


You didn't miss anything; you just caught something that probably doesn't matter. This never shows up or comes up in any subsequent episodes. I assume it's supposed to be simply George's breath/vapor from exhaling - just not done very well! It's so short that it might also just be a reflection mistake when filming.


Incidentally, unless there's a "pilot" episode on the DVDs that I'm not aware of, this scene actually occurs in episode 2.


algorithm - Find an integer not among four billion given ones




It is an interview question:




Given an input file with four billion integers, provide an algorithm to generate an integer which is not contained in the file. Assume you have 1 GB memory. Follow up with what you would do if you have only 10 MB of memory.




My analysis:



The size of the file is 4×109×4 bytes = 16 GB.




We can do external sorting, thus we get to know the range of the integers. My question is what is the best way to detect the missing integer in the sorted big integer sets?



My understanding(after reading all answers):



Assuming we are talking about 32-bit integers. There are 2^32 = 4*109 distinct integers.



Case 1: we have 1 GB = 1 * 109 * 8 bits = 8 billion bits memory.



Solution: if we use one bit representing one distinct integer, it is enough. we don't

need sort.
Implementation:



int radix = 8;
byte[] bitfield = new byte[0xffffffff/radix];
void F() throws FileNotFoundException{
Scanner in = new Scanner(new FileReader("a.txt"));
while(in.hasNextInt()){
int n = in.nextInt();
bitfield[n/radix] |= (1 << (n%radix));

}

for(int i = 0; i< bitfield.lenght; i++){
for(int j =0; j if( (bitfield[i] & (1< }
}
}



Case 2: 10 MB memory = 10 * 106 * 8 bits = 80 million bits




Solution: For all possible 16-bit prefixes, there are 2^16 number of
integers = 65536, we need 2^16 * 4 * 8 = 2 million bits. We need build
65536 buckets. For each bucket, we need 4 bytes holding all possibilities because the worst case is all the 4 billion integers belong to the same bucket.




  1. Build the counter of each bucket through the first pass through the file.

  2. Scan the buckets, find the first one who has less than 65536 hit.


  3. Build new buckets whose high 16-bit prefixes are we found in step2
    through second pass of the file

  4. Scan the buckets built in step3, find the first bucket which doesnt
    have a hit.



The code is very similar to above one.




Conclusion:

We decrease memory through increasing file pass.






A clarification for those arriving late: The question, as asked, does not say that there is exactly one integer that is not contained in the file -- at least that's not how most people interpret it. Many comments in the comment thread are about that variation of the task, though. Unfortunately the comment that introduced it to the comment thread was later deleted by its author, so now it looks like the orphaned replies to it just misunderstood everything. It's very confusing. Sorry.


Answer



Assuming that "integer" means 32 bits: Having 10 MB of space is more than enough for you to count how many numbers there are in the input file with any given 16-bit prefix, for all possible 16-bit prefixes in one pass through the input file. At least one of the buckets will have be hit less than 2^16 times. Do a second pass to find of which of the possible numbers in that bucket are used already.



If it means more than 32 bits, but still of bounded size: Do as above, ignoring all input numbers that happen to fall outside the (signed or unsigned; your choice) 32-bit range.




If "integer" means mathematical integer: Read through the input once and keep track of the largest number length of the longest number you've ever seen. When you're done, output the maximum plus one a random number that has one more digit. (One of the numbers in the file may be a bignum that takes more than 10 MB to represent exactly, but if the input is a file, then you can at least represent the length of anything that fits in it).


c# - Clean Up Vs Memory Reclaim in .Net



I was reading this MSDN reference:




Although the garbage collector is able

to track the lifetime of an object
that encapsulates an unmanaged
resource, it does not have specific
knowledge about how to clean up the
resource. For these types of objects,
the .NET Framework provides the
Object.Finalize method, which allows
an object to clean up its unmanaged
resources properly when the garbage
collector reclaims the memory used by

the object. By default, the Finalize
method does nothing. If you want the
garbage collector to perform cleanup
operations on your object before it
reclaims the object's memory, you must
override the Finalize method in your
class.




I understand how GC works but this give me a thought that what is actually CleanUp? Is it just reclaiming memory if it is than why it is having different name?



Answer



They used a generic phrase such as "clean up" because other things may need to be done besides just reclaiming memory. I can see how this may be a little confusing, since the quote mentions cleaning up resources and reclaiming memory in the same sentence. In that case, what they mean is that the garbage collector reclaims the memory used by the managed code that actually called into an unmanaged library (a wrapper class, for example), but leaves the unmanaged-specific reclamation process up to the developer (closing file handles, freeing buffers, etc).



As an example, I have a Graphviz wrapper library containing a Graph class. This class wraps the functions used to create graphs, add nodes to them, etc. Internally, this class maintains a pointer to an unmanaged graph structure allocated by Graphiz itself. To the .NET Framework, this is merely an IntPtr and it has no idea how to free it during garbage collection. So, when a managed Graph object is no longer being used, the garbage collector frees up the memory used by the pointer, but not the data it points to. To do this, I have to implement a finalizer that calls the unmanaged function agclose (the Graphviz function that releases the resources used by a graph).


c++ - What is most efficient way to read a file of integer in each line without opening it?




What is most efficient way to read a file of integer in each line without opening it?

I have a file with ONLY integer in each line, ie: num.txt



100
231
312
...


In my program, I use while loop to read it;




int input = 0;
while(cin >> input)
{
// Assignment
}


I use time a.out to read it in Linux
It turns out that it will take about 15 second (user time) to read 100 million numbers. So I was wondering is there any better way to decrease user time?




Thank you in advance!


Answer



int input = 0;
ios_base::sync_with_stdio(false);
//Add this statement and see the magic!
while(cin >> input)
{
// Assignment
}



To make it ultra fast (Not recommended for assignments!), use getchar_unlocked():



int read_int() {
char c = getchar_unlocked();
while(c<'0' || c>'9') c = gc();
int ret = 0;
while(c>='0' && c<='9') {
ret = 10 * ret + c - 48;
c = getchar_unlocked();

}
return ret;
}

int input = 0;
while((input = read_int()) != EOF)
{
// Assignment
}



Vaughn Cato's answer explains it beautifully.


regex - How to validate an email address in JavaScript



Regular expression to validate email address in javascript?


Answer



Using regular expressions is probably the best way. You can see a bunch of tests here (taken from chromium)



function validateEmail(email) {

var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}


Here's the example of regular expresion that accepts unicode:



var re = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;



But keep in mind that one should not rely only upon JavaScript validation. JavaScript can easily be disabled. This should be validated on the server side as well.



Here's an example of the above in action:





function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}


function validate() {
var $result = $("#result");
var email = $("#email").val();
$result.text("");

if (validateEmail(email)) {
$result.text(email + " is valid :)");
$result.css("color", "green");
} else {

$result.text(email + " is not valid :(");
$result.css("color", "red");
}
return false;
}

$("#validate").on("click", validate);





Enter an email address:










What does the css selectors ~, +, > do?

What do the CSS selectors ~, +, and > do?



I have seen these selectors many times, but it is not clear what the main difference between them is. Can someone explain the difference between these symbols? When we should use these symbols?

html - Writing regular expression in PHP to wrap with




I want to make it so that any occurance of an image gets wrapped with a link to the image source



How can I write a pattern, in PHP so that I can find these variations, which are scattered throughout text coming from the database:



blah blah blah
blah blah blah



In all cases, I want them to appear within an link.


Answer



preg_replace("{}ims", '', $str)



handles all non-practical cases



alt text


plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...