问:
Error 404 post name permalink wordpress
I have just migrated my WordPress site from a Windows to a Linux server. Everything seems to work except the posts with the permalinks set to /%postname%/. I assumed this was mod_overwrite issue.

I have changed the httpconf file from AllowOverride None to AllowOverride All

And then reset the server just to make sure it took effect.

My .htaccess looks like this:

```<code># BEGIN WordPress
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPress
</code>```

I'm running Apache 2.2 on CentOS5 on a dedicated server.

To add: all the pages are working except the posts with these custom permalinks.

I have set permission to 666 for the .htaccess

答:
Keep AllowOverride none.

Remove the .htaccess file and any trace of that messy set of rewrite rules and just add this in virtualhost:

```<code>FallbackResource /index.php
</code>```

Neither mod_rewrite, neither .htaccess are needed.

By adding per-dir configurations you are basically complicating your life. Everything will be much harder to do, for what? to have dynamic changes by changing a file? .htaccess is meant for non-admin users who need to modify directory configurations.

Since you are the admin, configure everything possible in Virtualhost instead.

Giving rw permissions to everyone to files is definetly not the way to go either. httpd does not need write access to anything.

Title: Error 404 post name permalink wordpress

Body:
I have just migrated my WordPress site from a Windows to a Linux server. Everything seems to work except the posts with the permalinks set to /%postname%/. I assumed this was mod_overwrite issue.

I have changed the httpconf file from AllowOverride None to AllowOverride All

And then reset the server just to make sure it took effect.

My .htaccess looks like this:

# BEGIN WordPress
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPress

I'm running Apache 2.2 on CentOS5 on a dedicated server.

To add: all the pages are working except the posts with these custom permalinks.

I have set permission to 666 for the .htaccess

Body:
Keep AllowOverride none.

Remove the .htaccess file and any trace of that messy set of rewrite rules and just add this in virtualhost:

FallbackResource /index.php

Neither mod_rewrite, neither .htaccess are needed.

By adding per-dir configurations you are basically complicating your life. Everything will be much harder to do, for what? to have dynamic changes by changing a file? .htaccess is meant for non-admin users who need to modify directory configurations.

Since you are the admin, configure everything possible in Virtualhost instead.

Giving rw permissions to everyone to files is definetly not the way to go either. httpd does not need write access to anything.


来源: stackexchange

问:
Race condition when accessing adjacent members in a shared struct, according to CERT coding rule POS49-C?
According to CERT coding rule POS49-C it is possible that different threads accessing different fields of the same structure may conflict.

Instead of bit-field, I use regular unsigned int.

```<code>struct multi_threaded_flags {
  unsigned int flag1;
  unsigned int flag2;
};

struct multi_threaded_flags flags;

void thread1(void) {
  flags.flag1 = 1;
}

void thread2(void) {
  flags.flag2 = 2;
}
</code>```

I can see that even unsigned int, there can still be racing condition IF compiler decides to use load/store 8 bytes instead of 4 bytes.
I think compiler will never do that and racing condition will never happen here, but that's completely just my guess.

Is there any well-defined assembly/compiler documentation regarding this case ? I hope locking, which is costly, is the last resort when this situation happens to be undefined.

FYI, I use gcc.

答:
Before C11, ISO C had nothing to say about threads, and writing multi-threaded code relied on other standards (e.g. POSIX which defines a memory model for pthreads), and multi-threaded code essentially depended on the way real compilers worked.

Note that this CERT coding-standard rule is in the POSIX section, and appears to be about pthreads without C11.  (There's a CON32-C. Prevent data races when accessing bit-fields from multiple threads rule for C11, where they solve the bit-field concurrency problem by simply promoting the bit-fields to unsigned char, which C11 defines as "separate memory locations".  This rule appears to be an insufficiently-edited copy of that, because many of its suggestions suck.)

But unfortunately POSIX pthreads doesn't clearly define what a "memory location is", and this is all they have to say on the subject:

Single UNIX® Specification, Version 4, 2016 Edition (online HTML copy, requires free registration)

4.12 Memory Synchronization

Applications shall ensure that access to any memory location by more
  than one thread of control (threads or processes) is restricted such
  that no thread of control can read or modify a memory location while
  another thread of control may be modifying it. Such access is
  restricted using functions that synchronize thread execution and also
  synchronize memory with respect to other threads.

This is why C11 defines it more clearly, where only bitfields are dangerous to write from different threads (barring compiler bugs).

However, I think everyone (including all compilers) agreed that separate int variables / struct members / array elements were separate "memory locations".  Most real-world software doesn't take any special precautions for int or char variables that may be written by separate threads (especially outside of structs).

A compiler that gets int wrong will cause problems all over the place unless the bug is limited to very specific circumstances.
Most bugs like this are very hard to detect with testing, because usually the other data that's non-atomically loaded and stored back isn't written by another thread very often / ever.  But if a compiler always did that for every int, problems would show up in some software pretty quickly.

Normally, separate char members would also be considered separate "memory locations", but some pre-C11 implementations might have exceptions to that rule.  (Especially on early Alpha AXP which famously has no byte store instruction (so a C11 implementation would have to use 32-bit char), but optimizations that invent writes when updating multiple members can happen anywhere, either by accident or because the compiler developers define "memory location" as a 32 or 64-bit word.)

There's also the issue of compiler bugs.  This can affect even compilers that intend to conform to C11.  For example gcc bug 52080 which affected some non-x86 architectures.  (Discovered in gcc4.7 in 2012, fixed in gcc4.8 a couple months later).  Using a bitfield "tricked" the compiler into doing a non-atomic read-modify-write of the containing 64-bit word, even though that included a non-bitfield member.  (Bitfields are bait for compiler bugs.  Any defensive / safe-coding standard should recommend avoiding them in structs where different members can be modified from different threads.  And definitely don't put them next to the actual lock.)

Herb Sutter's talk atomic<> Weapons: The C++ Memory Model and Modern Hardware part 2 goes into some detail about the kinds of compiler bugs that have affected multi-threaded code.  Most of these should be shaken out by now (2017) if you're using a modern compiler.  Most things like inventing writes (or non-atomic read and write-back of the same value) were usually still considered bugs before C11; C11 mostly just firmed up the rules compilers were already trying to follow.  It also made it easier to report such bugs, because you could say unequivocally that it violates the standard instead of just "it breaks my code".

That coding-rule article is poorly written.  Its examples with adjacent bit-fields are unsafe, but it claims that all variables are at risk.  This is not true in general, especially not with C11.  Many users of pthreads can or already do compile with C11 compilers.

(The phrasing I'm referring to is "Bit-fields are especially prone to this behavior", which incorrectly implies that this is allowed to happen with ordinary members of structs, or variables that happen to be adjacent outside of structs)

It's part of a defensive coding standard, but it should definitely make the distinction between what the standards require and what is just belt-and-suspenders defense against compiler bugs.

Also, putting variables that will usually be accessed by different threads into one struct is generally terrible.  False sharing of a cache line (typically 64 bytes) is really bad for performance, causing cache misses and (on out-of-order x86 CPUs) memory-ordering mis-speculation (like a branch mispredict requiring a roll-back.)  Putting separately-used shared variables into the same byte with bit-fields is even worse, because it prevents efficient stores (any store has to be a RMW of the containing byte).

Solving the bit-field problem by promoting the two bit-fields to unsigned char makes much more sense than using a mutex if they need to be independently writeable from separate threads.  Or even unsigned long if you're paranoid.

If the two members are often used together, it makes sense to put them nearby.  But if you're going to pad to a whole long to contain both members (like that article does), you might as well make them at least unsigned char or bool instead of 1-byte bitfields.

Although honestly, having two threads modify separate members of a struct at the same time seems like poor design unless one of the members is the lock, and the modification is part of an attempt to take the lock.  Using a bit-field as a lock is a bad idea unless you're writing for a specific ISA building and your own lock primitive using something like x86's lock bts instruction to atomically test-and-set a bit.  Even then it's a bad idea unless you need to pack it with other bitfields for space saving; the Linux code that exposed the gcc bug with an int lock:1 member was a horrible idea.

In addition, the flags are declared volatile to ensure that the compiler will not attempt to move operations on them outside the mutex.

If your compiler needs this, your compiler is seriously broken, and will create broken code for most multi-threaded programs.  (Unless the compiler bug only happens with bit-fields, because shared bit-fields are rare).

Most code doesn't make shared variables volatile, and relies on the guarantee that mutex lock/unlock stops operations from reordering at compile or run time out of the critical section.

Back in 2012, and possibly still today, gcc -pthread might affect code-gen choices in C89/C99 mode (-std=gnu99).  In discussion on an LWN article about that gcc bug, this user claimed that -pthread would prohibit the compiler from doing a 64-bit load/store when modifying a 32-bit variable, but that without -pthread it could do so (although on most architectures, IDK why it would).  But it turns out that gcc bug manifested even with -pthread, so it was really a bug rather than an aggressive optimization choice.

ISO C11 standard:

N1570, section 3.14 definitions:

memory location: either an object of scalar type, or a maximal sequence of adjacent bit-fields all having nonzero width

NOTE 1 Two threads of execution can update and access separate memory locations without interfering with each other.

A bit-field and an adjacent non-bit-field member are in separate memory locations.  ...  It is not safe to concurrently update two non-atomic bit-fields in the same structure if all members declared between them are also (non-zero-length) bit-fields, no matter what the sizes of those intervening bit-fields happen to be.

(...gives an example of a struct with bit-fields...)

So in C11, you can't assume anything about the compiler munging other bit-fields when writing one bit-field, but otherwise you're safe.  Unless you use a separator :0 field to force the compiler pad enough (or use atomic bit-ops) so that it can update your bit-field without concurrency problems for other fields.  But if you want to be safe, it's probably not a good idea to use bit-fields at all in structs that are written by multiple threads at once.

See also other Notes in the C11 standard, e.g. the one linked by @Fuz in Is it well-defined behavior to modify one element of an array while another thread modifies another element of the same array? that explicitly says that compiler transformations that would make this dangerous are disallowed.

ContentLicense: CC BY-SA 3.0

Body:
According to CERT coding rule POS49-C it is possible that different threads accessing different fields of the same structure may conflict.

Instead of bit-field, I use regular unsigned int.

struct multi_threaded_flags {
  unsigned int flag1;
  unsigned int flag2;
};

struct multi_threaded_flags flags;

void thread1(void) {
  flags.flag1 = 1;
}

void thread2(void) {
  flags.flag2 = 2;
}

I can see that even unsigned int, there can still be racing condition IF compiler decides to use load/store 8 bytes instead of 4 bytes.
I think compiler will never do that and racing condition will never happen here, but that's completely just my guess.

Is there any well-defined assembly/compiler documentation regarding this case ? I hope locking, which is costly, is the last resort when this situation happens to be undefined.

FYI, I use gcc.


问:
Place text under an image without moving the image(s)?
I've got a couple of images lined up next to each other, that part works fine. However, I want to place text under each of the images, but when i try to do so (by using 'br' or by creating its own 'div') the image creates its own row and pushes the other images down. I understand why it does that but I find it difficult to fix the issue. Here is my code:

```<code><div class="container-team">
    <div class="team">
        <h2>Our team</h2>
        <div class="team-members">
            <img src="test1.png">
            <img src="test1.png">
            <img src="test1.png">
            <img src="test1.png">
            <img src="test1.png">
            <img src="test1.png">
        </div>
    </div>
</div>

.container-team {
    background-color: #eee;
    display:block;
    overflow:auto;
    width: 100%;
}

.team {
    margin:0 auto;
    width: 100%;
    padding-left: 30px;
    padding-right: 30px;
}

.team h2 {
    color: #0E8DBD;
    padding-top: 40px;
    padding-left: 5%;
    padding-bottom: 100px;
    font-size: 32px;
    text-transform: uppercase;
}

.team-members {
    background: #eee;
    width: 100%;
    display:block;
    overflow:auto;
    margin: 0 auto;
    text-align: center;
}

.team-members img {
    width: 180px;
    height: 180px;
    margin: 20px;
}
</code>```

Here are also 2 images to make it more clear of what's happening:

This is what it currently looks like

This is what happens when I give an image its own 'div'

any help is appreciated, thank you for your time.

答:
Try this:

```<code><div class="container-team">
<div class="team">
    <h2>Our team</h2>
    <div class="team-members">
        <div>
            <img src="test1.png">
            <img src="test1.png">
            <img src="test1.png">
            <img src="test1.png">
            <img src="test1.png">
            <img src="test1.png">
        </div>
        <p>Your Text here</p>
    </div>
</div>
</code>```

You'll have to format the text more than that to get it to line up with each image, but it should get it onto the next line.

Body:
I've got a couple of images lined up next to each other, that part works fine. However, I want to place text under each of the images, but when i try to do so (by using 'br' or by creating its own 'div') the image creates its own row and pushes the other images down. I understand why it does that but I find it difficult to fix the issue. Here is my code:

Our team

.container-team {
    background-color: #eee;
    display:block;
    overflow:auto;
    width: 100%;
}

.team {
    margin:0 auto;
    width: 100%;
    padding-left: 30px;
    padding-right: 30px;
}

.team h2 {
    color: #0E8DBD;
    padding-top: 40px;
    padding-left: 5%;
    padding-bottom: 100px;
    font-size: 32px;
    text-transform: uppercase;
}

.team-members {
    background: #eee;
    width: 100%;
    display:block;
    overflow:auto;
    margin: 0 auto;
    text-align: center;
}

.team-members img {
    width: 180px;
    height: 180px;
    margin: 20px;
}

Here are also 2 images to make it more clear of what's happening:

This is what it currently looks like

This is what happens when I give an image its own 'div'

any help is appreciated, thank you for your time.

Body:
Try this:

<div class="container-team">
<div class="team">
    <h2>Our team</h2>
    <div class="team-members">
        <div>
            <img src="test1.png">
            <img src="test1.png">
            <img src="test1.png">
            <img src="test1.png">
            <img src="test1.png">
            <img src="test1.png">
        </div>
        <p>Your Text here</p>
    </div>
</div>

You'll have to format the text more than that to get it to line up with each image, but it should get it onto the next line.


问:
Syntax error in where clause in Access
The error I am getting is Syntax error in where clause in Access.

Here is the code:

```<code>SQL = "Select * FROM tblPermitAgencyInformation  & WHERE [RecordID] = " & Me.AgencyInfoRecordID.Value
Set rs = db.OpenRecordset(SQL)
</code>```

RecordID is an autonumber field and the AgencyInfoRecordID is an integer.

答:
It looks like you misread the article you state. It appears to be attempting to format the adhoc query in the text variable.
Note: it says

```<code>strSQL = "SELECT wazzle FROM bamsploot" & vbCrLf & " WHERE plumsnooker = 0"
</code>```

You need to make sure that you have the ampersands outside of the quotes, (they are used to append variables and strings together in this case)

Follow June7 advice and remove the ampersand there. It should help you get running.

Make your code this:

```<code>SQL = "Select * FROM tblPermitAgencyInformation WHERE [RecordID] = " & Me.AgencyInfoRecordID.Value
</code>```

Hope that helps

Title: Syntax error in where clause in Access

Body:
The error I am getting is Syntax error in where clause in Access.

Here is the code:

SQL = "Select * FROM tblPermitAgencyInformation  & WHERE [RecordID] = " & Me.AgencyInfoRecordID.Value
Set rs = db.OpenRecordset(SQL)

RecordID is an autonumber field and the AgencyInfoRecordID is an integer.

Body:
It looks like you misread the article you state. It appears to be attempting to format the adhoc query in the text variable.
Note: it says

strSQL = "SELECT wazzle FROM bamsploot" & vbCrLf & " WHERE plumsnooker = 0"

You need to make sure that you have the ampersands outside of the quotes, (they are used to append variables and strings together in this case)

Follow June7 advice and remove the ampersand there. It should help you get running.

Make your code this:

SQL = "Select * FROM tblPermitAgencyInformation WHERE [RecordID] = " & Me.AgencyInfoRecordID.Value

Hope that helps


问:
Unload CSS from webpage
Am wondering how it would be possible to unload a CSS from a page. e.g. In my page I have included a file called a.css. Now I want the user to be able to change the theme, which is CSS driven, thus he/she should be able to unload a.css and then I can load b.css (else they will conflict)

Any idea how to go about this?

答:
With jquery, this works:

```<code>$("link[href='fileToRemove.css']").remove();
</code>```

Obviously, replace fileToRemove.css with the relative path and filename of the file to be unloaded.

ContentLicense: CC BY-SA 2.5

Title: Unload CSS from webpage

Body:
With jquery, this works:

$("link[href='fileToRemove.css']").remove();

Obviously, replace fileToRemove.css with the relative path and filename of the file to be unloaded.


问:
issue in matching the size of a box to mobile css bootsrap
I'm facing an issue in matching the size of a  box to mobile(using bootstrap)
I have got 3 boxes, number 1 and 2 are images and number 3 has text,
and it looks like this

when I resize the screen to mobile size this is what happens(box number 3 is higher or in some devices shorter than box number 2, like here:error

I need it to look like that (box number 3 in the same height as 2):desired output

I tried to set max height and min hight to box3 but this is not the solution because it doesn't match to all the devices.

html:

```<code> <section id="carousel-section">

  <div class="container-fluid">

     <div class="row feature">
         <div class="col-lg-8 col-xl-8 col-md-12 col-xs-12 col-sm-12 ">
             <div class="carousel-margin">
<div id="myCarousel" class="carousel1 slide container-carousel" data-
 ride="carousel1">
  <!-- Indicators -->
 <ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
 </ol>

 <!-- Wrapper for slides -->
 <div class="carousel-inner">
<div class="item active">
  <img src="images/dragon_hunter_pic.png" alt="dragon_hunter_pic"
   id="mainImage1" >
</div>

 </div>

    </div>
         </div>
         </div>
            <div class="col-lg-4 col-xl-4 col-md-5 col-xs-5 col-sm-5 ">

       <div class="women-margin">
  <img src="images/women_3.png" alt="live" id="women-eyes1" >
            </div>
            </div>

  <div class="col-lg-4 col-xl-4 col-md-7 col-xs-7 col-sm-7 ">

      <div class="yellow-box">

      <h2 id="change_h2">THE DRAGON HUNTER</h2>
            <br/>
            <p id="change_p"> Lorem ipsum dolor sit amet, consectetur
       adipiscing elit, sed do eiusmod tempor incididunt ut labore et
        dolor aliqua. </p>

         </div>

      </div>

  </div>
 </div>

  </section>
</code>```

this is the problematic box, box number 3:

```<code>    <div class="yellow-box">
</code>```

css:

```<code>  .yellow-box{
 position: relative;

 display: block;
  background-repeat: no-repeat;
  background-size: cover;

    min-height: 204px;
 margin-top:150px;
background-color: #e6ff00;
margin-left: -15px;
margin-right: -15px;

   }
</code>```

this is box number 2:

```<code>  .women-margin{
  margin: -1px -15px -2px -17px;
position: relative;
display: block;
padding-right: 0;
   }
</code>```

答:
Try flex on the row. Does not work in some older browsers.

```<code>.row-eq-height {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display:         flex;
}
</code>```

See: http://getbootstrap.com.vn/examples/equal-height-columns/

Use media query maybe for mobile view only:

```<code>@media (max-width:768px) {
  .row-eq-height {
      display: -webkit-box;
      display: -webkit-flex;
      display: -ms-flexbox;
      display:         flex;
  }

}
</code>```

This is a sample you can try, flex makes columns equal height, but actually it is a contradiction to use Bootstrap and flex together. But just trying to fix your specific code:

```<code><html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<link rel="stylesheet" href="css.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</head>
<body>
<style>
  .yellow-box{
 position: relative;

 display: block;
  background-repeat: no-repeat;
  background-size: cover;

    min-height: 204px;
 margin-top:150px;
background-color: #e6ff00;
margin-left: -15px;
margin-right: -15px;

   }
.women-margin{
  margin: -1px -15px -2px -17px;
position: relative;
display: block;
padding-right: 0;
   }
  .row {
      display: flex;
      flex-wrap: wrap;
  }
</style>
<section id="carousel-section">
    <div class="container-fluid">
        <div class="row feature">
            <div class="col-lg-8 col-md-12">
                <div class="carousel-margin">
                    <div id="myCarousel" class="carousel1 slide container-carousel" data-
                    ride="carousel1">
                    <!-- Indicators -->
                    <ol class="carousel-indicators">
                    <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
                    <li data-target="#myCarousel" data-slide-to="1"></li>
                    <li data-target="#myCarousel" data-slide-to="2"></li>
                    </ol>
                    <!-- Wrapper for slides -->
                        <div class="carousel-inner">
                            <div class="item active">
                                <img src="images/dragon_hunter_pic.png" alt="dragon_hunter_pic" id="mainImage1" >
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-4 col-md-5">
                <div class="women-margin">
                    <img src="images/women_3.png" alt="live" id="women-eyes1" >
                </div>
            </div>
            <div class="col-lg-4 col-md-7">
                <div class="yellow-box">
                    <h2 id="change_h2">THE DRAGON HUNTER</h2>
                    <br/>
                    <p id="change_p"> Lorem ipsum dolor sit amet, consectetur
                    adipiscing elit, sed do eiusmod tempor incididunt ut labore et
                    dolor aliqua. </p>
                </div>
            </div>
        </div>
    </div>
</section>
</body>
</html>
</code>```

Body:
I'm facing an issue in matching the size of a  box to mobile(using bootstrap)
I have got 3 boxes, number 1 and 2 are images and number 3 has text,
and it looks like this

when I resize the screen to mobile size this is what happens(box number 3 is higher or in some devices shorter than box number 2, like here:error

I need it to look like that (box number 3 in the same height as 2):desired output

I tried to set max height and min hight to box3 but this is not the solution because it doesn't match to all the devices.

html:

THE DRAGON HUNTER

 Lorem ipsum dolor sit amet, consectetur
       adipiscing elit, sed do eiusmod tempor incididunt ut labore et
        dolor aliqua.

this is the problematic box, box number 3:

css:

  .yellow-box{
 position: relative;

 display: block;
  background-repeat: no-repeat;
  background-size: cover;

    min-height: 204px;
 margin-top:150px;
background-color: #e6ff00;
margin-left: -15px;
margin-right: -15px;

   }

this is box number 2:

  .women-margin{
  margin: -1px -15px -2px -17px;
position: relative;
display: block;
padding-right: 0;
   }

Body:
Try flex on the row. Does not work in some older browsers.

.row-eq-height {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display:         flex;
}

See: http://getbootstrap.com.vn/examples/equal-height-columns/

Use media query maybe for mobile view only:

@media (max-width:768px) {
  .row-eq-height {
      display: -webkit-box;
      display: -webkit-flex;
      display: -ms-flexbox;
      display:         flex;
  }

}

This is a sample you can try, flex makes columns equal height, but actually it is a contradiction to use Bootstrap and flex together. But just trying to fix your specific code:

<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<link rel="stylesheet" href="css.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</head>
<body>
<style>
  .yellow-box{
 position: relative;

 display: block;
  background-repeat: no-repeat;
  background-size: cover;

    min-height: 204px;
 margin-top:150px;
background-color: #e6ff00;
margin-left: -15px;
margin-right: -15px;

   }
.women-margin{
  margin: -1px -15px -2px -17px;
position: relative;
display: block;
padding-right: 0;
   }
  .row {
      display: flex;
      flex-wrap: wrap;
  }
</style>
<section id="carousel-section">
    <div class="container-fluid">
        <div class="row feature">
            <div class="col-lg-8 col-md-12">
                <div class="carousel-margin">
                    <div id="myCarousel" class="carousel1 slide container-carousel" data-
                    ride="carousel1">
                    <!-- Indicators -->
                    <ol class="carousel-indicators">
                    <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
                    <li data-target="#myCarousel" data-slide-to="1"></li>
                    <li data-target="#myCarousel" data-slide-to="2"></li>
                    </ol>
                    <!-- Wrapper for slides -->
                        <div class="carousel-inner">
                            <div class="item active">
                                <img src="images/dragon_hunter_pic.png" alt="dragon_hunter_pic" id="mainImage1" >
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-lg-4 col-md-5">
                <div class="women-margin">
                    <img src="images/women_3.png" alt="live" id="women-eyes1" >
                </div>
            </div>
            <div class="col-lg-4 col-md-7">
                <div class="yellow-box">
                    <h2 id="change_h2">THE DRAGON HUNTER</h2>
                    <br/>
                    <p id="change_p"> Lorem ipsum dolor sit amet, consectetur
                    adipiscing elit, sed do eiusmod tempor incididunt ut labore et
                    dolor aliqua. </p>
                </div>
            </div>
        </div>
    </div>
</section>
</body>
</html>


问:
VBA argument not optional error userfrom listbox
I wrote the following code for a UserForm but I keep getting an argument not optional error.

```<code>Option Explicit
Private Sub CommandButton3_Click()
   Select Case LCase(Me.ListBox2.Text)
   Case "Analysis": Call macro1
   Case ""
        MsgBox "nothing selected"
   Case Else
        MsgBox Me.ListBox2.Text
   End Select
End Sub
</code>```

macro 1 code:

```<code>Sub macro1()
'
' Macro1 Macro
Sheets.Add
ActiveSheet.Name = "Analysis"
Application.DisplayAlerts = False
Application.ScreenUpdating = False
'
Range("A13").Select
ActiveCell.FormulaR1C1 = "Year"
Range("B13").Select
ActiveCell.FormulaR1C1 = "0"
Range("C13").Select
ActiveCell.FormulaR1C1 = "=IFERROR(IF(RC[-1]+1>R9C2,"""",RC[-1]+1),"""")"
Range("C13").Select
Selection.AutoFill Destination:=Range("C13:HS13"), Type:=xlFillDefault
Range("C13:HQ13").Select
End Sub
</code>```

答:
First, your method of referencing the ListBox is a problem. See the code below Also, I had to add Sheet Name before Range and then this worked for me...</p>

```<code>Option Explicit

Private Sub CommandButton3_Click()
Dim i as Integer
Dim sValue as String
   For i = 0 To Me.ListBox2.ListCount - 1
       If Me.ListBox2.Selected(i) Then
           sValue = ListBox2.List(i)
       End If
   Next i

   Select Case LCase(sValue)
      Case "Analysis": Call macro1
      Case ""
          MsgBox "nothing selected"
      Case Else
          MsgBox sValue.Text
   End Select
End Sub

Sub macro1()
'
' Macro1 Macro
Sheets.Add
ActiveSheet.Name = "Analysis"
Application.DisplayAlerts = False
Application.ScreenUpdating = False
'
Sheets("Analysis").Range("A13").Select
ActiveCell.FormulaR1C1 = "Year"
Sheets("Analysis").Range("B13").Select
ActiveCell.FormulaR1C1 = "0"
Sheets("Analysis").Range("C13").Select
ActiveCell.FormulaR1C1 = "=IFERROR(IF(RC[-1]+1>R9C2,"""",RC[-1]+1),"""")"
Sheets("Analysis").Range("C13").Select
Selection.AutoFill Destination:=Sheets("Analysis").Range("C13:HS13"), Type:=xlFillDefault
Sheets("Analysis").Range("C13:HQ13").Select
End Sub
</code>```

Body:
I wrote the following code for a UserForm but I keep getting an argument not optional error.

Option Explicit
Private Sub CommandButton3_Click()
   Select Case LCase(Me.ListBox2.Text)
   Case "Analysis": Call macro1
   Case ""
        MsgBox "nothing selected"
   Case Else
        MsgBox Me.ListBox2.Text
   End Select
End Sub

macro 1 code:

Sub macro1()
'
' Macro1 Macro
Sheets.Add
ActiveSheet.Name = "Analysis"
Application.DisplayAlerts = False
Application.ScreenUpdating = False
'
Range("A13").Select
ActiveCell.FormulaR1C1 = "Year"
Range("B13").Select
ActiveCell.FormulaR1C1 = "0"
Range("C13").Select
ActiveCell.FormulaR1C1 = "=IFERROR(IF(RC[-1]+1>R9C2,"""",RC[-1]+1),"""")"
Range("C13").Select
Selection.AutoFill Destination:=Range("C13:HS13"), Type:=xlFillDefault
Range("C13:HQ13").Select
End Sub

Body:
First, your method of referencing the ListBox is a problem. See the code below Also, I had to add Sheet Name before Range and then this worked for me...

Option Explicit

Private Sub CommandButton3_Click()
Dim i as Integer
Dim sValue as String
   For i = 0 To Me.ListBox2.ListCount - 1
       If Me.ListBox2.Selected(i) Then
           sValue = ListBox2.List(i)
       End If
   Next i

   Select Case LCase(sValue)
      Case "Analysis": Call macro1
      Case ""
          MsgBox "nothing selected"
      Case Else
          MsgBox sValue.Text
   End Select
End Sub

Sub macro1()
'
' Macro1 Macro
Sheets.Add
ActiveSheet.Name = "Analysis"
Application.DisplayAlerts = False
Application.ScreenUpdating = False
'
Sheets("Analysis").Range("A13").Select
ActiveCell.FormulaR1C1 = "Year"
Sheets("Analysis").Range("B13").Select
ActiveCell.FormulaR1C1 = "0"
Sheets("Analysis").Range("C13").Select
ActiveCell.FormulaR1C1 = "=IFERROR(IF(RC[-1]+1>R9C2,"""",RC[-1]+1),"""")"
Sheets("Analysis").Range("C13").Select
Selection.AutoFill Destination:=Sheets("Analysis").Range("C13:HS13"), Type:=xlFillDefault
Sheets("Analysis").Range("C13:HQ13").Select
End Sub


问:
How to specify request params with Drive.Comments.list
I'm able to pull back the default 20 comments with the following code when I specify a single fileId param. But I would actually like to pull back a hundred or for curiousity's sake paginate to the next 20.

From my code below, in the getComments function, when i specify options as the param to Drive.Comments.list it renders an error. When I specify the fileId directly it returns 20.

It should be a simple fix - I'm a bit of rookie. Any suggestions? Please and thanks!

```<code>function main() {
  var fileId = getFileId();
  var fileComments = getComments(fileId);
//  logObj(fileComments);
  //Logger.log(fileComments);//.items.length); // this always says 20
//  logObj(fileComments);
  logObj(fileComments.items);
}

function getFileId() {
  return DocumentApp.getActiveDocument().getId();
}
function getComments(fileId) {
  var options = {
    'fileId': fileId,
    'pageSize': 99
  };

  var commnts =  Drive.Comments.list(fileId);

  return commnts;
  //Logger.log(cmnts.items.length);
}
function logObj(obj){
  for (key in obj) {
    var tmp =  obj[key];
    Logger.log(key + " = " + tmp );
  }
}

function findComments(criteria){

}
</code>```

答:
The Drive.Comments.list() will take 2 parameters. (fileId, {options}). Also, the option for result limits is maxResults (0 to 100). Use the result commnts.nextPageToken with the options.pageToken to page through large data sets

```<code>function getComments(fileId) {
  var options = {
    'maxResults': 99
  };

  var commnts =  Drive.Comments.list(fileId, options);

  return commnts;
  //Logger.log(cmnts.items.length);
}
</code>```

Body:
I'm able to pull back the default 20 comments with the following code when I specify a single fileId param. But I would actually like to pull back a hundred or for curiousity's sake paginate to the next 20.

From my code below, in the getComments function, when i specify options as the param to Drive.Comments.list it renders an error. When I specify the fileId directly it returns 20.

It should be a simple fix - I'm a bit of rookie. Any suggestions? Please and thanks!

function main() {
  var fileId = getFileId();
  var fileComments = getComments(fileId);
//  logObj(fileComments);
  //Logger.log(fileComments);//.items.length); // this always says 20
//  logObj(fileComments);
  logObj(fileComments.items);
}

function getFileId() {
  return DocumentApp.getActiveDocument().getId();
}
function getComments(fileId) {
  var options = {
    'fileId': fileId,
    'pageSize': 99
  };

  var commnts =  Drive.Comments.list(fileId);

  return commnts;
  //Logger.log(cmnts.items.length);
}
function logObj(obj){
  for (key in obj) {
    var tmp =  obj[key];
    Logger.log(key + " = " + tmp );
  }
}

function findComments(criteria){

}

Body:
The Drive.Comments.list() will take 2 parameters. (fileId, {options}). Also, the option for result limits is maxResults (0 to 100). Use the result commnts.nextPageToken with the options.pageToken to page through large data sets

function getComments(fileId) {
  var options = {
    'maxResults': 99
  };

  var commnts =  Drive.Comments.list(fileId, options);

  return commnts;
  //Logger.log(cmnts.items.length);
}


问:
print all the rows of of table into TextArea in javabook database
In my GUI, there is "Search" menuitem, and it should search the ssn number in the Faculty table and print them into the TextArea in javabook database. However, I only get the last row of the table that has 15 rows.
Here is the Search menuItem that calls the searchDB method.

```<code>MenuItem search = new MenuItem("Search");
    search.setOnAction((ActionEvent t) -> {
        try{
            searchDB(tArea);
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
    });
</code>```

Here is the searchDB method.

```<code>public void searchDB(TextArea tArea) throws SQLException, ClassNotFoundException {
    if (databaseName != null) {
        TextInputDialog dialog = new TextInputDialog();
        dialog.setContentText("Please enter Faculty ssn number follwing by %");
        Optional<String> search_id = dialog.showAndWait();

        try {

            Class.forName("com.mysql.jdbc.Driver");
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/" +databaseName+ "?autoReconnect=true&useSSL=false", "scott", "tiger");
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("select * from Faculty where ssn like '" + search_id.get() + "';");

            while (resultSet.next())
                tArea.setText(resultSet.getString(1) + "\t" + resultSet.getString(2) + "\t" + resultSet.getString(4) + "\t" + resultSet.getString(5));

        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
}
</code>```

Can you explain why do I get only the last row of the table? and How to print all the rows of the table in TextArea?

答: It is because you are using setText(), use append() instead. Check the javadoc for textarea.

Body:
In my GUI, there is "Search" menuitem, and it should search the ssn number in the Faculty table and print them into the TextArea in javabook database. However, I only get the last row of the table that has 15 rows.
Here is the Search menuItem that calls the searchDB method.

MenuItem search = new MenuItem("Search");
    search.setOnAction((ActionEvent t) -> {
        try{
            searchDB(tArea);
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
    });

Here is the searchDB method.

public void searchDB(TextArea tArea) throws SQLException, ClassNotFoundException {
    if (databaseName != null) {
        TextInputDialog dialog = new TextInputDialog();
        dialog.setContentText("Please enter Faculty ssn number follwing by %");
        Optional<String> search_id = dialog.showAndWait();

        try {

            Class.forName("com.mysql.jdbc.Driver");
            Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/" +databaseName+ "?autoReconnect=true&useSSL=false", "scott", "tiger");
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("select * from Faculty where ssn like '" + search_id.get() + "';");

            while (resultSet.next())
                tArea.setText(resultSet.getString(1) + "\t" + resultSet.getString(2) + "\t" + resultSet.getString(4) + "\t" + resultSet.getString(5));

        }catch(Exception ex){
            ex.printStackTrace();
        }
    }
}

Can you explain why do I get only the last row of the table? and How to print all the rows of the table in TextArea?


问:
How to automatically resubmit the form in Firefox on error
In case a (say login) form POST submission fails and Firefox displays "Try Again" message.

Is there any way to click this "Try Again" automatically or through any settings in Firefox about:config that it clicks it?

Related

答:
"Clicking" the Try Again button is relatively easy.  There is an extension that does just that, and lets you set the number of seconds between retries.

The real rub here is that you want to "blindly" retry form POSTs.  As we all know, just because you didn't get a response, that doesn't necessarily imply that nothing was changed on the server.

Re-submitting a login form sounds harmless enough, and usually is.  But if you imagine forms that result in orders being placed or money being moved, it's easy to understand why browsers have implemented this kind of warning:

This is what you'll see if you enable an extension like TryAgain and a form post fails.  It's the same behavior you'd get by pressing F5 yourself.  The extension will dutifully try to POST again, but the browser is going to intervene with an alert, and refuse to send the POST until "Resend" is clicked.

This kind of safety feature does a fair amount to protect end-users and developers from poor implementations and network hiccups.  However, it's really going to work against what you're trying to accomplish.

That said, if you could figure out a way to modify the extension to detect the alert and somehow click "Resend", you'd be in business.  I can't say for sure that this is impossible, put it kind of looks that way, at least for now: this issue was marked as "won't fix", and this issue is still open.


问:
Drupal8 retain quick edit functionality when inserting content from node variable
I have this markup in my twig file.

```<code><div class="post-title-block ilb">
  <h2 class="thin">{{ node.title.value }}</h2>
</div>
</code>```

I would like to retain Drupal quick edit functionality.
Where how how to I wrap {{ attributes }}, {{ title_prefix }}, {{ title_suffix }} etc.. ?

My twig file lives in templates/content/node--posts-full.html.twig

答:
You've indicated a node template, which means you will add {{attributes}} to a block element that surrounds the field content, and add the prefixes just after the same element so that the quickedit module can inject it's markup towards the top of the block.

Presuming the above is your template, you could do:

```<code><section{{ attributes }}>
  {{ title_prefix }}
    [you could wrap an actual title here...]
  {{ title_suffix }}
  <div class="post-title-block ilb">
    <h2 class="thin">{{ node.title.value }}</h2>
  </div>
</section>
</code>```

Body:
I have this markup in my twig file.

{{ node.title.value }}

I would like to retain Drupal quick edit functionality.
Where how how to I wrap {{ attributes }}, {{ title_prefix }}, {{ title_suffix }} etc.. ?

My twig file lives in templates/content/node--posts-full.html.twig

Body:
You've indicated a node template, which means you will add {{attributes}} to a block element that surrounds the field content, and add the prefixes just after the same element so that the quickedit module can inject it's markup towards the top of the block.

Presuming the above is your template, you could do:

<section{{ attributes }}>
  {{ title_prefix }}
    [you could wrap an actual title here...]
  {{ title_suffix }}
  <div class="post-title-block ilb">
    <h2 class="thin">{{ node.title.value }}</h2>
  </div>
</section>


问:
ng-valid and ng-invalid classes in angular dart forms are no more exposed
Dart: 1.24.2;
Angular: 4.0.0;
I created some CSS rules based on .ng-valid and .ng-invalid classes in angular forms. But, in last releases, it seems that ng-valid and ng-invalid classes are no more exposed, so my CSS rules are no more working.
Is it correct?
if yes, how can I by-pass this change?

Edit1: Test case
I simply generated a brand new project with angular and angular-material in my IDE (WebStorm). It generates a simple todo application. I took the todo_list_component.html and wrapped the whole content with a <form> </form> tag. In the todo_list_component.dart I have added an import for angular_forms and added formDirectives to the directives list.
Inspecting the form in dartium no ng-valid class has been added. The only class added, in my case is: class="_ngcontent-umj-2"

Edit2: Shortcut
Not very elegant, but working:

```<code><form #form="ngForm" [class.ng-valid]="form.valid" [class.ng-invalid]="!form.valid">
</code>```

答:
I don't know whether they are exposed or not.

At first I would recommend you to work with "Model driven forms" - and set the validation in your component. In my opinion it is better for UnitTests and easier to handle.

and here an example:

Specify CSS (test.component.css) class:

```<code>.error {
  border: 2px solid red;
}
</code>```

Component (test.component.ts):

```<code>imports ...;

@Component({
selector: 'test-component',
templateUrl: 'test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

 form: FormGroup;

 constructor(private navCtrl: NavController, private auth: AuthService, private toast: ToastController, private fb: FormBuilder) {

 }

 ngOnInit() {
  this.form = this.fb.group({
   email: ['', [
     Validators.required,
     Validators.email]],
   password: ['', [
     Validators.required,
     Validators.minLength(6)]],
 });
}
</code>```

and your template (test.component.html) looks like this:

```<code><form [formGroup]="form" (ngSubmit)="login()" [ngClass]="{'error': !form.valid}">
  *** YOUR FORM DIV'S HERE ***
</form>
</code>```

I don't know if this is working with Dart too. But as Verena commented, we can help you most if you upload some code.

Body:
Dart: 1.24.2;
Angular: 4.0.0;
I created some CSS rules based on .ng-valid and .ng-invalid classes in angular forms. But, in last releases, it seems that ng-valid and ng-invalid classes are no more exposed, so my CSS rules are no more working.
Is it correct?
if yes, how can I by-pass this change?

Edit1: Test case
I simply generated a brand new project with angular and angular-material in my IDE (WebStorm). It generates a simple todo application. I took the todo_list_component.html and wrapped the whole content with a <form> </form> tag. In the todo_list_component.dart I have added an import for angular_forms and added formDirectives to the directives list.
Inspecting the form in dartium no ng-valid class has been added. The only class added, in my case is: class="_ngcontent-umj-2"

Edit2: Shortcut
Not very elegant, but working:

<form #form="ngForm" [class.ng-valid]="form.valid" [class.ng-invalid]="!form.valid">

Body:
I don't know whether they are exposed or not.

At first I would recommend you to work with "Model driven forms" - and set the validation in your component. In my opinion it is better for UnitTests and easier to handle.

and here an example:

Specify CSS (test.component.css) class:

.error {
  border: 2px solid red;
}

Component (test.component.ts):

imports ...;

@Component({
selector: 'test-component',
templateUrl: 'test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

 form: FormGroup;

 constructor(private navCtrl: NavController, private auth: AuthService, private toast: ToastController, private fb: FormBuilder) {

 }

 ngOnInit() {
  this.form = this.fb.group({
   email: ['', [
     Validators.required,
     Validators.email]],
   password: ['', [
     Validators.required,
     Validators.minLength(6)]],
 });
}

and your template (test.component.html) looks like this:

<form [formGroup]="form" (ngSubmit)="login()" [ngClass]="{'error': !form.valid}">
  *** YOUR FORM DIV'S HERE ***
</form>

I don't know if this is working with Dart too. But as Verena commented, we can help you most if you upload some code.


问:
Issues connecting phpmyadmin to multiple instances
I'm rebuilding a database server on CentOS7 using mariadb (distrib 5.5.56). The original database server is Ubuntu 12.04 using mysql (distrib 5.5.29). The original server has multiple instances (running on different ports) and users can use phpmyadmin to log into the different database instances by selecting the server in the phpmyadmin login page.

Before I import the database to the new server I'm trying to a similar setup working on the new server. I've tried to keep most paths the same (my.cnf is a little different due to using mysql on one server and mariadb on another but database locations are the same)

I believe I've got the multiple instances running OK ('mysqld_multi report' reports both instances are running OK and I can connect to both instances via 'msql' command when a port is specified).

I got phpmyadmin working for the default mariadb database (did this prior to setting-up the other instances in my.cnf) so I know phpmyadmin is working OK. I've modified the file /etc/phpMyAdmin/config.inc.php to enable connecting into multiple instances by essentially copying the file from the original server.
I'm just unable to login to the actual instances I've configured. If the mariadb service is running then it will log me into the default mariadb database when specifying either instance rather than the actual instance I want. When I stop the mariadb service, although I can connect using 'mysql --port=xxxx.... command phpmyadmin simply gives me the error 'Cannot log in to the MySQL server'.

I just can't figure out when this is not working. I suspect it's something trivial in a config file somewhere but can't work out what it is. I've double-checked things like my.cnf and config.inc.php and can't see anything obviously wrong with them.

Any assistance would be appreciated!

Cheers,

Tim

答:
I believe I have figured it out. It appears to be a combination of things. In config.inc.php I had specified the host = 'localhost', because that's how it was configured on the original Ubtuntu mysql server. Once I changed to '127.0.0.1' then phpmyadmin was able to connect BUT this wasn't the only issue. The other issue was that selinux also needed to allow certain things (see https://community.spiceworks.com/topic/693552-mariadb-phpmyadmin-selinux-woes - refer to Jesse1648 comments - also need to use -P to set permanently). With these 2 changes I am now able to connect to instances on different ports.

What I don't actually understand is that I had tried to copy the config from the original server as much as possible because it worked. Why it actually works when specifying 'localhost' in config.inc.php (rather than '127.0.0.1') is a bit mystifying (I know that mysql commands ignore ports if 'localhost' is used when specifying hostname). The important thing is that it works!


问:
ZF3 error when cron runs
I've got route:

```<code>'console' => [
    'router' => [
        'routes' => [
            'cronroute' => [
                'options' => [
                    'route' => 'action',
                    'defaults' => [
                        'controller' => Controller\ConsoleController::class,
                        'action' => 'action',
                    ],
                ],
            ],
        ]
    ],
],
</code>```

and when I run it in console:

```<code>php /Applications/www/project/public/index.php action
</code>```

everything is ok, no errors

But when I try to add this script to crontab:

```<code>* * * * * php /Applications/www/project/public/index.php action >> /Applications/www/log/script_output.log 2>&1
</code>```

I get errors in the log:

```<code>Parse error: parse error in /Applications/www/project/vendor/phpunit/phpunit/src/Framework/TestCase.php on line 856
</code>```

I don't use phpunit anywhere in my code.

答:
My webserver uses php 7.0, command also 7.0, but cron 5.6.
Latest version of PhpUnit required >5.6, that why I get error.</p>

Title: ZF3 error when cron runs

Body:
I've got route:

'console' => [
    'router' => [
        'routes' => [
            'cronroute' => [
                'options' => [
                    'route' => 'action',
                    'defaults' => [
                        'controller' => Controller\ConsoleController::class,
                        'action' => 'action',
                    ],
                ],
            ],
        ]
    ],
],

and when I run it in console:

php /Applications/www/project/public/index.php action

everything is ok, no errors

But when I try to add this script to crontab:

* * * * * php /Applications/www/project/public/index.php action >> /Applications/www/log/script_output.log 2>&1

I get errors in the log:

Parse error: parse error in /Applications/www/project/vendor/phpunit/phpunit/src/Framework/TestCase.php on line 856

I don't use phpunit anywhere in my code.


问:
Tomcat & Eclipse integration
I'm developing on a Ubuntu 8.04 machine using Eclipse Ganymede. I installed Tomcat 5.5 using sudo apt-get install tomcat5.5 tomcat5.5-admin and using an Ant script I deploy my WAR file by copying it to $CATALINA_HOME/webapps.

I then created an Eclipse project and I have it output compiled source in a similar but separate directory structure under $PROJECT_ROOT/target/. I still deploy the WAR file by right clicking on the build.xml and choosing my deploy-war task.

As Tomcat is running as a deamon, automatically started up on booting, I'm not instructing it when to start or exit.

My problems with this setup are:

Using this approach I do not get any output to the Eclipse console, as Tomcat is running under the tomcat55 user and I have a different login and no access to Stdout of tomcat55.

The logging which occurs is also directed to Stdout at the moment, which I find pretty nice during development. But it's not nice when I can't see it. :-)

I don't have any servers under the Server tab and no Run configurations. This makes it impossible for me to use the Debug mode of Eclipse, which otherwise is quite convenient.

What do you think I should do to integrate them and in turn make my development environment much better?

答: You need eclipse to manage a copy of tomcat, then it can debug it.  The clue to the problem was that you have to push deploy-war, this means the files are leaving your development environment and entering an external server.  On a properly configured development environment, you only need to save your java file, it will auto-compile and already be on the local tomcat install, which might try to auto reload the web-app, and you can refresh your browser without reloading anything on the server.  Look up some more tomcat plugins, there are a few different ways to do this.</p>

Title: Tomcat & Eclipse integration

OwnerDisplayName: Karl


问:
catching all invalid URLs
I recently upgraded a site and almost all URLs have changed. I have redirected all of them (or so I hope) but it may be possible that some of them have slipped by me. Is there a way to somehow catch all invalid URLs and send the user to a certain page and somehow know what URL the person came from so I could log this, and fix those? I'm thinking I could use .htaccess somehow but am not sure how. I am using PHP Thanks so much!</p>

答:
You could use a custom ErrorDocument handler written in PHP to catch URLs having "slipped by":

```<code># .htaccess file
ErrorDocument 404 /not-found.php
</code>```

And in not-found.php:

```<code>switch($_SERVER['REDIRECT_URL']) {
    case '/really_old_page.php':
        header('HTTP/1.1 301 Moved Permanently');
        header('Location: /new-url/...');
    /*  As suggested in the comment, exit here.
        Additional output might not be handled well and
        provokes undefined behavior. */
        exit;
    default:
        header('HTTP/1.1 404 Not Found');
        die('404 - Not Found');
}
</code>```

Title: catching all invalid URLs

Body:
You could use a custom ErrorDocument handler written in PHP to catch URLs having "slipped by":

# .htaccess file
ErrorDocument 404 /not-found.php

And in not-found.php:

switch($_SERVER['REDIRECT_URL']) {
    case '/really_old_page.php':
        header('HTTP/1.1 301 Moved Permanently');
        header('Location: /new-url/...');
    /*  As suggested in the comment, exit here.
        Additional output might not be handled well and
        provokes undefined behavior. */
        exit;
    default:
        header('HTTP/1.1 404 Not Found');
        die('404 - Not Found');
}


问:
mysql SUM column on WHERE condition
Im trying to get a total sum of all the columns that meet a condition. Here is my current setup

```<code>    SELECT
                      COUNT(order_type = 'BUY') AS buy_fill,
                      COUNT(order_type = 'SELL') AS sell_fill,
                      SUM(btc_total) AS fill_sum
                      FROM fill_orders
                      WHERE coin_id = '$coin'
                      AND time_stamp >= DATE_SUB(NOW(), INTERVAL 55 SECOND)
</code>```

This is what I have now and its counting how many types of buy and sell orders I have and is also giving me sum of all orders but I need to the break the sum of the orders into BUY orders and SELL orders.

Heres the code that I'm trying trying to make work.  I've added (btc_total WHERE order_type = 'BUY') and  SUM(btc_total WHERE order_type = 'SELL')

```<code>      SELECT
                            COUNT(order_type = 'BUY') AS buy_fill,
                            COUNT(order_type = 'SELL') AS sell_fill,
                            SUM(btc_total) AS fill_sum,

                            SUM(btc_total WHERE order_type = 'BUY') AS buy_total
                            SUM(btc_total WHERE order_type = 'SELL') AS sell_total
                      FROM fill_orders
                      WHERE coin_id = '$coin'
                      AND time_stamp >= DATE_SUB(NOW(), INTERVAL 55 SECOND)
</code>```

答:
Change this:

```<code>SUM(btc_total WHERE order_type = 'BUY') AS buy_total
</code>```

to this:

```<code>SUM(IF(order_type='BUY',btc_total,NULL)) AS buy_total
</code>```

The MySQL IF() function evaluates the first argument as a boolean, if that's TRUE, it returns the second argument, else it returns the third argument.

The IF() will be evaluated for each row, and the return from that expression will get totaled up by the SUM() aggregate.

or, use the more ANSI-standard equivalent to achieve the same result:

```<code>SUM(CASE WHEN order_type = 'BUY' THEN btc_total END) AS buy_total
</code>```

This pattern is commonly referred to as "conditional aggregation".

For the "counts" we can replace COUNT with SUM, like this:

```<code>SUM(order_type = 'BUY') AS buy_fill
</code>```

MySQL evaluates the equality comparison as a boolean, which returns 1, 0 or NULL, which are then totaled up by the SUM aggregate. (A COUNT of that would include zeros and ones, not just the ones.)

The above is equivalent to

```<code>SUM( CASE
     WHEN order_type  = 'BUY' THEN 1
     WHEN order_type <> 'BUY' THEN 0
     ELSE NULL
     END
   ) AS buy_fill
</code>```

If we want to use a COUNT aggregate, we could do it like this:

```<code>COUNT(IF(order_type = 'Buy',1,NULL)) AS buy_fill
</code>```

(We could use any non-null value in place of 1, and get an equivalent result.)

Title: mysql SUM column on WHERE condition

Body:
Im trying to get a total sum of all the columns that meet a condition. Here is my current setup

    SELECT
                      COUNT(order_type = 'BUY') AS buy_fill,
                      COUNT(order_type = 'SELL') AS sell_fill,
                      SUM(btc_total) AS fill_sum
                      FROM fill_orders
                      WHERE coin_id = '$coin'
                      AND time_stamp >= DATE_SUB(NOW(), INTERVAL 55 SECOND)

This is what I have now and its counting how many types of buy and sell orders I have and is also giving me sum of all orders but I need to the break the sum of the orders into BUY orders and SELL orders.

Heres the code that I'm trying trying to make work.  I've added (btc_total WHERE order_type = 'BUY') and  SUM(btc_total WHERE order_type = 'SELL')

      SELECT
                            COUNT(order_type = 'BUY') AS buy_fill,
                            COUNT(order_type = 'SELL') AS sell_fill,
                            SUM(btc_total) AS fill_sum,

                            SUM(btc_total WHERE order_type = 'BUY') AS buy_total
                            SUM(btc_total WHERE order_type = 'SELL') AS sell_total
                      FROM fill_orders
                      WHERE coin_id = '$coin'
                      AND time_stamp >= DATE_SUB(NOW(), INTERVAL 55 SECOND)

Body:
Change this:

SUM(btc_total WHERE order_type = 'BUY') AS buy_total

to this:

SUM(IF(order_type='BUY',btc_total,NULL)) AS buy_total

The MySQL IF() function evaluates the first argument as a boolean, if that's TRUE, it returns the second argument, else it returns the third argument.

The IF() will be evaluated for each row, and the return from that expression will get totaled up by the SUM() aggregate.

or, use the more ANSI-standard equivalent to achieve the same result:

SUM(CASE WHEN order_type = 'BUY' THEN btc_total END) AS buy_total

This pattern is commonly referred to as "conditional aggregation".

For the "counts" we can replace COUNT with SUM, like this:

SUM(order_type = 'BUY') AS buy_fill

MySQL evaluates the equality comparison as a boolean, which returns 1, 0 or NULL, which are then totaled up by the SUM aggregate. (A COUNT of that would include zeros and ones, not just the ones.)

The above is equivalent to

SUM( CASE
     WHEN order_type  = 'BUY' THEN 1
     WHEN order_type <> 'BUY' THEN 0
     ELSE NULL
     END
   ) AS buy_fill

If we want to use a COUNT aggregate, we could do it like this:

COUNT(IF(order_type = 'Buy',1,NULL)) AS buy_fill

(We could use any non-null value in place of 1, and get an equivalent result.)


问:
trying to detect if three numbers within an array occur in a row
I am creating a function which takes in a number value as a parameter. From there, the goal is to detect if three numbers occured in a row, for example 3415633356 would pass as true and 3562455 would not.

I am doing something wrong in my function as scenarios which should be passing as true are not. The end goal of detecting if three numbers in a row occured can be done in any way.

By the way, I am new to programming and just starting out so I'm trying to increment my knowledge as I practice these things. If you can breakdown why your suggesstion works and what I am doing wrong instead of just providing the sole answer, that would be hugely appreciated. Many thanks!

```<code>var testNumbers = function(num1){
  var stringOne = num1.toString();
  var num1array = stringOne.split("");
  var tripleNum = [];
  num1array.reduce(function(a,b){
    if (a===b){
      tripleNum.push(a);
    }
  })
  if (tripleNum.length >= 3){
    console.log(tripleNum);
  } else {
    console.log("There wasnt a case of three straight triple numbers occuring");
  }

}
</code>```

答:
I would keep a counter that gets increased every time a new number equals a past number. If that count gets to three we quite and return true. Otherwise if the loop ends, we return false. For example:

function count3(arr) {
  // initialize a counter
  let count = 1

  // loop through the array, starting with the second
  // element, so we can compare it to the first
  for (let i = 1; i < arr.length; i++) {

    // does the count equal the previous?
    // if so increase it, otherwise set it back to 1
    count = arr[i] === arr[i - 1] ? count + 1 : 1 // <-- ternary operator
    // see if we're done
    if (count === 3) return true
  }
  // never reached three
  return false
}

// try it out
var arr = [3, 3, 4, 1, 5, 6, 3, 4, 3, 5, 6, 5]
console.log(count3(arr))

var arr = [3, 3, 4, 1, 5,5,5, 6, 3, 4, 3, 5, 6, 5]
console.log(count3(arr))

// make sure it works when array ends with three
var arr = [ 5, 6, 7, 3, 3, 3]
console.log(count3(arr))

// with strings too?
console.log(count3('34156335666'))```

Body:
I am creating a function which takes in a number value as a parameter. From there, the goal is to detect if three numbers occured in a row, for example 3415633356 would pass as true and 3562455 would not.

I am doing something wrong in my function as scenarios which should be passing as true are not. The end goal of detecting if three numbers in a row occured can be done in any way.

By the way, I am new to programming and just starting out so I'm trying to increment my knowledge as I practice these things. If you can breakdown why your suggesstion works and what I am doing wrong instead of just providing the sole answer, that would be hugely appreciated. Many thanks!

var testNumbers = function(num1){
  var stringOne = num1.toString();
  var num1array = stringOne.split("");
  var tripleNum = [];
  num1array.reduce(function(a,b){
    if (a===b){
      tripleNum.push(a);
    }
  })
  if (tripleNum.length >= 3){
    console.log(tripleNum);
  } else {
    console.log("There wasnt a case of three straight triple numbers occuring");
  }

}


问:
Implementing a Progress bar for long running task implemented with an ASP.NET MVC 2 AsyncController
After reading the documentation on AsyncControllers in ASP.NET MVC 2, I am wondering what's the best way to implement an ajax progress bar in this scenario. It seems a bit odd that the tutorial does not cover this at all.

I guess implementing an AJAX progress bar involves requires additional action method that returns the status of the current task. However, I am not sure about the best way to exchange information on the status of the task between worker threads and that action method.

My best idea so far was to put information on the curent progress into the Session dictionary along with a unique id, and share that id with the client so that it can poll the status. But perhaps there is a much easier way that I did not notice.

What's the best way to do this?

Thanks,

Adrian

答:
Very interesting question! Actually it seems that it is not a task for AsyncController. Async controllers are designed for long-running single-HTTP-query operations at server-side. When you are using async action, this could only help you to release ASP.Net worker thread during some long-running operation(s) and allow it to serve other requests while operation is performed. But from client-side point of view it doesn't matter, is this async controller or not. For client this is just single HTTP request.

You need to redesign this using some long-running queries service in your application. Here is example of controller, that could serve such workflow:

```<code>public class LongOperationsController : Controller
{
    public ActionResult StartOperation(OperationData data)
    {
        Guid operationId = Guid.NewGuid(); // unique identifier for your operation
        OperationsService.DoStartOperation(operationId, data); // service starts to perform operation using separate thread
        return new JsonResult(operationId); // operation id should be sent to client to allow progress monitoring
    }

    public ActionResult GetOperationStatus(Guid operationId)
    {
        var status = OperationsService.GetStatus(operationId); // this method returns some object, that describes status of operation (e.g. progress, current task etc.)
        return new JsonResult(status); // returning it to client
    }

    public ActionResult GetOperationResult(Guid operationId)
    {
        var result = OperationsService.GetOperationResult(operationId); // this should throw exception if operation is not yet completed
        return new JsonResult(result);
    }

    public ActionResult ClearOperation(Guid operationId)
    {
        OperationsService.ClearOperationResult(operationId); // we should delete operation result if it was handled by client
        return true;
    }
}
</code>```

And here are client-side code, that could interact with this controller:

```<code>var operationId;
function startOperation(data) {
    $.post('/LongOperations/StartOperation', data, function(response) {
        operationId = response; // store operationId
        startOperationMonitoring(); // start
    }, 'json');
}

function startOperationMonitoring() {
    // todo : periodically call updateOperationStatus() to check status at server-side
}

function updateOperationStatus() {
    // todo : get result of GetOperationStatus action from controller
    // todo : if status is 'running', update progress bar with value from server, if 'completed' - stop operation monitoring and call finishOperation()
}

function finishOperation() {
    // todo : get result of GetOperationResult action from controller and update UI
    // todo : call ClearOperation action from controller to free resources
}
</code>```

This is very basic concept, there are some missed items here, but I hope you will get the main idea. Also it's up to you how to design components of this system, for example:

use singleton for OperationsService,
or not;

where and how long operation result should be stored (DB? Cache?
Session?);

is it really required to manually release resources and what to do when
client stopped to monitor operation
(user closed browser) etc.

Best luck!

Body:
Very interesting question! Actually it seems that it is not a task for AsyncController. Async controllers are designed for long-running single-HTTP-query operations at server-side. When you are using async action, this could only help you to release ASP.Net worker thread during some long-running operation(s) and allow it to serve other requests while operation is performed. But from client-side point of view it doesn't matter, is this async controller or not. For client this is just single HTTP request.

You need to redesign this using some long-running queries service in your application. Here is example of controller, that could serve such workflow:

public class LongOperationsController : Controller
{
    public ActionResult StartOperation(OperationData data)
    {
        Guid operationId = Guid.NewGuid(); // unique identifier for your operation
        OperationsService.DoStartOperation(operationId, data); // service starts to perform operation using separate thread
        return new JsonResult(operationId); // operation id should be sent to client to allow progress monitoring
    }

    public ActionResult GetOperationStatus(Guid operationId)
    {
        var status = OperationsService.GetStatus(operationId); // this method returns some object, that describes status of operation (e.g. progress, current task etc.)
        return new JsonResult(status); // returning it to client
    }

    public ActionResult GetOperationResult(Guid operationId)
    {
        var result = OperationsService.GetOperationResult(operationId); // this should throw exception if operation is not yet completed
        return new JsonResult(result);
    }

    public ActionResult ClearOperation(Guid operationId)
    {
        OperationsService.ClearOperationResult(operationId); // we should delete operation result if it was handled by client
        return true;
    }
}

And here are client-side code, that could interact with this controller:

var operationId;
function startOperation(data) {
    $.post('/LongOperations/StartOperation', data, function(response) {
        operationId = response; // store operationId
        startOperationMonitoring(); // start
    }, 'json');
}

function startOperationMonitoring() {
    // todo : periodically call updateOperationStatus() to check status at server-side
}

function updateOperationStatus() {
    // todo : get result of GetOperationStatus action from controller
    // todo : if status is 'running', update progress bar with value from server, if 'completed' - stop operation monitoring and call finishOperation()
}

function finishOperation() {
    // todo : get result of GetOperationResult action from controller and update UI
    // todo : call ClearOperation action from controller to free resources
}

This is very basic concept, there are some missed items here, but I hope you will get the main idea. Also it's up to you how to design components of this system, for example:

use singleton for OperationsService,
or not;

where and how long operation result should be stored (DB? Cache?
Session?);

is it really required to manually release resources and what to do when
client stopped to monitor operation
(user closed browser) etc.

Best luck!


问:
How to pass variable in AJAX to node js file
I tried coding in AJAX where I need to pass data newval to data post.

```<code>function turnplug2On(){

    var newval=this.getAttribute("data-id");
    newval=newval+"On"
        $(document).ready(function() {
        $.ajax({
                    type: "POST",
                    url: 'http://localhost:8124/',
                    timeout: 2000,
                    data: '{"data":"plug2On"}',

                });
            });
        }
</code>```

Instead of passing hardcoded value in data , I wanted to pass newval variable.. can you please help explain how to do this.

```<code>    http.createServer (req, res) => {
    //console.log('request received');
    //util.log(util.inspect(req));
    console.log(req,res);

    res.writeHead(200, {'Content-Type': 'text/plain'});
    req.on('data', function (chunk) {
        //console.log(chunk);
        //req.on(function (chunk) {
        var obj = JSON.parse(chunk.toString());
        console.log(obj.data);

        switch (obj.data) {
}
}

    });
   // res.end('_testcb(\'{"message": "Plug1!"}\')');
    //res.end('callback(\'{\"msg\": \"OK\"}\')');

}).listen(8124);
</code>```

Thank you.

答:
Just figured out the way to do this.
In Ajax,
I have used
data: JSON.stringify({data:newval}),
So that the value will be JSON stringified for the nodejs to read the data</p>

Body:
I tried coding in AJAX where I need to pass data newval to data post.

function turnplug2On(){

    var newval=this.getAttribute("data-id");
    newval=newval+"On"
        $(document).ready(function() {
        $.ajax({
                    type: "POST",
                    url: 'http://localhost:8124/',
                    timeout: 2000,
                    data: '{"data":"plug2On"}',

                });
            });
        }

Instead of passing hardcoded value in data , I wanted to pass newval variable.. can you please help explain how to do this.

    http.createServer (req, res) => {
    //console.log('request received');
    //util.log(util.inspect(req));
    console.log(req,res);

    res.writeHead(200, {'Content-Type': 'text/plain'});
    req.on('data', function (chunk) {
        //console.log(chunk);
        //req.on(function (chunk) {
        var obj = JSON.parse(chunk.toString());
        console.log(obj.data);

        switch (obj.data) {
}
}

    });
   // res.end('_testcb(\'{"message": "Plug1!"}\')');
    //res.end('callback(\'{\"msg\": \"OK\"}\')');

}).listen(8124);

Thank you.


答:
"conditional aggregates" conventionally contain a case expression

```<code>SELECT
      COUNT(CASE WHEN order_type = 'BUY' THEN order_type END)      AS buy_fill
    , COUNT(CASE WHEN order_type = 'SELL' THEN order_type END)     AS sell_fill
    , SUM(btc_total)                                               AS fill_sum
    , SUM(CASE WHEN order_type = 'BUY' THEN btc_total ELSE 0 END)  AS buy_total
    , SUM(CASE WHEN order_type = 'SELL' THEN btc_total ELSE 0 END) AS sell_total
FROM fill_orders
WHERE coin_id = '$coin'
AND time_stamp >= DATE_SUB(NOW(), INTERVAL 55 SECOND)
</code>```

Title: mysql SUM column on WHERE condition

Body:
"conditional aggregates" conventionally contain a case expression

SELECT
      COUNT(CASE WHEN order_type = 'BUY' THEN order_type END)      AS buy_fill
    , COUNT(CASE WHEN order_type = 'SELL' THEN order_type END)     AS sell_fill
    , SUM(btc_total)                                               AS fill_sum
    , SUM(CASE WHEN order_type = 'BUY' THEN btc_total ELSE 0 END)  AS buy_total
    , SUM(CASE WHEN order_type = 'SELL' THEN btc_total ELSE 0 END) AS sell_total
FROM fill_orders
WHERE coin_id = '$coin'
AND time_stamp >= DATE_SUB(NOW(), INTERVAL 55 SECOND)


问:
How can I make a responsive scale grid when dragging and droping Images?
I'm pretty new to JS and CSS so i'm looking for help to make a Grid container in which I drag into an icons in different sizes and I want them to arrange themselves based on the size of each icon and the amount of them.

Let's say the minimum size that each icon can scale down is 20% of its original size.

I tried a lot of methods without finding the perfect way..
If anyone can send me a complete example of something like that I would be thankfull!

答:
There's no magic solution here. You're asking few questions - each has to be addressed separately and depends on the js framework you use. I'm going to assume you're using vanilla js / jQuery.

Grid layout - Bootstrap  is a trendy and working-out-of-the-box framework. Here's a simple grid example.

Drag n drop - There's no shortage in drag & drop libs like interactjs, jQueryUI, and Draggabilly (example)

Don't attempt to achieve all your goals at once. Instead, implement the grid, understand it, then move to drag n drop and sort by size logic.

ContentLicense: CC BY-SA 4.0


问:
How to pass argument to a controller method while testing with RSpec
Below are my controller methods which I am trying to test with RSpec

```<code>def login
    authorized_user = authenticate(params[:email], params[:password])
    if authorized_user
      # Creating a session if the User is Authorized
      session[:user_email] = authorized_user
      redirect_to(controller: 'home', action: 'details')
    else
      flash[:invalid] = 'Invalid Username or Password'
      redirect_to(action: 'signin')
    end
  end

def authenticate(email = '', password = '')
    url = 'http://localhost:8080/getUser/' + email
    response = RestClient.get(url)
    resp = JSON.parse(response)
    if resp[0]['id'] == 0
      return false  # If no user exists return false
    else
      return resp[0]['email']
    end
  end
</code>```

Here I am trying to mock the RestClient.get() method and return a dummy email to the login method to set the session with.
Below is my spec file

```<code>it "mocks the api method checks the user with a Invalid email" do
      RestClient.should_receive(:get).and_return('[{"id":"0"}]')
      get :authenticate
      expect(response).to redirect_to '/signin'
    end
</code>```

But here I need to pass email and password to the authenticate method. I am facing two problems here
1) How to pass the email and password to the authenticate method
2) When I call the authenticate method without the arguments like above I get an error like this

```<code>Failure/Error: url = 'http://localhost:8080/getUser/' + email

     TypeError:
       no implicit conversion of nil into String
</code>```

So how can I mock the the RestClient.get() method and return some JSON as response by calling the authenticate method with some dummy email and password?

答:
In RSpec you can pass the params as a Hash in the get method

```<code>get :show, email: 'abc@gmail.com', password: '1234567890'
</code>```

Body:
Below are my controller methods which I am trying to test with RSpec

def login
    authorized_user = authenticate(params[:email], params[:password])
    if authorized_user
      # Creating a session if the User is Authorized
      session[:user_email] = authorized_user
      redirect_to(controller: 'home', action: 'details')
    else
      flash[:invalid] = 'Invalid Username or Password'
      redirect_to(action: 'signin')
    end
  end

def authenticate(email = '', password = '')
    url = 'http://localhost:8080/getUser/' + email
    response = RestClient.get(url)
    resp = JSON.parse(response)
    if resp[0]['id'] == 0
      return false  # If no user exists return false
    else
      return resp[0]['email']
    end
  end

Here I am trying to mock the RestClient.get() method and return a dummy email to the login method to set the session with.
Below is my spec file

it "mocks the api method checks the user with a Invalid email" do
      RestClient.should_receive(:get).and_return('[{"id":"0"}]')
      get :authenticate
      expect(response).to redirect_to '/signin'
    end

But here I need to pass email and password to the authenticate method. I am facing two problems here
1) How to pass the email and password to the authenticate method
2) When I call the authenticate method without the arguments like above I get an error like this

Failure/Error: url = 'http://localhost:8080/getUser/' + email

     TypeError:
       no implicit conversion of nil into String

So how can I mock the the RestClient.get() method and return some JSON as response by calling the authenticate method with some dummy email and password?

Body:
In RSpec you can pass the params as a Hash in the get method

get :show, email: 'abc@gmail.com', password: '1234567890'


问:
Dialog Resizing Under VS2017
This is very bizarre. I ported a project that was working fine under VS2008 but when I build it with VS2017, the very presence of one line causes my dialog to resize - the code does not even need to run, it just needs to be present in a subroutine that does run!
I have created the simplest version of the program I could come up with to show this behavior. Try building/running under different versions of Visual Studio.
I would love both an explanation for why this is happening as well as how to fix it. Thanks.</p>

```<code>using System;
using System.IO;
using System.Windows.Forms;
using System.Windows.Media.Imaging; // Need reference to PresentationCore

namespace Test2017
{
    public class MainDlg : Form
    {
        [STAThread]
        static void Main() { Application.Run(new MainDlg()); }

        public MainDlg()
        {
            SuspendLayout();
            var button = new Button { Location = new System.Drawing.Point(7, 56), Size = new System.Drawing.Size(263, 23), Text = "Note size before and after clicking" };
            button.Click += Button_Click;
            ClientSize = new System.Drawing.Size(282, 253);
            Controls.Add(button);
            ResumeLayout(false);
            PerformLayout();
        }

        private void Button_Click(object sender, EventArgs e)
        {
            if (DateTime.Today.Year != 1234) return;    // This will always return
            try
            {
                // The following is never executed - but its very presence causes the dialog to shrink when running under VS2017
                BitmapFrame.Create((FileStream)null);   // Was using this to get metadata - that part works ok
                MessageBox.Show("Success");
            }
            catch { MessageBox.Show("Exception"); }
        }
    }
}
</code>```

答:
BitmapFrame is a class that comes from the PresentationCore assembly, always used in a WPF app.  It has a module initializer that automatically makes the program dpiAware.  Being dpiAware is very important to a WPF app.  And supposed to be a feature for a Winforms app, but it has to be turned on by hand.

The C# language has no support for module initializers.  It is roughly similar to a static constructor, but runs when an assembly gets loaded.  Assemblies get loaded by the just-in-time compiler, that is why it looked like just having the statement being present made the difference and executing it was not important.

So the best way to avoid the problem is to ensure your app is dpiAware before it creates its first window.  Follow the link to learn how to modify the manifest.  If it is undesirable to be dpiAware, writing dpiAware code in Winforms is not that intuitive, then you can disable what PresentationCore does by pasting this code:

```<code>[assembly:System.Windows.Media.DisableDpiAwareness]
</code>```

Which requires adding a reference to WindowsBase.  You can put it anywhere you like, AssemblyInfo.cs is a pretty logical place.

Title: Dialog Resizing Under VS2017

Body:
This is very bizarre. I ported a project that was working fine under VS2008 but when I build it with VS2017, the very presence of one line causes my dialog to resize - the code does not even need to run, it just needs to be present in a subroutine that does run!
I have created the simplest version of the program I could come up with to show this behavior. Try building/running under different versions of Visual Studio.
I would love both an explanation for why this is happening as well as how to fix it. Thanks.

using System;
using System.IO;
using System.Windows.Forms;
using System.Windows.Media.Imaging; // Need reference to PresentationCore

namespace Test2017
{
    public class MainDlg : Form
    {
        [STAThread]
        static void Main() { Application.Run(new MainDlg()); }

        public MainDlg()
        {
            SuspendLayout();
            var button = new Button { Location = new System.Drawing.Point(7, 56), Size = new System.Drawing.Size(263, 23), Text = "Note size before and after clicking" };
            button.Click += Button_Click;
            ClientSize = new System.Drawing.Size(282, 253);
            Controls.Add(button);
            ResumeLayout(false);
            PerformLayout();
        }

        private void Button_Click(object sender, EventArgs e)
        {
            if (DateTime.Today.Year != 1234) return;    // This will always return
            try
            {
                // The following is never executed - but its very presence causes the dialog to shrink when running under VS2017
                BitmapFrame.Create((FileStream)null);   // Was using this to get metadata - that part works ok
                MessageBox.Show("Success");
            }
            catch { MessageBox.Show("Exception"); }
        }
    }
}

Body:
BitmapFrame is a class that comes from the PresentationCore assembly, always used in a WPF app.  It has a module initializer that automatically makes the program dpiAware.  Being dpiAware is very important to a WPF app.  And supposed to be a feature for a Winforms app, but it has to be turned on by hand.

The C# language has no support for module initializers.  It is roughly similar to a static constructor, but runs when an assembly gets loaded.  Assemblies get loaded by the just-in-time compiler, that is why it looked like just having the statement being present made the difference and executing it was not important.

So the best way to avoid the problem is to ensure your app is dpiAware before it creates its first window.  Follow the link to learn how to modify the manifest.  If it is undesirable to be dpiAware, writing dpiAware code in Winforms is not that intuitive, then you can disable what PresentationCore does by pasting this code:

[assembly:System.Windows.Media.DisableDpiAwareness]

Which requires adding a reference to WindowsBase.  You can put it anywhere you like, AssemblyInfo.cs is a pretty logical place.


问:
Result of the sum of random-ordered IEEE 754 double precision floats
Here is a pseudocode of my problem.

I have an array of IEEE 754 double precision positive numbers.

The array can come in a random order but numbers are always the same, just scrambled in their positions. Also these numbers can vary in a very wide range in the valid IEEE range of the double representation.

Once I have the list, I initialize a variable:

```<code>double sum_result = 0.0;
</code>```

And I accumulate the sum on sum_result, in a loop over the whole array. At each step I do:

```<code>sum_result += my_double_array[i]
</code>```

Is it guaranteed that, whatever the order of the initial array of double, if the numbers are the same, the printed out sum result will be always the same?

答:
No.

As a simple example, adding 1 to 0x1p53 yields 0x1p53. (This uses hexadecimal floating-point notation. The part before the “p” is the significand, expressed in hexadecimal the same as a C hexadecimal integer constant, except that it may have a “.” in it to mark the start of a fractional part. The number following the “p” represents a power of two by which the significand is multiplied.) This is because the mathematically exact sum, 0x1.00000000000008p+53, cannot be represented in IEEE-754 64-bit binary floating-point, so it is rounded to the nearest value with an even low bit in its significand, which is 0x1p53.

Thus, 0x1p53+1 yields 0x1p53. So 0x1p53+1+1, evaluated left to right, also yields 0x1p53. However, 1+1 is 2, and 2+0x1p53 is exactly representable, as 0x1.0000000000001p+53, so 1+1+0x1p53 is 0x1.0000000000001p+53.

To show a more easily visualizable example in decimal, suppose we have only two decimal digits. Then 100+1 yields 100, so 100+1+1+1+1+1+1 yields 100. But 1+1+1+1+1+1+100 accumulates to 6+100 which then yields 110 (due to rounding to two significant digits).

Body:
Here is a pseudocode of my problem.

I have an array of IEEE 754 double precision positive numbers.

The array can come in a random order but numbers are always the same, just scrambled in their positions. Also these numbers can vary in a very wide range in the valid IEEE range of the double representation.

Once I have the list, I initialize a variable:

double sum_result = 0.0;

And I accumulate the sum on sum_result, in a loop over the whole array. At each step I do:

sum_result += my_double_array[i]

Is it guaranteed that, whatever the order of the initial array of double, if the numbers are the same, the printed out sum result will be always the same?


问:
Multiple types in one dynamic assembly is way slower than multiple dynamic assemblies with one type each
So I'm emitting some dynamic proxies via DefineDynamicAssembly, and while testing I found that:

One type per dynamic assembly: fast, but uses a lot of memory

All types in one dynamic assembly: very very slow, but uses much less memory

In my test I generate 10,000 types, and the one-type-per-assembly code runs about 8-10 times faster. The memory usage is completely in line with what I expected, but how come the time to generate the types is that much longer?

Edit: Added some sample code.

One assembly:

```<code>var an = new AssemblyName( "Foo" );
var ab = AppDomain.CurrentDomain.DefineDynamicAssembly( an, AssemblyBuilderAccess.Run );
var mb = ab.DefineDynamicModule( "Bar" );

for( int i = 0; i < 10000; i++ )
{
    var tb = mb.DefineType( "Baz" + i.ToString( "000" ) );
    var met = tb.DefineMethod( "Qux", MethodAttributes.Public );
    met.SetReturnType( typeof( int ) );

    var ilg = met.GetILGenerator();
    ilg.Emit( OpCodes.Ldc_I4, 4711 );
    ilg.Emit( OpCodes.Ret );

    tb.CreateType();
}
</code>```

One assembly per type:

```<code> for( int i = 0; i < 10000; i++ )
 {
    var an = new AssemblyName( "Foo" );
    var ab = AppDomain.CurrentDomain.DefineDynamicAssembly( an,
                                                            AssemblyBuilderAccess.Run );
    var mb = ab.DefineDynamicModule( "Bar" );

    var tb = mb.DefineType( "Baz" + i.ToString( "000" ) );
    var met = tb.DefineMethod( "Qux", MethodAttributes.Public );
    met.SetReturnType( typeof( int ) );

    var ilg = met.GetILGenerator();
    ilg.Emit( OpCodes.Ldc_I4, 4711 );
    ilg.Emit( OpCodes.Ret );

    tb.CreateType();
}
</code>```

答:
On my PC in LINQPad using C# 7.0 I get one assembly about 8.8 seconds, one assembly per type about 2.6 seconds. Most of the time in the one assembly is in DefineType and CreateType whereas in the time is mainly in DefineDynamicAssembly+DefineDynamicModule.

DefineType checks there is no name conflicts, which is a Dictionary lookup. If the Dictionary is empty, this is about a check for null.

The majority of the time is spent in CreateType, but I don't see where, however it appears that it requires extra time adding types to a single Module.

Creating multiple modules slows the whole process down, but most of the time is spent creating modules and in DefineType, which has to scan every module for a duplicate, so now has increasing up to 10,000 null checks. With a unique module per type, CreateType is very fast.

Body:
So I'm emitting some dynamic proxies via DefineDynamicAssembly, and while testing I found that:

One type per dynamic assembly: fast, but uses a lot of memory

All types in one dynamic assembly: very very slow, but uses much less memory

In my test I generate 10,000 types, and the one-type-per-assembly code runs about 8-10 times faster. The memory usage is completely in line with what I expected, but how come the time to generate the types is that much longer?

Edit: Added some sample code.

One assembly:

var an = new AssemblyName( "Foo" );
var ab = AppDomain.CurrentDomain.DefineDynamicAssembly( an, AssemblyBuilderAccess.Run );
var mb = ab.DefineDynamicModule( "Bar" );

for( int i = 0; i < 10000; i++ )
{
    var tb = mb.DefineType( "Baz" + i.ToString( "000" ) );
    var met = tb.DefineMethod( "Qux", MethodAttributes.Public );
    met.SetReturnType( typeof( int ) );

    var ilg = met.GetILGenerator();
    ilg.Emit( OpCodes.Ldc_I4, 4711 );
    ilg.Emit( OpCodes.Ret );

    tb.CreateType();
}

One assembly per type:

 for( int i = 0; i < 10000; i++ )
 {
    var an = new AssemblyName( "Foo" );
    var ab = AppDomain.CurrentDomain.DefineDynamicAssembly( an,
                                                            AssemblyBuilderAccess.Run );
    var mb = ab.DefineDynamicModule( "Bar" );

    var tb = mb.DefineType( "Baz" + i.ToString( "000" ) );
    var met = tb.DefineMethod( "Qux", MethodAttributes.Public );
    met.SetReturnType( typeof( int ) );

    var ilg = met.GetILGenerator();
    ilg.Emit( OpCodes.Ldc_I4, 4711 );
    ilg.Emit( OpCodes.Ret );

    tb.CreateType();
}


问:
Using word 'model' in package name creates resource and not package
I am trying to create a package called sc.edu.csce740.model in Eclipse. When I do so it ends up creating a folder and not a package.

But if I use any other word such as apples such as sc.edu.csce740.apples then it does successfully create the package.

I have also tried creating apples first and then refactoring but it changes itself to a folder (resource).

Is this a reserved word? Eclipse bug?

Eclipse Version: Oxygen.1a Release (4.7.1a)

Eclipse Build id: 20171005-1200

答: Sounds to me as if "model" has been set as an exclusion filter. Go to the project's Java Build Path and check if the owner source folder has any exclusion.


问:
Plugging custom transport into gRPC
Let‘s assume we develop a custom low level transport for gRPC. How can we “plug it” into the gRPC c++ API so that we can use it for a Channel?</p>

答: Regarding C++ API: Most of the existing custom transports are done by creating their own credentials C++ types and use those to enable the new transport.</p>

Title: Plugging custom transport into gRPC


问:
using jquery ui datepicker as inline calendar
I have a set of unique requirements.  I need to be able to show an entire year with hte jquery ui datepicker and then when the user picks a date, change the background color of that date and add a record to a database.  This seems to work well until many dates are selected, then it seems to bog down.  Is there a way for jquery ui datepicker to only render the selected cell instead of the whole calendar when a date is selected?  Is there another calendar I should use for this tasik?</p>

答:
Have you try this:</p>

```<code><label>Multiple Month DatePicker: </label>
<input id="date" />
<script type="text/javascript">
    $(function() {
        var dt = {
            numberOfMonths: 12
        };
        $("#date").datepicker(dt);
    });
</script>
</code>```

Body:
Have you try this:

<label>Multiple Month DatePicker: </label>
<input id="date" />
<script type="text/javascript">
    $(function() {
        var dt = {
            numberOfMonths: 12
        };
        $("#date").datepicker(dt);
    });
</script>


答:
This can also be done with a regex :)</p>

```<code>var testNumbers = function(num1){
  var stringOne = num1.toString();
  var regEx = /111|222|333|444|555|666|777|888|999|000/;

  if (regEx.test(stringOne)){
    console.log(stringOne.match(regEx)[0]);
  } else {
    console.log("There wasnt a case of three straight triple numbers occuring");
  }
}
</code>```

Title: trying to detect if three numbers within an array occur in a row

Body:
This can also be done with a regex :)

var testNumbers = function(num1){
  var stringOne = num1.toString();
  var regEx = /111|222|333|444|555|666|777|888|999|000/;

  if (regEx.test(stringOne)){
    console.log(stringOne.match(regEx)[0]);
  } else {
    console.log("There wasnt a case of three straight triple numbers occuring");
  }
}