mkdir() permission denied - PHP

Question: I am trying to make an XML doc based on a HTML form input. However, once the php is executed, I get a page that says:

<code><?php
header('Content-type: text/xml');
$dom = new DOMDocument("1.0","UTF-8");
$customer = $dom->createElement("customer");
$dom->appendChild($customer);

$dir = 'XMLfiles';
if ( !file_exists($dir) ) {
 $oldmask = umask(0);  // helpful when used in linux server
 mkdir ($dir, 0744);
 }

$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
$contact = $_POST['contact'];
$password = $_POST['password'];
$cust = $dom->createElement("customer");
$customer->appendChild($cust);
$name = $dom->createElement("fname",$fname);
$cust->appendChild($name);
$emailxml = $dom->createElement("Email", $email);
$cust->appendChild($emailxml);
$contactxml = $dom->createElement("Contact", $contact);
$cust->appendChild($contactxml);
$passxml = $dom->createElement("Password", $password);
$cust->appendChild($passxml);
//$dom->saveXML();
$dom->save($dir."/customer.xml");

?>
</code>
Point me in the right direction and I will learn it.
Thanks everyone!
PS: I am trying this on a mac (if that makes any difference in giving permissions and stuff). I am new to programming, so please ignore anything that's irrelevant or advise me.
Comment: I did when I used `echo $dom->saveXML();` Check the PHP log or turn on verbose error reporting maybe
Comment: Can you remove the final `?>` from your PHP script and see what happens? or what does it look like when you view the document source?
Comment: @Scuzzy: Just did. Still the same as in the first image ( a blank xml ) :(.
Comment: Can you use `echo $dom->saveXML();` instead of `$dom->save("customer.xml");`, this will echo it inline instead of writing it disk. `$dom->saveXML();` on it's own need echo or further processing.
Comment: @Scuzzy, I thought that saveXML is for inline processing and I needed to save the XML as a file so I used save(). But yeah, I did as suggested and still the same result. Nothing being displayed.
Comment: I can't reproduce the error sorry, maybe reivew the `name="submit"` submit element of your form?
Comment: @Scuzzy, hey, I just edited the post and added the HTML form as well. I am not able to understand the error. Would the HTML code help in any way?
Comment: Maybe, I do see you reference `fname/lname` but it's `firstname/lastname` in the form. also you have `name=password` twice
Comment: @Scuzzy, that was a stupid mistake. Thanks for pointing out. Even though I changed them, I am not able to solve the error.  When you tried, did you get the XML output?
Comment: @Scuzzy, I did not use echo before $dom->saveXML() :P. Thanks heaps! But I also wanted to save it as a file. If I use save(customer.xml), where does the file get saved? How do I access the xml file on my drive?
Comment: It saves to the directory relative to the current script execution, at which point your `header('Content-type: text/xml');` is useless if you're not echoing the XML content.
Comment: @Scuzzy. I added the save(customer.xml) line and removed the header() and isset(post(submit)) and I got this error: Warning: DOMDocument::save(customer.xml): failed to open stream: Permission denied in /Applications/XAMPP/xamppfiles/htdocs/Assignment2/savecust.php on line 31. (on the line where save(customer.xml) is written. How do I add permissions?
Comment: Not sure on that one sorry, it can be system dependant (looks like mac osx which I know nothing about)
Answer: Just came across a post on apple support that explained adding permissions. I just did this :View Info -> file sharing and permissions -> changed everything to read/write.
I will close the question now.

mkdir() permission denied - PHP


How to send IPv6 packets from different addresses under my prefix?

Question: I am trying to figure out how to make use of all of the addresses I have on my VPS with a /64 ipv6 prefix. However, when I try to send messages they always exit via the address assigned to the interface, I can't figure out how to get them to leave via a specific IP.
Here is my ifconfig output for the relevant interface:
ens3: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 51.x.y.z  netmask 255.255.255.255  broadcast 0.0.0.0
        inet6 fe80::i:j:k:1c0  prefixlen 64  scopeid 0x20<link>
        inet6 2607:a:b:c::55  prefixlen 64  scopeid 0x0<global>
        ether fa:16:l:m:n:o  txqueuelen 1000  (Ethernet)

When I check my IPv6 via CLI I clearly get:
# curl icanhazip.com
2607:a:b:c::55

If my understanding is correct 2607:a:b:c:1::55 is also an IP under my range. How would I send a message via that IP? My expected result would then be:
# curl icanhazip.com
2607:a:b:c:1::55

Thanks!
Answer: Assuming you want to use a different IPv6 address for a one-shot job or a short period, you can simply add (or change) an IP address using the ip command eg:
ip addr add 2607:a:b:c:1::55 dev eth0 valid_lft 120 preferred_lft 120

In this example you add an IP address to interface eth0 with a lifetime of just 2 minutes.
You can also tell Curl to use a specific interface/outbound IP address using the --interface option.
Also have a look at the valid_lft & preferred_lft directives.
Comment: You can of course have multiple addresses enabled. This is just an example. There are different ways to set this up in Linux, like for example virtual interfaces. Then you have to tell programs which IP address/interface to use or they will fall back on a default/random one.
Comment: I was hoping to assign multiple addresses permanently. This method means my original IP address isn't usable while the other is active.
Comment: So something like `ip link add dev virtual0 type ` then `ip addr add IPv6/prefix dev virtual0`?


finding maximum value in python list of tuples

Question: I have a list of tuples (list):
('2015-06-19', 3453455, 5, 'Scheduled')
('2015-05-19', 6786788, 6, 'Overdue')
('2015-04-19', 2342344, 2, 'Not Received')
('2015-03-19', 9438549, 0, 'Not Received')
('2015-02-19', 6348759, 7, 'Not Received')

When I run this, I get this:
>>> print(max(list))
('2015-06-19', 3453455, 5, 'Scheduled')

Obviously, max(list) determined the max based on the first value in the list of tuples. I'm just wondering if this is the default behavior of max(list) in regards to a list of tuples; to check only the first item in the tuple?
And, what if I wanted to return the tuple with the maximum based on the second item/column. How would I do that?
Comment: See this: http://stackoverflow.com/questions/5292303/python-tuple-comparison
Comment: it would check the subsequent values if the first value of any tuple matches.
Comment: You can change this behavior if you like: `max(tup_list, key= lambda x: x[1])`
Answer: You can specify which field to use for comparison using lambdas
max(list,key=lambda x:x[1])

or alternatively, using itemgetter
from operator import itemgetter
max(list,key=itemgetter(1))

Comment: great answer, i always prefer `itemgetter` which is faster


Logback to Elasticsearch through yaml or properties

Question: I have many spring based microservice project where I used Logback to Elasticsearch for saving all logs to Elastic search index. I have configured using xml based on some tutorials I got. The configuration is based on xml like as shown below. Instead of xml how can we configure Logback to Elasticsearch using yaml or key value property files.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <springProperty scope="context" name="microserviceName"
        source="spring.application.name" />
    <springProperty scope="context" name="profile"
        source="spring.profiles.active" />
    <springProperty scope="context" name="myESHost"
        source="logging.esHost" />
    <springProperty scope="context" name="myESPort"
        source="logging.esPort" />
    <springProperty scope="context" name="myESLoggingLevel"
        source="logging.esLoggingLevel" />
    <springProperty scope="context" name="consoleLoggingLevel"
        source="logging.consoleLoggingLevel" />

    <appender name="ELASTIC" class="com.internetitem.logback.elasticsearch.ElasticsearchAppender">
        <url>http://${myESHost}:${myESPort}/_bulk</url>
        <index>logs-%date{yyyy-MM-dd}</index>
        <type>tester</type>
        <loggerName>es-logger</loggerName>
        <errorLoggerName>es-error-logger</errorLoggerName>
        <connectTimeout>30000</connectTimeout>
        <errorsToStderr>false</errorsToStderr>
        <includeCallerData>false</includeCallerData>
        <logsToStderr>false</logsToStderr>
        <maxQueueSize>104857600</maxQueueSize>
        <maxRetries>3</maxRetries>
        <readTimeout>30000</readTimeout>
        <sleepTime>250</sleepTime>
        <rawJsonMessage>false</rawJsonMessage>
        <includeMdc>false</includeMdc>
        <maxMessageSize>100</maxMessageSize>
        <authentication class="com.internetitem.logback.elasticsearch.config.BasicAuthentication" />
        <properties>
            <property>
                <name>host</name>
                <value>${HOSTNAME}</value>
                <allowEmpty>false</allowEmpty>
            </property>
            <property>
                <name>severity</name>
                <value>%level</value>
            </property>
            <property>
                <name>thread</name>
                <value>%thread</value>
            </property>
            <property>
                <name>stacktrace</name>
                <value>%ex</value>
            </property>
            <property>
                <name>logger</name>
                <value>%logger</value>
            </property>
        </properties>
        <headers>

                <name>Content-Type</name>
                <value>text/plain</value>

        </headers>
    </appender>

    <root level="info">
        <appender-ref ref="FILELOGGER" />
        <appender-ref ref="ELASTIC" />
    </root>

    <logger name="es-error-logger" level="INFO" additivity="false">
        <appender-ref ref="FILELOGGER" />
    </logger>

    <logger name="es-logger" level="INFO" additivity="false">
        <appender name="ES_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">

            <encoder>
                <pattern>%msg</pattern>
            </encoder>
        </appender>
    </logger>

</configuration>

Comment: Does this help: https://stackoverflow.com/questions/42648195/how-to-set-logback-xml-properties-in-application-yaml ?
Comment: @Val Thanks for the reply, that SO link actually tells how to import yaml to logback.xml...what I was looking is to convert th logback.xml to yaml file
Comment: Doh, sorry, I got it reversed :-)
Answer: That is possible. The configuration would go to the application.yml file (see https://springframework.guru/using-yaml-in-spring-boot-to-configure-logback). Having many services to configure this may not be a solution for you as the configuration gets mangled with each services configuration.
To keep things separated you could use groovy (https://springframework.guru/logback-configuration-using-groovy), if you have it, or try to incorporate a logback.yml via external configuration files (https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html) which I have not used yet.
Comment: Thanks for the answer....I still could not figure it out how to write those `springProperty`, `appender` and `root` in yaml file
Comment: There are xml to yaml converters out there, did you try them? Maybe https://codebeautify.org/xml-to-yaml.


Error logging with PHP and mod_fcgid

Question: I have a mediawiki install that is acting up. Whenever I try to save an article, it goes to a blank screen. All though if I refresh that blank screen, it will go on to work.
I have no idea why it's doing that, but it seems to be that it's a problem with PHP. I guess by default errors don't get logged when using mod_fcgid, because I can't find an error log anywhere. I tried enabling logging in the /etc/php5/cgi/php.ini, but that didn't do anything. How do I achieve php error logging? I'm using ubuntu 9.10.
Comment: have you checked the apache error log?
Comment: yes but it has nothing
Answer: The solution was to change the debug settings in the apache config from "warn" to "debug". Now apache outputs helpful error messages from PHP.

Error logging with PHP and mod_fcgid


Allow anonymous upload for Vsftpd?

Question: I need a basic FTP server on Linux (CentOS 5.5) without any security measure, since the server and the clients are located on a test LAN, not connected to the rest of the network, which itself uses non-routable IP's behind a NAT firewall with no incoming access to FTP.
Some people recommend Vsftpd over PureFTPd or ProFTPd. No matter what I try, I can't get it to allow an anonymous user (ie. logging as "ftp" or "anonymous" and typing any string as password) to upload a file:
# yum install vsftpd

# mkdir /var/ftp/pub/upload

# cat vsftpd.conf
listen=YES
anonymous_enable=YES
local_enable=YES
write_enable=YES
xferlog_file=YES

#anonymous users are restricted (chrooted) to anon_root
#directory was created by root, hence owned by root.root
anon_root=/var/ftp/pub/incoming
anon_upload_enable=YES
anon_mkdir_write_enable=YES

#chroot_local_user=NO
#chroot_list_enable=YES
#chroot_list_file=/etc/vsftpd.chroot_list
chown_uploads=YES

When I log on from a client, here's what I get:

500 OOPS: cannot change directory:/var/ftp/pub/incoming

I also tried "# chmod 777 /var/ftp/incoming/", but get the same error.
Does someone know how to configure Vsftpd with minimum security?
Thank you.

Edit: SELinux is disabled and here are the file permissions:
# cat /etc/sysconfig/selinux
SELINUX=disabled
SELINUXTYPE=targeted
SETLOCALDEFS=0

# sestatus
SELinux status:                 disabled
# getenforce
Disabled

# grep ftp /etc/passwd
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin

# ll /var/
drwxr-xr-x  4 root root 4096 Mar 14 10:53 ftp

# ll /var/ftp/
drwxrwxrwx 2 ftp ftp 4096 Mar 14 10:53 incoming
drwxr-xr-x 3 ftp ftp 4096 Mar 14 11:29 pub

Edit: latest vsftpd.conf:
listen=YES
local_enable=YES
write_enable=YES
xferlog_file=YES

#anonymous users are restricted (chrooted) to anon_root
anonymous_enable=YES
anon_root=/var/ftp/pub/incoming
anon_upload_enable=YES
anon_mkdir_write_enable=YES

#500 OOPS: bad bool value in config file for: chown_uploads
chown_uploads=YES
chown_username=ftp

Edit: with trailing space removed from "chown_uploads", err 500 is solved, but anonymous still doesn't work:
client> ./ftp server
Connected to server.
220 (vsFTPd 2.0.5)
Name (server:root): ftp
331 Please specify the password.
Password:
500 OOPS: cannot change directory:/var/ftp/pub/incoming
Login failed.
ftp> bye

With user "ftp" listed in /etc/passwd with home directory set to "/var/ftp" and access rights to /var/ftp set to "drwxr-xr-x" and /var/ftp/incoming to "drwxrwxrwx"...could it be due to PAM maybe? I don't find any FTP log file in /var/log to investigate.

Edit: Here's a working configuration to let ftp/anonymous connect and upload files to /var/ftp:
listen=YES
anonymous_enable=YES
write_enable=YES
anon_upload_enable=YES
anon_mkdir_write_enable=YES

Comment: with chown_uploads you should also set chown_username
Comment: Now, I'm getting "bad bool value in config file for: chown_uploads" :-/
Comment: look if there is some kind of non-visible character in the conf file
Comment: @user15318: The vsftpd.conf you have posted above works fine on a CentOS system I have to hand. Are there any relevant messages in /var/log/messages ?
Comment: Indeed, there was an extra space at the end. Thanks for the tip.
Comment: @ian: No, the user logs on successfully: CONNECT: Client "192.168.0.9" [ftp] OK LOGIN: Client "192.168.0.9", anon password "test"
Comment: For me, the parameter `write_enable=YES` was missing. Reading your settings solved my issue.
Answer: You have created a dir called pub/upload:
# mkdir /var/ftp/pub/upload

But then you configured uploads to go to pub/incoming:
anon_root=/var/ftp/pub/incoming

So it's a simple path mismatch, all the rest seems OK.
Answer:
For anonymous logins, change the "ftp" users home directory in /etc/passwd.
ftp:x:119:131:ftp daemon,,,:/var/ftp/pub/:/bin/false

And add this to your /etc/vsftpd.conf file.
allow_writeable_chroot=YES

And make sure that the ftp user has access (chmod 755) to enter every directory up to the location /var/ftp/pub/

I was fighting this problem for hours. vsftpd doesn't give clear help or suggestions for errors.
Answer: You probably have SE linux enabled. Rather than disable the whole thing you can use
/usr/sbin/setsebool -P ftp_home_dir 1
to allow ftp to work correctly.
EDIT
Looking over this again, if the commands above are what you really typed then /var/ftp/pub/incomming doesn't exist so make sure it does then try again.
Comment: Thanks for the tip, but SELinux is disabled: # /usr/sbin/setsebool -P ftp_home_dir 1 : "setsebool:  SELinux is disabled."
Answer: You probably have userlist_deny=NO in your conf file. Change it to YES and make sure that the username you're using isn't in /etc/vsftpd/user_list or in /etc/vsftpd/ftpusers.
Answer: here is what worked for me (he said, while mentally strangling a developer)
vsftpd.conf:
anonymous_enable=YES
anon_upload_enable=YES
anon_mkdir_write_enable=YES
anon_root=/var/ftp/

create/chown Directories
mkdir /var/ftp
chown nobody:nogroup /var/ftp
mkdir /var/ftp/uploads
chown ftp:ftp /var/ftp/uploads
#edit for good measure also (gave me grief with pure-ftpd)
chmod 777 /var/ftp/uploads

change homedir in
/etc/passwd:

    ftp:x:116:124:ftp daemon,,,:/var/ftp:/usr/sbin/nologin

(default home dir on debian is /srv/ftp so you can make yo life
easier sticking to that dir)
uploads are possible to /var/ftp/uploads
SElinux/Apparmor is disabled on this system, debian 10.3
Note: vsftp will throw an errormessage if the initial homedirectory
has rw rights (aka chown ftp:ftp) on /var/ftp directly
Edit note: with the faint hope, this whole text is somewhat understandable.
Klaus
Answer: Is SE linux enabled. Folks in that forum were able to resolve the issue by disabling SE linux.
http://rackerhacker.com/2007/06/14/500-oops-error-from-vsftpd/
Comment: Thanks for the tip, but still no go: SELinux is disabled, and the dir/file permissions seems OK. I edited the question.
Comment: Disabling SELinux is a bad idea, especially when it's blindly used to "solve" a problem with configuration.

Allow anonymous upload for Vsftpd?


Building a USB Tree in Objective C

Question: I am trying to build a tree to store USB device information.  I thought that I would use NSMutableArray and NSMutableDictionary to contain this information.  My problem is that I've never studied software engineering - I'm learning as I go - and I haven't the faintest idea about tree theory.
I'm basing my tree on the USB Location ID, which is eight nibbles long.  As I understand it, each nibble represents a layer of the tree (if you see what I mean).  I've written a little bit of test code to see if I can build my tree properly - and, sadly, it seems that I can't!
#import <Foundation/Foundation.h>

#define MAXCHILDREN 0xf

NSDictionary* AddItemToTree(NSDictionary* nodeEntry, unsigned int value, int depth)
{
    // Convert the value into a set of nibbles
    char *bytes = (char *)&value;
    char byte = bytes[depth];

    NSMutableDictionary* thisEntry = [[[NSMutableDictionary alloc] initWithDictionary:nodeEntry] autorelease];

    if (byte == 0)
    {
        [thisEntry setObject:[NSString stringWithFormat:@"%08x",value] forKey:@"Value"];
        [thisEntry setObject:[NSString stringWithFormat:@"%08x",byte] forKey:@"Byte"];
        [thisEntry setObject:[NSNumber numberWithInt:depth] forKey:@"Depth"];

        return thisEntry;
    }

    if(![[thisEntry allKeys]containsObject:@"ChildEntries"])
    {
        NSMutableArray* childArray = [[NSMutableArray alloc]init];
        NSMutableDictionary* newNode = [[NSMutableDictionary alloc] init];

        [childArray addObject:AddItemToTree(newNode,value,++depth)];

        [thisEntry setObject:[NSNumber numberWithInt:depth] forKey:@"Depth"];
        [thisEntry setObject:[NSString stringWithFormat:@"%08x",value] forKey:@"Value"];
        [thisEntry setObject:[NSString stringWithFormat:@"%08x",byte] forKey:@"Byte"];
        [thisEntry setObject:childArray forKey:@"ChildEntries"];

        [newNode release];
        [childArray release];

    }
    else
    {
        [[thisEntry objectForKey:@"ChildEntries"]addObject:AddItemToTree(thisEntry,value, ++depth)];

    }

    return thisEntry;
}

int main(int argc, char *argv[]) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSMutableDictionary* treenode=[[NSMutableDictionary alloc]init];

    char bytearray[4] = {0x0F, 0x0F, 0x02, 0x00};
    unsigned int *value = (unsigned int*)bytearray;
    char bytearray2[4] = {0x0F, 0x02, 0x00, 0x00};
    unsigned int *value2 = (unsigned int*)bytearray2;
    char bytearray3[4] = {0x0F, 0x02, 0x00, 0x00};
    unsigned int *value3 = (unsigned int*)bytearray3;

    [treenode setObject:[NSNumber numberWithInt:0] forKey:@"Depth"];
    [treenode setObject:[NSString stringWithFormat:@"%08x",*value] forKey:@"Value"];
    [treenode setObject:AddItemToTree(treenode,*value, 0) forKey:@"ChildEntries"];

//    [[treenode objectForKey:@"ChildEntries"]addObject:AddItemToTree(treenode,*value2, 0)];

    [treenode writeToFile:@"/Users/headbanger/Desktop/test.plist" atomically:YES];

    [pool release];
}

Adding one USB location ID works perfectly.  Adding a second (by uncommenting-out the line in main) causes SIGABRT.  I'm sure that it's perfectly simple, and I've committed a typical newbie error.  However, it's not obvious to me and any help that you can provide would be more than welcome.
My tree will need to look something like this:
F-
 |--F-
 |   |--2
 |
 |--2

This tree should be true even if an attempt is made to add the third byte array.If you can answer the question without being USB specific then that would be most helpful, because I'd really like to understand about trees and what I've done wrong.  That said, if there's a quick and easy way to get a tree built for me in Objective-C then I'd love to hear it.So please, experts, can someone tell me what I'm doing wrong? Thank you for your time.
Comment: I think you need to get a big sheet of paper and walk through your algorithm on paper.  Generally your tree root should be a global pointer that isn't changed once the root is allocated.
Comment: Hot Licks, thank you for taking the time to reply.  I'm not certain that I entirely understand your suggestion - I did walk through already on paper (I'd never have gotten as far as I have, otherwise!)  Do you know of any tutorials that I can follow?  Or could you provide a specific suggestions with reference to my code.  That might help me understand what you mean.
Comment: @HotLicks: Why should it be global? Globals are usually ill-advised.
Comment: Globals are relative.  The root should be anchored somewhere outside of the method.
Comment: @HotLicks: That doesn't conform to any definition of "global" I've ever encountered.
Comment: If I were doing this (and I was bound and determined to build a real tree, vs taking a shortcut) I'd probably create a dictionary for the root and for each node in the tree.  The dictionary for the root would contain name/value pairs to identify all the 1st-level branches.  Each node (representing a branch) would contain name/value pairs for sub-branches.  (The "name" in this case is the "nibble" value, and the "value" is the next level of the tree.)
Comment: @MarceloCantos - Then you haven't encountered very many definitions.
Comment: In `else` you are calling a`ddObject:` but the object in CHildEntries is a dicctionary. You can catch these errors easy if you activate NSZombieEnabled, and enable catching all exceptions (the later you do it in breakpoint navigator (cmd+6), pressing the + at the bottom left). If you like, you can also use ARC and skip all the retain/release stuff.
Comment: @HotLicks: Your relative notion of global isn't found on the relevant [Wikipedia entry](http://en.wikipedia.org/wiki/Global_variable) or, I'd hazard to guess, any mainstream book on programming theory or practice. Perhaps you're thinking of class-static variables, which are merely namespace-qualified globals, and which are also ill-advised for the same reasons as regular globals. Otherwise, I'm at a loss as where you got your definition from.
Comment: @MarceloCantos - I've been programming for 40 years.  I know what I'm talking about far better than Wikipedia does.  "Global" is a relative term, as in "a more global scope".
Comment: @HotLicks: I've only been doing this for about 28 years. I guess that extra 12 years makes all the difference. Maybe 12 years from now, I'll just intuitively "know" about relative globals without having to read about them somewhere. Or perhaps it was only in the 70's that such knowledge could be acquired, and I've simply missed out. In any event, it would be nice to have somewhere to refer to so I'm not forced to appeal to the authority of one person (Isn't that some kind of logical fallacy?). BTW, when you say, "a more global scope," it sounds like you meant to say, "an outer scope".
Comment: The extra 12 years means that I've dealt with languages like Pascal and Modula that have rather complex models of scope.
Comment: @HotLicks: My day job involves a lot of Pascal (Delphi). I can't think of any scoping construct in there that matches your notion of a global that isn't absolutely global. All the constructs that come to mind (module-level var, function-level const, static class fields, etc.) are essentially globals in that they represent singletons with respect to the process. The only difference between them is visibility. Are you suggesting that the OP's tree needs to be a singleton? If so, I'd still dispute that, but at least then we'd be on the same page.
Comment: Whatever.  You use your terms and I'll use mine.  They're not written in stone.
Answer: One problem is that you set dictionary as the type of the ChildEntries:
[treenode setObject:AddItemToTree(treenode,*value, 0) forKey:@"ChildEntries"];

but elsewhere you attempt to use it as a NSMutableArray (mind the addObject: method):
[[thisEntry objectForKey:@"ChildEntries"]addObject:AddItemToTree(thisEntry,value, ++depth)];

To fix it, in your main you could do
[treenode setObject:[[NSMutableArray alloc] initWithObjects:AddItemToTree(treenode,*value, 0), nil]forKey:@"Children"];

but even when your recursion progresses towards the 0x00 byte if (byte==0), I think, from mentally inspecting it, that it's going to add duplicated children and produce a reeeally deep tree.
There is something wrong with your environment if you didn't get a message warning you of the wrong method addObject with the SIGABORT.
Btw, it's hard to read. Lines like these
[treenode setObject:[[NSMutableArray alloc] initWithObjects:AddItemToTree(treenode,*value, 0), nil]forKey:@"Children"];

are easier to scan and less prone to mistakes if you write:
NSString * const kChildren = @"Children";
// ...
NSMutableArray *children = [[NSMutableArray alloc] initWithObjects:AddItemToTree(treenode,*value, 0), nil];
[treenode setObject:children forKey:kChildren];

The style is not very objective-c-ish, you could use NSUInteger and NSData instead unsigned int and char arrays.

You should first write a generic tree, then use it for your purposes. This is my tree example. It's ugly but it's mine. As you see, it's common sense. You could set conditions like, two childs per node, and left child < root < right child, and then you would get a binary search tree which has better properties to find stuff. But that will take you a lot more code I guess.
#import <Foundation/Foundation.h>

typedef NS_ENUM(unsigned char, MyTreeVisitingOrder) {
    MyTreeOrderDepthFirst,
    MyTreeOrderValueFirst
};

#define Tree NSObject<MyTree>

@protocol MyTree
@property (nonatomic,strong) NSObject<NSCopying>* key;
@property (nonatomic,strong) NSObject *value;
@property (nonatomic,strong) NSMutableDictionary *children;
-(void) insertChild:(Tree*)node;
-(void) each:(void(^)(NSObject*))block order:(MyTreeVisitingOrder)order;
@end

@interface TreeImpl : NSObject <MyTree>
-(id) init __attribute__((unavailable("disabled")));
@end

@implementation TreeImpl

@synthesize key = _key;
@synthesize value = _value;
@synthesize children = _children;

-(id) initWithKey:(NSObject<NSCopying>*)key value:(NSObject*)value {
    self = [super init];
    if (self){
        _key = key;
        _value = value;
        _children = [NSMutableDictionary new];
    }
    return self;
}

-(void) insertChild:(Tree*)node {
    [_children setObject:node forKey:node.key];
}

-(void) each:(void(^)(NSObject*))block order:(MyTreeVisitingOrder)order {
    switch (order) {
        case MyTreeOrderDepthFirst:{
            if (_children) {
                for (id key in _children){
                    [[_children objectForKey:key] each:block order:order];
                }
            }
            block(_value);
            break;
        }
        case MyTreeOrderValueFirst:{
            block(_value);
            if (_children) {
                for (id key in _children){
                    [[_children objectForKey:key] each:block order:order];
                }
            }
            break;
        }
    }
}

@end

int main(int argc, char *argv[]) {
    @autoreleasepool {

        TreeImpl *a = [[TreeImpl alloc] initWithKey:@"A" value:@"A"];
        TreeImpl *b = [[TreeImpl alloc] initWithKey:@"B" value:@"B"];
        TreeImpl *c = [[TreeImpl alloc] initWithKey:@"C" value:@"C"];
        [a insertChild:b];
        [a insertChild:c];

        [a each:^(NSObject* value) {
            NSLog(@"> %@",value);
        } order:MyTreeOrderValueFirst];
        return EXIT_SUCCESS;
    }
}

Comment: Jano, I will give this a go and see if I have the wit to adapt it to my purposes.  I still can't see what's wrong with my attempt though - are you able to identify what I've mucked up in my code (I was feeling quite pleased with my first stab at a tree!)
Comment: It's clever, but you should aim to write it so you don't have to execute the code mentally to understand it. That often means splitting code in methods that do one thing only. Don't aim for short code, aim for readability from a high level.
Comment: Wow!  Thank you for your help.  The tree isn't deep - and, as I say, it works for one usb entry (the trouble comes when adding additional entries!)  Looking at your example code, I thought I could try to use that - see if I could understand what's going on.  I can't though.  I'm afraid that I can't work out how to call it.  What would the 'main' be for an example use of your code? I'm not too worried about search speed - after all, it can only be a maximum of 16*8 devices.  Not too onerous on a modern system.
Comment: oh I was wrong I guess. I'll edit with a working example tomorrow (if I remember!). But if your example works as it is now, all good.
Comment: Sadly, my example doesn't work for anything other than one entry.  I'm still bashing my brains out with it!
Comment: Ah!  Got it, with your help.  Thank you all - and sorry for my delay in responding to you.

Building a USB Tree in Objective C


PacketInputStream not moving ahead bytes

Question: I have a PacketInputStream class like this:
public class PacketInputStream extends DataInputStream {

    private static final Charset UTF8 = Charset.forName("UTF-8");

    public PacketInputStream(InputStream myis) {
        super(myis);
    }

    public String readString() throws IOException {
        int length = readVarInt();
        byte[] data = new byte[length];
        readFully(data);
        return new String(data, UTF8);
    }

    public int readVarInt() throws IOException {
        int i = 0;
        int j = 0;
        while (true) {
            int k = read();
            if (k == -1)
                throw new IOException("End of stream");

            i |= (k & 0x7F) << j++ * 7;

            if (j > 5)
                throw new IOException("VarInt too big");

            if ((k & 0x80) != 128)
                break;
        }

        return i;
    }

    public long readVarLong() throws IOException {
        long varInt = 0;
        for (int i = 0; i < 10; i++) {
            byte b = readByte();
            varInt |= ((long) (b & (i != 9 ? 0x7F : 0x01))) << (i * 7);

            if (i == 9 && (((b & 0x80) == 0x80) || ((b & 0x7E) != 0)))
                throw new IOException("VarInt too big");
            if ((b & 0x80) != 0x80)
                break;
        }

        return varInt;
    }

    public byte[] readBytes() throws IOException {
        return readBytes(readShort());
    }

    public byte[] readBytes(int length) throws IOException {
        if (length < 0)
            throw new IOException("Invalid array length");
        byte[] data = new byte[length];
        readFully(data);
        return data;
    }

}

And I have this code running:
System.out.println("Logic data version (always 0) : " + is.readVarInt());
        System.out.println("User ID: " + is.readVarLong());
        System.out.println("Home ID: " + is.readVarLong());

is is defined
Now the problem I am having is that it is always showing me 0 as the returned number.
Here is the first bit of the inputstream:
00000000000000030035C708000000030035C708010000004 Now as you can see it shouldn't be giving 0 each time for the first 3 so where is the error and how can I fix it?
Thanks :)
Comment: How do you think that an int is represented on your file? You are reading bytes, but the composition and termination condition look very funny to me. - Is the User ID supposed to be 3?
Comment: Looks like `readVarInt()` and `readVarLong()` use variable-length integer encoding, so the result you are getting is not unexpected.
Comment: Did you write this class PacketInputStream?
Answer: Either your way of input is not as per the code or the code is not as per the input. Here is how I could execute the code:
main()
public static void main(String[] args) throws Exception {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byteArrayOutputStream.write(new byte[] { 0, 3,
            4, 5, (byte)128, 0, 0, 3, 0, 0, 3, 5, 0XC, 7, 0, (byte)8, 0, 0, 0, 0, 0, 0,
            0, 3, 0, 0, 3, 5, 0XC, 7, 0, 8, 0, 1, 0, 0, 0, 0, 0, 0, 4 });
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
            byteArrayOutputStream.toByteArray());
    PacketInputStream is = new PacketInputStream(byteArrayInputStream);
    System.out
            .println("Logic data version (always 0) : " + is.readVarInt());
    System.out.println("User ID: " + is.readVarLong());
    System.out.println("Home ID: " + is.readVarLong());
}

More items to look into:

Why i |= (k & 0x7F) << j++ * 7;? why not i |= (k & 0xFF) << j++ * 7;
Why int k = read();' and notbyte k = readByte();`? Is varinteger size > varlong size where you read by byte?
Why if ((k & 0x80) != 128) and not if ((k & 0x80) == 128)? I believe if ((k & 0x80) != 128) is the condition you look forward to terminate reading integer.
Should if ((b & 0x80) != 0x80) be if ((b & 0x80) == 0x80)?

Below is the modified class which I tried to read varint followed by two varlong for my input:
    class PacketInputStream extends DataInputStream {

        private static final Charset UTF8 = Charset.forName("UTF-8");

        public PacketInputStream(InputStream myis) {
            super(myis);
        }

        public String readString() throws IOException {
            int length = readVarInt();
            byte[] data = new byte[length];
            readFully(data);
            return new String(data, UTF8);
        }

        public int readVarInt() throws IOException {
            int i = 0;
            int j = 0;
            while (true) {
                byte k = readByte();
                if (k == -1)
                    throw new IOException("End of stream");

                i |= (k & 0xFF) << j++ * 7;

                if (j > 5)
                    throw new IOException("VarInt too big");

                if ((k & 0x80) == 128)
                    break;
            }

            return i;
        }

        public long readVarLong() throws IOException {
            long varInt = 0;
            for (int i = 0; i < 10; i++) {
                byte b = readByte();
                varInt |= ((long) (b & (i != 9 ? 0x7F : 0x01))) << (i * 7);

                if (i == 9 && (((b & 0x80) == 0x80) || ((b & 0x7E) != 0)))
                    throw new IOException("VarInt too big");
                if ((b & 0x80) == 0x80)
                    break;
            }

            return varInt;
        }

        public byte[] readBytes() throws IOException {
            return readBytes(readShort());
        }

        public byte[] readBytes(int length) throws IOException {
            if (length < 0)
                throw new IOException("Invalid array length");
            byte[] data = new byte[length];
            readFully(data);
            return data;
        }

    }


Should I down-grade to Drupal 6.x? There seems to be much better support!

Question: If I'm only looking to throw some easy-to-use modules together for a client and then put the Zen theme on, should I stick to Drupal 6.x? I've noticed in my exploration of Drop-down menus in 7.x that there is very little support for it in the form of modules.
Answer: Drupal 6 is certainly an option, and it will likely retain a sizable installed-base for some time to come, until February 24, 2016, the date after which Drupal 6 will not be anymore supported and it will not receive any security fix.
That said, Drupal 7 is where the focus is now; it will continue to be in the future, until November 1, 2023, the date of the Drupal 7 end-of-life, the date after which no security issues will be fixed for Drupal 7.
In my experience, the simple/basic/popular modules are already quite well supported in Drupal 7; only the more "exotic" modules have not been ported to Drupal 7, yet.
I've moved my site to Drupal 7 with relatively few issues; Drupal-7-specific documentation, or the lack of it, can be a challenge.
With regards to drop-down menus, Superfish is a Drupal 7 module with releases for Drupal 8 and Drupal 9 too. At least, the 8.x-1.4 release is reported to be compatible with both those Drupal releases, but some issues need to still be fixed, to warranty a complete compatibility with Drupal 9 or Drupal 10.


Amazon CodeDeploy failing on invalid certificate

Question: For the past year or so, I've been deploying to AMI ubuntu-trusty-14.04-amd64-server-20150325 (ami-d85e75b0) running on C3.large instances with Amazon CodeDeploy. I'm using the standard user-data script from the documentation to install the CodeDeploy agent:
#!/bin/bash
apt-get -y update
apt-get -y install awscli
apt-get -y install ruby2.0
cd /home/ubuntu
aws s3 cp s3://aws-codedeploy-us-east-1/latest/install . --region us-east-1
chmod +x ./install
./install auto

I recently found that I needed the performance offered by an M4.large, but in order to do that I needed to be running on HVM virtualization type, so I fired up ubuntu-trusty-14.04-amd64-server-20160114.5 (ami-fce3c696), SSD Volume AMI Type using the same exact script.
When I tried to deploy with CodeDeploy this time, CodeDeploy wasn't reporting any events, so I ssh'd into the new instance to read the CodeDeploy logs, and found two interesting lines:
2016-04-01 20:49:25 ERROR [codedeploy-agent(2080)]: Error validating
    the SSL configuration: Invalid server certificate
2016-04-01 20:49:25 ERROR [codedeploy-agent(2080)]: booting child:
    error during start or run: SystemExit - Stopping CodeDeploy agent
    due to SSL validation error.
    - /opt/codedeploy-agent/lib/instance_agent/plugins/codedeploy/command_poller.rb:53:in `abort'

I can't seem to find anything in the docs that is useful, and the few reports of this issue that I found via Google talked about HTTP proxys and SSL environment variables. This just confused me because there's no mention of any of these things in the docs.
Does anybody know what might be going on here?
Comment: Check if the E2C instance has internet access. It can be the cause of your problem. Best,
RMRodrigues
Comment: @rmrodrigues is right (at least in my case). It was down to my VPC routing improperly set up, so the new instance didn't have any Internet access.
Answer: I had this same problem. CodeDeploy had been working for a couple years with various personal projects on the same server. Last week, I noticed any attempted deployment failed with this error.
All of the (scant) advice found online was either not applicable or didn't do anything. I had no special SSL environment variables set. I had the latest version of the codedeploy agent. I even updated everything with yum update.
Solution: Restart the server.
No joke.
I had enabled verbose logs in /etc/codedeploy-agent/conf/codedeployagent.yml, and I restarted the server just to make sure it took effect. All deployments began working again.
Have you tried turning it off and turning it back on again?
Comment: Lol, wth, I've been staring at this problem for a few days and then find your post, restarted, worked. Thank you for saving my sanity, haha.


Perda de informação ao ordenar um datatable dentro de uma Modal com AJAX

Question: Boa Tarde.
Tenho uma lista ação que abre uma modal e exibe uma série de informações com paginação dentro de um datatable, e quero dar a opção do usuario ordenar essa informação, porem ao clicar no icone de order, independente de qual atributo eu uso pra ordenar, os dados somem, gostaria de pensar em uma solução que nao precisasse fazer uma nova consulta ao banco somente com os dados que já foram carregados. Segue códigos.
    $('#modalCandidatos').on('show.bs.modal', function (e) {
    $('#loader').removeClass('d-none');
    $('#candidatos').addClass('d-none');
    $('#vaga-vazia').addClass('d-none');

    var button = $(e.relatedTarget);
    var recipient = button.data('id-vaga');

    $('#lista_candidatos').empty();

    $.ajax({
      url: '/candidatos_vaga/'+recipient,
      type: 'get',
      dataType: 'json',
      success:function(data)
      {

        if(data.candidatos.length == 0){
          $('#loader').addClass('d-none');
          $('#vaga-vazia').removeClass('d-none');
        }
        else{
          $('#loader').addClass('d-none');
          $('#candidatos').removeClass('d-none');
          for (var i = 0; i < data.candidatos.length; i++) {

            var nome = '';

            if(data.candidatos[i].status == 1){
              nome = ''+data.candidatos[i].nome+'Novo	';
            }
            else{
              nome = ''+data.candidatos[i].nome+'	';
            }

            $('#lista_candidatos').append(
            '
'+
                nome+
                ''+data.candidatos[i].cidade+'/'+data.candidatos[i].estado+'	'+
                ''+data.candidatos[i].curriculo+'%	'+
                ''+
                  'Ver currículo'+
                '	'+
            '
'
            );
          }
        }
      }
    });
  });

Codigo ajax que recebe a ação de exibir e popular a modal. Codigo abaaixo é da modal

Candidatos à vaga

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

Carregando...

Nenhum currículo cadastrado para essa vaga.

                          Nome
                          Cidade
                          Currículo
                          Ações

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>

Ele atualiza a pagina em vez de somente ordenar os dados. Grato.
Answer: È o  modo que você está limpado a table com o
$('#lista_candidatos').empty();
coloca ele depois do success do ajax
Comment: Vou testar aqui, já te dou o retorno, Obrigado!
Comment: Nao funcionou : /. ai continua sumindo com os dados
Comment: pode ser o modo que você esteja limpado a table com o `$('#lista_candidatos').empty();` coloca ele depois do `success` do `ajax`
Comment: Foi isso mesmo, um colega de trabalho chegou na mesma conclusão hahaha. Obrigado. responde ae pra eu marcar como resposta.
Comment: que bom que deu certo kk. editada!


Posição XY em C, reposicionamento

Question: Pessoal estou necessitando das coordenadas atuais "cursor" da tela, para que o usuário permaneça na linha atual.
EXEMPLO
void main{

    char nome[50];
    char sobrenome[50];

    int linhaAtual;
    linhaAtual = ????;

    gotoxy(1, linhaAtual);
    printf("Insira seu nome:");
    scanf("%[^\n]s", nome);

    gotoxy(1, linhaAtual);
    printf("Insira seu sobrenome:");
    scanf("%[^\n]s", nome);

    system("pause");
}

OBS
No exemplo não estou levando em considerando a necessidade de limpar toda linha. Irei desenvolver.
PESQUISAS
propriedade wherex() , wherey()   -  não funciona, não sei por que motivo.
propriedade __LINE__  - aparentemente a contagem é diferente.
Comment: Ainda bem que `__LINE__` não deu certo. Você já pensou porque só existe a linha e não a coluna nisto? Vamos ao que está relacionado ao que você quer: porque o `where?()` não funciona? Se você que fez a aplicação não sabe o motivo, nós sabemos menos ainda. Você não colocou o `#include` que está usando. Isto é importante. Espero que não esteja usando o `conio.h`, isto não faz parte do padrão e está obsoleto.
Comment: @guilherme-lautert Para você, **ponteiro** = **cursor**? Edita a pergunta e ajusta esse detalhe, faz bastante diferença.
Comment: @bigown, fiquei curioso com "Ainda bem que `__LINE__` não deu certo." e pesquisando chegando a isto: http://www.lemoda.net/c/line-file-func/
Muito interessante, na minha pesquisa anterior `__LINE__`, foi apontado como posição da coordenada y, só não foi mencionado "do arquivo".
Quanto ao `#include conio.h`, na verdade é exatamente o que estou usando, estou ciente da existência do `conio2.h`, contudo achei que poderia existir alguma propriedade paterna no próprio C.
Comment: @karlphillip eu sei que *ponteiro != cursor*, mas tecnicamente também não encaro `|` de linha como um cursor. Não conseguiu me expressar corretamente na hora.
Comment: @GuilhermeLautert Eu te entendo, mas quando queremos ajuda da comunidade temos que utilizar os termos técnicos que fazem parte da terminologia da área, senão corremos o risco de não sermos entendidos. Se **cursor** é um nome apropriado ou não para definir esta funcionalidade eu não sei, mas os livros, manuais e documentações se referem a ela por este nome.
Answer: Você está se referindo à funções do header conio.h (criado para apps de linha de comando no Windows). Esse header não faz parte da biblioteca padrão da linguagem C, e são poucos compiladores que suportam ele nativamente.
O que acontece é que ao rodar sua aplicação em IDEs como Qt Creator, ou outros que possuam um console próprio, não existem garantias de que essas funções irão funcionar. O melhor é usar um compilador que suporta nativamente o conio.h, e depois rodar seu aplicativo diretamente do Command Prompt do Windows (cmd.exe).
Bem, dizer que algo "não funciona" é bastante vago, então eu vou assumir que você não teve problemas de compilação ou linkagem com essa biblioteca.
Se você seguiu as orientações acima, de acordo com a documentação, invocar as funções abaixo:
int x = wherex();
int y = wherey();
printf("x: %d  y:%d\n", x, y);

irá imprimir na tela a posição (X,Y) do cursor.
Comment: creio que minha IDE possui a `conio.h`, mas não a rode corretamente como você comentou, pois eu possui o `#include conio.h` e estes comandos apresentam erro quanto utilizados.
Comment: Agora chegamos ao ponto: qual é o **erro**? Seja bem específico, por favor, senão não poderemos te ajudar.
Comment: Então o que acontece quando você imprime `x` e `y` na tela? Quais são os valores deles?
Comment: como citei no no comentário para o @bigown, tive de usar a biblioteca `conio2.h`, pois a minha atual `conio.h` não possui estas funções, assim quando tento compilar ele exibe `where?() not declared in this scope`.

Posição XY em C, reposicionamento


Email validation, using if else statements wont allow it to continue checking if there was an error with the first if?

Question: I have:
if(isset($_POST['submit'])) {
    if (empty($name)) {
        echo'ERROR: Missing Name
';
    } else if(empty($phone) || empty($email)) {
        echo'ERROR: You must insert a phone number or email
';
    } else if(!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
        echo'ERROR: Please Insert a valid Email
';
    }  else {
        mail( "firstname.lastname@example.com", "Monthly Specials Email",
            "Name: $name
            Email: $email
            Phone Number: $phone
            Comment: $comment", "From: $email" );
        echo'Message has been sent
';
    }
}

How else could I check for all of those issues without using else if?
When I use else if, it checks through the first if statement, if there is an issue with it it will not continue going through the other if statements following that one.
Any ideas? Thank you
Answer: You could collect all errors in an array like this:
if (isset($_POST['submit'])) {
    $errors = array();
    if (empty($name)) {
        $errors[] = 'ERROR: Missing Name
';
    }
    if (empty($phone) || empty($email)) {
        $errors[] = 'ERROR: You must insert a phone number or email
';
    }
    if (!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
        $errors[] = 'ERROR: Please Insert a valid Email
';
    }
    if ($errors) {
        echo 'There were some errors: ';
        echo '

', implode('

', $errors), '

';
    } else {
        mail( "firstname.lastname@example.com", "Monthly Specials Email",
            "Name: $name\n".
            "Email: $email\n".
            "Phone Number: $phone\n".
            "Comment: $comment", "From: $email");
        echo'Message has been sent
';
    }
}

With this you can check all requirements and report all errors and not just the first one.
Answer: use:
$error = 0;
if(empty($var1)){ $error = 1; }
if(empty($var2)){ $error = 1; }
if(empty($var3)){ $error = 1; }
if(empty($var4)){ $error = 1; }
if(empty($var5)){ $error = 1; }

if($error > 0)
{
   // Do actions for your errors
}
else
{
   // Send Email
}

Comment: This is how I do it, though sometimes I will make an array of error messages so I can loop over them and display all errors.  If the error array is empty, then I know that I am good to go.
Answer: you can use try...catch statements for error checking like this.
whenever you encounter a condition where an error should be generated, you can use throw new Exception clause.
Answer: Use a dirty flag.  Check them all and append the message to the dirty variable.
Answer: Try this:
if(isset($_POST['submit'])) {
    $errors = array();

    if (empty($name)) {
        $errors[] = 'Missing Name';
    }
    if(empty($phone) || empty($email)) {
        $errors[] = 'You must insert a phone number or email';
    }
    if(!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
        $errors[] = 'Please Insert a valid Email';
    }

    if (!empty($errors)) {
        for ($i = 0; i < count($errors); $i++) {
            echo sprintf('ERROR: %s
', $errors[$i]);
        }
    }  else {
        mail( "email@example.com", "Monthly Specials Email",
                                            "Name: $name
                                             Email: $email
                                             Phone Number: $phone
                                             Comment: $comment", "From: $email" );
        echo'Message has been sent
';
     }
}

Answer: if(isset($_POST['submit'])) {
    $valid = true;
    if (empty($name)) {
        echo'ERROR: Missing Name
';
        $valid = false;
    }

    if(empty($phone) || empty($email)) {
        echo'ERROR: You must insert a phone number or email
';
        $valid=false;
    }

    if(!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
        echo'ERROR: Please Insert a valid Email
';
        $valid = FALSE;
    }

    if($valid) {
        mail( "email@example.com", "Monthly Specials Email",
            "Name: $name
            Email: $email
            Phone Number: $phone
            Comment: $comment", "From: $email" );
        echo'Message has been sent
';
    }
}


call serverside script upon textbox value change

Question: I know I'm doing it wrong, not sure how to proceed. Please help. If there is any other way!
I've a Textbox, which is loaded using JQuery. Once the textbox value is changed, I need to call the server side script which is defined in OnTextChanged
<asp:TextBox runat="server" ID="Textbox1"  OnTextChanged="Textbox1_TextChanged" AutoPostBack="true"/>

In JQuery, I've assigning the value. I've a Textbox and a button. On click of this button, I open a window with TreeView. Once the value is selected from TreeView, I need to populate in Textbox AND I need to refresh few Server controls. This is where I needed Textbox1_TextChanged Server call
 $('#Textbox1').val("TreeView Selected Value");

Once this value is assigned, I need to call Textbox1_TextChanged event to be called. The server side method is not being called after I change the textbox value!
Solution:
Here is a good article on how to implement the post back from JavaScript.  http://www.dreamincode.net/forums/topic/217965-calling-c%23-event-in-javascript/ . Also add EnableEventValidation="false" in your page which is not mentioned in the link.
Comment: You can do this only by using ajax, if you want it to be dynamic
Comment: The problem with AJAX is, I need to either user a WebMethod or a HTTP Handler, where I cannot access the web page server controls. Please correct me if I'm wrong!
Comment: You have added this textbox dynamically with jquery so the option is to use ajax, or you have to handle the change event in client side.
Comment: Does the OnTextChange event fire if you input text manually? ... You could also use an UpdatePanel for roundtrips to the server http://stackoverflow.com/questions/6361680/asp-net-updatepanel-and-javascript-dopostback
Answer:
Change Event is only called after your DOM gets ready . It cannot be called by dynamically setting values to the textbox . Setting values dynamically and changing values when the DOM is ready are different things . The former is not the change-event but the latter is .

Why don't you handle all these in client side only ? Secondly on-change event will only be called when you change the value inside the textbox ( when the DOM is ready ) . You are assigning the value to the textbox in the document-ready I guess . So it's not a change event . Try this :-
  $("#TextBox1").on('change',function(){
    //your logic ;

  });

And if you really want to do this from server side , then assigning values from the jQuery code will not make that work . As when your DOM is ready , the value Testing you are assigning is already there . So it's not a change event . Try assgning values after your DOM gets ready . Your server side on-change method will be called for sure .
Hope i am clear to you .
Thanks !!
Comment: I tried onchange of  html control, but it didn't work. I have updated the question to understand why I need server script. I am not assigning textbox value when DOM is ready.
Answer: You should use GetPostBackEventReference and create a js function like this:
function Textbox1_OnChange() {
    <%=Page.GetPostBackEventReference(Textbox1, "TextChanged")%>;
}

Then you will be able to call this from jQuery after you change the text:
 $('#Textbox1').val("TreeView Selected Value");  // your code
 Textbox1_OnChange(); // new line

This will automatically postback the page and invoke your Textbox1_TextChanged server-side event.


drupal_render($form) not rendering a form

Question: I wonder if anyone has found a solution to the problem I'm seeing.  I've built a very simple "beginner's form" in drupal.
function simple_nameform() {
    $form = array(
        '#method'           => 'post',
        '#prefix'           => '
',
        '#suffix'           => '
',
        'your_name'         => array(
            '#title'        => t('Your Name'),
            '#type'         => 'textfield',
            '#description'  => t('Please enter your name')
        ),
        'submit'            => array(
            '#type'         => 'submit',
            '#value'        => t('submit')
        )
    );
    return $form;
}

I've put this form in a module, with info, I've enabled the block in admin.  When I'm on the main page render I run the commands

Send to a Friend

    <?php
        $output = drupal_get_form('simple_nameform');
        drupal_render($output);
    ?>

<?php // debug purposes only
          print_r($output);
    ?>

The form does not appear to render from the "drupal_render" line, however, the $output variable is most definitely full of something that looks very much like it might be a drupal form.
(it's a huge array filled with my form elements.  at parts it even manages to render some of the elements to page correctly).
Anyone with an idea of what I've missed?
Comment: The question could easily be answered by reading the documentation of the used function: http://api.drupal.org/api/drupal/includes--common.inc/function/drupal_render/7
Answer: Try:
<?php print render(drupal_get_form('simple_nameform')); ?>

Answer: EDIT -- My original answer was incorrect in that it applies to Drupal 6.
it seems that the form builder function in D7 needs 2 arguments, $form and $form_state
<?php
function simple_nameform($form, &$form_state) {
/...
?>

I wonder if the _valdiate and _submit function aren't also required, as they are present in the D7 example here:
http://api.drupal.org/api/drupal/includes--form.inc/group/form_api/7
if that doesn't work, try using hook_forms() to register your form with a module

original solution for D6
<?php
$output = drupal_get_form('simple_nameform');
print $output;
?>

drupal_get_form returns a rendered form.  notice the last line here: drupal_get_form()
also, unrelated, you probably need to add a line to your submit button:
<?php

        'submit'            => array(
            '#type'         => 'submit',
            '#value'        => t('submit'),
            '#executes_submit_callback' => true
        )
?>

and to make debugging easier, try this:
<?php // debug purposes only
          drupal_set_message("
".print_r($output,true)."
");
?>

(the 2nd arg of print_r makes it return inline instead of pooping at the top of your document.)
Comment: See I'd tried that (with echo instead of print) and got the result "Array" printed in the space that I expected the form to be rendered in.  One of the non-standard drupal features installed is "chaos tools" is there perhaps something that is creating a conflict ?
Comment: is this drupal 6.x or 7.x?
Comment: nevermind -- just saw in your tags.. it's 7
Comment: that form generation link might turn out to be far more useful than what I was doing.  the command render() as opposed to drupal_render appeared to have the desired effect.
Comment: thanks so much for your help though.  I've learned a good deal from your answer.


How can I replace a string in a text?

Question: With {{ content.field_myfield.0 }}, I get a text. When I use {{ content.field_myfield.0|replace({"foo" : "bar"}) }}, nothing is rendered and no errors are reported.
I also tried replacing content.field_myfield.0 with content.field_myfield.value or `content.field_myfield.0.value, but I still get an empty string.
How can I replace a string?
Thanks
Answer: content.field_some_field is a render array, but the replace filter operates on strings. You need to render your field before calling replace.
For example:
{{ content.field_some_field|render|replace({"hello": "goodbye"}) }}

Answer: If this is a formatted text field you can replace the source text before it is rendered. This has the advantage that HTML tags are preserved:
{% set field_item = content.field_myfield.0  %}
{% set text_replaced = field_item['#text']|replace({'foo': 'bar'}) %}
{{ field_item|merge({'#text': text_replaced}) }}

If you are not sure about the field type check the render array {{ dump(field_item) }}.
You can flatten the render array before replacing, as @sonfd suggested, if the replaced text doesn't contain HTML tags.
In general there are better ways to replace texts. Implement a text filter or a pre_render/post_render callback. See for example https://www.drupal.org/forum/support/module-development-and-code-questions/2020-01-28/creating-a-custom-text-filter or How to alter page content?

How can I replace a string in a text?


Prevent TCP Connections from Timing out on Restarting Service

Question: On Ubuntu 14.04, an app communicates with clients at intervals of about 1 per sec to 1 per min. However the service have to be restarted regularly and this causes all the connections to drop/timeout. It takes only about 10-15sec for the service to restart.
Is it possible to tune the system such that these connections do not timeout/drop when the service is restarted?
<code>$ ulimit -n
1048576
$ cat /proc/sys/net/ipv4/tcp_fin_timeout
60
$ cat /proc/sys/net/ipv4/tcp_tw_recycle
0
$ cat /proc/sys/net/ipv4/tcp_tw_reuse
0
</code>
Answer: In a word, no.
When you restart the service, you must kill the process which holds the socket file descriptors open. Assuming these are TCP sessions, that means the TCP session must finish (FIN) and a new session be established (SYN) after the service has restarted and a new process is listening on a socket again.
Why do you need to restart the service? You shouldn't. Solve that and your issue goes away.
Comment: Does this mean that when a server exits, it closes all the connections? Let's say a server had 50k users connected. When it exits it should perform the [four-way handshake](https://en.wikipedia.org/wiki/Transmission_Control_Protocol#Connection_termination) with all of them?
Comment: Yes, all 50k file descriptors will be closed when the process terminates. The kernel will send a FIN and follow the Active Closer path through the FIN-WAIT states and TIME-WAIT state.


correct way to implement multipule users registration form

Question: I want to create a site where users get to chose between being an employee or employer.
So when users first go to the registration they need to be asked which role will they be, and on that choice a different registration form will appear.
What would a good implementation method be?
Thanks
Answer: First you need to use Profile 2 module and create two separate profiles for employee and employer roles.
Then you can use module Auto Assign Role or Profile2 Registration Path to allow users select which role do they want to register with.
Comment: Seems like it could work, but I rather not work with profile2 module anymore, I got frustrated last time trying to make profile2 fields searchable.
Comment: "You may use Views and/or the Search API to provide listings or searches for profiles." Not to be smug but it's on the profile 2 description. I was curious about the question, and it might be a change in the description.
Answer: You could create a multi-step form in a module that gives the user the opportunity to make that choice and once the form is completed by the user you could store the data.
Comment: Could you tell me more about your approach please?
Comment: http://drupal.org/node/1121110 examples of a form module. But if you create a module from the form api that answers the questions. When they got to sign up the form is a part of the process
Answer: You could use Field conditional state module and Rules for this. Add a select list with employer and employee option and depending on which one the user selects, show or hide fields relevant for each role. Then create a rule that assigns new users a role based on the value of the select field that they selected.


Background CSS images won't be changed after reuploading & Cache flushing

Question: If I Download a css background image of my site, changing it with GIMP (or MS paint for that matter) and re upload it, nothing will happen. Moreover, even after I delete the file from the server, the image stays online... clicking "Flush all caches" nothing happens... I also note that the image basically stays the same --- Same filename and file extension, so it's extremely wired. What would you suggest of checking?
What I already tried and didn't help:

Turning off server external caching tool (for both static and dynamic cache).
Turning off AdvAgg from config/development/performance/advagg (Unchecked "Enable...")
Turning off Drupal's internal cache system.

Update: Working answer found... See below for the answer with green checkmark.
Comment: Try flushing your browser cache
Comment: Are you using the color module or AdaptiveTheme? Also what version of AdvAgg do you have?
Comment: I use the color module but I don't use Adaptive theme. My Advagg version is 2.11.7. Clicking ctrl+F5 or total clear of browser's cache doesn't help.
Comment: are you positive you are replacing the file correctly? try a different browser.
Comment: Tried Chrome - No change. I've tried it with 3 files already (replaced them as described above), but it keeps render the old files --- unless I change the filename and the CSS path respectively.
Comment: if your site is online give me the url
Comment: I hope you have cleared the browser caches :P I generally miss this and waste a lot of time.
Comment: what happens if you just delete the file on the server?
Comment: The URL is on my profile @Drupalist. Clearing browser cache does nothing. When I delete the file it still appears... The problem might be Cloudflare cache related...
Comment: are you sure you are allowed to delete the file?
Comment: Yes, I can delete any file I want, anytime. After the cloudflare cache was purged the file no longer appeared but it's unnatural to purge the CDN cache after every image manipulation and re-uploading, I'm sure you would agree...
Answer: Since all caching aren't able to fix, let's try narrowing down the issue.
First, try to delete the image from your theme. Flush all caches and see if the background image is still there. If it is, open your browser development tool and check the background image URL and try opening it in a new tab, check the URL of the image and follow it in your server's directory if it really still exists.
Second, try restarting the server or any related running services you have in your server.
Hope this can at least give an idea on where to find what's causing the issue.
Answer: Go to your theme's settings page and save it. The color module can cause issues like you're describing. AdvAgg tries really hard to detect this but it can't catch every use case. This is an issue with core that AdvAgg fixes 95% of the time.
Comment: Saved the theme's settings, flushed all caches right afterwards, and clicked ctrl+f5, but I give my word - nothing has changed... I've never encountered this problem before. Until last week I had no caching in my website - Not the Drupal internal cache of any kind, and not any external caching tool... Is there anything I should check in Advagg that might help?
Comment: Notification: totally uninstalled color module, nothing's changed...
Comment: Well it was worth a shot. I'm out of ideas.
Comment: One last notification (?)... Even deleting the file from mytheme/images/, flushing all caches, and clicking ctrl+f5 in two browsers didn't change the render! It's most probably the external caching tool on Cpanel...
Answer: This is a caching issue, and there are different places this could happen depending on your set up:

Proxy (like Varnish)
Webserver (like apache or nginx)
browser

Webservers usually don't cache resources, I've seen some short lived caches on nginx - like 5-10 secs.
Most likely the caching is going on in a proxy or your browser. You would probably know about the proxy issue if you did use a proxy, so my best guess, is that your browser is caching the image.
To test if the issue is a caching issue, you can try to view the image from the url used in the CSS and you should see the same image as on the webpage. You can then try to alter the URL by adding a GET param.
If the url to the image is: http://example.com/image.png, you can change the url to http://example.com/image.png?test=1
Since the url is now completely different, the browser (and proxy) wouldn't have stored a cache for this, and you should see the image that you just uploaded. If that is the case, it proves you need to clear caches.
When doing development, it can be an advantedge to turn off browser cache completely to avoid issues like this. There are many extensions for all browsers that can help you with this, if it's not built in the browser.
Comment: Spoke with my servers support guys - Told them I totally disabled the Drupal cache, External caching tool (Supercacher), Mechmade, and than flushed all drupal cache + browser cache and nothing helped, so one of them flushed ("purged") the Cloudflare cdn cache and suddenly the image no longer appeard in my end, but, this is still problematic because it never was that way that a manual flushing of the cdn's cache is needed, So I told them that and they told me "Clear" your DNS cache from Windows CLI (didn't help), and contact your ISP... Purging CDN cache each time is not natural I guess...
Answer: The problem is apparently CDN based. I use the free version of the Cloudflare CDN service, and after purging it's cache, the deleted image no longer appeared on-line at site... I've tried to repeat the procedure to vindicate that indeed it was the CDN service so I reuploaded the image with some color changes and another file name, and again, after I deleted it, it kept appearing on-line at the site, but disappeared only after purging the CDN cache (but not any other type of cache) via the Cpanel based Cloudflare managing area.
So, Better try to purge it if you come across this problem, or purge and turn off the CDN for a while (especially if it won't damage your loading times and on-page optimization scores). Maybe dev mode is an alternative for turning it off completely - didn't try that option. Ben.
Answer: I get this randomly and also the same thing with favicons. I wasn't running a CDN and never solved it, instead I just started incrementing the file names one by one to avoid the issue completely.
It's not a clever solution, but if you're in a rush it should work.


Remover aspas simples javascript

Question: Preciso remover aspas simples de uma string, já tentei string.replace(/\'/g, ''),
.replace(/"'"/g, '') e não funciona, alguém pode me ajudar?
Comment: Podes mostrar um exemplo da string?
Comment: Não vejo problema com o replace, provavel que não esteja re-atribuindo, dessa forma: `string.replace(/\'/g, '')` deve ser `string = string.replace(/\'/g, '')`, porque o replace em si não altera a string.
Comment: Seria algo como isso:

` dataVencimento: '{$gte:ISODate("2017-11-09T02:00:00.000Z")}'`

Preciso remover as aspas simples antes de `{$gte` e depois de `)}`
Comment: O teu código funciona para essa string... https://jsfiddle.net/Sergio_fiddle/jefwatnk/
Answer: Apenas utilizando o replace() é o suficiente:
var a = "joao's empreendimento";
var b = a.replace(/'/g, '');
console.log(b);

Exemplo: https://jsfiddle.net/85bnxq5x/
Comment: O código ao AP funciona. Acho que o problema é outro...
Comment: Testei dos 2 jeitos e o código sugerido pelo @Everson funcionou, agradeço imensamente a ajuda de todos
Comment: @LeonardoEbert Agradeço o retorno e que bom que tenha lhe ajudado ;)

Remover aspas simples javascript


C# Databases SQLite Locked Database Error

Question: I am currently writing a code using C# and SQLite. There is an error being throwing stating that the database is locked twice in a message box.
The query works on SQLite DB Browser however, when it is placed in C# code it throws the error.
Here is the code that is giving me an error:
cmd.CommandText = "UPDATE customers SET Bill = Bill - "+textBox2.Text+" WHERE customers.CustomerID = " + textBox1.Text + ";";

There seems to be an issue with the equals sign, might be something wrong with the arithmetic process.
Complete code:
 SQLiteConnection myconn = new SQLiteConnection(@"Data Source = C:\Users\chick\Newspaper.db");
        SQLiteCommand cmd = myconn.CreateCommand();
        cmd.CommandText = "UPDATE customers SET Bill = (Bill - "+textBox2.Text+") WHERE customers.CustomerID = " + textBox1.Text + ";";
        myconn.Open();
        try
        {
            cmd.ExecuteNonQuery();
            MessageBox.Show("Succesfully Update");
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

UPDATE:
Changed format to using() {} however it is still not working. Program is crashing
New Code:
   using (SQLiteConnection myconn = new SQLiteConnection(@"Data Source = C:\Users\chick\Newspaper.db"))
        {

            var sql = "Update customers SET Bill = Bill - @pay WHERE customers.CustomerID = @cid;";
            myconn.Open();
            using (var cmd = new SQLiteCommand(sql, myconn))
            {
                cmd.Parameters.AddWithValue("@cid", textBox1.Text);
                cmd.Parameters.AddWithValue("@pay", textBox2.Text);
                cmd.ExecuteNonQuery();
            }
        }

Comment: Please use parameterized queries. This generally solves many of the formatting and syntax errors in queries from the get go and as an added benifit it will protect your system from sql injection attacks. Please refer to [How can I add user-supplied input to an SQL statement?](https://stackoverflow.com/q/35163361/1260204)
Comment: and you need single quotes around string values
Comment: You have SQL Injection vulnerabilities.  The locking issue is likely related to how you use the connection/command objects, which you have not shared.
Comment: Connections & Commands need to be disposed, preferably by using a `using () {}` construct.
Comment: I just can't believe how many Sql injectable queries I see every day. This needs to stop.
Comment: I updated the code with all the connection lines and the rest of the function
Comment: I tried using the using construct however it is still now working. I placed the updated code above.
Comment: Place a `using` block around the connection. `using (SQLiteConnection myconn = new SQLiteConnection(/*connection*/)) { ..... /*code from question in here*/ }`. Also pass the parameters using the correct type and pass the values in their native type. if `@cid` is an `int` then convert the value to an `int` and pass the `int`.
Comment: I updated the code to what you said and I am still getting the database locked appearing 2 times.
Answer: The problem is that some other part of the program (or some other program) still has an active transaction.
You must properly clean up all commands that access the database, i.e., use using everywhere.
Answer: Thank you to all that have answered. We realized the issue was that we never closed the reader in previous code.


Making a model to predict the error of another model

Question: So basically I have a machine learning model where I want to have a prediction interval, the model is XGBoost so it is tricky to do Quantile Regression and I was looking for an alternative method to achieve this goal.
I have came across this article that suggests to estimate the standard deviation for the prediction by creating another machine learning model to predict the error of the original machine learning model. So the process would be:

Fit machine learning model to training data.
Calculate the error for each datapoint.
Fit a second machine learning model to predict the squared error of the datapoints.
When making a prediction use the initial prediction as mean and the square root of the prediction of the squared error as an estimate of the standard deviation.
With the mean and std deviation build a confidence interval for the prediction.

The assumptions here is that the distribution of the predictions is Normal and that we can estimate the mean and standard deviation in the way mentioned.
My question is, does this method make sense? And is there a better way to do this?
Comment: I'm looking at a similar question and found this blog is useful: https://medium.com/@qucit/a-simple-technique-to-estimate-prediction-intervals-for-any-regression-model-2dd73f630bcb
Comment: Related: [error-correction models](https://en.wikipedia.org/wiki/Error_correction_model). Also: Welcome to CV, Franco Piccolo!
Answer: While I cannot fully evaluate the approach cited in the blog post you pointed to, I can at least propose another way of obtaining confidence intervals, which is via bootstrapping.
Bootstrap methods are convenient mainly for two reasons: they're simple to implement and doen't need assumption of the underlying statistics you are bootstrapping.
The implementation follows, in general, the following pseudocode:
<code>statistics = []
for i in bootstraps:
    train, test = select_sample_with_replacement(data, size)
    model = train_model(train)
    stat = evaluate_model(test)
    statistics.append(stat)
</code>
which comes from this blog post, that has a really nice intro presentation on how to use bootstrapping to evaluate ML models.
Also check this really nice answer explaining why bootstrap works.
Comment: Thanks Lucas, I've actually looked into bootstrap but it's applicable only to the  evuation error. Im trying to predict a prediction confidence interval.
Comment: @FrancoPiccolo Not at all, that's not the only case bootstrap can be used. Look [here](https://stats.stackexchange.com/questions/226565/bootstrap-prediction-interval), [here](https://machinelearningmastery.com/prediction-intervals-for-machine-learning/) and [here](http://www.math.ucsd.edu/~politis/PAPER/BPIforARjspiFINAL.pdf), for example.
Comment: Thanks for the links, but I didn't find anything to work for my case where I want prediction interval for XGBoost. The links there work for linear regression.
Comment: @FrancoPiccolo have you seen [this](https://towardsdatascience.com/regression-prediction-intervals-with-xgboost-428e0a018b) article?
Comment: Yes that's what I was trying to avoid for complexity.. Maybe Ill need to go deeper there or just use a model to estimate error as in the question.
Comment: @FrancoPiccolo If simplicity is a priority, you could check [bagging](https://datascience.stackexchange.com/questions/25443/prediction-intervals-using-xgboost).
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/90989/discussion-between-lucas-farias-and-franco-piccolo).


Multiseat Linux Remote Desktop with KVM and Spice

Question: I have a server running Ubuntu 14.04LTS. On it I created a (KVM) VM with Ubuntu 16.04 Desktop.
I setup Spice on this VM so that I can access it remotely. Everything is working fine, got TLS, USB redirection, everything working nicely.
However, this machine is intended to be used by two people, I was hoping that I could have User1 access it, be greeted with the login screen, login and use the machine at will. Then at the same time, User2 would be able to launch the spice client (using remote-viewer), also be greeted with a login screen, and use the machine at the same time as User2.
However, what I get is, when User2 connects, User1 is disconnected immediatelly and takes over the Desktop of User1.
I searched and found some brief mentions to multi-monitor support, read about enabling ticketing (setting a password for Spice), etc and thought it would lead me to the solution I want but nope.
I tried adding a second Spice Display to the VM but when launching the VM using virt-manager it says only one Spice Display can exist at a time.
Do not know what else to try, does anyone know how to accomplish this?
PS: I know I could create two VMs, one for each user, but please that is not what I want.
Answer: spice provides direct access to the console, opening spice is pretty much the same thing as sitting in front of the virtual machine. You can't sit two people in front of the same desktop (well you can, but that's not very conventional and requires special hardware. and furniture.) So when the second user connects, he pretty much kicks the chair from under the first one, and takes his place.
To accomplish what you want, you need to set up a terminal server on this VM and connect using the appropriate protocol. There's a hack available that allows you to run spice as a server inside a machine, instead of providing a console from the host side, but last time I tried it, it was pretty much broken.
Answer: For the original poster, have you tried X2Go?  I know that's another server piece you have to install in your 16.04 system, but using that on my machines, with the X2go client allowed multiple users to login with different X sessions at the same time.
I find that depending on your hardware capabilities, the Mate and XFCE desktops perform really well.  Haven't tried Gnome 3, KDE, Cinnamon, or Unity yet, but intend to over the next few weeks.
I have done this to a Digital Ocean droplet on which I installed Mate desktop and X2Go sever, and have also done it on a home PC with Mate installed, but have not done it on a KVM virtual machine yet.
Comment: Thanks, I will investige X2Go. If it has USB redirection it will fit my requirements.
Answer: It's not a flashy, but you could always run a shared session over VNC - that does allow multiple connections to share the same session and display. x11vnc is a common example which works well in this situation.
Keep in mind that VNC doesn't handle encryption so running through a encrypted SSH/VPN tunnel is highly recommended.


A sequence of continuous functions whose limit is discontinuous at infinitely many points

Question: I am trying to find a convergent sequence of continuous real-valued functions on $[0,1]$ whose limit function fails to be continuous at an infinite number of points. I have thought about $f_n(x)=x^n$ which is convergent to $1$, but how do I show the limit fails to be continuous at an infinite number of points?
Comment: Also, I TeX-ified your post and added what I think is a better title. Feel free to edit.
Answer: Well, the pointwise limit of the sequence of functions $f_n: [0,1] \rightarrow \mathbb{R}$ given by $f_n(x) = x^n$ is the function which is $0$ on $[0,1)$ and $1$ at $1$.  This function is discontinuous only at $x = 1$, so it is not an example of what you're looking for.
Here's a suggestion for a correct answer: try building a sequence by subdividing $[0,1]$ into $n$ pieces and having $f_n$ do something like your sequence of functions at $n$ different points $0,\frac{1}{2},\ldots,1-\frac{1}{2^n}$.  You should be able to construct a sequence where the limit function is zero except at points $1-\frac{1}{2^n}$.
Answer: It's easier if you start with a function discontinuous infinitely often and then find continuous functions converging to it. I recommend letting the limiting function be the one that is zero on the irrationals and $1/q$ at the rational $p/q$ (in lowest terms).


Can you help me understand what I am doing with these arpeggios?

Question: I have a song with a part that I am wanting to play arpeggios over with the guitar. But just using the actual chord tones sounds boring to me. So I have started with an arpeggio pattern on the first chord that I am then repeating.
What I am doing is this:
The song is in E minor. On the part that starts with the G7 chord I start playing the arpeggio: A B D F# (and then up to the higher A and then back to F# and D, so just using these 4 notes). It sounds good. And then I start finding out what it is that I am doing there.
So I look at the scale chart for the E natural minor. The third chord is Gmaj7 and that is the closest to the G7 chord that I am getting in this chart. I am in Ionian mode (it says). And I am playing the 2nd, 3rd, 5th and 7th degrees of this mode in my arpeggio. Okay, so far so good.
Now I am applying this same step to the other chords.
Next chord is E-7, which is Aeolian mode, and again I play the 2, the 3, the 5 and the 7 of this mode, resulting in the notes F#, G, B and D. This sounds all fine and dandy.
But now my question.
The next chord I play is B-7. Applying the same procedure, I am now in Phrygian mode (or the fifth degree of the E natural minor scale.) The second degree is "C" but it sounds absolutely terrible! It is better to use C# instead. I play C#, D, F# and A, and it sounds cool over B-7.
So I have to break with my formula, and I am fine with doing so, but I would love to know what is going on on a more theoretical level to understand what is happening here.
Appreciate any insight you might have!
Comment: Don't be trapped by the 'rules'. It makes more sense to use ears rather than what you think are 'rules'. Guess why 'rules' is written like this!
Comment: I don't understand how your A B D F# gets close to what goes over a G7 chord. G7=GBDF. 2 out of 4 notes hardly constitutes  chord, and the other 2 aren't in that chord.
Comment: Funny enough, your A B D F# is more or less Bm7, not G7; that already makes a switch to B7 feel a little "ad hoc". Also, the second degree of B would be C#, not C (must be a whole tone up from B).
Comment: Even if there's a C  in your scale chart there's no need to stick to C for your whole piece.
Comment: Don't get trapped by rules, I get that, but I am interested to know why C# sounds awesome on B-7, and C does not. Even though it belongs to the scale and C# does not. I am interested in knowing what rules I am breaking, haha, if you get my drift!
Comment: I don't know that it comes close, Tim, but this is just the arpeggio that I started out with. The chord in the song is G7 and I played those A B D F# notes and found that they sounded good over it. So I tried to apply that same note structure (or i guess its a melodic pattern) over my other chords. Now all I am trying to do is find out why the same pattern does not really fit with some of the other chords, notably: B-7.
Comment: Can't see how the F# works with the F natural of G7.
Comment: Are the arpeggios being played alone or against the melody?
Answer: Not directly answering your question, but pieces don't 'change modes' for each chord played. If four bars in key G were G, Am, C, D7, then all of that would be G Ionian. It seems you would consider it G Ionian, A Dorian, C Lydian, D Mixolydian. Modes don't work like that.
There's probably where you get confused. ALL the modes from a parent key use exactly the same set of notes. That's one of the points of their existence. And pieces are generally in one mode throughout.
When you get to minor keys, there isn't just the one exclusive. Between them, there are more than the 7 notes we find in major keys. In fact, there are 9 that are included in all minor scales/keys. So thinking like you do, changing mode for each bar/chord, any 'rules' get screwed up anyhow!
Use whatever notes you think sound appropriate. Sounding good = probably is good. Someone will then come up with a good reason (a 'rule') why. But that should be after the fact, not before it.
Comment: Use either E harmonic or E melodic minor notes, and you'll find that the first has C, the other has C#. Thinking in Bm, the supertonic (2nd) note *is* C#.
Comment: @Jelmar Throw all those charts away, they're getting in your way.
Comment: Thanks for this, Tim. I understand that the piece does not change modally, and that it is one key. But it is also my understanding that each of the chords in, say the key of G, can have a mode associated with it. And I have a chart that says so. All I am actually doing is extracting the 2nd, the 3rd and the 5 and 7th note from each of the modal scales associated with each chord degree of the G major (or E minor scale). It is just a procedure. I am not interested why it is right or wrong, but only in why it works in some cases and not in others. So actually, yes, I am trying to find the rule.
Comment: @PiedPiper haha, yeah I get that is what it looks like! But I jut got them and the're real handy to figure out these arps!
Comment: @Tim, these melodic and harmonic scales, that's probably where I can dig in more. Thanks!
Answer: This is what I understand you have in terms of chords and pitches...

G7 + A B D F# = G(?)9

Em7 + F# G B D = Em9

Bm7 + C# (not C) D F# A = Bm9

E G B D F# A C# E = E dorian

(The stuff you mention about scale and mode and chord charts sounds like the "chord/scale system" which I think is not helpful for understanding music theory/tonality/harmony, because it teach about keys.)
The first thing I notice is your choice of pitches in the arpeggio guitar part extend the chords to ninth chords. With A, F#, C# you add a major ninth to the set of pitches for each chord. The other tones are already in the chord part.
The quality of the seventh on the G chord is ambiguous, because there is F natural in G7 and F# in the second part. It's hard to say much more about that chord without know other details. It seems to be a non-functional dominant seventh chord. That means it doesn't resolve in a dominant to tonic way. That isn't a problem, but if you want to say more about it, more detail is need. For example, the voicing and voice leading could be important. If it was like this...

You might say about the cross relationship between F/F#:

the dissonance is mitigated by burying one of the tones in an inner voice
the F natural moves by smooth voice leading
the dissonance is places into a fairly high register (lower starts sounding muddy or clanging)
F# in top voice and B in the bass outlines a perfect fifth in the outer voices mitigating the sense of F# as a dissonance

That's just my example. An analysis would depend on what exactly you are doing. But those are some of the factors you would look at: inner/outer voices, voice leading, register, etc.
Your avoidance of C natural is important. It ensures the Bm7 is extended to a minor ninth chord - with a major ninth - which is the standard minor 9th chord, and it also adds the crucial pitch to make E dorian. In an indirect way the absence of C natural supports the notion that the G7 is non-functional. C would be it's tonic, but you exclude it.
Comment: Hi Michael, a great answer, thank you. It sheds a lot of light on what is happening. Not being burdened with a lot of theoretical knowledge, I sometimes struggle to create things that are fitting, yet INTERESTING. I find it is often not good advice to 'use my ears' as they often resolve things in a conventional way. I really have to work at it, and sometimes think it's interesting to find procedures. I now have some things that I can use to dig in more. I didn't realize I was using the 'chord/scale system', but that's the trouble: these youtube teachers never reveal their sources!


Materialize CSS simple installation

Question: I am trying to install Materialize CSS, it looks pretty cool.
I installed it as per (simple) instructions, however non of the tags are working, so I assume it is an installation issue.
Below are snippets of code:

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <link rel="stylesheet" type="text/css" href="index.css">
    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/materialize.min.css" type="text/css"  media="screen,projection"/>

and at the bottom of the HTML script:

I'm just testing it with a simple card:

          I am a very simple card. I am good at containing small bits of information.
      I am convenient because I require little markup to use effectively. I am similar to what is called a panel in other frameworks.

  </div

however all that appears is text across the website, and no card.
Below is a screenshot of the files I have uploaded:

and finally, here is the website URL! www.econengines.com . As you can probably tell, the site is going through a lot of development, and is kinda messy right now. I'm just tryna get a navbar going, which isn't working either.
How can I get Materialize CSS to materialise?
Comment: Assuming the HTML code you pasted above is in `home.html`, all of the resources (except `cgi-bin`) are in the same directory. So you should adjust your URI to the CSS and JS files accordingly.
Comment: the code above is in 'index.html'. what would I need to change?
Answer: Since the HTML file is in the same location as your CSS and JS resources, you should change the locations as below.

to

and
<link rel="stylesheet" href="/css/bootstrap.min.css">
<link rel="stylesheet" href="css/materialize.min.css" type="text/css"  media="screen,projection"/>

to
<link rel="stylesheet" href="bootstrap.min.css">
<link rel="stylesheet" href="materialize.min.css" type="text/css"  media="screen,projection"/>

More details on having links relative to root.

Materialize CSS simple installation


Facebook-like share a link parsing?

Question: How does facebook share a link parsing work?
Given a url, i need to extract title, blurb and thumbnail (if any).
Are there any libraries or widgets that already do this?
(preferably client side javascript)
Answer: You cant do this on client only.
For the reason see: Why cant I load an external resource from jQuery load method? And the accepted answer there gives you the options.
You will have to do it like this:

Create a server script that loads the page. Your javascript code sends a request with the given link to this script.
This script may parse the requested page to get the wanted information (This answer may help you for PHP and this one for java)
Your script may return JSON Data which you can process with javascript in the browser

Facebook-like share a link parsing?


For any $\varepsilon >0$, there is an $n\in\mathbb{N}$ such that $\dfrac {1} {n} < \varepsilon$.

Question: Archimedean Property. For any $x,\varepsilon\in\mathbb{R}$, $\varepsilon>0$, there is an $n\in\mathbb{N}$ such that $n\varepsilon>x$.
Corallary. For any $\varepsilon >0$, there is an $n\in\mathbb{N}$ such that $\dfrac {1} {n} < \varepsilon$.
Proof of Corollary. If we calculate this inequality, we obtain $n\varepsilon >1$. So, by the Archimedean property we have $n\varepsilon >1$. So, we are done.
Can you check my proof of corollary?
Comment: It's not clear, what it is you mean by calculate the inequality. You should also mention explicitly that for $x=1$, and so on...
Comment: @AnotherJohnDoe Okey. Thanks.
Answer: Working backwards is a good technique to figure out how to get your proof to work out, but when presenting your proof, usually you want to present it in the "forward" direction. So something along the lines of,

Let $\varepsilon >0$. Since $\varepsilon > 0$, then by the
  Archimedian property, there exists an $n \in \mathbb{N}$ such that
  $n\varepsilon > 1$. From this, one sees that $1/n < \varepsilon$.

Note that you'll need to work through some of the details such as showing that the inequality you get from the Archimedian property is equivalent to the desired inequality. Doing this will depend on your set of axioms and theorems you have at your current disposal.
Comment: My apologies...I'm up a bit later than usual and somehow ended up reading the statement of the Archimedian property as saying "$x, \varepsilon >0$". I've edited my answer.
Comment: Why do we need to show that $1\gt 0$??