text:
Q: DynDNS and mail servers I have set up an Ubuntu box with EXIM4 for handling my email, for now I only care about outgoing email.  My router manages my DynDNS.com psuedo static-IP addressing.  Port forwarding for port 25 is open and shows up with a port-scan.  The firestarter firewall on the box shows access attempts and I have added a permit rule.
Outgoing email seems to work as I wanted, and it is configured to send through my gmail account.  The problem is that GMail is spamming me every 10-20 minutes with a Delivery Status Notification message complaining about connection refused.  It seems to be that Google is trying to email my root@<dyndns-account> account.
How should I overcome this problem?  How could I set up complete in/out email access?  What is the best course of action for a private web-site that needs minimal email support (e.g. the MediaWiki I'm hosting, etc).
EDIT - added an anonymous copy of the email
    This is an automatically generated Delivery Status Notification

    THIS IS A WARNING MESSAGE ONLY.

    YOU DO NOT NEED TO RESEND YOUR MESSAGE.

    Delivery to the following recipient has been delayed:

        root@mydomain.is-a-geek.com

    Message will be retried for 2 more day(s)

    Technical details of temporary failure:
    The recipient server did not accept our requests to connect. Learn more at http://mail.google.com/support/bin/answer.py?answer=7720
    [mydomain.is-a-geek.com (1): Connection refused]

      ----- Message header follows -----

    Received: by 10.210.89.7 with SMTP id m7mr1107333ebb.14.1246185600392;
           Sun, 28 Jun 2009 03:40:00 -0700 (PDT)
    Return-Path: <me@gmail.com>
    Received: from MyMachine (isp.com [xx.xx.xx.xxx])
           by mx.google.com with ESMTPS id 10sm7080189eyz.31.2009.06.28.03.39.59
           (version=TLSv1/SSLv3 cipher=RC4-MD5);
           Sun, 28 Jun 2009 03:39:59 -0700 (PDT)
    Received: from smmsp by MyMachine with local (Exim 4.69)
           (envelope-from <smmsp@mydomain.is-a-geek.com>)
           id 1MKrnl-00075G-Oe
           for root@mydomain.is-a-geek.com; Sun, 28 Jun 2009 11:40:01 +0100
    From: Cron Daemon <me@gmail.com>
    To: root@mydomain.is-a-geek.com
    Subject: Cron <smmsp@MyMachine> test -x /etc/init.d/sendmail && /usr/share/sendmail/sendmail cron-msp
    Content-Type: text/plain; charset=UTF-8
    X-Cron-Env: <MAILTO=root>
    X-Cron-Env: <SHELL=/bin/sh>
    X-Cron-Env: <HOME=/var/lib/sendmail>
    X-Cron-Env: <PATH=/usr/bin:/bin>
    X-Cron-Env: <LOGNAME=smmsp>
    Message-Id: <E1MKrnl-00075G-Oe@MyMachine>
    Date: Sun, 28 Jun 2009 11:40:01 +0100

      ----- Message body suppressed -----

A: Wait... Is mail to local users going out to gmail's smtp servers and then coming back to your server?  That's something you want to avoid.  You need to tell exim that all mail to your domain(s) should be delivered locally, and all other mail can then go via gmail as a smarthost (definitely not as a delivery agent).
Edit: These instructions may help.

A: Did you check if you correctly set your domain's MX record?
DynDNS.com Support - E-mail, Mail Exchangers, and DNS
A wrong configuration would explain that you "see" port 25 when you connect from outside to your IP address, but not the sending SMTP service which is unable to resolve your domain's MX record.


text:
Q: After Hours Server Monitoring Procedures How does your company handle monitoring and administering servers after-hours and during holidays?  Do you require that some come into the office?  If not, how do you insure that staffing is available to handle any issues that come up?
Presumably it would be possible to give out mobile data cards, but is this a practical solution in the real world?  Are employees compensated for this in any way?

A: Simple!  Draw straws... the guy who draws the "short straw" loses. ;-)

On a more serious note.  We have a monitoring system that pages all of the sys-admins whenever something goes down.
We have a good bunch of people who are on top of things.  Nobody is compensated for logging in with VNC and restarting the mail server but people ARE compensated when say a hard drive crashes and it requires a trip down to the colo and a RAID rebuild or something.
Most companies I know of do pay for the sysadmin cell phones or gives a good discount.  Depends on if the phone is for personal use as well.  I've also seen company issued laptops and in some rarer cases broadband internet cards.
In the REAL world... there's a PC around or a hotspot (be sure to THINK and encrypt your stuff traffic) around somewhere.
The reality is... right now most people are happy to be gainfully employed right now and when you love your job... its just PART of the job.

The only REAL problem I've heard of (in regards to perks) was with an employee who was absolutly OBSESSED with his Red Swingline stapler.  Management wouldn't listen, took the stapler away, and as a result the employee lost it and burned the whole place down!
(tongue in cheek reference) ;-)

A: Right now, I'm the only admin at my company, so when there is an issue, I get an SMS & email from the Nagios server that monitors the affected host.
I'm soon to be hiring a junior admin, and when that happens, we're going to get to do on-call rotation (once the person is trained and ready, anyway).
My cell phone is paid for (as will the new admin's), and we have a certain flexibility in terms of when I come in and leave. As long as I don't abuse it, it works fine.
We're a small company with 17 people and somewhere between 50-70 servers that runs 24x7x365 automated processes.

A: When I ran a group of admins the issue of who was oncall was always a concern.
At the time I felt that it was all part of the job of being an admin, but alas, in hindsight, while I loved the job, it didn't mean they did.
Not paying a stipend or some other acknowledgement of required ad-hoc hours (either onsite or remote) is just a slap-in-the-face.  Regardless of budgeting, folks asked to carry pagers and response in a timely manner should be given credit either as pay, flex hours, paid cell plans, etc.
Where I work now it's a flat-fee stipend.  You can spend it on your cell plan, internet connection, laptop, etc... if you do your job well, 'in theory' you wont get calls that could be avoided, just 'acts of god' ;-)
Luckily all the stuff I do now does not require on-site presence (whew).

A: We have a central monitoring server which notifies administrators of issues with their machines.  We are all strictly speaking on call 24x7.  So when the blackberry goes off we look and decide if we have to do something about it.  In theory we're paired up with another administrator and should be able to back the other up.  This works better or worse depending on the paring.  So when I'm on vacation my buddy should cover my stuff and vice versa.
Blackberries are provided by the university, but we get taxed on them, so they're not totally free, but pretty cheap. We also have partial reimbursement for our broadband internet expenses.  We have a VPN too.  So really I don't have to be at work to work except in the most extreme situations.
We don't have an official plan for compensating people for time worked outside normal hours.  In practice if you work a couple late night hours you can email in that you'll be in after lunch.  We have a ton of flexibility in when we have to be here, which makes up for the lack of on call rotations.
During working hours we have a couple people who's job it is to process route and sort tickets. They also watch the queues in the evenings.  For serious emergencies there is a phone, that gets called, (and is usually in the possession of one of the managers) and then the right resources are dispatched.  Sad for those of us who got woke up to say "Uh- that's not mine but I can fix it if you can't find the right guy"  but it works out pretty fair in the end.

A: We use a company paid cellphone that is able to do tethering, So laptops can connect to the internet through their phone (most employees just use their home connection since it is faster)
The cellphone receives TXT messages & Emails from Nagios with alerts.
As an IT company with today's VPN capabilities we do not require any technician / engineer to actually come into the office after-hours or during holidays unless solving the issue requires them to.

A: We give pagers out and have an on call rotation. The person who is on call can take a wireless modem if required, but everybody has a home internet connection also that is used. Re: compensation, it depends on the situation. On option is to have compensation be salary based (same regardless of number of hours worked), and let potential employees know this up front and to take the on call time into account when negotiating salary.

A: *

*We run a monthly on-call rota

*We use Citrix and VPN extensively so 95% of problems (almost everything has Remote Console) can be resolved from any internet connected computer in the world, removing the need to physically attend an office

*We have housed all our servers (000's) at [insert large Telco here] data centres, who provide 24/7 hands & eyes support when required

*We utilise [insert large Telco here] Helpdesk to deal with 1st line user issues 24/7

*We utilise [insert large Telco here] ticketing system that has escalation paths, and is tied into the on-call rota

*We issue data cards and laptops to staff that will be in remote locations during their on-call period

A: I've worked at "it's part of the job, suck it up" companies.  It got old after a while.
My current employer does a voluntary rotation.  If you take the rotation, you get one week in (how ever many people are in the rotation).  You get a small extra pay for being the "on-call" person that week, and time-for-time for anything you have to do after hours.
It only works if time-for-time is tracked (which is easy, since 95% of everything we do is billable back to a customer) and you are actually permitted to take it.
My current employer pays for phone/Blackberries through a corporate plan, but that's due to the nature of our business and isn't special to on-call staff.

redpajama_set_name: RedPajamaStackExchange


text:
Q: NSXMLParser does not finish file I am parsing an XML file in my app and the oddest thing happens. It stops after a number of elements, not finishing that element yet the parse method still returns succes. I have the feeling it is a wrong character somewhere but cannot figure it out. Does anyone have any idea why it halts during the parsing. And why, if it doesn't finish the file does it return true for being done parsing?
File that parses:
MOOAnimal *soort;
NSString *currentElementValue;

- (void) getData
{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"soorten" ofType:@"xml"];

    NSURL *xmlUrl = [NSURL fileURLWithPath:filePath];

    NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:xmlUrl];

    [parser setDelegate:self];

    BOOL succes = [parser parse];

    if(succes)
    {
        data = true;
        beestjes = [NSArray arrayWithArray:soorten];
    }

}

- (void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if([elementName isEqualToString:@"soorten"])
    {
        soorten = [[NSMutableArray alloc] init ];
    }
    else if([elementName isEqualToString:@"soort"])
    {
        soort = [[MOOAnimal alloc] init];
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    currentElementValue = nil;
    currentElementValue = [[NSString alloc] initWithString:string];
     NSLog(@"Naam: %@", currentElementValue);
}

- (void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if([elementName isEqualToString:@"soorten"])
    {

    }
    else if([elementName isEqualToString:@"soort"])
    {
        [soorten addObject: soort];
        soort = nil;
    }
    else if([elementName isEqualToString:@"nl"])
    {
        [soort setName:currentElementValue];

    }
}

The XML file:
<soorten>
<soort><wormscode>117644</wormscode><localnames><nl>Ruwe zeerasp </nl></localnames><latinname>Hydractinia echinata </latinname><omschrijving></omschrijving><opmerkingen></opmerkingen></soort>
<soort><wormscode>231751</wormscode><localnames><nl>Haringgraat </nl></localnames><latinname>Halecium halecinum </latinname><omschrijving></omschrijving><opmerkingen></opmerkingen></soort>
<soort><wormscode>117273</wormscode><localnames><nl>Lampenkapje  </nl></localnames><latinname>Aequorea vitrina</latinname><omschrijving></omschrijving><opmerkingen></opmerkingen></soort>
<soort><wormscode>125333</wormscode><localnames><nl>Dodemansduim  </nl></localnames><latinname>Alcyonium digitatum</latinname><omschrijving></omschrijving><opmerkingen></opmerkingen></soort>
<soort><wormscode>283798</wormscode><localnames><nl>Viltkokeranemoon </nl></localnames><latinname>Cerianthus lloydii </latinname><omschrijving></omschrijving><opmerkingen></opmerkingen></soort>
<soort><wormscode>100803</wormscode><localnames><nl>Rode paardeanemoon </nl></localnames><latinname>Actinia equina </latinname><omschrijving></omschrijving><opmerkingen></opmerkingen></soort>
<soort><wormscode>100834</wormscode><localnames><nl>Zeedahlia  </nl></localnames><latinname>Urticina felina</latinname><omschrijving>- Doorsnede van de zuil en de voetschijf niet groter dan 10 tot 15 cm. De hoogte circa 6 cm. De tentakels tot 2 cm hoog.
- Een Zeedahlia is een grote brede zeeanemoon met korte dikke tentakels.
- Kenmerkend is de helder gekleurde tekening op de mondschijf. Deze bestaat uit dubbele lijnen die vanaf de mond gezien vóór de tentakels beginnen.
- Vrijwel alleen op hard substraat zoals stenen maar soms ook op veen of onder veenranden. Af en toe op pontons. De soort wordt aangetroffen vanaf iets boven de laagwaterlijn tot diepten van 15 meter en meer.
- Algemeen  in het Nederlandse zoute water.</omschrijving><opmerkingen></opmerkingen></soort>
<soort><wormscode>100872</wormscode><localnames><nl>Golfbrekeranemoon  </nl></localnames><latinname>Diadumene cincta</latinname><omschrijving></omschrijving><opmerkingen></opmerkingen></soort>
<soort><wormscode>395099</wormscode><localnames><nl>Groene golfbrekeranemoon  </nl></localnames><latinname>Haliplanella lineata</latinname><omschrijving></omschrijving><opmerkingen></opmerkingen></soort>
</soorten>

Where it stalls (by logging all the data/characters found)
2012-06-07 10:49:31.654 MOOFormulier[27852:f803] Naam:
2012-06-07 10:49:31.654 MOOFormulier[27852:f803] Naam: 283798
2012-06-07 10:49:31.655 MOOFormulier[27852:f803] Naam: Viltkokeranemoon
2012-06-07 10:49:31.655 MOOFormulier[27852:f803] Naam: Cerianthus lloydii
2012-06-07 10:49:31.655 MOOFormulier[27852:f803] Naam:
2012-06-07 10:49:31.656 MOOFormulier[27852:f803] Naam: 100803
2012-06-07 10:49:31.656 MOOFormulier[27852:f803] Naam: Rode paardeanemoon
2012-06-07 10:49:31.657 MOOFormulier[27852:f803] Naam: Actinia equina
2012-06-07 10:49:31.657 MOOFormulier[27852:f803] Naam:
2012-06-07 10:49:31.658 MOOFormulier[27852:f803] Naam: 100834
2012-06-07 10:49:31.658 MOOFormulier[27852:f803] Naam: Zeedahlia
2012-06-07 10:49:31.659 MOOFormulier[27852:f803] Naam: Urticina felina
2012-06-07 10:49:31.659 MOOFormulier[27852:f803] Naam: - Doorsnede van de zuil en de voetschijf niet groter dan 10 tot 15 cm. De hoogte circa 6 cm. De tentakels tot 2 cm hoog.

A: In parser:foundCharacters: you should append string to currentElementValue, not overwrite the whole string. Also log your values in parser:didEndElement:
NSMutableString *currentElementValue;
[...]

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    currentElementValue = [NSMutableString new];
    [...]
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
     NSLog(@"Element: %@ Value: %@",elementName, currentElementValue);
    [currentElementValue release];
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    [currentElementValue appendString:string];
}

A: A colleague who also looked into the problem pointed out I did not define a character set in a  tag at the beginning of the file. This caused the parser to trip over certain unique characters in the file. With that set it works fine now.
Credit goes to my colleague who I still need to convert to a StackOverflow user.


text:
Q: I have n number of elemet in the 2 sets and i have to go through them such that at each iteration i get the current element ans also the next element BELOW , Is the code i wrote which is showing error ( that we cant use end()-1 and itr+1 operations).
MY purpose is to go through the set as in pair. eg X[1 2 3] i want to get {1 2} {2 3}.
    for(itr=X.begin();itr!=X.end()-1;itr++)
    {
        int l1,l2;
        l1 = *(itr+1) - *itr;
        for(itr1=Y.begin();itr1!=Y.end()+1;itr1++)
        {

            l2 = *(itr1+1) - *itr1;

            int l = min(l1,l2);
            int num = (l*l)/(a*a);

            count += num;
        }
    }

A: Set iterators don't support + or -. This seems like the easiest way to do what you want
std::set<int> X = ...;
auto i = X.begin();
if (i != X.end())
{
    auto j = ++i;
    while (j != X.end())
    {
        int l1 = *j - *i;
        ...
        // similar code for Y loop
        ...
        ++i;
        ++j;
    }
}

It basically the same as your code but it uses two adjacent iterators i and j in one loop to avoid having to use + and -.


text:
Q: How do I implement these angles in my ThreePoint triangle program in java? I'm trying to implement

in my ThreePoint program in java.
Here is my getLength method to calculate the sides
   private double getLength(int side){

     if(side == 0 && isTriangle()){
         return Math.sqrt((x2-x1) * (x2-x1) + (y2-y1) * (y2-y1));
     } else if (side == 1 && isTriangle()){
         return Math.sqrt((x2-x0) * (x2-x0) + (y2-y0) * (y1-y0));
     } else if (side == 2 && isTriangle()){
         return Math.sqrt((x1-x0) * (x1-x0) + (y1-y0) * (y1-y0));
     }else{ return 0;

     }
     }

The parameter vertex should be 0, 1, or 2 and is used to specify angle a0, a1, or a2. The method returns the angle of the specified vertex. If the three points do not form a triangle, this method should return zero. To determine the angles of the triangle you can use the law of cosines.(as above)
so below is what the skeleton would look like, how do I implement the diagram though?
 public double getAngle(int vertex){

            if(vertex == 0 && isTriangle()) {
           return a0 here; }
           else if(vertex == 1 && isTriangle()) {
           return a1 here; }
           else if(vertex == 2 && isTriangle()) {
           return a2; }

A: My java is a little rusty, and my trig is even rustier, but I think what you want for a0 is below.  You can figure out a1 and a2 from below.  Also note that Java trigonometry uses Radians not degrees, but that shouldn't be a problem here.
double s02 = Math.pow(this.getLength(0),2);
double s12 = Math.pow(this.getLength(1),2);
double s22 = Math.pow(this.getLength(2),2);
a0 = Math.acos((-s02+s12+s22)/(2*s12*s22));

Note:  I assume s0 s1 and s2 are the lengths of side 0,1, and 2 correct?


text:
Q: Finding out the length between two points I have following diagram with these values:

How can I determine the length of OD and BD?

A: $BD:BC=OD:OA$ and $BD+OD=4$ are two linear equations. The solution is $BD=5/2$ and $OD=3/2$.


text:
Q: Spliting std::string and a character array into two halves (efficiently) How can we split a std::string and a null terminated character array into two halves such that both have same length?
Please suggest an efficient method for the same.You may assume that the length of the original string/array is always an even number.
By efficiently I mean using less number of bytes in both the cases, since something using loops and buffer is not what I am looking for.

A:     std::string s = "string_split_example";
    std::string half = s.substr(0, s.length()/2);
    std::string otherHalf = s.substr(s.length()/2);

    cout << s.length() << " : " << s << endl;
    cout << half.length()  << " : " << half << endl;
    cout << otherHalf .length()  << " : " << otherHalf  << endl;

Output:
20 : string_split_example
10 : string_spl
10 : it_example

Online Demo : http://www.ideone.com/fmYrO

A: You've already received a C++ answer, but here's a C answer:
int len = strlen(strA);
char *strB = malloc(len/2+1);
strncpy(strB, strA+len/2, len/2+1);
strA[len/2] = '\0';

Obviously, this uses malloc() to allocate memory for the second string, which you will have to free() at some point.


text:
Q: How to get exact position of a panel or picturebox? I'm creating C# application where I have a text box and a panel on the main form. I want to get the exact position of the panel relative to the screen's top-left corner (0,0). When I call this.Left and this.Top at the form it gives me the correct coordinates, but when I call panel.Location.X and panel.Location.Y it results in coordinates relative to the form, which is constant no matter where my form is located on the screen.
I want to get the top and left coordinates of a panel not relative to the form but relative to the screen, assuming top & left of the screen is (0,0).
How can I get the absolute position of my panel?

A: Use Control.PointToScreen Method to get location relative to screen:
Point location = PointToScreen(panel.Location);


text:
Q: GlusterFS how to failover (smartly) if a mounted Server is failed? In GlusterFS, lets say i have 2 Nodes (Servers) on a Volume. Lets say the volume info is something like this:
Volume Name: volume-www

Brick1: gluster-server-01:/volume-www/brick
Brick2: gluster-server-02:/volume-www/brick

From the Client, as we know, we have to mount the volume volume-www by mounting from one Server. Like:
mount -t glusterfs  gluster-server-01:/volume-www  /var/www

I still feel there's a choke point since i am connecting to that gluster-server-01 only.

*

*What if it is FAILED?

Ofcourse I can manually mount from another healthy Server again. But is there a smarter way (industrial approach) to solve this?

A: OpenUserX03's answer is not quite accurate.
When a client connects to a Gluster server node, it receives information about all the nodes. After that, it starts communicating with multiple nodes simultaneously. So when one node dies, it does not "failover", it just lose that node but keep the communication going on with the others:
In their documented note:

The server specified in the mount command is only used to fetch the
  gluster configuration volfile describing the volume name.
  Subsequently, the client will communicate directly with the servers
  mentioned in the volfile (which might not even include the one used
  for mount).

A: When you are doing this:
mount -t glusterfs  gluster-server-01:/volume-www  /var/www

You are initially connecting to one of the nodes that make up the Gluster volume, but the Gluster Native Client (which is FUSE-based) receives information about the other nodes from gluster-server-01.  Since the client now knows about the other nodes it can gracefully handle a failover scenario.

A: You can use two way below:

*

*Use backupvolfile options fstab

server1_name:/media /media glusterfs
  defaults,_netdev,backupvolfile-server=server2_name,log-level=WARNING,log-file=/var/log/gluster.log
  0 0

*create data file /etc/datastore.vol example

volume mymedia-client-0
    type protocol/client
    option clnt-lk-version 1
    option volfile-checksum 0
    option volfile-key /mymedia
    option client-version 3.8.12
    option process-uuid server01.vn-7565-2017/10/03-02
    option fops-version 1298437
    option ping-timeout 42
    option remote-host 192.168.10.79
    option remote-subvolume /data01/brick
    option transport-type socket
    option transport.address-family inet
    option send-gids true end-volume   volume mymedia-client-1
    type protocol/client
    option clnt-lk-version 1
    option volfile-checksum 0
    option volfile-key /mymedia
    option client-version 3.8.12
    option process-uuid server01.vn-7565-2017/10/03-02
    option fops-version 1298437
    option ping-timeout 42
    option remote-host 192.168.10.80
    option remote-subvolume /data01/brick
    option transport-type socket
    option transport.address-family inet
    option send-gids true end-volume   volume mymedia-replicate-0
    type cluster/replicate
    subvolumes mymedia-client-0 mymedia-client-1 end-volume   volume mymedia-client-2
    type protocol/client
    option ping-timeout 42
    option remote-host 192.168.10.81
    option remote-subvolume /data01/brick
    option transport-type socket
    option transport.address-family inet
    option send-gids true end-volume   volume mymedia-client-3
    type protocol/client
    option ping-timeout 42
    option remote-host 192.168.10.82
    option remote-subvolume /data01/brick
    option transport-type socket
    option transport.address-family inet
    option send-gids true end-volume   volume mymedia-replicate-1
    type cluster/replicate
    subvolumes mymedia-client-2 mymedia-client-3 end-volume   volume mymedia-dht
    type cluster/distribute
    option lock-migration off
    subvolumes mymedia-replicate-0 mymedia-replicate-1 end-volume   volume mymedia-write-behind
    type performance/write-behind
    subvolumes mymedia-dht end-volume   volume mymedia-read-ahead
    type performance/read-ahead
    subvolumes mymedia-write-behind end-volume   volume mymedia-readdir-ahead
    type performance/readdir-ahead
    subvolumes mymedia-read-ahead end-volume   volume mymedia-io-cache
    type performance/io-cache
    subvolumes mymedia-readdir-ahead end-volume   volume mymedia-quick-read
    type performance/quick-read
    subvolumes mymedia-io-cache end-volume   volume mymedia-open-behind
    type performance/open-behind
    subvolumes mymedia-quick-read end-volume   volume mymedia-md-cache
    type performance/md-cache
    subvolumes mymedia-open-behind end-volume   volume mymedia
    type debug/io-stats
    option log-level INFO
    option latency-measurement off
    option count-fop-hits off
    subvolumes mymedia-md-cache end-volume   volume meta-autoload
    type meta
    subvolumes mymedia end-volume

vs fstab content:
/etc/datastore.vol /media glusterfs defaults,_netdev,log-level=WARNING,log-file=/var/log/gluster.log 0 0


text:
Q: How can I use data group and exhibit the results in a Column Chart? Is it possible? I have this:
    <!DOCTYPE html>

        <meta charset="UTF-8"/>

Actually displays a blank page.
I need to group this data because later i'll need to use multiple charts and tables with the same data source to be controlled by the only string filter in page, that will filter all the charts by the column "Branch".
Is it possible?
Dont know what I'm doing wrong

A: first, the container id,
when using getElementById, do not include #
it should be...
document.getElementById('t2')

next, the chart class should capitalized --> ColumnChart
see following working snippet...

google.charts.load('current', {'packages':['corechart', 'controls']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
  var data = new google.visualization.DataTable();
  data.addColumn('number', 'ID');
  data.addColumn('string', 'Customer_Name');
  data.addColumn('number', 'Credits');
  data.addColumn('string', 'Date');
  data.addColumn('string', 'Seller');
  data.addColumn('string', 'Branch');

  data.addRows([
    [123, 'Customer1', 400, '01/02/03', 'Seller1', 'Branch1'],
    [321, 'Customer2', 300, '01/02/03', 'Seller2', 'Branch1'],
    [213, 'Customer3', 500, '01/02/03', 'Seller3', 'Branch3']
  ]);

  var groupedData = google.visualization.data.group(data, [5], [{
    column: 0,
    type: 'number',
    label: data.getColumnLabel(0),
    aggregation: google.visualization.data.count
  }]);

  var t2 = new google.visualization.ColumnChart(document.getElementById('t2'));
  t2.draw(groupedData);
}


text:
Q: django-rest-auth urls not found I'm trying to implement django-rest-auth, but the url is not recognized and throw 404 error. The 'rest_auth' is added in the INSTALLED_APPS and path also included in the urls.py file.
Request URL:    http://127.0.0.1:8000/api/v1/rest-auth/login/
Using the URLconf defined in blog_project.urls, Django tried these URL patterns, in this order:

admin/
api/v1/ <int:pk>/
api/v1/
api-auth/
api/v1/rest-auth ^password/reset/$ [name='rest_password_reset']
api/v1/rest-auth ^password/reset/confirm/$ [name='rest_password_reset_confirm']
api/v1/rest-auth ^login/$ [name='rest_login']
api/v1/rest-auth ^logout/$ [name='rest_logout']
api/v1/rest-auth ^user/$ [name='rest_user_details']
api/v1/rest-auth ^password/change/$ [name='rest_password_change']
The current path, api/v1/rest-auth/login/, didn't match any of these.

settings.py content
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # 3rd Party
    'rest_framework',
    'rest_framework.authtoken',
    'rest_auth',

    # Apps
    'posts.apps.PostsConfig',
]

Below is the content of my urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/v1/', include('posts.urls')),
    path('api-auth/', include('rest_framework.urls')),
    path('api/v1/rest-auth', include('rest_auth.urls')),
]

I'm not able to figure out, what is wrong with the code.

A: Your problem is here.
path('api/v1/rest-auth', include('rest_auth.urls')),

You need to add a / at the end of your URL string like this -
path('api/v1/rest-auth/', include('rest_auth.urls')),

A: In your urls.py, you need to implement a url for api/v1/rest-auth/login/.

A: found the cause, was just missing an "/" in the path. Now its working fine.
path('api/v1/rest-auth/', include('rest_auth.urls'))


text:
Q: How to use MapView in google map V2 android? I want to use onTouch events (to handle the rotation gesture of an object on map). I cannot do it with extending the Activity in mainActivity and using fragments. So I guess I should use MapView class. How can I do this in new version of google maps android (V2)?
This will show nothing. a blank white screen on phone only.
The MainActivity:
public class MainActivity extends Activity {

 // MapView mapV;
 // GoogleMap map;

 @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mapV = ((MapView) findViewById(R.id.map));
    map = mapV.getMap();
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
  }

}

The activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

   <com.google.android.gms.maps.MapView
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

A: In your activity you have to implement all the life cycle methods (onPause, etc) and in there forward it on to your map, e.g.
@Override
public void onPause() {
    map.onPause();
    super.onPause();
}


text:
Q: Retain expanded rows after databinding Kendo UI grid This is my first time working with Kendo UI. I have a Kendo UI grid with child nodes. I want to retain the expanded rows after databinding. Right now its getting collapsed after a row is added in the child
I have tried suggestion from here
dataBound: function() {
    this.expandRow(this.tbody.find("tr.k-master-row").first());
}

But this expands the first row only.
How to retain rows? What am I missing?
Codepen

A: After a lot of playing around with your code example in CodePen, I believe I've come up with an elegant solution that works.
Having worked with Kendo UI for over three years, I've become pretty familiar with some of its inner workings. As such, I'm going to take advantage of one of these - the data-uid attribute. Kendo UI puts these on all <tr> elements in its grid. I chose this attribute because I know that when we call grid.expandRow() we're going to need to fashion a valid jQuery selector to pass in as a parameter. This eliminates the need for us to add our own attributes or classes and the code to handle them.
First, we need to define a variable to hold our row reference. We'll call it expandedRowUid. To set its value, we hook into the detailExpand event of the grid. So, when the user expands a row, we store its data-uid number.
var expandedRowUid;

var grid = $('#grid').kendoGird({
  // ...
  detailExpand: function(e) {
    expandedRowUid = e.masterRow.data('uid');
  }
});

Then, whenever a change is made that causes the master grid to re-bind to its data, we hook into the dataBound event of the grid and re-expand the row that has a data-uid equal to the one stored in expandedRowUid.
var grid = $('#grid').kendoGird({
  // ...
  detailExpand: function(e) {
    expandedRowUid = e.masterRow.data('uid');
  },
  dataBound: function() {
    this.expandRow($('tr[data-uid=' + expandedRowUid + ']'));
  }
});

Here is the working CodePen example.
NOTE: This will only re-expand the last row that was expanded before the data bind is triggered. So, if you expand rows 4, 5, and 2 in that order, and then trigger a data bind, only row 2 will be re-expanded. You can obviously extend this functionality to handle use cases like that though.

A: GridDetailExpand: function (e) {
   var gridId = e.sender.element[0].id;
   var grid = $("#" + gridId).data("kendoGrid");
   var data = grid.dataItem(e.masterRow);
   addToArray(expandedRows, data.UniqueIdOfYourDataInGrid);
  },
  GridDetailCollapse: function (e) {
   var gridId = e.sender.element[0].id;
   var grid = $("#" + gridId).data("kendoGrid");
   var data = grid.dataItem(e.masterRow);
   removeFromArray(expandedRows, data.UniqueIdOfYourDataInGrid);
  }

And then on databound
var gridId = e.sender.element[0].id;
var grid = $("#" + gridId).data("kendoGrid");
$.each(grid.tbody.find('tr.k-master-row'), function () {
 var data = grid.dataItem(this);
 if (isInArray(expandedRows, data.UniqueIdOfYourDataInGrid)) {
   grid.expandRow(this);
 }
});

Functions required:
var expandedRows = [];

function addToArray(arr, value) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] === value) return;
    }

    arr.push(value);
}

function removeFromArray(arr, value) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] === value) {
            delete arr[i];
            return;
        }
    }
}

function isInArray(arr, value) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] === value) return true;
    }

    return false;
}

Hope this helps ... took me a while to figure it out...

A: Solution for Retaining Last Expanding row in the parent grid after records added in the child grid get refreshed.

 detailInit: function (e) {

    //Get Parent Grid Last expanded Row index
    lastRowIndex = $(e.masterRow).index(".k-master-row");

 },
 dataBound: function () {

    //Check any parent grid row is expanded based on row index
    if (lastRowIndex != null && lastRowIndex != undefined){

      //find the Grid row details based on row index
      var row = $(this.tbody).find("tr.k-master-row:eq(" + lastRowIndex + ")");

      //If expand Row exists then it will expanded
      this.expandRow(row);
    }
    else {

      //None of the Parent Grid row is expanded then,default First row is expanded
      this.expandRow(this.tbody.find("tr.k-master-row").first());

    }
}


text:
Q: What is the difference between requirements and specifications? I've been tasked with developing requirements and specifications for a project our group is starting.
I realized that I don't know the difference; a Google search just confused me more -- it seems some people say that specifications are requirements, but at a lower level.

A: Requirements are the users' description of what the finished product, in their eyes, should do.
Specification is the technical description of the solution in general, covering the requirements and much more - e.g. cost, technicalities, problems, etc.
Therefore, one of the main points is that the Requirements must come first before a Specification can be written.
(Notice the terminology - product and solution - the same thing but from different perspectives...)

A: Requirements document what is needed - they shouldn't specify the how, but the what.
Specifications document how to achieve the requirements - they should specify the how.
In many places these documents are not separate and are used interchangeably.

A: Perhaps the confusion is that I have heard specifications refer to Business Requirement Specification documents or IEEE standard SRS (Software Requirement Specification) documents.
IEEE standard SRS Template Example
I have also heard the term specifications refer more informally to Technical Specifications which explain design decisions and an implementation plan.
EDIT: I just noticed the link is incorrect... I will post a correct link shortly.

A: Requirement - what the system or subsystem should (must) do.
Specification - What the component, subsystem or system IS.
This is critical in the medical device manufacturing industry since you must conduct Verification against your requirements (Inputs) to demonstrate that you have valid specifications (Outputs). Typical pitfalls in this industry is that companies (1) forget to define requirements (because they don't understand the difference between requirement versus spec); (2) Conduct Verification against only specifications and (3) Do not assure that Requirements are being translated accurately in to subassembly and component specifications.
Once this is all done, you are then required to Validate the User requirements for the product have been met.

A: A specification is a requirement that passed feasibility and is ready to be implemented.
It is a requirement that has evolved to the design phase.
In other words:

*

*A requirement is behavior (or non-behavior) "as planned" or "as
wished"

*A specification is behavior (or non-behavior) "to be built" or "as built"

Example:

*

*requirement:    1. user presses OK button 2. system prints invoice

*specification:   1. user presses OK button 2. system prints invoice

As you can see, the content of both can be the same. The difference is that requirement is an analysis artifact. The specification is a design artifact.
In a final as-built documentation, you will typically find the word "specification", instead of "requirement", since the requirements have been converted to specifications.
Remark:  example above contains design elements, because of design constraint.

A: I am a systems engineer in the aerospace field, where both terms are used extensively. The distinction is clear and not as complex as the others are making it.
A specification is a document that specifies a system or product, e.g. a prime-item development specification for an F-14. There are lots of sections/content in a spec: requirements, definitions, reference documents, glossary, verification information, etc.
A requirement is a single statement of something the product or system must do. A  spec may have hundreds of requirements in it. Old school methodology says the requirement statement must use the word "shall", to separate requirements from statements of facts, or definitions. (Not sure if the new-fangled agile kids keep to all this or not; the fastidiousness has it's use but is a little fussy at times.)
So a spec is a document full of requirements, plus some other supporting and ancillary information.

A: The sound-bite answer is that requirements are what your program should do, the specifications are how you plan to do it.
Another way to look at it is that the requirements represent the application from the perspective of the user, or the business as a whole. The specification represents the application from the perspective of the technical team. Specifications and requirements roughly communicate the same information, but to two completely different audiences.

A:
Requirements:
Determine the needs or conditions to meet for a new or altered product, taking account of the possibly conflicting requirements of the various stakeholders.
Specifications:
They provide a precise idea of the problem to be solved so that they can efficiently design the system and estimate the cost of design alternatives. They provide guidance to testers for verification (qualification) of each technical requirement.

The quote is from "Systems Engineering Fundamentals*".
Requirements are based on stakeholders needs, specifications are more an inside detailed and technical document. They are different, but they talk about the same thing.
* Defense Acquisition University Press, 2001. PDF version of the text.

A: Requirements are what the application DOES
Specifcations are HOW the application does what it does.
They must be orthogonal !
Product managers write the requirements, head engineers write the specs.

A: One way, maybe not the right way, to look at it:
Requirements are things (capabilities, features, behaviours, etc) that yield value to the user. Not concerned with internals; only the box's inputs and outputs (and maybe size, shape, and colour) are important here.
Specifications are things (capabilities, features, behaviours, etc) that enable that value for the user. Here the box internals are important, because along with the external interfaces and characteristics mentioned above they define the entire system.

A: In a previous company creating commercial products we had the following distinction:
Requirements are what the system must do. They can be lower level, detailed requirements, and they can be functional or non functional.
Specifications are those things the system as-built actually does.
E.g. you could have a requirement that states the system shall have behaviour X at –10°C. The actual specification of the system may be that the system does X at –5°C; this would be in the sheet sent to potential customers when they want to buy the system.
NB in this case the specification does not equal the requirement.

A: In my research, I have found Specifications to be used for patents and House Construction (as part of a contract).
The definition of a requirement from Webster's Unabridged Dictionary (3rd New Int'l Ed.) is:
a) something that is wanted or needed: Necessity
 b) something called for or demanded: a requisite or essential condition: a required    quality, course, or kind of training
I think the above shows them to be clearly different.  I guess you could call spec's lower level requirements, but I think it is a perversion of the term requirement imho.

A: Think, you are going to build a high rise building on a land.
Now you need to consider the Requirements before you start, such as:

*

*Architecture or Design Engineer

*Soil Test Engineer

*Wind Pressure Test Team

*Demolisher

*Digger

*Man Power

*Water Supply

*Workers living/rest area

*Enough Fund

*Project Management

*Quality Management

*Security and Safety Control

Etc.
Now the above contents are part of Requirements to build a high rise building.
From the above team, you get the technical outcome, which they hold as part of profession.
This is exactly, what is happening in software industry, a group of professional people involved to provide knowledge to build the technical specification, such as someone works on UI design, OO design, database design, graphic design, test case design, coding, integration,  deployment team etc.
The above para will be part of handbook, that you can call Technical Specification.


text:
Q: Scala View Bounds Chaining Issue I know view bounds may be deprecated soon. Please ignore that.
The following code compiles if only one of the last 3 implicit conversions are uncommented. Is this a compiler bug?
object Viewable extends App {
  /** Speed of light in m/s */
  val C: Double = 299293458d

  /** @param weight in kilograms */
  case class Matter(name: String, weight: Double) {
    /** @return matter-energy equivalence in megajoules */
    def energy: Double = weight * C * C / 1000000d

    def megaJouleMsg: String = f"$name's mass-energy equivalence is $energy%.0f megajoules."
  }

  case class Animal(name: String, height: Double, weight: Double)
  case class Vegetable(name: String, height: Double, weight: Double)
  case class Mineral(name: String, weight: Double)

  case class Bug(name: String, height: Double, weight: Double, canFly: Boolean)
  case class Whale(name: String, height: Double, weight: Double, hasTeeth: Boolean)

  case class AppleTree(name: String, height: Double, weight: Double, age: Int)
  case class Grass(name: String, height: Double, weight: Double, edible: Boolean)

  case class Sand(name: String, color: String, weight: Double)
  case class Rock(name: String, color: String, weight: Double)

  implicit def sandToMineral(sand: Sand) = Mineral(sand.name, sand.weight)
  implicit def rockToMineral(rock: Rock) = Mineral(rock.name, rock.weight)

  implicit def appleTreeToVegetable(tree: AppleTree) = Vegetable(tree.name,  tree.height,  tree.weight)
  implicit def grassToVegetable(grass: Grass)        = Vegetable(grass.name, grass.height, grass.weight)

  implicit def bugToAnimal(bug: Bug)       = Animal(bug.name, bug.height, bug.weight)
  implicit def whaleToAnimal(whale: Whale) = Animal(whale.name, whale.height, whale.weight)

  implicit def animalToMatter[X <% Animal](animal: X)          = Matter(animal.name,    animal.weight)
  implicit def vegetableToMatter[X <% Vegetable](vegetable: X) = Matter(vegetable.name, vegetable.weight)
  implicit def mineralToMatter[X <% Mineral](mineral: X)       = Matter(mineral.name,   mineral.weight)

  println(Animal("Poodle", 1.0, 8.0).megaJouleMsg)
  println(AppleTree("Spartan", 2.3, 26.2, 12).megaJouleMsg)
  println(Rock("Quartz crystal", "white", 2.3).megaJouleMsg)
}

The error messages are:
type mismatch;
 found   : solutions.Viewable.Animal
 required: ?{def megaJouleMsg: ?}
Note that implicit conversions are not applicable because they are ambiguous:
 both method animalToMatter in object Viewable of type [X](animal: X)(implicit evidence$1: X => solutions.Viewable.Animal)solutions.Viewable.Matter
 and method vegetableToMatter in object Viewable of type [X](vegetable: X)(implicit evidence$2: X => solutions.Viewable.Vegetable)solutions.Viewable.Matter
 are possible conversion functions from solutions.Viewable.Animal to ?{def megaJouleMsg: ?}
  println(Animal("Poodle", 1.0, 8.0).megaJouleMsg)
                ^

type mismatch;
 found   : solutions.Viewable.AppleTree
 required: ?{def megaJouleMsg: ?}
Note that implicit conversions are not applicable because they are ambiguous:
 both method animalToMatter in object Viewable of type [X](animal: X)(implicit evidence$1: X => solutions.Viewable.Animal)solutions.Viewable.Matter
 and method vegetableToMatter in object Viewable of type [X](vegetable: X)(implicit evidence$2: X => solutions.Viewable.Vegetable)solutions.Viewable.Matter
 are possible conversion functions from solutions.Viewable.AppleTree to ?{def megaJouleMsg: ?}
  println(AppleTree("Spartan", 2.3, 26.2, 12).megaJouleMsg)
                   ^

A: Well the compiler gives the error precisely. This is because there is more than one function which can Animal => Matter. i.e. your below 3 functions:
  implicit def animalToMatter[X](animal: X) (implicit ev: X => Animal) =  Matter(animal.name,    animal.weight)
  implicit def vegetableToMatter[X ](vegetable: X) (implicit ev: X => Vegetable) = Matter(vegetable.name, vegetable.weight)
  implicit def mineralToMatter[X ](mineral: X) (implicit ev: X => Mineral)  = Matter(mineral.name,   mineral.weight)

are equally eligible to be called when you do Animal("Poodle", 1.0, 8.0).megaJouleMsg.
When you call megaJouleMsg the compiler looks for any implicit function available that can take Animal and return an object containing method megaJouleMsg (Matter in your case). Now all the 3 functions can take Animal (there is no constraint coded any where) and can return Matter. So the compiler gets confused on which function to calls
Solution: From what it appears, the view bound is not required. This will do:
  implicit def animalToMatter(animal: Animal)  = Matter(animal.name,    animal.weight)
  implicit def vegetableToMatter(vegetable: Vegetable) = Matter(vegetable.name, vegetable.weight)
  implicit def mineralToMatter(mineral: Mineral)       = Matter(mineral.name,   mineral.weight)

  scala> Animal("Poodle", 1.0, 8.0).megaJouleMsg
  res1: String = Poodle's mass-energy equivalence is 716612592013 megajoules.

Edit: Looks like the confusion is because of X <% Animal. In animalToMatter function, it expects an implicit argument which can take X and return Animal. Now if you see in your scope there is no such function X => Animal. But because you are passing Animal("Poodle", 1.0, 8.0) it doesn't need any implicit function because it has already obtained Animal.
In short to repeat the compiler process on seeing Animal("Poodle", 1.0, 8.0).megaJouleMsg:

*

*Sees all functions in the current scope which can take Animal and return Matter.

*All the 3 functions can take Animal and return Matter. Note that vegetableToMatter and mineralToMatter will fail if accepted. i.e. though they are eligible but they will not succeed because they dont have any implicit function available that can X => Animal

*Throws Error

As an example consider this:
scala> implicit def f[T <% Int](n:T) = Matter("",1)
warning: there were 1 feature warning(s); re-run with -feature for details
f: [T](n: T)(implicit evidence$1: T => Int)Matter

scala> 1.megaJouleMsg
res2: String = 's mass-energy equivalence is 89576574002 megajoules.

scala> "a".megaJouleMsg
<console>:12: error: No implicit view available from String => Int.
              "a".megaJouleMsg
              ^
<console>:12: error: value megaJouleMsg is not a member of String
              "a".megaJouleMsg

Notice the error? It gives:

No implicit view available from String => Int.

and not just value megaJouleMsg is not a member of String
Which simply means "a" was eligible for the implicit function f but f could not find a function that could convert it to Int and hence it gives error No implicit view available.... If it was not eligible for function f, then it would just throw error megaJouleMsg is not a member...


text:
Q: How to create windows service to run a powershell script? I have infinite loop PowerShell (Testing purpose) script, which I want to run as a Service in Windows Server 2008 R2 (Standard).
I'm using the following command to create the Windows service,
sc.exe create "My PS1Service" binPath= "powershell.exe -NoLogo -Path D:\TEST\test.ps1"

And the result is  [SC] CreateService SUCCESS
But when I try to run the service My PS1Service , it return the following error
Windows Could not srart the My PS1Service service on Local
Computer
Error 1053: The service did not respond to the start or control
request in a family

Any help here !!!

A: Due to the length of the articles I don't want to paste them in the answer.
Check out this post which is the most comprehensive source of info I've found regarding powershell services: https://msdn.microsoft.com/en-us/magazine/mt703436.aspx
which links to an example powershell service:
 http://jf.larvoire.free.fr/progs/PSService.ps1
I didn't end up successfully modifying this as it was going to take me longer to read through it and understand it than it would to use a different method for my use case, but I'd certainly be going back to that if I needed to create a service in powershell in the future.
Also this: https://www.sapien.com/blog/2017/07/12/write-a-windows-service-in-powershell/

A: I've been looking all over the place for a decent way to make a PS1 into a service.
Easiest way I found is with Winsw:
https://github.com/kohsuke/winsw
Works like a charm.

A: I have had success with Non-sucking Service Manager (NSSM) as well.  https://nssm.cc/

A: you can create by below step:

*

*First go to the path where PowerShell script located.

*Then run below Command:
powershell.exe -ExecutionPolicy UnRestricted -File .\filename.ps1


text:
Q: Can I write codes to count the frequency of each integer, and then print each integer with its frequency? Given a list of integers:
Write codes to count the frequency of each integer, and then print each integer with its frequency. (The order of the elements does not matter)
For example, for n = [1,1,1,3,3,3,2,2,4,4,4,4,4,5,5,5,6,6,6,6,6,6,6,6,6], the print out will be:
1 3
2 2
3 3
4 5
5 3
6 9

And make each two numbers in a row.
i.e. in the first row, 3 is the frequency of 1 in the list n
My code is like that, and it shows 'builtin_function_or_method' object is not subscriptable:
n = [1,1,1,3,3,3,2,2,4,4,4,4,4,5,5,5,6,6,6,6,6,6,6,6,6]

def question_7_1(n=n):
    count=0
    for i in n:
        if i==n.index[i]:
            count=count+1
            print(i,count)

A: Implementing it in a comparatively easy to understand method.
n = [1,1,1,3,3,3,2,2,4,4,4,4,4,5,5,5,6,6,6,6,6,6,6,6,6]

freq = {}
for i in n:
    if i in freq:
      freq[i] += 1
    else:
      freq[i] = 1

print ("Count is :\n "+  str(freq))

This should return the integer and the count.
The error in your code is the use of n.index[i]. It should've been n.index(i).
Output:
Count is :
 {1: 3, 3: 3, 2: 2, 4: 5, 5: 3, 6: 9}

For a better implementation, refer to the answer by @Sheri!

A: n = [1,1,1,3,3,3,2,2,4,4,4,4,4,5,5,5,6,6,6,6,6,6,6,6,6]

def question_7_1(n):
    dict ={}
    for j in n:
        count=1
        #print(j)
        if j in dict.keys():
            count = dict[j]
            count=count+1
            dict[j] = count
        else:
            dict[j] = count
    dict[j] = count
    #print(dict)
    return dict

result = question_7_1(n)
print(result)

output :
{1: 3, 2: 2, 3: 3, 4: 5, 5: 3, 6: 9}

A: Tons of ways of doing this some ways are:
Solution1:
n = [1,1,1,3,3,3,2,2,4,4,4,4,4,5,5,5,6,6,6,6,6,6,6,6,6]
def question_7_1(n):
    myCountDict = {}
    for i in n:
        countOfaNum = n.count(i)
        myCountDict[i] = countOfaNum
    print(myCountDict)

question_7_1(n)

Solution2:
More effective and optimal:
a = [1,1,1,3,3,3,2,2,4,4,4,4,4,5,5,5,6,6,6,6,6,6,6,6,6]
d = {x:a.count(x) for x in a}
print(d)

Output:
{
 1: 3,
 2: 2,
 3: 3,
 4: 5,
 5: 3,
 6: 9
}


text:
Q: How to decode the value of the variable that stores the value returned from glm::value_ptr()? if I have this snippet code:
glm::mat4 someMatrix(1.0f);

GLfloat * a = glm::value_ptr(someMatrix);

How can I decode the values from the variable 'a'. I know the value is someMatrix but jus for curiosity is possible I could get the same Matrix value by decoding the variable a? I tried with this:
std::cout<<"value: "<< a <<"\n";   // It throws me the address : 0x7fff609e91f0
std::cout<<"value: "<< *a <<"\n"; // It gives me this value: 8.88612e-39

But I don't know how to get the matrix and its values. This question might be meaningless because obviously I already know the value of the matrix but just for curiosity I want to know if is possible to decode. Anyway. Thanks in advance.

A: By "decoding" I'm assuming you're referring to reading each individual element of the matrix.
If it's for the purpose of printing you can do:
glm::mat4 someMatrix(1.0f);
std::cout << glm::to_string(someMatrix) << std::endl;

If you insist on using the result of glm::value_ptr.
glm::mat4 someMatrix(1.0f);
GLfloat *a = glm::value_ptr(someMatrix);

for (int j = 0; j < 4; ++j) {
    for (int i = 0; i < 4; ++i) {
        std::cout << a[j * 4 + i] << " ";
    }
    std::cout << std::endl;
}

Which for someMatrix would print:
1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1


text:
Q: GetDriveType() equivalent in Java Is there any method which performs similar tasks to the GetDriveType() method of Microsoft Visual C++. I've already gone through the FileSystemView class of Java Swing. But the method available there are limited and does not fulfill my requirement.
So please tell me someone if Java defines any such method for Windows platform or Platform Independent.

A: You can use File.listRoots() method. It will list all the drives in your system.
And to get detail information about that drive you can use the following code.

List roots = Arrays.asList(File.listRoots());
  for(File f:roots)
  {
  String s = FileSystemView.getFileSystemview().getSystemTypeDescription(f);
  }

This code shows the actual information of drives and other PnP devices. Use this link to know more. And according to your question you must be want to know the hardware details of connected drives to PC. Use JNI if you want to do all code in java.

A: Are you using JDK7?
If so, there is FileStore which returns the type as a String.
However, looking at the source code itself (FileStore.java) there is a warning that the return value might be implementation specific.


text:
Q: JS internal function not being executed on IE8 I have a problem with a javascript function on my webpages, it works for FF but not for IE8.
Here is how it is called :

                <input id="supporter" type="radio" name="group" value="Supporter" class="mlm" onclick="javascript:handleForm('supporter')" required/>
                {{ 'inscription.supporter.titre'|trans({}, 'messages') }}

and the function :

For reason i don't know ie comes out with a strange error that says the value of the property handleForm is null or undefined, not a function object.
Do anyone as an idea why IE would not execute my code ?
Thanks for reading.

A: Sounds like you might be using Angular > 1.3, in which case, IE8 is not supported.
There could be a number of things, some things to try include changing out the variable replacement (or simplifying it) or getting rid of the required attribute as IE8 does not support that either.
You also do not need the javascript: bit, onclick="handleForm( 'supporter' ) is all that is required, although it should be ringing alarm bells why you aren't handling that function as part of your Angular stuff. Seems odd to mix global functionality with angular-powered functionality, although this does not relate to your question, more of an observation.


text:
Q: ¿Por qué Angular no recompila el proyecto? Angular CLI: 6.2.4
Node: 8.10.0
OS: linux x64
Angular: 6.1.9
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.8.4
@angular-devkit/build-angular     0.8.4
@angular-devkit/build-optimizer   0.8.4
@angular-devkit/build-webpack     0.8.4
@angular-devkit/core              0.8.4
@angular-devkit/schematics        0.8.4
@angular/cli                      6.2.4
@ngtools/webpack                  6.2.4
@schematics/angular               0.8.4
@schematics/update                0.8.4
rxjs                              6.2.2
typescript                        2.9.2
webpack                           4.20.2

Estoy trabajando en Ubuntu 16.04 y esas son mis especificaciones.
Mi problema es que hay veces que angular-cli no me detecta cambios en los archivos que no tengo agregados en mi app.module pero si los tengo en otro módulo. Esto no siempre pasa, pero tengo que parar el servidor y volver a levantarlo para que detecte cambios en los archivos declarados en otros módulos. ¿Hay una manera de solucionar esto? Nunca me había pasado en Mac OS o Windows.

A: Hola Akko por lo visto alguien ya se enfrentó a este problema en Ubuntu 16.04, la solución radica en ajustar la configuración de los Inotify Watches en linux. Puedes chequearlo aqui


text:
Q: How to store long text to MySql DB using Rails? I am trying to store a long text (in my case a raw rss feed, but could just as well be a long blog post or similar) to a MySql database.
I have a migration with:
change_column :contents, :description, :longtext

But this gives a schema.rb with:
t.text     "description",       :limit => 2147483647

When the limit should in fact have been set to 4294967295.
Why does Rails impose an upper limit which is half of what should be possible?

A: I don't know if rails supported :longtext officially in previous versions, but in the current version according to rails documentation, :longtext is in fact not specified as legal datatype. I think it's only a convenience of the mysql adapter that translates this to :text.
The correct way to do it is then:
change_column :contents, :description, :text, :limit => 4294967295
Keep it mind that the effective maximum size is less when using multi-byte characters.
Edit: Thinking a second about it and it makes sense that rails halves the size. Re-reading the mysql docs on this topic , they speak of effective size. I guess specifying 2147483647 could lead to an effective size of 4294967295 when filled with 2-byte UTF-8 characters. As UTF-8 is the default encoding in ruby 1.9 (at least on my machine), it's the only correct way to do it. I think?!
ruby-1.9.2-p136 :002 > "".encoding
=> #<Encoding:UTF-8>


text:
Q: Difference between printing out value with for loop and simple variable input What is the difference between simply printing out 'a' and looping it as illustrated by the example
CODE 1:
a = ['banana','apple','microsoft']

print(a)

['banana', 'apple', 'microsoft']

CODE 2:
for i in a:
    print(i)

banana
apple
microsoft

A: The first piece of code prints an list object. Python then picks the notation
['banana', 'apple', 'microsoft']

to represent the list one line. It also displays brackets to indicate that the objects within the list are strings. The list can even contain a mixture of types.
In your second piece of code you request a seperate line for every element in this list.
No square brackets are displayed as the list itself is never printed, it was just carrying the content before it was printed.


text:
Q: Is this expected behaviour for a Set of arrays in Ruby? We're doing a bit of work in Ruby 1.8.7 that requires traversing and partitioning an undirected graph, that has been failing weirdly in production. When I distil the failing code down to its barest components, I get this strangely failing test:
it 'should be able to clear a ruby set of arrays' do
  a = ["2", "b", "d"]
  b = ["1", "a", "c", "e", "f"]
  set = Set.new([a, b])
  a.concat(b)

  p "before clear: #{set.inspect}"
  set.clear
  p "after clear: #{set.inspect}"
  set.size.should == 0
end

The test fails with this output:
"before clear: #<Set: {[\"1\", \"a\", \"c\", \"e\", \"f\"], [\"2\", \"b\", \"d\", \"1\", \"a\", \"c\", \"e\", \"f\"]}>"
"after clear: #<Set: {[\"2\", \"b\", \"d\", \"1\", \"a\", \"c\", \"e\", \"f\"]}>"

expected: 0
     got: 1 (using ==)

Attempts to delete from the set also behave in strange ways. I'm guessing that Ruby is getting hung up on the hash values of the keys in the array changing under concat(), but surely I should still be able to clear the Set. Right?

A: There is a workaround for this, if you duplicate the set after you modify the keys, the new set will have the updated keys and clear properly. So setting set = set.dup will fix that problem.

A: The .dup approach was indeed my first work-around, and did as advertised.
I ended up adding the following monkey-patch to Set:
class Set
  def rehash
    @hash.rehash
  end
end

which allows me to rehash the set's keys after any operation that changes their hash values.
This appears to all be fixed in Ruby 1.9.


text:
Q: Initializing BitmapImage in background task My runtime background task is supposed to change the desktop wallpaper image, but when I try to initialize a new BitmapImage I get this exception:
System.Exception: The application called an interface that was marshalled for a different thread.

I've tried doing this:
var dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;
await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => {

var testBitImg = new BitmapImage();
});

But then I get this exception:
System.InvalidOperationException: A method was called at an unexpected time

I really have no idea what these exceptions mean or how to fix them?


text:
Q: Sticky table header inside scrollable box I'm currently experimenting with sticky table headers inside a relative complex setup.
I want the table header to stick beneath the main header if the scrollContainer is scrolled down without loosing the ability to scroll horizontally inside the box:

The Problem is, that the table container is horizontal scrollable and the outside container "scrollContainer" is also scrollable vertically. To make things even more interesting there is also a static main header ;-)
Is there a jQuery-Plugin out there, that can handle this use case or is there a other solution for this?

$('table.floatthead').floatThead({
  responsiveContainer: function($table) {
    return $table.closest('#scrollContainer');
  }
});
html, body {
  background: red;
  padding: 0;
  margin: 0;
  height: 100%;
}

header {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  padding: 1em;
  height: 3em;
  color: white;
  background: black;
}

#scrollContainer {
  box-sizing: border-box;
  background: lightgray;
  height: calc(100% - 3em);
  width: 100%;
  padding: 0;
  position: absolute;
  top: 3em;
  overflow: hidden;
  overflow-y: scroll;
}

section.content {
  width: 70%;
  margin-left: auto;
  margin-right: auto;
  background-color: darkgray;
  padding: 1em;
}

.box {
  border: 1px solid yellow;
  margin-bottom: 2em;
}

.box .header {
  background: yellow;
  box-sizing: border-box;
  padding: 0.5em;
  font-weight: bold;
}

.box .content {
  overflow-y: hidden;
  overflow-x: scroll;
}

table {
    border-collapse: collapse;
    width: 600px;
    background: orange;
}

td, th {
    border: 1px solid black;
    text-align: left;
    padding: 0.5em;
}

th {
  background-color: gray;
}

  Main Header

Boxheader

                Company
                Contact
                Country

              Alfreds Futterkiste
              Maria Anders
              Germany

              Centro comercial Moctezuma
              Francisco Chang
              Mexico

              Ernst Handel
              Roland Mendel
              Austria

              Island Trading
              Helen Bennett
              UK

              Laughing Bacchus Winecellars
              Yoshi Tannamuri
              Canada

              Magazzini Alimentari Riuniti
              Giovanni Rovelli
              Italy

              Magazzini Alimentari Riuniti
              Giovanni Rovelli
              Italy

              Magazzini Alimentari Riuniti
              Giovanni Rovelli
              Italy

              Magazzini Alimentari Riuniti
              Giovanni Rovelli
              Italy

              Magazzini Alimentari Riuniti
              Giovanni Rovelli
              Italy

              Magazzini Alimentari Riuniti
              Giovanni Rovelli
              Italy

              Magazzini Alimentari Riuniti
              Giovanni Rovelli
              Italy

              Magazzini Alimentari Riuniti
              Giovanni Rovelli
              Italy

              Magazzini Alimentari Riuniti
              Giovanni Rovelli
              Italy

              Magazzini Alimentari Riuniti
              Giovanni Rovelli
              Italy

Boxheader

                Company
                Contact
                Country

              Alfreds Futterkiste
              Maria Anders
              Germany

              Centro comercial Moctezuma
              Francisco Chang
              Mexico

              Ernst Handel
              Roland Mendel
              Austria

              Island Trading
              Helen Bennett
              UK

              Laughing Bacchus Winecellars
              Yoshi Tannamuri
              Canada

              Magazzini Alimentari Riuniti
              Giovanni Rovelli
              Italy

              Magazzini Alimentari Riuniti
              Giovanni Rovelli
              Italy

              Magazzini Alimentari Riuniti
              Giovanni Rovelli
              Italy

              Magazzini Alimentari Riuniti
              Giovanni Rovelli
              Italy

              Magazzini Alimentari Riuniti
              Giovanni Rovelli
              Italy

              Magazzini Alimentari Riuniti
              Giovanni Rovelli
              Italy

              Magazzini Alimentari Riuniti
              Giovanni Rovelli
              Italy

              Magazzini Alimentari Riuniti
              Giovanni Rovelli
              Italy

              Magazzini Alimentari Riuniti
              Giovanni Rovelli
              Italy

              Magazzini Alimentari Riuniti
              Giovanni Rovelli
              Italy


text:
Q: Uploading a PNG into a Canvas After a few hours of research, I have not found the best way of uploading a PNG so it can be used inside a Canvas element. All the solutions that I have found use server side code one way or another. I want this solution to be entirely client side. Is there a way to do this?
Workflow:
User uploads an image
JS gets access to this image in some form (base64)
Image gets loaded into a Canvas

A: Yes, it can be done.
It is possible to read the files that are being passed in an input of type="file" from JavaScript, the problem is reading the file as an image and placing it in the canvas this can be worked by loading the image in a img element and then draw the image from the img element into the canvas as shown by Zword.

My original answer
You can take advantage of the project JavaScript-Load-Image by Sebastian Tschan (aka blueimp). See the demo.
It has been very easy to set up a working example based on it:
<script src="load-image.min.js"></script>
<input id="file-input" type="file">
<script>
    document.getElementById('file-input').onchange = function (e)
    {
        var loadingImage = loadImage(
            e.target.files[0],
            function (img)
            {
                document.body.appendChild(img);
            },
            {maxWidth: 600}
        );
        if (!loadingImage)
        {
            // Alternative code ...
        }
    };
</script>

Note: The above code uses load-image.min.js, download it for use. I don't provide a "jsfiddle" (or similar) because I haven't found this lib on any CDN.

A: As far as what i have understood and you asked for a complete client-side solution i think this is what you want:
http://jsfiddle.net/gvk9p/1/
<script>

function PreviewImage() {
    var oFReader = new FileReader();
    oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);

    oFReader.onload = function (oFREvent) {
        document.getElementById("uploadPreview").src = oFREvent.target.result;
var c=document.getElementById("imgPreview");
var ctx=c.getContext("2d");
var img=document.getElementById("uploadPreview");
ctx.drawImage(img,10,10);
    };
};

</script>


text:
Q: My function runs file when called inside the file, but errors when called from another I have a main file, which handles my PyQt5 UI. I have the program create a new table for each set of data I have, and name it accordingly. The update_status function edits a certain item on a certain table by the ID I gave it.
mainfile.py
class MyUi(object)
    def setupUi(self, MyWindow):...

    def retranslateUi(self, MyWindow):...

    # this is what I want to call from another file
    def update_status(self, tid, text):
        # getting task's group for writing to table
        t_file = json.load(open('Data/Tasks/tasks.json', 'r'))

        for group in t_file:
            for task in group['tasks']:
                if task['id'] == tid:
                    task_parent = group['group name']

        for i in self.TaskScreen.children():
            if str(i.__class__.__name__) == 'QTableWidget':
                try:
                    if i.objectName() == task_parent:
                        row = i.rowCount()

                        for r in range(row):
                            task_id = i.item(r, 0).text()
                            if task_id == tid:
                                i.setItem(r, 6, QtWidgets.QTableWidgetItem(str(text)))
                                i.update()

                except UnboundLocalError:
                    print('Item doesnt exist')

When I call update_status from mainfile.py, it works fine.
test.py (the file I need to call update_status from)
from mainfile import MyUi
update_status = MyUi().update_status

update_status(tid='ABC123', text='Test')

This is the traceback I get:
AttributeError: 'MyUi' object has no attribute 'TaskScreen'

I hope I explained this well, Any help would be appreciated.


text:
Q: With Pandoc, how to converting between different formats with additional rules? I have some existing Mediawiki format texts that contain categories tokens like
[[Category:XXX]]
[[Category:YYY]]

I'd like to convert them to Markdown texts.  The basic command for doing that with Pandoc is
pandoc -f mediawiki -t markdown -s mytext.mediawiki -o mytext.md

The resultant Markdown text is mostly usable except that it converts the category tokens to
<Category:XXX> <Category:YYY>

which isn't really what I need.  Instead, I need
[[!tag XXX YYY]]

because I'm using the resultant Markdown files as source files in a special content management system called Ikiwiki which has its idiosyncratic format for tags. How to do that with Pandoc?

A: It's probably easiest to do this as a second step with a search and replace on <Category:XXX>. Note that pandoc without the -o option writes to standard-out, so you can pipe it directly to some custom post-processing script.
[[Category:XXX]] is converted by pandoc internally to a link along the lines of Category:XXX (try pandoc -f mediawiki -t native).
So generally, additional rules for elements are implemented through custom scripts that match on Pandoc's internal data types, see Pandoc scripting. So you could match on those kind of links. It's more work (the first time), but makes quite sure you don't replace false positives.


text:
Q: Kotlin App crashes when I try to navigate through BottomNavigation I'm competely new to Kotlin trying to build an app following a tutorial, but trying to navigate to fragment it completely crashes.
This what I got after I tried to navigate to the other fragment:
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.application, PID: 10385
    java.lang.IllegalArgumentException: No view found for id 0x7f08005a (com.example.application:id/container) for fragment Create{b25f2a9 (ffc51d9a-d9bb-425d-a264-1a68c77134fb) id=0x7f08005a}
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:875)
        at androidx.fragment.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManagerImpl.java:1238)
        at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:1303)
        at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:439)
        at androidx.fragment.app.FragmentManagerImpl.executeOps(FragmentManagerImpl.java:2079)
        at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1869)
        at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824)
        at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727)
        at androidx.fragment.app.FragmentManagerImpl$2.run(FragmentManagerImpl.java:150)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

This how I try to navigate to  the fragment.
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val bottomNavigation: BottomNavigationView = findViewById(R.id.nav_view)
        bottomNavigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)

    }
    private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
        when (item.itemId) {
            R.id.menu_home -> {

                val fragment_main = Main.newInstance()
                openFragment(fragment_main)
                return@OnNavigationItemSelectedListener true
            }
            R.id.menu_create -> {

                val fragment_create = Create.newInstance()
                openFragment(fragment_create)
                return@OnNavigationItemSelectedListener true
            }
            R.id.menu_your -> {

                val fragment_your_articles = YourArticles.newInstance()
                openFragment(fragment_your_articles)
                return@OnNavigationItemSelectedListener true
            }
        }
        false
    }

    private fun openFragment(fragment: Fragment) {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.replace(R.id.container, fragment)
        transaction.addToBackStack(null)
        transaction.commit()
    }

}

One of the  Fragment class
class Create : Fragment() {
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
        inflater.inflate(R.layout.fragment_create, container, false)

    companion object {
        fun newInstance(): Create = Create()
    }

}

I want to know what mistake did I made to cause the crash and how can I fix it.
This xml file of one of the fragment:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical">

   <TextView
       android:id="@+id/textView4"
       android:layout_width="100dp"
       android:layout_height="50dp"
       android:layout_marginStart="150dp"
       android:layout_marginLeft="150dp"
       android:layout_marginTop="200dp"
       android:text="@string/create_screen"
       />
</LinearLayout>

A: The id passed into FragmentTransaction.add(), in your case R.id.fragment_create, must be a child of the layout specified in setContentView().
For help: A view is a child of another view if it is declared inside of the parent view in the XML. ie. a TextView inside of a RelativeLayout is a child of the RelativeLayout

A: As I said I'm completely new to Kotlin and I'm still getting used to how and what must be displayed if I'm trying to use Fragment. I forgot that I need FrameLayout to my main_activity.xml
As I added FrameLayout in my main_activity.xml file it's started working as I wanted.

A: This line in your openFragment function
transaction.replace(R.id.container, fragment)

tells it to place the fragment in the ViewGroup with the ID "container". But your layout does not contain a ViewGroup with this ID. Check your activity_main.xml layout and make sure it has one with that ID.


text:
Q: How safe is auth !== null? Firebase I've been using Firebase for quite some time, but I only now decided to really look into the security rules.
My question is, how safe is "auth !== null"? Yes, I realize that this means that only an authenticated user can access the data, but how easy is it to become authenticated? Can someone sign up for the app, and then use those credentials to GET request right into my database?
Like I said, I'm new to Security rules, so I'm sorry if this is an obvious question.
Here's my security rules:
{
  "rules": {
    "Users": {
      "$user_id": {
        ".write": "$user_id === auth.uid",
        ".read" : "auth !== null",
        "shoofers" : {
          ".write" : "auth != null"
        }
      }
    }
  }
}

Thanks!
Neil

A: You can give users access to the database either after sign in authentication or with out authentication.
But it is good and safe to allow users to access your database with authentication
with authentication security rules are
  {
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

and without authentication
     {
  "rules": {
    ".read": "auth == null",
    ".write": "auth == null"
  }
}

A: A user can authenticate via anonymous, email/password, various OAuth providers and phone number sign in. You can enable/disable either of them. Your root rule above allows read only access to any authenticated user via any of the mechanisms stated and write access for a specified user to their own data. It is very difficult to fake sign in. The database will always check that the request has an ID token (when auth is not null). ID tokens use public-key cryptography and are hard to fake without possession of the private key.

A: {
  "rules": {
     ".read" : "auth.uid != null",
     ".write" : "auth.uid != null",
  }
}

or without authentication
{
  "rules": {
     ".read" : "auth.uid == null",
     ".write" : "auth.uid == null",
  }
}

A: The thing i have seen is, when you use 'simulator' from firebase console and fake authentication by giving some random string as uid, firebase doesn't check it and allows access. So auth!=null is not enough because it authenticates even if uid=1.


text:
Q: How to show what a method returns in my application I have a method called "showWorkers" that will show all the workers in my company, with the name, when they started working and their cargo but I'm kinda new to JavaFX and I've been looking on videos and stuff and nothing is working. I want to create a button that when it is pressed, goes to another stage and shows all the information.
**JAVAFX**
btnshowWorkers.setText("Mostrar Conjunto de Fichas"); // create button
btnshowWorkers.setLayoutX(10); // localização do botão btnshowWorkers.setLayoutY(250); // localização do botão btnshowWorkers.setPrefWidth(150); // localização do botão  relativamente ao comprimento
btnshowWorkers.setOnAction(new EventHandler<ActionEvent>(){
   @Override
   public void handle(ActionEvent event){

   Stage newWindow2 = new Stage(); // cria nova variavel do tipo stage
   primaryStage.hide(); // esconde o menu principal
   VBox painelList = new VBox(); // cria nova variavel do tipo VBox
   Button btnSee=new Button(); // cria novo botão
   Button btnExit=new Button(); // cria novo botão
   Text erro = new Text(); // cria um variavel do tipo text
   erro.setLayoutX(193); // localização da variavel tipo text
   erro.setLayoutY(120); // localização da variavel tipo text

   company.showWorkers();

**JAVA**
 public void showWorkers()
    {
        int n_empregdos = 0;
        for(Empregado e: worker)
        {
            System.out.println("ID : " +e.getId());
            System.out.println("Nome : " +e.getName());
            System.out.println("Data de entrada : " +e.getDataEntrada());
            System.out.println("Dias de Trabalho: " + e.workDays);
            System.out.println("Cargo : " +e.getCargo());
            n_empregdos += 1;
        }

        if(n_empregdos == 0)
        {
            System.out.println("Não existem empregados inseridos!");
        }
    }


text:
Q: Finding percentile of a particular input in R I have a dataset column which contains values. When a new input is given, I want to check this column and finding the percentile of that input value in that column.
I tried with quantile function. But the quantile function gives the values of 25th,50th percentile and so on. But I want the reverse of it. I want the percentile of a given value.
The following is my reproducible example,
data <- seq(90,100,length.out=1000)
input <- 97

My output should be the percentile of 97 in the data column. Is this possible to do?
Thanks

A: You may also use a somewhat more statistical version with an empirical cumulative distribution function:
ecdf(data)(input)

or
F <- ecdf(data)
F(input)

This approach also allows for vectorization over input.

A: I think you want to count the fraction of the data that are (is?) less than the input value:
mean(input>data)
## [1] 0.7


text:
Q: Text input background scrolling in IE7 I think most of us know about this annoying bug in IE7 where the background image of a text input will scroll if the text entered is longer than the width of the text input.
Numerous questions have been asked and blogged.
Those questions and post all require one to wrap a div around the text input. This is something that I cannot do as I am working with markup generated by a CMS.
However, I would like to gracefully degrade the experience. For IE7 and below, I am happy with not displaying the background image and just displaying a color.
This is the css being used:
form input[type="text"], form input[type="password"]{
    background-image: url('bg.png');
    background-repeat: no-repeat;
    background-size: 100% 100%;

    padding-left: 4px;
    padding-right: 4px;

    width: 100%;
    height: 30px;
        border: #008296 1px solid;
}

I have tried adding background-attachment: fixed but the background-image ceases to be shown in all versions of IE, firefox and chrome! Since I only want this behaviour for IE7 and below, how can I go about doing this besides creating an IE7 only stylesheet?

A: You could always use an IE7 specific CSS selector filter to override your desired styles for IE7.
To make a class that applies only to IE7, simply put *:first-child+html in front of your classname.
Another option is to declare CSS rules that are specific to IE (aka IE CSS hacks).  This would involve putting an asterisk (*) before the attribute that is only to apply for IE7 and below.  This isn't as highly regarded though since it is not valid CSS syntax.
You may find this site interesting for dealing with IE and CSS hacks: http://www.javascriptkit.com/dhtmltutors/csshacks2.shtml


text:
Q: Entity Framework Core Migrations Separate CI/CD Pipeline My company is moving to microservices and as part of this shift devops is standing up CI/CD build release pipelines in Azure with VSTS and GIT.
The current model for managing migrations is a developer is given 2 projects in 2 separate git repositories.
Project 1 - API Services project - .NET Framework / .Net Core
Project 2 - Database project based on EF6 using the migration API
These projects have completely independent release pipelines based on the repositories. So when you create a pull request into master the pipeline builds and releases the project.
This new architecture also supports blue green deployments and our app services run on multiple nodes.
The issue we have is that with this set up we have to basically hand code our migrations and can't use any of the tooling provided in EF Core.
Most of the articles and documentation I have read shows running the migrations from app start up, but if you have multiple app service nodes how do you prevent 2 nodes from running the migrations?
Other articles I have looked at show moving migrations into a separate project, but that project needs a reference to the project with the dbcontext in it. In my company's setup this is not possible. Neither can we do the reverse since moving the dbcontext into the database project prevents us from referencing it in the api services project.
Is there any way to support this model with EF Core?
What is the preferred way to implement blue green deployments with EF Core Migrations on a multi node app service?

A: I will try to claim that there isn't and not because EF Core doesn't support it in some way, but because this sounds impossible from what I understood in your question.
Your company want the ability to do blue/green deployments, but it is only really possible on the service layer, but not on database. The idea sounds really cool, fast rollback, almost no downtime. But in reality databases complicate things a lot.
So imagine your Project 1 is running on machines A and B (representing blue and green deployments). A currently is a production environment and B is identical but not serving any requests ATM. Both of them are pointing to the exact same database (if not, it's not blue/green, it's just a separate environment). When you want to deploy your DB changes, you migrate your database, but now both of the machines A and B will be pointing to the updated database. You can keep switching from A to B, but they both might have stopped working if your database migration broke anything.
Therefore I don't really understand what you achieve with having DB migrations in a separate repository with a separate pipeline. This just complicates coordination of the releases as they are clearly dependent, but I don't see how it helps to solve anything. As you noted, you can't delegate creation of migration scripts to EF Core, at least without some manual work.
Would be happy to hear any advantages of such design.


text:
Q: USB Ports are not working in BIOS I have a Lenovo H530S desktop with 6 USB Ports. 2 USB 2.0 (Black) Ports at the front, 2 USB 3.0 (Blue) Ports and 2 USB 2.0 (Black) Ports at the rear.
Only 1 USB 2.0 (Black) Port is working in BIOS or at boot time. Rest of the Ports are not working. USB 3.0 (Blue) Ports are working when PC is up & running and detecting the USB 3.0 drive but not detecting the keyboard & mouse (i.e USB 2.0). when I plugin the USB drive in any of the USB port, it starts blinking (i.e Ports are getting power when Windows is running).
Please assist to make the rest of the USB ports working.
Problem

*

*2 USB 3.0 (Blue) Ports and 1 USB 2.0 (Black) Port are not working in BIOS

*USB 3.0 (Blue) Ports are only detecting the USB 3.0 drive while the Windows is Up and running

Troubleshooting Done

*

*USB Ports are enabled in BIOS

*Tried to update the drivers from Device Manager, already best drivers installed

*Uninstalled USB Root Hub, Standard USB 3.0 eXtensible Host Controller and USB 3.0 from the Device manager to let windows get the USB drivers

*Installed Chipset drivers from the manufacturer (Lenovo) site

*Installed Lenovo Vantage to get the latest drivers, already up to date

*Tried third party (IOBit Driver Booster) Driver updater tool

*Updated BIOS

*Disable "Allow computer to turn off this device to save power" from USB properties

*Disabled USB Selective suspend setting from Power Options

*Installed Windows Updates

Still, I am facing the same problem. USB 3.0 Ports are only working when Windows in Up and running and only detecting the USB 3.0 devices. Please assist.


text:
Q: How to sort a list of timings like this [ 2:00 AM , 10:00 AM , 6:00 PM ] in dart-flutter? I'm working on a flutter app, one of its features is to add your drug dose timings to get a reminder to take your drug. and I need to sort the timings to get the 'next_dose' to appear here :
https://drive.google.com/file/d/1j5KrRbDj0J28_FrMKy7dazk4m9dw202d/view?usp=sharing
this is an example of the list which I want to sort
[8:30 AM, 3:30 PM, 9:30 AM, 7:00 AM]

function I made to get the greater between 2 timings
int greater(String element,String element2){
      var hour = element.toString().split(':')[0];
      var hour2 = element2.toString().split(':')[0];
      var minute = element.toString().split(':')[1].split(' ')[0];
      var minute2 = element2.toString().split(':')[1].split(' ')[0];
      var day = element.toString().split(':')[1].split(' ')[1];
      var day2 = element2.toString().split(':')[1].split(' ')[1];
      if(day == 'AM' && day2 == 'PM')
        return -1;
      else if(day2 == 'AM' && day == 'PM')
        return 1;
      else if(day == day2)
      {
        if(int.parse(hour) > int.parse(hour2)) return -1;
        else if(int.parse(hour) < int.parse(hour2)) return 1;
        else{
          if(int.parse(minute) > int.parse(minute2))
            return 1;
          else
            return -1;
        }
      }

here I tried to use the function to sort the list'Dose'
dose.sort((a,b)=>greater(a,b));

A: Instead of creating a sort callback with a lot of complicated logic, it'd be simpler if the callback parsed the time strings either into an int or into a DateTime object and compared those.  For example:
/// Parses a time of the form 'hh:mm AM' or 'hh:mm PM' to a 24-hour
/// time represented as an int.
///
/// For example, parses '3:30 PM' as 1530.
int parseTime(String time) {
  var components = time.split(RegExp('[: ]'));
  if (components.length != 3) {
    throw FormatException('Time not in the expected format: $time');
  }
  var hours = int.parse(components[0]);
  var minutes = int.parse(components[1]);
  var period = components[2].toUpperCase();

  if (hours < 1 || hours > 12 || minutes < 0 || minutes > 59) {
    throw FormatException('Time not in the expected format: $time');
  }

  if (hours == 12) {
    hours = 0;
  }

  if (period == 'PM') {
    hours += 12;
  }

  return hours * 100 + minutes;
}

void main() {
  var list = ['8:30 AM', '3:30 PM', '9:30 AM', '7:00 AM'];
  list.sort((a, b) => parseTime(a).compareTo(parseTime(b)));
  print(list); // Prints: [7:00 AM, 8:30 AM, 9:30 AM, 3:30 PM]
}

Alternatively, you can use package:intl and DateFormat.parse to easily parse strings into DateTime objects.

A: Here we get the time slot by passing the start and end time duration.
List<String> createTimeSlot(
    Duration startTime, Duration endTime, BuildContext context,
    {Duration step = const Duration(minutes: 30)} // Gap between interval
    ) {
  var timeSlot = <String>[];

  var hourStartTime = startTime.inHours;
  var minuteStartTime = startTime.inMinutes.remainder(60);

  var hourEndTime = endTime.inHours;
  var minuteEndTime = endTime.inMinutes.remainder(60);

  do {
    timeSlot.add(TimeOfDay(hour: hourStartTime, minute: minuteStartTime)
        .format(context));
    minuteStartTime += step.inMinutes;
    while (minuteStartTime >= 60) {
      minuteStartTime -= 60;
      hourStartTime++;
    }
  } while (hourStartTime < hourEndTime ||
      (hourStartTime == hourEndTime && minuteStartTime <= minuteEndTime));

  debugPrint("Number of slot $timeSlot");

  return timeSlot;
}

Function call
createTimeSlot(Duration(hours: 1, minutes: 30),
        Duration(hours: 3, minutes: 30), context);

Output:
Number of slot [1:30 AM, 2:00 AM, 2:30 AM, 3:00 AM, 3:30 AM]


text:
Q: drawing mutliple images in one line How would i simplify this, so it has the same effect?
context.drawImage(imgs2[0],enemy.x+135,enemy.y,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y2,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y3,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y4,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y5,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y6,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y7,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y8,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y9,tileWidth,tileHeight);

I have "imgs2" saved like this, in an array
function images2(callback){
    for(var i = 0; i<enemy2.length; i++){
        var tile4 = new Image();
        imgs2.push(tile4);

        tile4.onload = function(){
            imagesdraw=true;
            if (imagesdraw == true) {
                callback();
            }
        }
        tile4.src = enemy2[i];
    }
}

so how would I make the drawImage simpler, so it doesn't look so drawn out, so that it is just one line that can work for multiple images alongside the different y's?

A: Taking advantage of being able to access properties via obj.["propertyToGet"], you can simplify this:
ontext.drawImage(imgs2[0],enemy.x+135,enemy.y,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y2,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y3,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y4,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y5,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y6,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y7,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y8,tileWidth,tileHeight);
context.drawImage(imgs2[0],enemy.x+135,enemy.y9,tileWidth,tileHeight);

into this:
for(var i = 1; i <= 9; i++){
  var propertyName = "";
  if(i > 1){
    propertyName = "y" + i;
  }
  context.drawImage(imgs2[0],enemy.x+135,enemy[propertyName], tileWidth, tileHeight);
}

It just seems cleaner.


text:
Q: Using IIFE to improve Canvas code I'm creating a Canvas game, the code below shows the global variables and the init function. From my understanding creating global variables is bad practice and may lead to clashes with other files.
Can someone give me an example of how to improve this code using IIFE?
    canvasEntities = document.getElementById("canvasEntities"), // foreground canvas
    ctxEntities = canvasEntities.getContext("2d"),

    canvasWidth = 400,
    canvasHeight = 400,

    player1 = new Player(),
    enemies = [],
    numEnemies = 5,
    obstacles = [],
    isPlaying = false,
    requestAnimFrame =  window.requestAnimationFrame ||   // Controls timing and update of game
                        window.webkitRequestAnimationFrame ||
                        window.mozRequestAnimationFrame ||
                        window.oRequestAnimationFrame ||
                        window.msRequestAnimationFrame ||
                        function(callback) {                // Older broswers
                            window.setTimeout(callback, 1000 / 60);
                        },

imgSprite = new Image();   // create sprite object
imgSprite.src = "images/sprite.png";
imgSprite.addEventListener("load", init, false);

// event listener looks at image sprite waits for it to load, then calls init

function init() {
    defineObstacles();
    initEnemies();
    begin();
}

A: An iife (Immediately Invoked Function Expression) is a very simple technique for avoiding globals indeed.
(function() {

  //your code

})();

However you should consider using modules such as ES6 modules, CommonJS (node's module.exports/require) or AMD modules, as these will all have their own scope and makes iife's unnecessary.